Long-Context LLM Architecture and Engineering Practices for Million-Token Contexts

    This article breaks down the bottlenecks of million-token contexts, mainstream architecture solutions such as hybrid and sparse attention, KV cache engineering, MoE cost models, training stability, evaluation, and a practical guide for developers. It explains how to make ultra-long context efficient to compute, affordable to cache, and stable to serve.

    1. Introduction: From “Fitting It In” to “Affordable to Compute, Feasible to Store, Stable to Serve”

    As competition among large models shifts from parameter count to test-time scaling, the compute invested during inference has become a key variable that determines both user experience and cost. A notable class of recent advances pushes the native context length to the million-token scale while compressing per-token inference compute and cache usage to very low levels. The value of this work lies not in the window size itself, but in answering a fundamental engineering question: when the context reaches millions of tokens, can the model compute efficiently, cache at low cost, and serve reliably?

    This article takes a general technical perspective to systematically break down the bottlenecks of ultra-long context, mainstream architectural solutions, key training and inference engineering points, and a reusable practical guide.

    2. Why Long Context Is a “Nonlinear” Problem

    In a standard Transformer, the self-attention mechanism incurs compute and memory costs that grow quadratically with sequence length. When the context expands to a million tokens, two bottlenecks erupt at the same time.

    • Compute bottleneck (FLOPs): Generating each new token theoretically requires interaction with all historical Key/Value entries. The longer the sequence, the higher the per-token decoding cost, and both time to first token (TTFT) and time per output token (TPOT) deteriorate together.
    • Memory bottleneck (KV Cache): Autoregressive decoding needs to cache the K/V tensors of historical tokens at every layer. Its memory usage can be approximated as:
    1. KV_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes

    Here, 2 corresponds to K and V. As the formula shows, memory scales linearly with seq_len, and million-token sequences turn the cache into the primary cost source while severely compressing the concurrency batch size.

    • Stability bottleneck: Under ultra-long sequences, the attention distribution tends to become overly concentrated or overly dispersed, the numerical range widens, and both training and inference become more prone to precision and convergence issues.

    The real technical problem, therefore, is to optimize compute, storage, and stability at the same time under a million-token context.

    3. Architecture-Level Solutions: Hybrid Attention and Sparsification

    The mainstream industry approach can be summarized as a combination of “hybrid attention + sparse/compressed attention + locality preservation.”

    1. Hybrid Attention
      Stack different types of attention alternately by layer or by block: some layers handle global information aggregation, while others focus on local window modeling. Global layers ensure long-range dependencies can be retrieved, and local layers cover high-frequency neighboring dependencies with low complexity. The two complement each other, making the overall complexity significantly lower than pure global attention.

    2. Sparse and Compressed Attention

    • Sparsification: Compute attention only for the historical blocks most relevant to the current query, reducing complexity from O(n²) to nearly O(n·k).
    • Compression: Apply low-rank or pooling compression to historical K/V, using a small number of “summary vectors” to represent large spans of history, balancing recall and cost.
    • Block-wise strategy: Perform retrieval and cache eviction at the block level, which naturally fits paged memory management.
    1. Position Encoding Extrapolation
      Long context relies on reliable position modeling. Common approaches include position interpolation, frequency scaling, and block-wise relative positions, with the goal of maintaining stable extrapolation beyond the training length and avoiding the “break as soon as the length exceeds the limit” failure mode.

    Illustrative pseudocode (expressing the idea of hybrid scheduling, not a specific implementation):

    1. for layer_idx in range(num_layers):
    2. if layer_idx % 2 == 0:
    3. x = global_sparse_attention(x, kv_cache) # Global sparse aggregation
    4. else:
    5. x = local_window_attention(x, window=w) # Local window
    6. x = moe_mlp(x) # Sparse-activated FFN

    4. KV Cache Engineering: Paging, Quantization, and Eviction

    Architecture sets the ceiling; engineering determines what actually ships. Cache governance usually advances along four paths at once.

    • Paged management (Paged KV): Split the cache into fixed-size blocks, allocate on demand, and store non-contiguously, which significantly reduces fragmentation and improves concurrency.
    • Quantization compression: Store K/V at lower bit widths (such as 8-bit/4-bit), with per-block scaling factors to control error; memory drops roughly linearly.
    • Cross-layer/cross-head sharing: Share cache representations across similar layers or heads to reduce redundancy.
    • Eviction and recomputation: Block-level eviction based on attention importance; compressed history can be partially recomputed when needed, trading compute for memory.

    Engineering also requires attention to hit rate and scheduling: prefix caching (prefix reuse) lets the same system prompt and long document be reused across multi-turn requests, and in practice the cost improvement for long-document question answering is very significant.

    5. MoE and the Cost Model: Activated Parameters Are What Matter

    Long-context products often adopt a sparse expert (MoE) design with “large total parameters, small activated parameters.” The point is that total capacity determines the knowledge ceiling, while activated parameters determine the per-token compute. Combined with hybrid attention, this can push per-token FLOPs and cache usage to a very low level under a million-token context.

    A simplified cost estimation framework:

    1. Cost per request ≈ Prefill cost(seq_len) + Decode cost(out_len × per-token FLOPs)
    2. Peak memory ≈ Weights + KV(seq_len) + Activations and temporary buffers

    Conclusion: optimization for long-context scenarios focuses on “prefill + cache,” not simply piling on compute.

    6. Training Stability and Long-Context Evaluation

    • Training stability: Ultra-long sequences easily trigger loss spikes. Common measures include a more conservative learning rate and warmup, numerical stabilization of attention and normalization, and progressive length extension (short to long, annealed in stages).
    • Evaluation dimensions: Do not only check “can it read 1 million tokens.” Build a multi-dimensional benchmark:
      1. Retrieval: needle-in-a-haystack, multi-hop retrieval;
      2. Reasoning: cross-section reasoning over long documents, global summarization;
      3. Code: understanding cross-file dependencies;
      4. Efficiency: TTFT, TPOT, cache hit rate, cost per token.

    7. A Practical Guide for Developers

    1. Scenario fit: Long-document review, contract comparison, code base question answering, and full meeting transcript analysis are where million-token context delivers the most value.
    2. Input governance: Clean and denoise first, then chunk and structure (headings, paragraphs, tables), and add a “table of contents/index” prompt when necessary to improve retrieval hits.
    3. Prompt design: Explicitly state the task and output format; under long context, constrain the model to “answer only based on the material” to reduce hallucination.
    4. Cache reuse: Put stable, unchanging long material in the prefix and use prefix caching to amortize cost.
    5. Observability: Integrate logging services and monitoring alerts, track TTFT, TPOT, cache hits, and failure rates, and close the loop on capacity and cost.
    6. Deployment shape: Combine container platforms with elastic scaling and schedule by peak and trough; use object storage for long documents and message queues for asynchronous batch processing.

    Reference call skeleton (general illustration):

    1. resp = client.chat(
    2. model="<your-long-context-model>",
    3. messages=[
    4. {"role": "system", "content": "Answer only based on the given material and cite the source paragraph."},
    5. {"role": "user", "content": doc + "\n\nQuestion: " + question}
    6. ],
    7. temperature=0.2
    8. )

    8. Conclusion

    The real threshold for million-token context is being “affordable to compute, feasible to store, and stable to serve.” With hybrid attention as the backbone, cache governance as the circulatory system, and sparse activation as the lever, plus rigorous evaluation and an observability system, ultra-long context can be turned from a demo feature into a reliable engineering capability. With the general capabilities of cloud platforms such as Baidu AI Cloud (for example, object storage, container platforms, logging services, and monitoring alerts), teams can focus more on business logic and turn long context into real productivity.