Understanding Million-Token LLM Architectures: Hybrid Attention, KV Cache Compression, and MoE

    This article breaks down what it actually takes to build and deploy LLMs with million-token context windows. It explains why compute cost and memory usage—not the advertised window size—are the real bottlenecks, then walks through three core architectural upgrades: hybrid attention to reduce quadratic complexity, KV cache compression and lifecycle management to control memory, and MoE sparse activation to decouple parameters from compute. It also covers staged training for stability and a four-dimension framework for evaluating whether a long-context solution is truly production-ready.

    1. Why “Fitting It In” Is Not the Same as “Making It Usable”

    When the context window grows from 32K all the way to 1M, the real challenge is not how much text you can paste into the input box. It is that two things degrade at the same time: compute cost and memory usage.

    Standard Transformer self-attention has O(n²) complexity in the sequence length n. Every time a new token is generated, a relevance computation must be performed against all historical key/value pairs; the longer the sequence, the higher the per-token inference FLOPs. At the same time, autoregressive decoding must cache the key/value tensors of historical tokens at every layer. This memory footprint is proportional to n and is strongly tied to the number of layers, the number of attention heads, and head_dim.

    This leads to a typical phenomenon: a model “supports” a million-token context, but actual throughput is so low that it cannot be used in production, or a single accelerator card overflows before the KV Cache even fits. Therefore, the core problem of ultra-long context should be restated as: at million-scale lengths, how do we drive down the per-token compute cost, compress the cache representation, and keep both training and inference stable?

    2. Capability Tiers: The Product Trade-off Between a High-Capability Version and an Efficient Version

    When the industry releases ultra-long-context models, it commonly adopts a “two-tier” strategy: one tier has a large parameter count with moderate activated parameters, aiming for the upper bound of complex reasoning and long-form writing; the other has both total and activated parameters that are smaller, aiming for throughput and response speed per unit cost. Both share the same long-context capability, and the difference shows up in the capability ceiling and the cost curve.

    This tiering is critical for engineering selection: offline batch processing and repository-level code understanding can use the efficient tier; hard math problems and in-depth analysis of long documents should use the high-capability tier. When evaluating, you should not look only at the “maximum context,” but at the effective throughput in the target length range, the first-token latency, and the combined cost per million tokens.

    3. Architectural Upgrade One: Hybrid Attention, Splitting Apart the Quadratic Complexity

    The mainstream approach is hybrid attention, which combines multiple attention forms within the same model: some layers retain global attention, responsible for long-range information integration across segments; other layers use local-window, compressed, or chunked attention to reduce complexity to near-linear.

    A common combination is “compressed sparse attention + hierarchical/chunked attention”: the former first compresses long history into a small number of representative representations, then performs attention in the compressed space; the latter performs fine-grained interaction only within a chunk or between adjacent chunks. A sketch is shown below (pseudocode, expressing structure only):

    1. # Global layer: kept at low frequency, responsible for long-range retrieval
    2. if layer_idx in global_layers:
    3. out = full_attention(x, kv_cache) # O(n^2), but few layers
    4. else:
    5. # Local layer: used at high frequency, near-linear complexity
    6. q = q_proj(x)
    7. k_local, v_local = window_kv(x, w=4096) # keep only in-window KV
    8. c = compress(history_kv, stride=256) # compress history into a few tokens
    9. out = local_attention(q, k_local, v_local) \
    10. + cross_attention(q, c) # interact with compressed representation

    The engineering benefit is that the number of global layers is strictly controlled (for example, appearing once every 4–6 layers), and the vast majority of layers take the linear path, significantly lowering per-token FLOPs at million-scale lengths. The cost is that positional encoding and training-data ratios must be redesigned; otherwise, long-range retrieval capability will degrade.

    4. Architectural Upgrade Two: KV Cache Representation Compression and Lifecycle Management

    The KV Cache is the number-one memory killer. Common compression techniques in the industry fall into four categories:

    1. Low-rank/latent representation caching: project key/value into a low-dimensional latent space before caching, then reconstruct it during inference, reducing memory usage by an order of magnitude.
    2. Quantized caching: store KV at a lower bit width (such as 8-bit or lower), combined with error-compensation strategies to preserve accuracy.
    3. Eviction and sparse access: score attention importance, keep only the KV of hot tokens, and evict or fold cold tokens into a summary.
    4. Cross-request sharing and tiered storage: compute an identical prefix (system prompt, code repository context) only once and put the KV into a shared cache pool; sink cold data to host memory or even object storage, swapping it in on demand.

    Engineering also requires attention to cache management: paged KV pools, prefix-hash reuse, and fragmentation defragmentation under continuous batching—these determine whether long-context serving can run stably under high concurrency.

    1. Rough memory budget: kv_bytes ≈ 2 × layers × kv_heads × head_dim × bytes × tokens
    2. # At 1M tokens this value is often on the order of hundreds of GB, and must be compressed via a combination of low-rank + quantization + eviction

    5. Architectural Upgrade Three: MoE Sparse Activation, Decoupling Parameters from Compute

    Ultra-long-context models commonly adopt a Mixture-of-Experts (MoE) structure: total parameters are large to carry knowledge, but each token activates only a small number of experts, keeping the actual compute within a controllable range. Combined with fine-grained expert partitioning and shared experts, this can improve expressiveness without significantly increasing activated parameters.

    For long-context scenarios, MoE has another implicit benefit: different experts can separately handle “local syntactic processing” and “global semantic integration,” complementing the layered structure of hybrid attention. It is worth noting that expert load balancing, routing jitter, and communication overhead can become throughput bottlenecks, usually requiring capacity-factor control, auxiliary balancing loss, and expert-parallel strategies to constrain them together.

    6. Training Stability: Long Context Is Not “Extrapolated”

    Stretching the window from short to a million often leads to attention-entropy collapse and long-range retrieval failure when relying on positional-encoding extrapolation. Reliable practices include: staged extension of training length (such as 32K → 128K → 1M), adjusting the RoPE base frequency or adopting learnable positional scaling, constructing “needle-in-a-haystack” retrieval synthetic data, and controlling the learning rate and gradient clipping on long sequences.

    Stability metrics must be quantified: retrieval accuracy at different depths, factual consistency of long-document summaries, and the entropy curve of the attention distribution. Without this monitoring, long-context capability easily ends up “looking good on metrics while actually dropping information.”

    7. Deployment Evaluation: How to Tell Whether a Long-Context Solution Is Truly Usable

    It is recommended to replace the single “maximum length” marketing claim with a four-dimension evaluation table:

    • Effective length: whether retrieval and reasoning accuracy hold at the target length;
    • Economics: the combined cost per million tokens (including cache and recomputation);
    • Serviceability: first-token latency, throughput, and P99 under concurrency;
    • Operability: cache hit rate, eviction rate, failure retries, and fallback paths.

    In a platform environment like Baidu AI Cloud, the above capabilities are typically delivered as combinations of general categories: a container platform hosts inference services, object storage holds long documents and cache snapshots, a message queue smooths out request peaks, and logging and monitoring/alerting services handle observation of the cache and latency metrics specific to long context.

    8. Conclusion

    The competition around million-token context has shifted from the “window number” to “effective intelligence per unit cost.” Hybrid attention reduces computational complexity, compressed KV Cache reduces memory pressure, MoE sparse activation decouples parameters from compute, and staged training ensures stability—none of the four can be missing. For developers, selection should be guided by measured throughput and cost in the target length range, rather than the maximum value on a spec sheet.