KV Cache Optimization for Long-Context Models: Hierarchical Encoding and Cross-Layer Sharing

    This article explores KV cache optimization strategies for long-context language models dealing with read-heavy workloads. It analyzes the KV cache cost model and introduces a hierarchical encoder-decoder architecture to reduce prefill computation. By combining cross-layer sharing, low-precision storage, and retrieval result reuse, the approach effectively lowers storage and bandwidth costs. The article also explains how lighter sequence compression paired with these techniques can reduce the global KV cache to approximately one-quarter of its original size while maintaining long-input fidelity.

    KV Cache Optimization for Long-Context Models: Hierarchical Encoding and Cross-Layer Sharing

    1. The Starting Point: Read-Heavy Workloads

    Evaluating a long-context model requires looking beyond parameter scale or single-turn benchmarks to understand the actual workloads. Take a programming Agent as an example: after modifying a file, it might read back tens of thousands of words of source code, test logs, tool outputs, and historical conversations, ultimately generating only a few hundred words for the next action. This cycle repeats with continuous context continuation. Consequently, the resources spent on “reading” easily exceed those spent on “writing.”

    Such workloads share three characteristics: long inputs, short outputs, and frequent context continuation. In inference systems, the prefill phase processes massive tokens, while the decode phase, though generating one token per step, repeatedly reads the historical KV cache. Therefore, optimizing long context is not just about “compressing sequences shorter” but also about reducing the storage copies, precision, and access bandwidth of the KV cache.

    2. From Attention Formula to KV Cache Cost Model

    Language models split text into tokens. Each token forms hidden vectors across different Transformer layers. In the attention mechanism, Q (query) is emitted from the current position, K (key) determines which historical positions are relevant, and V (value) carries the information to be read back. The computation for a single query and attention head is:

    [
    o=\operatorname{softmax}\left(\frac{qK^{\mathsf T}}{\sqrt c}\right)V
    ]

    where ( q ) is the current query vector, ( K ) and ( V ) contain keys and values of historical positions, ( c ) is the number of channels, and ( o ) is the read-back result. When generating the next token, the K and V of historical positions can be reused, so the system caches them—this is the KV cache.

    Roughly, the KV cache size can be expressed as:

    [
    C \approx L \times T \times c_{kv} \times b \times S
    ]

    Here, ( L ) is the number of layers, ( T ) is the effective sequence length, ( c_{kv} ) is the number of KV channels per layer per token, ( b ) is the bytes per element, and ( S ) is the sharing or compression factor. To reduce ( C ), five directions can be explored: reducing layer copies, shortening the effective sequence, lowering channel dimensions, reducing storage precision, and increasing cross-layer sharing rates. Relying solely on sequence compression may lose long-context details; coordinating multiple factors is more likely to balance quality and cost.

    3. Hierarchical Encoder-Decoder: Half-Journey for Long Inputs

    A notable design approach divides the network layers into a “causal encoder” and a “decoder.” For instance, a 40-layer network can be split into 20 causal encoder layers and 20 decoder layers: processing long inputs primarily runs the first half (encoder), while generating new tokens runs the complete network.

    Intuitively, long-context prefilling resembles “understanding and indexing,” while token-by-token generation is more like “decision-making based on existing representations.” Concentrating the long input phase in the first half significantly reduces prefill computation. Although the generation phase runs the full network, the output token count is small, keeping the total cost manageable. The cache can also be organized hierarchically by encoder and decoder for unified management.

    Pseudocode is as follows:

    1. def prefill(tokens):
    2. h = embed(tokens)
    3. for layer in encoder_layers: # First 20 layers
    4. h = causal_attention(h, kv_store.group_of(layer))
    5. return h
    6. def decode_step(token, state):
    7. h = embed(token)
    8. for layer in all_layers: # Full network
    9. h = attention(h, kv_store.group_of(layer))
    10. return lm_head(h)

    Note that this is not simply “cutting half the layers.” The encoder representations must align with the decoder, and causal masks, positional encodings, and inter-layer interfaces must be adapted during training. Otherwise, long input information may be lost at the hierarchical boundary.

    4. Cross-Layer Sharing of Global KV Cache: What to Share and Why It Works

    The traditional approach stores a separate K and V for each layer. More layers and longer sequences mean larger caches. The idea of cross-layer sharing a global KV cache is that several layers share a set of global K/V, or reuse the same cache through projection, gating, and grouping; some layers can also reuse retrieval results to reduce redundant encoding.

    The direct benefit of sharing is reducing the “layer copy” factor. If every 4 layers share a cache group, the effective layer factor approaches one-quarter of the original. Sharing also brings engineering advantages: a more centralized cache layout makes paging management, quantization, prefetching, and eviction strategies easier to implement uniformly. However, sharing is not free. Different layers have varying sensitivities to key-value representations, and overly large sharing groups may reduce expressive capacity. Common mitigation methods include grouped sharing, lightweight inter-layer projection, gated residuals, and per-attention-head sharing.

    5. Low-Precision Storage and Retrieval Result Reuse

    Another major cost of the KV cache is bytes. Reducing cache from high precision to lower precision directly lowers memory footprint and read bandwidth. Practical systems usually require per-head scaling, group quantization, outlier handling, and dequantization fusion to prevent precision loss from degrading long-context quality.

    Retrieval result reuse targets “frequent continuation” scenarios: the same retrieved content may be referenced repeatedly across multiple rounds. If its K/V representations can be reused at the cache layer, redundant computation is minimized. However, reuse must include versioning and invalidation mechanisms to prevent reading stale representations after context changes.

    6. Why Lighter Sequence Compression Yields a Quarter-Sized Global Cache

    A seemingly contradictory result often appears here: new designs apply lighter sequence compression—preserving more token details—yet the global KV cache drops to about one-quarter of its predecessor. The reason is that total cache size is determined by the product of multiple factors, not just the sequence compression rate.

    Assume the previous generation cache was:

    [
    C_0 = L_0 \times T_0 \times c \times b_0
    ]

    The new design is:

    [
    C1 = L{eff} \times T_1 \times c \times b_1
    ]

    Here, ( T1 ) might be greater than ( T_0 ) because of lighter sequence compression; however, ( L{eff} ) drops significantly due to cross-layer sharing, and ( b_1 ) drops due to low-precision storage. After multiplying these factors, ( C_1 ) can still drop to about one-quarter of ( C_0 ). In other words, the main source of space savings is not “compressing the sequence harder,” but rather inter-layer sharing and lower storage precision. Lighter sequence compression actually benefits long-input fidelity, with the cost offset by sharing and precision optimizations.

    7. Engineering Implementation and Evaluation Metrics

    When implementing, it is recommended to account for benefits separately: how much the layer factor drops due to sharing groups, how many bytes drop due to low precision, and how the token count changes due to sequence compression. Evaluation metrics should include prefill throughput, decode latency per token, peak KV cache size, cache bandwidth, time-to-first-token, multi-round continuation consistency, and long-context task quality. Stress testing should simulate the real-world ratio of “long input, short output, frequent continuation” rather than just short Q&A.

    During tuning, sharing groups should not be blindly expanded; low-precision storage requires calibration and regression testing; retrieval result reuse needs invalidation strategies; cache paging and prefetching should be laid out continuously by sharing group. Ultimately, the hierarchical encoder-decoder handles the “half-journey for long inputs,” while cross-layer sharing and low precision handle “store less, read faster.” Combining both shifts long-context inference from the heavy “one cache per layer per token” model to a more controllable engineering solution.