Decoding Million-Token Context LLM Architecture: Hybrid Attention and KV Cache Compression

    This article breaks down what it really takes to support million-token context in large language models, reframing the challenge as a unit-cost problem rather than a window-size feature. It explains why standard self-attention hits FLOPs and memory walls, how hybrid attention combines compressed global and dense local branches, and the four main paths to KV Cache compression. It also covers long-context training and stability, plus practical guidance on evaluation, tiered routing, context engineering, observability, and cloud deployment. Readers will learn which metrics matter and why hybrid attention and KV Cache compression are the key levers.

    1. Reframing the Problem: Million-Token Context Is a Unit-Cost Problem, Not a Window Problem

    Over the past year, the growth of large model capabilities has increasingly relied on test-time scaling, shifting part of the compute budget from training to inference: models need to generate longer chains of thought and to retrieve, compare, and make decisions across longer materials. As a result, context length has turned from an “input limit” into a “capability ceiling.”

    But the self-attention of a standard Transformer scales quadratically with sequence length. When the context reaches the 1M token range, it hits two walls at the same time:

    • The FLOPs wall: generating each new token requires an attention computation over all historical key/value pairs. The longer the context, the more compute each token needs, and both first-token latency and output throughput degrade.
    • The memory wall: autoregressive decoding must cache the K/V representations of historical tokens at every layer. At million-token scale, the KV Cache often consumes more memory than the model weights and becomes a direct bottleneck on batch concurrency.

    So the technical metrics that actually matter are not “the maximum number of tokens supported,” but three operational questions: can you afford the compute, can you fit the cache, and can you reliably use long-range information. A representative approach from the industry (data given in a preview release of one model family) quantifies the goal clearly: in million-token scenarios, per-token inference FLOPs are within about 30% of the previous generation, and the KV Cache is reduced to about one tenth. The significance of such numbers is that they pull “long context” back from a demo feature into an engineering feature that is billable and scalable.

    2. Architecture: Why Hybrid Attention Has Become the Mainstream Answer

    A single attention form can hardly satisfy both global retrieval and fine-grained local modeling, so the mainstream approach is hybrid attention: stacking modules with different attention measures in alternation, dividing the work of handling the sequence among them.

    • Sparse/compressed attention branch: it first compresses or summarizes the historical context into block-level representations, then lets the current token interact globally only with the compressed representations. Complexity drops from quadratic to nearly linear, at the cost of an extra training objective for the compressed representations.
    • Dense/local high-precision branch: it keeps full K/V within a smaller window and handles short-range dependencies, format constraints, code indentation, and long-table alignment—signals that “must not blur.”

    The two are arranged in alternation at a certain ratio: the global branch ensures things can be “found,” while the local branch ensures they can be “seen clearly.” Three points deserve special attention in engineering:

    1. Layer ratio: the ratio of global to local layers directly determines the balance between long-range recall and short-term precision, and needs ablation studies against the task distribution.
    2. Position encoding extrapolation: at million-token lengths, the base-frequency scaling and segmentation strategy of rotary position encoding must be designed explicitly; otherwise attention collapse can occur in the middle of the sequence.
    3. Parallel partitioning: the partition boundaries of sequence parallelism and attention parallelism must avoid compressed-block boundaries, or communication overhead will eat up the compute gains.

    A schematic layer structure (pseudocode, only expressing the arrangement idea):

    1. for layer_idx in range(num_layers):
    2. if layer_idx % 3 == 2:
    3. # Local high-precision branch: full K/V within a small window
    4. h = local_dense_attention(h, window=4096)
    5. else:
    6. # Global compressed branch: block-level compressed representations + linear-complexity interaction
    7. h = compressed_global_attention(h, block=512)
    8. h = moe_mlp(h) # Sparse-activation feed-forward

    3. Cache Layer: Four Viable Paths to KV Cache Compression

    The KV Cache is the real cost center of long context. Common industry techniques fall into four categories and are usually combined:

    • Low-rank/latent vector compression: project K/V into a low-dimensional latent space for caching, then restore it when needed, greatly reducing memory usage.
    • Quantized storage: store KV at low bit-width. Note the distinction between “storage quantization” and “compute quantization”; the former carries lower risk.
    • Cross-layer sharing: reuse the same K/V representation across multiple layers, trading a little precision for orders-of-magnitude memory savings.
    • Eviction and tiering: keep hot data in memory and push cold data down to host memory or object storage, with block-level swap-in and swap-out.

    A rough capacity estimation, useful for resource planning before launch:

    1. # bytes_per_token = layers * 2(K/V) * kv_heads * head_dim * bytes
    2. kv_bytes = tokens * layers * 2 * kv_heads * head_dim * bytes_per_elem
    3. max_batch = gpu_memory // (weights_bytes + kv_bytes + activation_buffer)

    The conclusion is straightforward: compressing the per-token cache to one tenth is equivalent to increasing the serviceable concurrency by an order of magnitude, which is more cost-effective than simply adding memory.

    4. Training and Stability: Long Context Is Trained, Not Configured

    Native support for million-token context means the training phase must cover that length. Common engineering practices include progressive window extension (warm up on short sequences, then gradually lengthen), long-document concatenation with document-boundary masking, construction of retrieval-style long-range dependency tasks, and load-balancing and routing-stability monitoring under the MoE architecture. If you only change settings on the inference side, it usually shows up as loss of mid-sequence information and a sharp drop in long-document summarization quality.

    5. Implementation Advice: How to Evaluate and Choose

    • Do the math first: estimate compute with “per-token FLOPs × average context × daily call volume,” and estimate the concurrency ceiling from KV capacity.
    • Tiered routing: send short requests to efficient small models and long-document requests to high-capability large models, avoiding globally high cost.
    • Context engineering: retrieval pre-filtering, segmented summarization, and structured placeholders often bring bigger gains than switching models.
    • Observability: build monitoring, alerting, and log analysis for first-token latency, cache hit rate, and long-range recall accuracy.
    • Cloud form: a common combination is container platforms hosting inference services, object storage hosting cold caches, message queues for request peak-shaving, and monitoring/alerting and logging services for cost attribution; Baidu AI Cloud can be assembled on demand from these general capabilities.

    In one sentence: to evaluate million-token context, look at the slopes of its three curves—compute, memory, and stability—rather than the window number itself. Hybrid attention and KV Cache compression are critical precisely because they flatten all three curves at the same time.