Cache Compression and Sharing Mechanisms for Long-Context LLM Inference

    This article breaks down why reading long context costs more than generating output in LLM inference, and how two techniques address it: layered execution that splits a deep network into a causal encoder and a decoder, and global KV cache sharing that combines cross-layer reuse, lower-precision storage, and block-based eviction. It includes a rough cache capacity formula, the main engineering practices for cache hit rate, scheduling, precision tiers, observability, and elastic serving, and the key takeaway that turning repeated reads into one-time encoding with multiple reuse is what pays off when inputs are far longer than outputs.

    Cache Compression and Sharing Mechanisms for Long-Context LLM Inference

    1. Where the Problem Starts: Why Reading Costs More Than Writing

    In applications such as AI coding assistants, document Q&A, and log analysis, a typical turn looks like this: the model first reads back tens of thousands of words of source code, test logs, and tool-call output, then generates a few hundred words describing the next action. Input and output lengths are severely asymmetric, so inference resources end up dominated by the “read” side.

    Understanding this requires going back to the basic structure of the Transformer. Text is split into tokens, each token produces a hidden vector at every layer, attention pulls information from the historical context, and the feed-forward network keeps processing it. When a new token is generated, the keys and values at historical positions do not need to be recomputed, so they are cached. This is the KV cache. If every layer stores its own copy, the cache grows linearly with sequence length and layer count; even to generate a single token, the entire historical cache must be read in.

    A request therefore splits naturally into two phases:

    • Prefill: all input tokens are processed in parallel. This is compute-intensive and can make full use of matrix parallelism.
    • Decode: tokens are generated one at a time. This is memory-access-intensive, with the bottleneck in cache read bandwidth and capacity.

    A schematic single-head attention computation can be written as:

    1. # q: [1, c], K/V: [t, c], t is the visible history length
    2. score = softmax(q @ K.T) # [1, t]
    3. o = score @ V # [1, c]

    This expression is only meant to build intuition: real systems also layer on compression, sharing, and precision handling, which change the actual storage layout.

    2. Layered Execution: Splitting the Network into an Encoder and a Decoder

    One approach widely explored in the industry is to split a deep network into two parts: the first several layers form a causal encoder, and the last several layers form a decoder. When processing long input, mainly the first half runs, compressing the long context into a more compact representation; when generating new tokens, the full network runs.

    With 40 layers, for example, this can be split into a 20-layer encoder and a 20-layer decoder. There are three benefits:

    1. Prefill only goes halfway, so the encoding cost for long input drops significantly;
    2. The encoder output is reused, avoiding re-encoding the same context every turn;
    3. The decode phase keeps full depth, so generation quality is not noticeably degraded.

    Engineering-wise, attention is needed on representation-dimension alignment at the layer interface, where normalization is placed, and the incremental update strategy for encoder output when continuing a context.

    3. Global Cache Sharing: Why Lighter Sequence Compression Can Still Yield a Smaller Cache

    Key conclusion: reducing the compression pressure along the sequence direction does not necessarily make the cache larger. A global KV cache can be brought down to roughly one quarter of the previous generation’s approach, with the space savings coming mainly from cross-layer sharing and lower storage precision.

    • Cross-layer sharing: multiple layers share the same global key-value cache instead of each keeping its own copy, reducing the number of copies from “layer count” to “group count”;
    • Retrieval result reuse: some layers also reuse the results obtained from retrieval augmentation, cutting duplicate writes;
    • Low-precision storage: the cache is written and moved at lower numerical precision, combined with block-wise quantization to control error;
    • Blocking and eviction: the cache is managed in blocks, combined with a sliding window and importance scoring for selective retention.

    Capacity can be roughly estimated as:

    1. cache_bytes ≈ layers_shared × heads × head_dim × seq_len × bytes_per_elem × batch

    Here layers_shared is the number of sharing groups, and bytes_per_elem is determined by the storage precision. Dropping layers_shared from 40 to 1–2 groups and precision from 16-bit to 8-bit or lower explains the order-of-magnitude reduction.

    4. Engineering Implementation Points

    1. Prioritize hit rate: stabilize prefixes for system prompts and repository context to improve cache reuse;
    2. Block-based scheduling: swap cache in and out by block, avoiding moving a long sequence as one whole segment;
    3. Precision tiers: keep higher precision for precision-sensitive layers, lower precision for the rest, with error monitoring;
    4. Observability: use logging services and monitoring alerts to track cache hit rate, prefill latency, and GPU memory usage;
    5. Elastic capacity: pair stateless inference instances with a container platform and a message queue to smooth out peaks, with the cache scheduled by session affinity.

    5. Conclusion

    The main line of long-context inference optimization is turning “repeated reads” into “encode once, reuse many times.” Layered execution lowers prefill cost, while cross-layer sharing and low-precision storage shrink the cache; only when the two are combined do you get gains under workloads where input is far longer than output. For developers, understanding the cache capacity model and the conditions for a hit is more valuable than chasing a single parameter. In cloud environments such as Baidu AI Cloud, the mechanisms above can be put into production reliably by combining general capabilities like object storage, container platforms, and monitoring alerts.