Technical Architecture and Engineering Practices for Million-Token Context Large Language Models

    This article breaks down the technical architecture and engineering practices behind million-token context in large language models. It explains why long context has become a baseline requirement, how sparse mixture-of-experts designs decouple total parameters from activated parameters, and which attention and position-encoding strategies make extreme sequence lengths feasible. It also covers inference caching and scheduling, kernel-level optimization, context budgeting on the application side, and dedicated long-context evaluation, ending with practical guidance for deploying these capabilities in your own systems.

    1. Why Long Context Is Shifting from a Nice-to-Have to a Must-Have

    In multi-turn conversations, code comprehension and refactoring, and long-document analysis, an insufficient context window breaks usability outright. After a few dozen exchanges, historical messages, tool return values, and retrieved snippets accumulate quickly into the hundreds of thousands of tokens. If the context window is too small, the system can only truncate or summarize, which means earlier constraints are lost, coreference links break, and the task “forgets” itself midway.

    Repository-level code comprehension is another typical source of pressure. A mid-sized project often contains hundreds of files, and the type definitions, call chains, configuration, and tests that span those files together form the evidence set required to understand a single function. Without long-context capability, the engineering side can only apply coarse-grained chunking, so the model sees a “patchwork of fragments” and struggles to perform consistent refactoring.

    It is worth stressing that long context is not simply a matter of enlarging the window. It is a system-level redesign: attention computation, position encoding, caching strategy, batch scheduling, and kernel implementations all have to evolve together. Otherwise, the compute and memory overhead introduced by a larger window grows non-linearly.

    2. Parameter Scale and Sparse Activation: Decoupling Two Curves

    Today’s mainstream ultra-large models generally adopt a sparse mixture-of-experts structure that decouples “total parameter count” from “activated parameters per token.” Total parameters determine knowledge capacity, while activated parameters determine the compute cost of a single forward pass. A common industry approach is to offer two tiers: one with trillion-scale total parameters and tens-of-billions-scale activation, and another with hundred-billion-scale total parameters and activation under ten billion. Both share the same technical approach but target different cost ranges.

    Two common misconceptions need clarification:

    • The smaller tier is not a distilled product of the larger one. Both tiers are typically sparse expert networks obtained from independent pre-training, differing only in scale and sparsity. As a result, the smaller tier is often more cost-effective under the same budget rather than proportionally weaker in quality.
    • Long context is not an optional switch. When both tiers natively support million-token context, the serving side no longer needs to maintain two separate pipelines for “long-text models” and “short-text models,” which significantly simplifies routing logic and capacity planning.

    The engineering implication is direct: capacity planning should estimate compute based on “activated parameters + context length,” and estimate memory and loading cost based on “total parameters.” The two cannot share the same formula.

    3. Attention and Position Encoding: The Core Bottleneck of Long Context

    Standard attention has quadratic complexity with respect to sequence length, so scaling it directly to one million tokens is not viable. The industry generally relies on several complementary paths:

    1. Hybrid sparse and local windows: most tokens interact only with their neighbors, while a small number of global tokens handle cross-segment information aggregation.
    2. Chunking and hierarchical aggregation: fine-grained modeling is completed within small blocks first, then a second attention pass is applied over block-level representations to form a hierarchy.
    3. Position information extrapolation: general techniques such as frequency scaling in rotary position embeddings and position interpolation improve length extrapolation stability.
    4. Linear or near-linear attention variants: replacing quadratic-complexity operators in specific layers in exchange for length scalability.

    Illustrative pseudocode for hierarchical attention:

    1. def hierarchical_attention(x, block=2048):
    2. # Layer 1: fine-grained attention within each block
    3. local = block_attention(x, window=block)
    4. # Layer 2: global attention across block-level summaries
    5. summary = pool(local, mode="mean", axis=block)
    6. glob = attention(summary, summary)
    7. # Fusion: broadcast global information back to local representations
    8. return local + broadcast(glob, like=local)

    The practical point is “mix rather than replace”: full linearization loses precision, while full globalization loses control over cost. Assigning different strategies to different layers is usually the more stable choice.

    4. Inference Caching and Scheduling: Driving Down the Cost of Long Context

    The real bottleneck in long-context serving is often memory and scheduling rather than raw compute. The cached key-value tensors grow linearly with length, and once multiple concurrent requests stack up, memory pressure is easily triggered. Common engineering measures include:

    • Prefix cache reuse: stable prefixes such as system prompts, tool definitions, and long documents are computed only once and shared across requests.
    • Paged cache management: the cache is split into fixed-size blocks and swapped in and out on demand, reducing fragmentation.
    • Chunked prefill: an extra-long prompt is split into multiple batches to complete prefill, avoiding a single request occupying the device for a long time.
    • Continuous batching: dynamic batch assembly at iteration-level granularity lets long and short requests run together, improving overall throughput.

    Illustrative scheduling pseudocode:

    1. def schedule(requests, max_batch_tokens):
    2. batch, used = [], 0
    3. for r in sorted(requests, key=lambda r: r.prefill_tokens):
    4. if used + r.prefill_tokens > max_batch_tokens and batch:
    5. yield batch
    6. batch, used = [], 0
    7. batch.append(r)
    8. used += r.prefill_tokens
    9. if batch:
    10. yield batch

    5. Kernel and Operator Optimization: Turning Theoretical Compute into Effective Compute

    Even the best architecture needs operators to land on. Kernel optimization for long-context scenarios usually focuses on three things: first, fusing attention with neighboring operators such as normalization and residual connections to reduce memory round trips; second, load balancing for sparse expert routing so that individual experts do not become hotspots; third, compact layout for variable-length sequences to reduce padding waste. In addition, general quantization ideas such as low-precision computation and online scaling can substantially improve effective throughput while keeping precision within a controllable range.

    6. Context Budget Management: What the Application Side Must Do

    A model that supports million-token context does not mean you can blindly stuff in all content. It is recommended to establish an explicit context budget table:

    Purpose Recommended Share Notes
    Instructions and constraints 5%~10% Keep concise and structured
    Tool and structured definitions 10% Retain only what is available this turn
    Retrieved evidence 40%~50% Include source markers for traceability
    Conversation history 20%~30% Apply layered summarization when exceeded
    Reserved output space 10% Prevent input from squeezing it out

    Supporting strategies include deduplicating and reranking retrieved snippets, layered summarization of history, structured compression of tool results, and avoiding re-injection of large context blocks when retrying after a failure.

    7. Evaluating Effectiveness: Long Context Must Be Tested Separately

    Long-context capability must be validated with a dedicated evaluation set. Common dimensions include “needle in a haystack” localization, multi-hop reasoning across segments, structured extraction from long documents, and cross-file code consistency modifications. During evaluation, also record time to first token, output latency per thousand tokens, cache hit rate, and cost per request, so that service feasibility is not overlooked while focusing only on accuracy.

    8. Deployment Recommendations

    To use million-token context capability in your own system, you can integrate it through Baidu AI Cloud model services, paired with object storage for hosting long documents, a message queue for decoupling asynchronous tasks, a container platform for hosting inference and business services, and logging plus monitoring and alerting services for observing latency and cost. The overall principle is: accept “sparsification + hierarchical attention” at the architecture level, rely on “cache reuse + chunked scheduling + operator fusion” at the engineering level, and enforce strict context budgeting and dedicated evaluation at the application level. Only when all three are in place can you deliver reliably in ultra-long context scenarios.