System-Level Engineering Behind Million-Token Context: Attention, KV Cache, and Serving Optimization
This article breaks down the system-level engineering required to make million-token context practical in production. It explains why the industry's assumed convergence on compressed attention was overturned, offers four criteria for choosing an attention design under real constraints, and identifies the dual walls of KV cache memory capacity and memory bandwidth. It also covers practical techniques such as paged caching, prefix reuse, quantization, parallelism, and scheduling, followed by a closed-loop optimization workflow, training-side software-hardware co-design, inference framework and cloud deployment patterns, and scenario-based evaluation guidance.
1. Introduction: From Parameter Race to System-Level Co-Optimization
Over the past year, the main line of ultra-large-scale models has shifted from simply stacking parameters to coordinating the full chain of architecture, training, inference, and serving. A defining change is that million-token context has moved from a demo feature to a usable capability. This is not the result of any single trick, but of the joint evolution of attention structures, memory management, operator implementations, parallel strategies, and caching systems.
Using the technical divergence of “abandoning the previous mainstream attention in favor of a more bandwidth-efficient approach” as a starting point, this article abstracts a reusable engineering methodology to help developers make architecture choices and performance optimizations in their own systems.
2. Attention Mechanisms: Why the “Convergence” Narrative Broke Down
1. Common Ground and Differences Across Three Generations of Attention
- Original Multi-Head Attention (MHA): each head independently holds Key/Value, offering strong expressiveness but high memory and bandwidth overhead.
- Multi-Query Attention (MQA): all query heads share one set of Key/Value, significantly reducing KV cache and memory access pressure, at the cost of limited expressiveness.
- Latent vector compression approaches (carrying KV via low-rank latent vectors): a compromise between MHA and MQA, trading memory for compressed representations, but requiring additional projection and decoding logic.
The industry once widely assumed that architectures had converged on compression approaches, with only minor refinements to follow. The fact that a new generation of models returned to the low-bandwidth route of shared KV shows that “convergence” is only a stage conclusion: when context length, concurrency scale, and hardware bandwidth structure change, the optimal point shifts.
2. Selection Criteria: Not “Which Is Stronger,” but “Which Is Better Under Your Constraints”
A quantitative evaluation across four dimensions is recommended:
- KV memory usage per request (determines the maximum context and concurrency ceiling);
- Memory access per token (determines decode-phase throughput);
- Operator implementation maturity (determines whether hardware can be fully utilized);
- Training stability and convergence cost (determines iteration speed).
Illustrative pseudocode for comparing the KV budget of different attention structures:
kv_bytes = layers * 2 * kv_heads * head_dim * seq_len * bytes_per_elem * batch# smaller kv_heads and more controllable head_dim save memory for long context# the essence of shared-KV approaches: shrink kv_heads to a minimum, trading bandwidth for capacity
3. The Real Bottleneck: The “Double Wall” of Memory Capacity and Memory Bandwidth
The serving cost of long context is mainly not compute, but the KV cache. Context length linearly amplifies the cache, and concurrency multiplies it by another layer, quickly hitting the memory wall; during decoding, every generated token requires re-reading all historical KV, leading to the bandwidth wall.
Engineering practice usually combines the following techniques:
- Paged cache management: split KV into fixed blocks allocated on demand, reducing fragmentation and reserved waste;
- Prefix reuse and cache hits: stable prefixes such as system prompts, long documents, and tool descriptions can be shared across requests;
- Quantization and compression: reduce bytes per element, trading controllable precision loss for capacity;
- Parallel partitioning: tensor parallelism, pipeline parallelism, and context parallelism share memory and bandwidth pressure;
- Scheduling and batching: pool long and short requests separately to avoid long requests blocking the queue.
Among these, “cache-hit pricing” is a common serving-side practice: inputs that hit the cache are billed at a lower price to encourage callers to reuse stable prefixes, thereby lowering overall unit cost. This is a general billing approach and does not involve any specific vendor’s rules.
4. System-Level Co-Optimization: Harder and More Valuable Than Single-Point Innovation
Single-point innovation can be validated in a paper, but system-level optimization must hold under real workloads. The difficulty lies in constraints that constrain each other: compressing KV saves memory but adds decoding logic; increasing concurrency amplifies bandwidth contention; parallel partitioning introduces communication overhead.
A practical closed-loop sequence is recommended:
- Profile: measure input length distribution, prefix overlap, output length, and concurrency peaks;
- Locate: determine whether the bottleneck is memory capacity, bandwidth, or communication;
- Modify: prioritize structural changes with minimal operator intrusion and easy rollback;
- Stress test: validate throughput and tail latency with realistic mixed workloads;
- Solidify: write parameters and strategies into configuration and monitoring alerts to form a long-term baseline.
5. Training-Side Coordination: Software-Hardware Co-Design of Optimizers and Operators
Architecture changes alter gradient statistics, requiring corresponding adjustments on the training side. Common industry directions include matrix-style adaptive optimizers to reduce optimizer state overhead, sharding and offloading to relieve memory pressure, and high-performance operator writing and compilation frameworks to map new structures efficiently to hardware. The core principle is that a new structure must have efficient forward, backward, and inference implementations at the same time; otherwise, the gains are only on paper.
6. Inference Frameworks and Cloud Deployment: Turning Capability into Service
The framework layer translates model structures into high-throughput services. Key capabilities include continuous batching, paged caching, prefix caching, structured output constraints, and multi-GPU parallelism. For cloud deployment, general-purpose category combinations are typically used: container platforms host inference instances, object storage hosts models and data, message queues smooth request peaks, logging services and monitoring alerts provide observability, and elastic scaling handles peaks.
A simplified server-side pseudocode illustrating cache reuse and pooled scheduling:
if prefix in cache:reuse(prefix) # skip repeated prefill on hitelse:prefill(prefix); cache.put(prefix)route(request) = long_pool if request.input_len > L else short_pool# separate long and short pools to avoid long-context requests slowing overall tail latency
7. Capability Evaluation: Look Beyond Leaderboards to Scenario Closure
The new generation of models is usually stronger in mathematical reasoning, code generation, and instruction following, with fewer hallucinations; but on complex code tasks it may still be weaker than top closed-source solutions, while approaching same-generation open-source solutions. Evaluation should return to the business: build an evaluation set covering long-document QA, multi-turn tool calls, and structured extraction, while recording accuracy, unit cost, and tail latency, avoiding decisions based on a single metric.
8. Conclusion
Million-token context entering reality is essentially a victory of systems engineering: attention structures are re-balanced, caching and scheduling are finely governed, and training and inference are co-designed across software and hardware. The takeaway for developers is direct: quantify constraints first, then make structural choices, and finally validate with real workloads in a closed loop. In such long-context and large-scale inference scenarios, Baidu AI Cloud typically supports engineering implementation through combinations of general cloud product categories, helping teams turn architectural gains into stable services.
