Engineering Implementation and Optimization Paths for Million-Token Contexts

    Ultra-long context is more than just a bigger window. In agent scenarios, it directly affects inference cost, response latency, and task reliability. Starting from real-world use cases, this article breaks down the sources of context bloat, reviews the main optimization directions—sparse attention, MoE architectures, KV cache management, and inference kernel optimization—and presents practical approaches to context governance at the application layer.

    Ultra-long context is about more than just enlarging the window. In agent scenarios, it directly impacts inference cost, response latency, and task reliability. Drawing on real-world scenarios, this article breaks down where context bloat comes from, reviews the major optimization directions, and provides actionable methods for context governance.

    1. Where Ultra-Long Contexts Come From

    Many developers still think of context in terms of Q&A scenarios, where a few thousand tokens per turn are usually sufficient. Agents work very differently. Take a coding agent that runs for 30 turns—each turn appends new content to the context:

    • User instructions: typically a few hundred tokens;
    • Source files read: three or four files can easily reach thousands to tens of thousands of tokens;
    • Executed shell commands and their standard output: compilation logs and test reports often run to several thousand tokens;
    • The model’s own reasoning process: this also counts toward the context, usually several thousand tokens.

    By this estimate, accumulating hundreds of thousands of tokens after 30 turns is the norm. If the agent also has persistent memory—that is, writing historical experience back into the context—window consumption accelerates further. In multi-turn complex tasks, a 128k window often cannot survive more than a few full iterations.

    In short, the demand for long context primarily stems from changes in task patterns.

    2. The Cost of Context Bloat

    As context grows longer, costs rise at different rates, mainly in three areas.

    1. Compute cost: the computation of standard self-attention scales quadratically with sequence length. Expanding from 128k to 1M increases sequence length by roughly 7.8×, while the number of elements in the attention matrix grows by about 61×, i.e., (1M/128k)² ≈ 61.

    2. Memory cost: during inference, the keys and values of every token must be cached (the KV cache). The estimation formula is:

      KV cache bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element

      For example, with 60 layers, 8 KV heads, a head dimension of 128, and 2 bytes per element (FP16 or BF16), each token occupies about 240KB, so 1M tokens require roughly 240GB of memory. This does not even include the model weights themselves.

    3. Latency cost: the prefill stage of a long context is noticeably time-consuming, which increases time to first token and degrades the interactive experience.

    Therefore, long-context capability must be designed together with cost control. Otherwise, it remains a spec-sheet metric that cannot support real business workloads.

    3. Core Technical Challenges of Long Context

    3.1 Extrapolation of Positional Encoding

    Models are trained on sequences of limited length. When directly inferring longer sequences, positional representations may fall outside the training distribution, degrading output quality. Common engineering approaches include position interpolation and staged length-continued training. The key is to complete post-training calibration with sufficient long-text data.

    3.2 Uneven Information Recall

    Even when the window is large enough, the model does not use information at all positions equally. A common phenomenon is that content near the beginning and end is more readily utilized, while key information in the middle tends to be overlooked. When evaluating long-context capability, targeted information-retrieval tests should be used, examining performance at different depths and different lengths—do not rely on the window size limit alone.

    3.3 Balancing Inference Throughput and Memory

    Long requests consume large amounts of memory, squeezing out resources for other requests in the same batch and dragging down overall throughput. On the serving side, trade-offs must be made among concurrency, maximum length, and batching strategy.

    4. Mainstream Engineering Optimization Directions

    4.1 Sparse Attention

    Sparse attention computes attention only between a subset of positions. Common approaches include:

    • Sliding window: each token attends only to a recent segment, suitable for text with strong local dependencies;
    • Chunking with global tokens: the sequence is split into blocks while a small number of global positions are retained, balancing local and global information;
    • Dynamic selection: based on the query, the most relevant positions are chosen to participate in computation.

    Sparsification can reduce computation from quadratic to near-linear. However, teams need to verify whether the model’s recall of critical information is affected.

    4.2 Mixture-of-Experts Architecture

    Mixture-of-Experts (MoE) models split the feed-forward network into multiple experts, activating only a small fraction of them per token. The total parameter count can be very large, while each forward pass uses only a portion of the parameters, striking a balance between model capacity and inference cost. When evaluating such models, two metrics must be distinguished: total parameters determine knowledge capacity, while activated parameters determine the compute cost of a single inference.

    4.3 KV Cache Compression and Management

    Common techniques include:

    • Paged management: the KV cache is divided into fixed-size pages and allocated on demand, reducing memory fragmentation;
    • Quantization: compressing the KV cache from 16-bit to 8-bit or lower reduces memory footprint, while accuracy loss must be evaluated;
    • Prefix reuse: identical system prompts or document prefixes can be cached and shared, eliminating redundant prefill computation.

    4.4 Inference Kernel Optimization

    The bottleneck in attention computation often lies in memory read/write rather than the arithmetic itself. Fused kernels load data in tiles and complete intermediate computations on-chip, reducing round trips to memory—a common method for improving throughput. These optimizations depend on coordination between hardware and compilers. Engineering teams should prioritize well-validated inference frameworks, then tune parameters based on their own workloads.

    5. Context Governance on the Agent Side

    No matter how capable the model is, you should not stuff all historical content into the window. A more reliable approach is to actively control context at the application layer.