Million-Token Context LLMs: A Technical Breakdown and Engineering Practices

    This article breaks down the technical foundations of million-token context large language models layer by layer, covering architecture, data, training, and infrastructure. It explains why context length is expensive through the KV Cache memory footprint and attention's quadratic computation, then shows how to reduce the "length tax" via hybrid attention, low-rank compression, and sparsity. It also covers long-context data construction, progressive length-extension training, and the infrastructure needed to run million-token sequences—memory optimization, parallelism strategies, load balancing, and serving deployment—and closes with selection guidance and an evaluation checklist for long-context capability.

    I. Introduction: Why Million-Token Context Is Hard

    Over the past few years, the context window of large language models has expanded from a few thousand tokens to 32K and 128K, and today many models are targeting the million-token level. This length corresponds roughly to thousands of pages of documents, a small code repository, or a single long-running conversation. People expect the model to “read” all of this material in one pass and reason over it directly, without needing to chunk, retrieve, and stitch the pieces back together.

    But a context window is never a parameter you can freely scale up. Going from 128K to 1M increases the token count nearly 8-fold, yet the growth in attention computation is far greater than that. The bottlenecks behind this can be broken down into four categories:

    • Architecture bottleneck: The computation of standard multi-head attention grows quadratically with sequence length. Every generated token must cache its key-value pairs against all previous tokens, so the longer the context, the heavier the memory footprint.
    • Data bottleneck: High-quality long documents are relatively scarce. The effective long-range dependencies each task needs must be constructed deliberately—simply concatenating short documents does not teach a model to associate information across large spans.
    • Training paradigm bottleneck: Directly extrapolating on long sequences tends to run into failures in positional encoding, numerical instability, and optimization difficulties.
    • Infrastructure bottleneck: A single GPU’s memory cannot hold the activations and parameter states of an ultra-long sequence. Any weak link in communication, load balancing, or operator efficiency causes training throughput to plummet.

    These four bottlenecks constrain one another and are hard to solve through single-point optimization alone. A common approach to long context usually advances on four fronts in tandem: redesigning the attention structure, carefully constructing long-context data, adopting progressive length-extension training, and deeply adapting the training framework and operators.

    Below, using a general-purpose architecture’s “million-token capability” as an example, this article breaks down the technical system layer by layer. All numbers in the text are illustrative estimates derived from formulas, used to show orders of magnitude, and do not represent measured data from any specific model.

    II. Start with the Cost: The “Length Tax” of KV Cache and Attention

    2.1 Memory Overhead of KV Cache

    In standard autoregressive decoding, every already-generated token participates in attention computation for all subsequent positions. To avoid recomputing repeatedly, inference frameworks cache the Key and Value vectors each token produces at every layer—this is the KV Cache.

    Taking batch size 1 and BF16 caching precision (2 bytes per number) as an example, the memory footprint of the KV Cache can be written as:

    1. KVCache ≈ L_ctx × N_layers × N_kv_heads × (d_K + d_V) × 2 bytes
    Parameter Meaning
    L_ctx Context length (number of tokens)
    N_layers Number of model layers
    N_kv_heads Number of Key/Value heads per layer
    d_K, d_V Dimension of a single Key / Value head

    Assuming N_layers = 60, N_kv_heads = 8, d_K = d_V = 128:

    • Each token requires 8 × (128 + 128) × 2 = 4 KB per single layer;
    • 60 layers total about 240 KB;
    • At a context length of 128K, the KV Cache is about 30 GB, already close to the memory limit of many single-GPU inference scenarios;
    • At a context length of 1M, the KV Cache is about 240 GB, which can only fit with multi-GPU tensor parallelism.

    And this is an estimate under the ideal case of batch size 1. Online serving usually handles dozens or even hundreds of requests simultaneously, and the model weights themselves consume a large amount of memory, so the pressure multiplies. One noteworthy fact: the full KV Cache grows linearly with context length, while the compute cost of incremental prefill grows quadratically with context length. The longer the context, the more both curves—memory and compute—tighten at once. Meanwhile, limited by memory bandwidth, token-by-token decoding must re-read the entire KV Cache at every step. Long-context decoding is therefore often bandwidth-bound rather than compute-bound.

    2.2 The Quadratic Computation of Attention

    Computing attention scores and the weighted sum requires two matrix multiplications: Q with K, and A with V. The computation is approximately:

    1. FLOPs_attn ≈ 4 × L² × d_model

    where d_model = N_heads × d_head, and in the derivation each multiply-add is counted as 2 floating-point operations.

    Still using the above architecture, assume d_model = 4096 and 60 layers, and perform one full forward pass over a million tokens:

    • The attention portion is about 4 × 10^12 × 4096 × 60 ≈ 1.0 × 10^18 FLOPs;
    • The per-token portion in linear layers, MLPs, and so on is roughly 3.4 × 10^17 FLOPs, only about a quarter of the total.

    For the same model processing a 4K sequence, the attention portion is only about 1.6 × 10^15 FLOPs, a negligible share. It can be said that the length tax of context is mainly reflected in attention, and this is the starting point for all long-context architecture designs.

    III. The Architecture Layer: Making Attention “Compute Less, Store Less”

    3.1 Three Basic Forms and “Layered Division of Labor”

    Attention in long-context scenarios can broadly be grouped into three forms:

    1. Full attention: Every token can see the entire history. It has the strongest expressive power but the largest compute and cache overhead.
    2. Sliding-window attention: Each token attends only to the most recent W tokens, reducing complexity to O(L × W) and constraining memory to a fixed window. But it cannot establish long-range dependencies, requiring enough stacked layers for information to propagate step by step to distant positions.
    3. Compressed/sparse attention: Represents the global history at a granularity far lower than the token count, letting each token “see” the whole sequence at low cost.

    Each used alone has obvious shortcomings. Pure window attention struggles to model long-range dependencies, while pure full attention cannot scale to million-level lengths. The mainstream approach is therefore layered mixing, which can roughly be summarized into two categories:

    • One is budget-partitioned hybrid attention: While maintaining full-length coverage, it compresses the KV budget of all layers into a fixed total and then allocates the budget per layer. Layers near the input and output use wider windows, middle layers use narrower ones, and some layers use global compressed attention.
    • The other is a hybrid structure dominated by local layers: Most layers use window-limited local attention, while a few layers use global compressed attention.

    What both approaches share is this: a small number of global layers hold the long-range information pathway, while a large number of local layers control compute and memory costs. It is generally advisable to pair window size with the number of layers so that information can propagate layer by layer across the entire context.

    The following illustrative code shows a typical layered strategy:

    1. def attention_mode(layer_idx, num_layers, win):
    2. """Select the attention form per layer; parameters must be tuned by ablation."""
    3. # Insert a global compressed attention layer every k layers
    4. if layer_idx % 4 == 0:
    5. return "global_compressed"
    6. # First and last layers typically focus on local and nearby info; widen the window
    7. if layer_idx < 2 or layer_idx >= num_layers - 2:
    8. return "local_window", win * 2
    9. # Middle layers use a local sliding window
    10. return "local_window", win

    3.2 Compression: Reducing Storage with Low-Rank Representations and Re-compression

    Low-rank latent representation

    The core idea of compression approaches: let Key/Value be computed by a projection matrix from a latent vector whose dimension is far lower than the full key/value. During inference, only this latent vector is cached, and it is projected back up on demand when Key/Value is needed.

    Illustrated below (dimensions and layer counts are example values):

    1. Full KV cache: per token per layer, cache 8 × (128 + 128) × 2 bytes = 4 KB
    2. Low-rank latent: per token per layer, cache latent vector 512 × 2 = 1 KB
    3. + position-dependent key component 64 × 2 bytes = 128 B
    4. (shared once per attention block, amortized per token here)
    5. Total ≈ 1.1 KB, a compression ratio of about 3.6x

    There is a point here that is often overlooked: the position-sensitive key component cannot be absorbed into other projection matrices and must be cached separately. Otherwise positional information is lost as the latent vector is projected up, causing a clear performance drop in long-range extrapolation. So when evaluating compression gains, you cannot look only at the latent vector dimension—you must count the full cache including this component.

    Heavy compression

    To pursue million-level context, these approaches further shrink the latent vector dimension. For example, reducing the latent vector of each attention block from 512 to 128 dimensions, the cache per token per layer is about:

    1. 128 × 2 + 64 × 2 = 384 bytes
    2. 60 layers total about 23 KB / token

    As a result:

    • The KV Cache for 1M context is about 23 GB, roughly an order of magnitude lower than the 240 GB of the full key/value;
    • By the number of attention invocations, the extra compute from up-projection is under 1% and negligible.

    However, compression also comes with preconditions. In short-context settings, compared with the already highly optimized GQA structure, compression approaches may be slightly at a disadvantage due to the lack of mature high-performance operators; the longer the context, the more pronounced the memory and bandwidth benefits of compression become.

    The meaning of re-compression

    Some approaches add a further compression step inside each layer’s attention, after the latent representation—that is, heavy compression. It further reduces the per-layer storage cost at the price of a small amount of extra matrix computation per token per layer. Re-compression is like adding another compression-ratio knob on top of “number of layers × per-layer representation,” letting the architecture trade off more finely between global accuracy and memory usage.

    3.3 Sparsity: Letting Only the Tokens That Should Be Seen Participate

    Compression solves “how much to store,” while sparsity solves “how much to compute.” Common approaches include:

    • Combining a sliding window with a small number of global tokens (such as the attention sink at the start, summary tokens, or key fragments retrieved);
    • Dynamically selecting the tokens to participate in computation based on the relevance between queries and keys;
    • Using a unified sparse pattern in both training and inference, to avoid the distribution shift caused by “seeing everything during training but only half at inference.”

    A key distinction: only sparsity that does not cache unselected tokens can reduce memory at the same time; approaches that sparsify only already-cached content mainly save compute.

    3.4 Effect Estimation of the Hybrid Structure

    Estimating with an illustrative configuration of “60 layers, window 4096, local attention at 75%”:

    • 45 local layers: per-layer in-window KV is about 4096 × 4 KB = 16 MB, totaling about 720 MB across 45 layers, and independent of the total context length;
    • 15 global compressed layers: at about 1.1 KB per layer per token, at million-token context totaling about 16 GB;
    • The total KV Cache for 1M context is about 17 GB, more than an order of magnitude lower than the ~240 GB of the full key/value;
    • At training time, per forward pass, the attention computation drops from about 1.0 × 10^18 FLOPs to 4 × 10^6 × 4096 × 4 KB × 45 + 1.0 × 10^12 × 4096 × 15 ≈ 6.5 × 10^16 FLOPs, about one-fifteenth of the original.

    It can be seen that layered mixing turns “million-token context” from a dual infeasibility of memory and compute into an engineering-manageable target. As for how to allocate across layers, how large to set the window, and how much compression to use, all of these need to be determined through ablation experiments combined with the target task.

    3.5 Position Encoding, Normalization, and Activation Caching

    Beyond the attention form itself, there are several kinds of details that are easily underestimated:

    • Extrapolation of positional encoding: In Rotary Position Embedding (RoPE), positional information is injected in the form of rotation angles. When extrapolating directly to positions far beyond the training length, the high-frequency and low-frequency dimensions behave inconsistently. A common improvement is to apply rotation on only a subset of dimensions (partial RoPE), with the remaining dimensions carrying content information, while adjusting the base frequency to improve long-range extrapolation.
    • Numerical stability: Adding a learnable RMSNorm-style normalization on attention scores, or normalizing Q/K before the dot product, can suppress numerical divergence in ultra-long contexts, which is especially critical in long-sequence training.
    • Attention sinks: Research has found that Softmax allocates a considerable share of attention to the few tokens at the very start of the sequence, regardless of whether their content is relevant. The reason is that Softmax requires weights to sum to 1, so when a token is irrelevant to all others, the attention still needs somewhere to “land.” Preserving this part of high-quality global attention helps stabilize streaming and long-context inference.
    • Activation caching: In local attention, the Key/Value at each position within a token’s window is read repeatedly. If not handled carefully in the implementation, the cached amount of these activations grows in proportion to the window size. This cost needs to be controlled through activation recomputation or block-wise processing.

    IV. The Data Layer: Long-Context Ability Comes from the “Data Recipe”

    The architecture determines the maximum context length a model can handle; the data determines whether it can actually make good use of that context. Constructing long-context data usually needs to consider the following:

    1. Real long documents: Books, long reports, complete code repositories, long-running conversation logs, structured logs, and so on. The key is to preserve the document’s natural structure—such as chapter hierarchy and function/file relationships—because these structures themselves are clues to long-range dependencies.
    2. Synthetic long-context samples: In real data, reasoning tasks that require spanning large distances are not common. Common practices include:
      • Embedding key information in long documents and constructing corresponding questions, training the model to “find a needle in a haystack”;
      • Cross-chapter summarization, full-document consistency checks;
      • Repository-level cross-file defect localization in code, and so on.
    3. Short-text regression: Keep enough high-quality short samples in the training data, to avoid the model losing short-task ability during the length transition.
    4. Progressive difficulty: As training proceeds, gradually increase the proportion of long samples and the effective dependency distance, letting the model transition from local dependencies to global dependencies.

    Evaluation data likewise needs to be diverse. A single “needle search” test is easily “gamed” by simple patterns; tasks such as multi-needle, multi-hop reasoning, and long-generation consistency also need to be added to truly measure long-context ability.

    V. The Training Paradigm: Progressive Extension and Continued Training

    A fairly common training paradigm can be summarized as “short context to build a foundation, gradual extension, targeted continued training, and post-training reinforcement.”

    1. Short-context pretraining: Complete most of the parameter learning at 4K–32K lengths, where the range of positional encoding is far smaller than the final target length.
    2. Progressive extension:
      • As the context gradually extends to 128K, 256K, and even 1M, adjust the rotational base frequency of positional encoding in sync;
      • Introduce long-sample data to continue training, letting the model adapt to more distant relative positions;
      • Mix in short samples at each stage to prevent catastrophic forgetting.
    3. Long-context continued training: Building on completed extension, use large-scale long documents and synthetic tasks for targeted enhancement, focusing on training abilities such as cross-segment retrieval, multi-hop reasoning, and long-document consistency.
    4. Post-training stage: Instruction data and preference data likewise need to cover long-input tasks, and reinforcement learning and similar methods are used to strengthen the “locate first, then reason” behavior pattern.

    Progressive extension works because it keeps the optimization process taking small steps near the positional distribution the model is already familiar with, avoiding the training oscillation caused by a sudden shift in the positional distribution.

    VI. The Infra Layer: Making Million-Token Context Actually Run

    6.1 Memory Optimization

    The main memory cost of long-sequence training comes from intermediate activations such as the attention score matrix. Taking an unoptimized implementation as an example, the attention score matrix of a single layer is about L² × batch × heads × 2 bytes:

    • At sequence length 128K, a single layer is about 34 GB, already exceeding single-GPU capacity;
    • At sequence length 1M, a single layer is about 2.1 TB, completely infeasible without blocking.

    The common industry solution is: with the help of IO-aware block-wise attention operators, split the attention computation into small blocks and compute Softmax incrementally online, so the full score matrix is never explicitly stored; combined with activation recomputation, recompute the necessary forward results during backpropagation, trading a small amount of extra computation for a large reduction in memory.

    6.2 Parallelism Strategies

    • Tensor parallelism: Partition parameters and attention heads across GPUs. Efficient for short sequences, but communication-heavy for long sequences.
    • Sequence parallelism: Partition the input sequence across devices, each holding a segment of tokens, then exchange Key/Value blocks via ring communication and merge results incrementally with online Softmax. This is one of the key technologies supporting million-level sequence training.
    • Expert parallelism: In Mixture-of-Experts architectures, assign different experts to different devices and route tokens via All-to-All communication.
    • Pipeline parallelism: Assign different layers to different devices, and with reasonable partitioning and scheduling, reduce bubble waiting.

    In practice, it is usually a combination of multiple parallelism methods, with the specific configuration depending on the cluster’s interconnect bandwidth and the sequence length.

    6.3 Load Balancing and Operators

    Long documents vary greatly in length. If samples are simply arranged in order, one device might get a large number of long samples while others wait idle early on. Common practices include:

    • Sorting by length and then doing sequence packing;
    • Splitting ultra-long samples into multiple segments and distributing them across different batches;
    • Using unified alignment and masking for variable-length sequences.

    In addition, high-performance operators need to be written for custom structures such as grouped-query attention and compressed attention, and memory reads/writes reduced through compilation optimization and kernel fusion.

    6.4 Serving Deployment

    Beyond training, the inference side is likewise a testing ground for long-context ability:

    • Block-wise prefill, to avoid a single ultra-long request occupying compute resources for a long time;
    • Prefix caching, to reuse the KV Cache of common prefixes such as system prompts and long documents;
    • KV Cache quantization and paged management, to improve memory utilization;
    • On-demand eviction strategies, to retain summaries and key fragments in long-session scenarios.

    VII. Selection Recommendations and Implementation Checklist

    Long context is not the optimal solution for every scenario. When selecting, refer to the following principles:

    Scenario characteristic Recommendation
    Clear information location, can be pre-chunked Prefer retrieval-augmented generation (RAG); lower cost and faster to update
    Needs global understanding and cross-segment reasoning, such as long-document review and repository-level analysis Prefer long-context models
    High-concurrency online serving Combine block-wise prefill, prefix caching, and KV quantization to control the impact of long requests on overall throughput

    No matter which approach is chosen, when evaluating long-context ability it is advisable to focus on:

    1. Key information retrieval: Cover single-needle and multi-needle tests across different positions, checking whether the model has truly “seen” the information.
    2. Cross-segment reasoning: Questions that require synthesizing multiple distant fragments to answer, assessing long-range information integration ability.
    3. Context perturbation: Whether irrelevant content interferes with conclusions, and whether outputs are stable and reproducible.
    4. Effective context length: The actually usable context is often shorter than the nominal value, so it should be judged by task effectiveness.
    5. Cost structure: Pay attention to prefill latency, memory usage, and per-request cost at the same time.

    From an engineering perspective, the deployment of million-token context LLMs does not rely on any single “black-magic” technique, but is the result of coordinated evolution across the four layers of architecture, data, training, and infrastructure. The attention mechanism lowers the “length tax” through compression and sparsification; data construction makes the model truly learn to use long context; progressive training keeps the optimization process stable; and high-performance operators, sequence parallelism, and serving capabilities make all of this run at scale. For developers, understanding the internal logic of this system is more valuable than memorizing any single parameter: only by first seeing where the cost comes from can you make reasonable trade-offs among performance, memory, and cost.