Long-Context Inference Architecture: Decoupled Encoding and Generation with KV Cache Compression

    This article examines why long-context agent workloads spend more on reading input than writing output, then explains an inference architecture that splits a 40-layer model into a causal encoder and a decoder, shares a global KV cache across layers, and stores cache entries at lower precision. It also analyzes the trade-offs among layer sharing, sequence compression, and quantization, and offers practical guidance for developers building long-context systems.

    Starting from a Typical Scenario: Why Reading Costs More Than Writing

    Consider the workflow of an automatic coding agent. It modifies a source file, then reads back tens of thousands of tokens of code, test logs, and tool outputs. After analyzing them, it generates only a few hundred tokens of next-step instructions. This loop runs repeatedly, and the compute and storage resources consumed by processing the input (reading) far exceed the cost of generating the output (writing).

    This type of workload has three distinct characteristics:

    1. Extremely long input: historical context may reach tens of thousands or even hundreds of thousands of tokens.
    2. Frequent continuation: context is continuously appended, but there are many reusable prefixes.
    3. Short output: the content actually generated in each round accounts for only a small fraction.

    Traditional inference architectures treat all tokens equally. Every layer and every token must fully participate in forward computation and maintain its own cache. This is clearly not the optimal use of resources. The architecture discussed in this article is organized around these pain points: let long inputs pass through half of the network, share the KV cache across layers, and compress overhead along both the compute and storage dimensions.

    First, Understand the Basics: Where the KV Cache Comes From and Why It Inflates

    To understand the optimization, we first need to understand what is being optimized. A language model splits text into tokens, and each token forms hidden vectors as it passes through the layers of a Transformer. Attention has three core concepts usually denoted as Q, K, and V:

    • Q (query): what the current position is looking for.
    • K (key): what historical positions provide as identity information, used to match relevance.
    • V (value): the information actually carried by historical positions and read back.

    For a single query and a single attention head, attention computation can be expressed as:

    1. o = softmax(q · Kᵀ / √c) · V

    Here, q is the current query vector, K and V aggregate the keys and values of t visible historical positions, softmax normalizes relevance scores into weighting coefficients, and the final read-back result is o.

    The key property is that once the K and V of a historical position are computed, they do not change. Therefore, the inference system stores them for subsequent tokens to read repeatedly. This is the KV cache. The problem is that if every layer independently stores its own K and V, cache size is proportional to “number of layers × sequence length × vector dimension × storage precision.” When a 40-layer network processes context at the 100k-token scale, the cache can easily reach tens of GB and become the largest consumer of GPU memory.

    This leads to two clear optimization paths: reduce the number of layers that need to store cache (cross-layer sharing), and reduce the size of each cache entry (dimension compression and low-precision storage).

    Core Design 1: A Two-Stage Split Between Causal Encoder and Decoder

    This architecture divides a 40-layer network into a causal encoder made up of the first 20 layers and a decoder made up of the last 20 layers, and it uses an asymmetric execution strategy:

    • When processing long input: mainly run the first half, the encoder. The input’s role is to “digest” context information into a compact intermediate representation, and these computation results are the basis for subsequent generation.
    • When generating new tokens: run the full 40-layer network to ensure that generation quality is not degraded by input-side compression.

    The intuition behind this design is that reading and writing are two tasks of different natures. Reading compresses and refines massive context; writing requires the model’s full expressive capacity to produce accurate and coherent content. Letting the input side run “light” and the generation side run “at full effort” matches the heavy-read, light-write workload characteristics of the coding-agent scenario described above.

    From an engineering perspective, this also brings an additional benefit: when context is frequently continued, the representations of long prefixes already processed on the encoder side can be reused. Only the small amount of newly added input needs incremental processing, avoiding full recomputation.

    Core Design 2: A Global KV Cache Shared Across Layers

    The second key design is that multiple layers share the same global KV cache, and some layers even reuse the attention retrieval results as well.

    In the traditional approach, 40 layers each maintain an independent cache. Under the shared scheme, multiple layers read the same global KV. This means the “layer count” dimension of the cache is greatly compressed—this is the main source of the reduction in total cache size.

    Why does cross-layer sharing not severely damage model capability? This can be understood from two angles:

    1. Representational redundancy: attention patterns in adjacent layers are often highly correlated. Lower layers focus on local syntactic structure, while higher layers focus on semantic relationships, but there is a large amount of shareable “common context information” in between.
    2. Retrieval result reuse: when some layers’ relevance judgments over historical positions converge, the decision of “which positions to read” can itself be reused, further eliminating repeated attention computation.

    This is consistent with ideas such as grouped-query attention and multi-query attention in the industry—both exploit the empirical fact that the demand for K/V diversity is much lower than for Q. The difference is that the sharing granularity extends from “between attention heads” to “between layers.”

    A Seemingly Contradictory Result: Lighter Sequence Compression, Yet More Cache Savings

    Here, a phenomenon deserves careful explanation: the new architecture applies lighter compression along the sequence dimension than the previous generation (that is, it retains more complete sequence information), yet the global KV cache drops to roughly one quarter of the previous-generation scheme.

    The answer is that total cache size is determined by multiple dimensions together, and compression can occur along different dimensions.

    Compression dimension Technique Effect
    Layer dimension Share global KV across layers Far fewer cache copies
    Sequence dimension Compress along the sequence Shorter cache length per copy
    Precision dimension Lower-bit storage format Fewer bytes per element

    The previous-generation scheme may have relied more on aggressive sequence-dimension compression to save cache, while the new architecture shifts the focus to cross-layer sharing and low-precision storage. This brings an additional benefit: retaining sequence information more completely means better read quality for long-distance dependencies—smaller cache and more complete information retention no longer necessarily conflict.

    For engineering practice, this is also a general lesson: when facing multi-dimensional resource bottlenecks, there is no need to maximize a single dimension; combining several moderate techniques often costs less than one aggressive technique.

    Low-Precision Storage: The Final Piece of Cache Compression

    In addition to sharing, storing the KV cache at lower numerical precision is another major source of savings. Reducing the cache from 16-bit floating point to 8-bit or even lower integer representation can halve or further reduce the per-element footprint.

    Low-precision storage requires attention to the following engineering points:

    • Quantization granularity: per-channel or per-group scaling factor statistics control error better than global uniform quantization.
    • Sensitive-layer protection: layers that are especially sensitive in attention patterns can retain higher precision, using a mixed-precision strategy.
    • Compute path matching: store in low precision and dequantize back to high precision for computation. This requires specialized support from inference kernels; otherwise, bandwidth savings will be offset by extra computation.

    Practical Implications for Developers

    Although this architecture was born from a specific model, its ideas can be generalized to the design of any long-context inference system:

    1. Profile first, then optimize: quantitatively analyze the share of resources consumed by “reading” and “writing” in your workload. If input is much longer than output, input-side computation is the primary optimization target.
    2. Prefix reuse is low-hanging fruit: in scenarios with frequent continuation, make sure the inference framework has prefix cache reuse enabled to avoid recomputing historical context.
    3. Combine multiple cache compression dimensions: layer sharing, head sharing, sequence compression, and low-precision storage can be used together. Introduce them incrementally, ordered by cost-effectiveness and quality loss.
    4. Build quality regression benchmarks: any cache compression may affect long-distance retrieval capability. Prepare needle-in-a-haystack-style long-context test sets and compare key metrics before and after compression.

    Conclusion

    The cost dilemma of long-context inference is essentially a “multiplicative explosion of storage and computation”: number of layers multiplied by sequence length multiplied by precision, with each term directly increasing GPU memory and bandwidth overhead. The combination of the encoder/decoder two-stage split and the globally shared KV cache demonstrates two complementary ways to break the bottleneck—on the compute side, let input pass through half of the network; on the storage side, let multiple layers share one cache and reduce precision. For teams building applications such as intelligent coding assistants and long-document analysis, understanding these principles is essential for making rational trade-offs between framework selection and in-house optimization.