Efficient Computation and KV Cache Optimization for Million-Token Context LLMs

    This article breaks down the practical engineering challenges of serving million-token context in large language models, where the real bottleneck shifts from accepting long input to controlling compute and cache costs. It covers a hybrid attention architecture that combines local window attention with compressed or sparse global attention, KV cache reduction techniques such as low-rank latent caching, grouped query sharing, quantization, paged eviction, and prefix reuse, plus training-side length extrapolation and stability practices. It also outlines how to build a minimal long-context service on cloud primitives, which metrics to monitor, and a selection and tuning checklist for balancing cost and quality.

    1. The Real Problem: Long Context Is Not About Fitting More Tokens In

    As test-time scaling takes a larger share of inference compute, models are expected to generate longer reasoning traces and to retrieve, summarize, and make decisions over much larger contexts. Once the context grows from tens of thousands of tokens to the million-token range, the quadratic attention cost of a standard Transformer quickly becomes the system bottleneck. This shows up as two distinct problems.

    The first is exploding floating-point compute. During autoregressive decoding, every new token must interact with the key and value representations of all previous tokens. The longer the context, the more compute each token requires, so both time-to-first-token and overall throughput degrade.

    The second is uncontrolled cache overhead. Decoding requires caching the key/value tensors of every historical token at every layer, and the memory footprint scales roughly with “layers × attention heads × head dimension × sequence length × batch size.” At million-token sequence lengths, the KV cache becomes the primary source of memory and scheduling pressure, directly capping the number of concurrent requests.

    As a result, the industry goal for very long context is shifting from “supporting long input” to “remaining reliably usable under acceptable compute and cache costs.” This is the first-principles standard to apply when evaluating any long-context approach.

    2. Capability Tiers and Native Long Context

    A model family offers two MoE large language models as preview releases: a high-capability tier with roughly 1.6T total parameters and about 49B activated parameters, and an efficiency tier with roughly 284B total parameters and about 13B activated parameters. Both natively support a 1 million token context.

    The phrase “native support” matters here: long context is not achieved through external stitching, segmented summarization, or inference-time patches, but is an optimization target built in during pre-training and post-training. The practical engineering benefit is better stability under long-range dependencies, avoiding the “lost in the middle” behavior caused by a mismatch between training and inference distributions.

    MoE becomes even more valuable in long-context scenarios: because activated parameters are far smaller than total parameters, per-token compute stays controllable, providing the structural basis for extending context without proportionally scaling compute.

    3. Optimization Track One: Hybrid Attention Architecture

    The core idea is a hybrid structure that combines sparse or compressed attention with dense local attention, assigning different responsibilities to different branches:

    • The local branch preserves fine-grained modeling of nearby tokens, keeping syntax, coreference, and local logic intact.
    • The global or compressed branch performs summary-style interaction over distant history at lower resolution, handling long-range topics and information aggregation.
    • Through branch ratios and layer alternation, overall complexity is pushed from quadratic growth in sequence length toward near-linear growth.

    A schematic representation of the structure (pseudocode, for illustration only):

    1. for layer in range(num_layers):
    2. if layer % 2 == 0:
    3. # Local window attention: complexity roughly O(n * w), where w is the window length
    4. h = local_window_attention(h, window=w)
    5. else:
    6. # Compressed/sparse attention: aggregate history into blocks, then interact with the current query
    7. h = compressed_attention(h, block=b, topk=k)
    8. h = moe_mlp(h) # Sparse activation to control per-token compute

    Engineering note: window length, compression block size, and the number of sparse selections need to be tuned jointly with the task type. Long-document question answering can favor broader global coverage, while repository-level code analysis needs finer local windows to preserve symbol-level dependencies.

    4. Optimization Track Two: KV Cache Compression and Reuse

    At million-token scale, cache governance matters as much as the attention algorithm itself. The techniques below can be combined:

    1. Low-rank or latent representation caching: compress keys and values into a lower-dimensional latent space before caching, significantly reducing cache bytes per token.
    2. Multi-query or grouped-query sharing: multiple query heads share the same key/value, removing redundancy along the head dimension.
    3. Quantized storage: apply low-bit quantization to the cache, trading controlled accuracy loss for lower memory usage.
    4. Block-level paging and eviction: manage cache blocks using an OS paging analogy, enabling prefix reuse and on-demand swapping out.
    5. Prefix cache reuse: stable prefixes such as system prompts and long document bodies are shared across requests, avoiding repeated prefill.

    A practical formula for capacity estimation:

    1. cache_bytes ≈ 2 * layers * kv_heads * head_dim * seq_len * batch * bytes_per_elem

    For example, if cache compression and sharing reduce both effective kv_heads and bytes_per_elem by an order of magnitude each, cache usage at million-token context drops by roughly one order of magnitude. This is the logic behind claims of reducing the cache to about 10%.

    5. Optimization Track Three: Training Stability and Long-Context Extrapolation

    Long-context capability cannot come from inference-side tricks alone; the training side needs matching design:

    • Position encoding extrapolation: use a scalable position scheme and continue training on long sequences so inference lengths do not exceed the training distribution.
    • Curriculum-style length extension: transition gradually from short to long sequences while adjusting learning rate and batch size to suppress loss spikes.
    • Joint warm-up of attention and sparse structures: train the dense branch first, then introduce the compressed branch to reduce early optimization difficulty.
    • Data construction: embed supervision signals in long documents that require crossing large distances to answer, reinforcing the behavior of genuinely using distant information.

    For evaluation, report three categories of metrics together: whether general short-context capability regresses, long-context retrieval and multi-hop reasoning accuracy, and per-token latency and memory cost. Reporting accuracy without cost, or cost without effectiveness, leads to misleading conclusions.

    6. Implementation: Supporting Long Context with General Cloud Capabilities

    On cloud platforms such as Baidu AI Cloud, long-context applications are typically carried by a combination of general capabilities: a container platform handles elastic scaling and canary releases for inference services; object storage holds long documents and datasets; a message queue smooths request spikes and decouples asynchronous tasks; and logging plus monitoring and alerting provide visibility into time-to-first-token, cache hit rate, and memory watermarks.

    A minimal runnable service skeleton:

    1. from service_gateway import ChatRequest, invoke_model
    2. def handle(req: ChatRequest):
    3. # 1) Prefix cache reuse: a stable prefix hit can skip repeated prefill
    4. prefix = req.system_prompt + req.document
    5. # 2) Chunk and prefetch very long input to cap peak memory usage
    6. chunks = [prefix[i:i + 200_000] for i in range(0, len(prefix), 200_000)]
    7. ctx = "".join(chunks)
    8. # 3) Explicitly limit output length and concurrency to avoid cache contention
    9. return invoke_model(ctx, max_new_tokens=req.max_output, concurrency=8)

    The observability metrics should include at least: cache hit rate, share of time spent in prefill, per-token decode latency, peak memory usage, and the proportion of evicted cache blocks. When hit rate drops or the eviction ratio rises, adjust the prefix reuse strategy and concurrency limit first rather than blindly scaling capacity.

    7. Selection and Tuning Checklist

    • Capability tier: use the high-capability version for complex multi-hop reasoning and long-form writing; use the efficiency version for large-scale batch processing and cost-sensitive workloads.
    • Length strategy: not every request needs a million-token context, and routing by task tier can cut costs significantly.
    • Cache strategy: keep stable prefixes at the front and unchanged, and place variable content later to improve reuse rates.
    • Precision strategy: run A/B evaluations on cache quantization and sparsity to lock in an acceptable accuracy-loss range.
    • Capacity planning: estimate memory with the formula above first, then work backward to the maximum concurrency and batch size.
    • Regression protection: build an automated regression suite across short, medium, and long context lengths to prevent optimizations from introducing capability regressions.

    8. Conclusion

    For million-token context, the central question has moved from “can it accept the input” to “can we afford to compute it, fit it in memory, and run it reliably.” Hybrid attention pushes complexity back toward linear, cache compression and reuse cut memory usage by an order of magnitude, and training-side length extrapolation and stability design keep quality from regressing. All three are required. For developers, the real engineering payoff comes from treating long context as a system problem: designing the algorithm, cache, scheduling, and observability together is what delivers a sustainable balance of cost and quality in scenarios like long-document understanding and repository-level code analysis.