Long-Context LLM Architecture Breakdown: Hybrid Attention and MoE in Practice
As language models scale from thousands to millions of tokens, GPU memory—not compute—becomes the first bottleneck. This article breaks down why KV cache grows with sequence length, how hybrid attention combines compressed shared attention with hierarchical context attention to reduce cache size, and how four MoE paradigms differ in expert organization. It also covers capacity planning, serving, observability, and long-text evaluation practices for deploying long-context models.
1. The Bottleneck as Context Length Grows
As large language models move from thousands of tokens to millions, the first resource to break is not compute but GPU memory. Standard multi-head attention caches the Key/Value tensors for every layer during inference. The cache size grows linearly with sequence length and is further amplified by the number of layers, attention heads, and head dimension. At million-token context lengths, the KV cache alone can consume tens of gigabytes, leaving little room for weights and batching, and throughput collapses.
This calls for separating two types of cost: training is primarily a quadratic compute problem, while inference is mainly a matter of memory bandwidth and capacity. There are three engineering directions: sparsifying attention to compute only the most relevant segments; compressing and summarizing long sequences into fixed-length representations; and hierarchical design, where shallow layers look globally and deep layers look locally. Hybrid attention combines the second and third approaches.
2. Hybrid Attention: Turning Linear Cache Growth into a Constant
A typical approach runs two mechanisms in parallel within the same model: Compressed Shared Attention (CSA) handles global information, and Hierarchical Context Attention (HCA) handles local information.
- CSA: Compresses long sequences into blocks, generates fixed-length summary vectors, and shares them across multiple layers, so global information no longer grows linearly with length.
- HCA: In deep layers, applies fine-grained attention only to the context segments most relevant to the current query, recovering details lost during compression.
The masking and compression logic can be sketched as:
# Pseudocode: block compression + local fine-grained attentiondef hybrid_attention(x, q, block=256, n_summary=64, local_win=1024):summary = pool_compress(x, block=block, out_len=n_summary) # fixed-length global summarykv_cache = concat(summary, x[-local_win:]) # constant summary + sliding local windowreturn scaled_dot_product(q, kv_cache, kv_cache)
There are three key engineering points. First, the compression ratio should be dynamically adjustable: compress aggressively for simple inputs and retain more summaries for complex ones to avoid information loss. Second, the compression objective must be part of training: hierarchical pretraining objectives let the model learn what to compress and what to keep; otherwise, inference-time compression causes noticeable quality drops. Third, the sharing scope must be designed carefully: cross-layer sharing saves memory but reduces expressiveness, so it is typically applied broadly only in shallow layers.
The gains are order-of-magnitude: with reasonable compression ratios and local window configurations, the KV cache can drop by roughly 90%, making million-token contexts feasible on a single machine with multiple GPUs. The costs are implementation complexity, operator adaptation, and accuracy regression evaluation, which must be paired with a long-text evaluation set.
3. Comparing Four MoE Paradigms
Sparse Mixture-of-Experts (MoE) trades total parameter count for capacity and controls cost through the number of activated parameters. The main differences among the five strong approaches lie in how experts are organized.
- Shared experts plus routed experts: Several routed experts activate top-k per token, plus one always-active shared expert that carries general knowledge. This offers stable training, preserves general capabilities, and keeps load relatively balanced.
- Fine-grained expert splitting: Experts are made smaller and more numerous with a higher top-k, allowing more flexible combinations and greater capacity at the same activated compute, but increasing communication and scheduling overhead.
- Hierarchical routing: Coarse grouping first, then expert selection within each group, which reduces routing noise and suits scenarios with clear domain differences.
- Capacity factor and token-dropping trade-offs: A larger capacity factor keeps throughput stable but wastes compute; a smaller one saves compute but may drop tokens, so it must be tuned to the workload distribution.
Two metrics must be monitored in production: the coefficient of variation of expert load, which reflects balance, and the fraction of dropped tokens, which directly reflects quality loss.
4. Deployment Recommendations: From Selection to Launch
- Capacity planning: Estimate memory in three parts—weights, KV cache, and activations plus temporary buffers—then decide the parallelism strategy. For long contexts, prioritize splitting along the sequence dimension.
- Serving: On the inference side, use paged cache management, prefix reuse, and continuous batching. Orchestrate training and inference on a container platform, use object storage for corpora, and use message queues to decouple the data pipeline.
- Observability: Bring time-to-first-token, time-per-token, cache hit rate, and expert load into logging and alerting, forming a capacity regression baseline.
- Evaluation: Combine three long-text tasks—needle-in-a-haystack retrieval, multi-hop question answering, and long-document summarization. Short-text regression tests are still required to prevent compression mechanisms from damaging base capabilities.
The conclusion is straightforward: the core competitiveness of ultra-long context comes from hierarchical and compressed attention structures and from stable MoE expert organization. Reducing the cache, balancing the load, and making evaluation solid form a reproducible engineering path. These capabilities can be deployed and stress-tested on Baidu AI Cloud’s general compute, container, and storage products.
