Large Language Model Architectures and Inference Optimization for Million-Token Contexts

    This article explains why million-token context windows are primarily a memory problem and how to address them across model architecture, training data, and inference infrastructure. It covers KV cache scaling, compressed and sparse attention, position encoding adjustments, long-context training strategies, serving optimizations such as paged KV management and prefix reuse, and a four-dimension evaluation framework for measuring whether optimizations deliver real gains.

    1. Why Million-Token Context Is First a Memory Problem

    The ceiling on long-context capability is usually set not by whether a model can read the tokens, but by whether it can fit them in memory during inference. Standard attention keeps a set of Key/Value vectors for every token, and the memory footprint can be approximated as:

    1. KVCache ≈ L_ctx × N_layers × N_kv_heads × (d_k + d_v) × bytes_per_value

    Here L_ctx is the context length, N_layers the number of layers, N_kv_heads the number of KV heads, d_k/d_v the dimensions, and each value takes 2 bytes under half precision. Push L_ctx to 1,000,000 and, even at batch size 1, the KV cache jumps from hundreds of megabytes to tens of gigabytes, competing with weights, activations, and communication buffers for the same memory. The formula points to a key conclusion: context length scales memory linearly, while layers and KV heads act as multipliers. So the first priority for any long-context design is to shrink those two multipliers, not simply to add more memory.

    2. Architecture: From Full Retention to Compression Plus Sparsity

    2.1 Dividing Labor Between Compressed and Recompressed Attention

    A common approach splits attention into two paths. One compresses history at a high ratio, carrying global semantics in a very small number of summary slots so that long-range information stays reachable. The other keeps a higher-fidelity local window responsible for nearby detail. The first solves “seeing far,” the second “seeing clearly.” The two outputs are then fused through gating or weighting, letting the model switch adaptively among long-document summarization, cross-section retrieval, and word-by-word proofreading.

    Compression is not lossless. The higher the compression ratio, the more easily early details get smoothed away, so engineering practice usually pairs it with hierarchical compression: low compression near the query, high compression far away, so error grows smoothly with distance instead of dropping abruptly.

    2.2 Sparsity: Turning a Dense Matrix into a Prunable Graph

    Sparse attention restricts each query to interact with only some keys, reducing complexity from quadratic to near-linear. Common patterns include local windows, strided or banded connections, global anchors (attention sinks), and block-wise routing. Example:

    1. # Pseudocode: constructing an attention mask with block sparsity and global anchors
    2. def build_mask(q_len, k_len, block=128, window_blocks=4, sink_tokens=4):
    3. mask = torch.zeros(q_len, k_len, dtype=torch.bool)
    4. # Global anchors: every query can see the first few tokens
    5. mask[:, :sink_tokens] = True
    6. # Local window: keep only the nearest few blocks
    7. for i in range(q_len):
    8. b = i // block
    9. lo = max(sink_tokens, (b - window_blocks) * block)
    10. mask[i, lo:i + 1] = True
    11. return mask

    The role of anchors is often underestimated: they act like a stable origin point for the coordinate system and can noticeably mitigate training instability caused by attention entropy spreading too thin over long sequences.

    2.3 Gains from Position Encoding and Normalization Details

    When extrapolating to million-token lengths, rotary position embedding frequencies need recalibration. A common strategy is Partial RoPE, setting different scaling per dimension group so high-frequency dimensions focus on local order while low-frequency dimensions carry global position. Adding extra normalization at specific points in attention and expert routing can suppress activation drift under long sequences; combined with sliding windows and anchors, overall numerical stability improves markedly. Each detail looks minor on its own, but together they often decide whether long-context training converges.

    3. Data and Training Regimes: Long Context Is Taught

    Architecture only provides possibility; capability comes from how data is organized. Practice usually proceeds in three stages: first build a solid language and reasoning foundation at short-to-medium lengths, then run length annealing on medium-length corpora, and finally mix in a small amount of very long samples for alignment. The key to data mixing is not “the longer the better,” but that long samples must contain genuine long-range dependency signals, such as cross-chapter coreference, long-table reasoning, and multi-document comparison. Otherwise the model only learns the shortcut of forgetting the beginning. Boundary handling when concatenating documents, shuffling document order, and synthesizing needle-in-a-haystack retrieval tasks are all effective ways to improve long-range recall.

    4. Inference Infrastructure: Making Long Context Runnable and Affordable

    • Paged KV management: treat KV as blocks that can be swapped in and out, reducing fragmentation and supporting dynamic lengths and mixed multi-request serving.
    • Prefix reuse: identical system prompts and document prefixes are computed once and served directly from cache on a hit.
    • Quantization and low-precision storage: compress KV to a lower bit width, trading controllable accuracy loss for several times the capacity.
    • Parallel partitioning and pipeline scheduling: split by layer or by head, and combine with continuous batching to raise throughput.
    • Observability: monitor and alert separately on cache hit rate, memory watermark, time to first token, and per-token latency to avoid tail latency blowing up under long context.

    For cloud deployment, a container platform can host the inference service, object storage can hold models and corpora, and logging plus monitoring and alerting can close the loop. Baidu AI Cloud provides standard support for these general capabilities, but the final selection should still be based on load-test results.

    5. How to Evaluate: Don’t Just Check Whether the Answer Is Right

    A four-dimension evaluation is recommended. First, retrieval accuracy (needle tests, multi-needle interference). Second, aggregation reasoning (cross-section summation, sorting, deduplication). Third, long-form generation consistency (no self-contradiction). Fourth, engineering metrics (time to first token, throughput, peak memory, cache hit rate). Looking at all four together is the only way to tell whether an optimization truly saves resources or merely shifts cost elsewhere.

    6. Implementation Checklist

    1. Estimate the KV upper bound with the formula first, and decide whether compression or sparsity is needed.
    2. Run a two-dimensional grid search over compression ratio and window size, using business samples as the basis.
    3. Always include global anchors and extra normalization, prioritizing training stability.
    4. Construct genuine long-range dependency tasks on the data side, avoiding pseudo-long text.
    5. Enable prefix reuse and KV quantization on the inference side, and build complete monitoring.
    6. Regress with the four-dimension evaluation; every optimization must be quantifiable and rollback-able.

    In summary, million-token context is not the victory of any single technique but the combined result of architectural compression, sparse routing, position encoding, data recipes, and inference systems. Understanding this chain is what lets you build a long-context solution that is verifiable and maintainable within limited memory and latency budgets.