Rebuilding Attention for Million-Token Context
Long-context serving is now an engineering requirement, not a paper metric. This article explains why KV cache dominates cost at million-token scale, compares MHA, MQA/GQA, and latent-space compression, and outlines capacity math plus system-level work on parallelism, kernels, prefix cache, and observability.
Million-token context is an engineering demand, not a slogan
Over the past year, long context moved from a paper metric to a product metric. Real workloads push from three directions: repository-scale code understanding, joint analysis of very long documents and multi-turn chats, and multi-step agent planning. These loads share a pattern: inputs of hundreds of thousands to a million tokens, with short outputs.
That pattern hits classic inference architecture. Prefill is compute-bound; decode is memory-bandwidth-bound; KV-cache capacity and bandwidth grow linearly with context. From 8K to 1M tokens, KV cache can go from negligible to larger than the model weights. Long context is therefore a system-coupling problem, not only a model-architecture problem.
Three attention paths and their costs
1. Multi-head attention (MHA): full expressiveness, redundant KV
Standard MHA keeps independent Key/Value per head, so memory and bandwidth scale with the number of heads. It is the quality baseline and the least economical choice for long-sequence inference.
2. Multi-query and grouped-query attention (MQA/GQA): share KV for bandwidth
MQA shares one K/V set across all query heads; GQA is a grouped compromise. Expressiveness drops slightly; KV cache can shrink by one or two orders of magnitude.
# Illustrative: GQA KV-head replication (mechanism only, not a product API)def expand_kv(kv, n_rep):# kv: [batch, kv_heads, seq, head_dim]b, h, s, d = kv.shapereturn kv[:, :, None].expand(b, h, n_rep, s, d).reshape(b, h * n_rep, s, d)
3. Latent low-rank compressed attention: extreme compression, complex coupling
This path projects K/V into a low-dimensional latent space, caches only latent vectors, and up-projects at inference. Compression is high, but two hidden costs appear: theoretical gains need specific matrix absorption and operator fusion; adapting to parallelism, quantization, and the compiler stack is expensive. If kernels or toolchains do not cooperate, paper memory wins do not become throughput.
That explains a recent architecture swing: some new models drop latent compression and return to simpler KV sharing. Architectures have not converged; they trade off. Until an ecosystem is mature around one design, an operator-friendly, sharding-friendly, compiler-friendly “plain” scheme often ships faster than a theoretically better “clever” one.
Capacity first: count the bytes before choosing an architecture
Before shipping any long-context design, quantify memory and bandwidth.
# Illustrative: KV-cache size and decode-step bandwidth lower bounddef kv_bytes(layers, kv_heads, head_dim, seq, batch, dtype_bytes=2):per_token = 2 * kv_heads * head_dim * dtype_bytes # K and Vreturn layers * per_token * seq * batchdef decode_step_lower_bound(weight_bytes, kv_cache_bytes, bandwidth):# Each decode step at least moves weights plus the full KV cachereturn (weight_bytes + kv_cache_bytes) / bandwidth
Two selection rules:
- If
kv_bytesat the target length is a large fraction of single-GPU memory, you must change structure (shared KV, quantized KV) or scheduling (paging, hierarchical offload). Adding GPUs alone will not fix it. - If
decode_step_lower_boundalready nears the latency budget, shift from model structure to bandwidth use and batching.
Four system-level levers
Lever 1: Joint design of attention structure and parallelism
Sequence, tensor, and expert parallelism interact with KV sharing. Too few KV heads can starve a split dimension. Search attention splits and expert splits on one parallelism table rather than tuning them separately.
Lever 2: Deep customization of operators and compilation
The real barrier is kernels: paged KV, variable-length sequences, and mask shapes, plus tensor compilers and autotuning near hardware peak. A practical loop: a minimal reproducible performance baseline, compiler search for the target hardware, then freeze configs into regression tests.
Lever 3: Serving, scheduling, and prefix cache
Prefix-cache hit rate is the first variable in the long-context cost model. Route by prefix similarity, page the cache with eviction, and make hit metering and billing transparent. Cache-hit pricing often changes user behavior more than a model price cut.
Lever 4: End-to-end observability
Track time to first token, time per token, cache hit rate, in-batch length distribution, memory watermarks, and preemptions, closed with logs and alerts. Without length-distribution visibility, capacity planning is guesswork.
Scale, sparsity, and training-side work
Parameter scale-up and sparsity often arrive together: more total parameters for knowledge capacity, low activated-parameter ratio to control compute per token. Pressure then moves to routing balance, expert-parallel communication, and fault-tolerant training.
Two training directions: orthogonalization-style optimizers that improve the condition number of updates for stability and convergence; residual-path changes, including finer-grained layer residuals and attention residuals, to ease signal decay in deep nets. Architecture, optimizer, and operators evolve together.
Shipping advice and common mistakes
- Do not substitute short-context eval for long-context eval. Build cases for long-range dependence, cross-segment retrieval, and long-document aggregation.
- Do not treat compression ratio as the win. Only end-to-end throughput and latency count.
- Do not ignore hallucination and instruction following. Instruction drift on long inputs is the main risk; constrain structured outputs and add validation.
- Do not tune without a baseline. Freeze a benchmark and regression set before changing structure or kernels.
- Assemble cloud serving from generic capabilities. Model files and data can live in object storage, inference in containers, async work on message queues, metrics and logs in logging and monitoring. Platforms such as Baidu AI Cloud provide this class of generic building blocks.
Closing
The swing in attention design is not “which structure is better.” In real systems, a feasible second-best beats a paper-optimal design. Million-token context ships when model structure, parallelism, kernels/compilers, and scheduling/cache line up. For engineering teams, a quantitative capacity model and a regressable performance baseline are the assets that survive the next architecture change.
