Engineering Million-Token Context in Large Language Models: Attention, KV Cache, and Training Stability

    As context windows expand toward one million tokens, the bottleneck shifts from window size to the compute and memory cost per token. This article breaks down two reference architectures for long-context LLMs—hybrid attention that splits global and local work across layers, and KV cache compression, quantization, and tiered storage—along with the training practices that keep long-context output stable, a four-layer approach to running long context as a system, and common misconceptions to avoid when choosing a configuration.

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

    The capability boundary of large language models is moving from the training stage to the inference stage. As test-time scaling becomes a shared assumption, models are expected not only to generate longer chains of thought but also to retrieve, compare, summarize, and make decisions within longer contexts. That pressure lands directly on the attention mechanism: once the context reaches the million-token range, the question is no longer “is the window big enough” but “is the compute and storage cost per token acceptable.”

    Standard Transformer self-attention has two built-in weaknesses.

    The first is that compute grows too fast. Every new token has to interact with all historical tokens, so theoretical complexity rises quadratically with sequence length. In engineering terms, per-token inference FLOPs climb linearly as the context grows, and time to first token (TTFT) and throughput degrade at the same time.

    The second is that cache overhead spirals out of control. Autoregressive generation requires keeping the key/value representations of every historical token at every layer, and memory usage is proportional to sequence length, number of layers, number of attention heads, and head dimension. At million-token context lengths, the KV cache often consumes more memory than the model weights and becomes the main bottleneck for scheduling and paging.

    A usable million-token context design therefore has to answer three questions at once: can we afford the compute, can we fit it in memory, and can we keep it stable.

    2. Reference Architecture 1: Hybrid Attention, Splitting Global and Local Work

    One widely accepted approach is hybrid attention: instead of making every layer carry the same global interaction duty, work is divided by layer.

    • Local/sliding-window layers: dense attention within a fixed window, with complexity that is roughly linear in sequence length, handling short-range syntax, coreference, and format constraints.
    • Global/sparse layers: fewer in number, keeping only a small set of key interactions through compression, blocking, or routing, and handling cross-section topic consistency, long-range dependencies, and global retrieval.

    The benefit of this split is explainable: local layers keep short-range modeling from regressing, while sparse global layers add long-range capability at a lower cost. Implementations typically also rely on the following points:

    1. Hierarchical attention structure. Compressed representations from upper layers can be reused by lower layers, avoiding repeated construction of a global view at every layer.
    2. Position encoding extrapolation. Long contexts depend on stable extrapolation of position information; common approaches include position interpolation, frequency scaling, and band-wise handling, tuned jointly with the sparse pattern.
    3. Consistency between training and inference. If the sparse pattern exists during pre-training, no extra adaptation is needed at inference time; if it is introduced later, continued pre-training is required for alignment.

    Illustrative layer split (pseudocode):

    1. for layer_idx, layer in enumerate(model.layers):
    2. if layer_idx % 4 == 0:
    3. x = layer.global_sparse_attn(x, block_size=2048, top_k_blocks=16)
    4. else:
    5. x = layer.local_window_attn(x, window=4096)
    6. x = layer.ffn(x)

    3. Reference Architecture 2: KV Cache Compression, Quantization, and Tiering

    If attention decides “how much to compute,” the KV cache decides “how much to store.” Practical measures usually come in three layers.

    • Representation compression: low-rank projection, cross-token merging, and cross-layer sharing reduce the number of entries that must be stored.
    • Numerical compression: KV quantization (for example, 8-bit/4-bit group quantization) trades controllable precision loss for several times the capacity.
    • Storage tiering: hot data stays in GPU memory, warm data moves down to host memory, and cold data lands on local NVMe or remote object storage, combined with paging management and prefix reuse.

    A simplified formula is enough to build intuition about capacity:

    1. KV_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × bytes_per_elem × batch

    The 2 accounts for the two copies, key and value. Raising seq_len from 4K to 1M while holding everything else constant inflates usage by 256x, which is exactly why compression and tiering are unavoidable. In practice, plan capacity in four segments—“weights + KV + activations + fragmentation headroom”—and reserve 15%~25% of GPU memory for burst concurrency.

    In multi-turn conversations and document question answering, prefix reuse pays off heavily: system prompts, knowledge base snippets, and long document bodies often stay unchanged across requests, and a cache hit removes the repeated prefill.

    4. Training Stability: Long Context Is Not an Inference Trick

    Whether million-token context produces stable output depends largely on the training stage. Common practices include:

    • Progressive window expansion: extend from short sequences to long ones step by step, adjusting position encoding and learning rate at each stage to avoid the attention entropy collapse that one-shot extrapolation can cause.
    • Long-text data mix: raise the proportion of long documents, code repositories, and structured tables, and bucket samples by length so short samples do not dominate gradients.
    • Numerical stability: scale and clip attention logits, subtract the maximum before softmax, and accumulate at higher precision under mixed precision.
    • Load balancing for sparse routing: blocked or expert routing needs an auxiliary loss to avoid hotspots that leave some compute units idle.

    Evaluation should separate “retrieval ability” from “reasoning ability”: the former can be verified with needle-in-a-haystack, multi-needle, and cross-section aggregation tests; the latter needs multi-hop question answering, long-document summary consistency, and repository-level code understanding. Looking at a single long-text metric alone tends to overestimate real usability.

    5. Enterprise Deployment: Treating Long Context as a Systems Engineering Problem

    When deploying on your own platform or on Baidu AI Cloud, break long-context capability into four layers to govern:

    1. Access layer: a unified gateway routes by length tier, sending short requests to low-cost small-window instances and long requests to large-window instances to avoid resource mismatch.
    2. Service layer: a container platform hosts inference instances and scales elastically by memory and concurrency; object storage holds long documents and cache snapshots; a message queue smooths request peaks.
    3. Data layer: document parsing, chunking, vectorization, and original-text indexing are built in parallel, with long context and retrieval augmentation complementing rather than excluding each other.
    4. Observability layer: a logging service records TTFT, throughput, cache hit rate, and memory watermarks; monitoring and alerting link thresholds to KV overflow and timeouts.

    A practical routing example:

    1. def route(req):
    2. tokens = estimate_tokens(req)
    3. if tokens <= 32_000:
    4. return "small_window_pool" # low cost, low latency
    5. if tokens <= 256_000:
    6. return "mid_window_pool"
    7. return "long_context_pool" # large window + tiered cache

    6. Common Misconceptions and Selection Advice

    • Misconception 1: bigger is always better. The actual gain depends on whether the task needs global interaction; most business workloads are satisfied at 32K~128K, and jumping to a million only drives up cost.
    • Misconception 2: looking only at TTFT. For long context, stable throughput and tail latency (P99) matter more.
    • Misconception 3: treating the cache as free. Tiered caching needs capacity planning and an eviction policy, or it will squeeze inference memory.

    For selection, score on three dimensions—capability, cost, and stability: capability looks at long-text multi-hop and retrieval accuracy; cost looks at per-request FLOPs and memory usage; stability looks at output consistency and timeout rate in long sessions. For model portfolios that offer both a high-capability version and an efficient version, route by scenario: complex reasoning goes to large-parameter, high-activation configurations, while massive volumes of simple requests go to small-parameter, low-activation configurations.

    Overall, the focus of competition in million-token context has shifted from parameter scale to the coordinated design of attention structure, cache representation, and training stability. Understanding how these three couple together is what makes truly usable ultra-long context possible at a controllable cost.