Million-Token Context in LLMs: Attention, Training, and Applications
This article explains why long-context inference is costly and how sparse attention and compression reduce the computation and memory required. It also covers training stability, KV cache sizing, and evaluation, with guidance for developers choosing and deploying long-context models.
1. Why Long Contexts Are Hard
Standard Transformer self-attention requires every token to compute its relevance to every other token. With a sequence length of n, the attention score matrix contains n² elements. A 10,000-token sequence produces a matrix with 100 million elements. A 1-million-token sequence produces one with 1 trillion elements. Even with block-wise methods such as FlashAttention, which avoid writing the full matrix to GPU memory, the amount of computation still scales with n².
Inference adds another burden: the KV cache. The model must store the Key and Value vectors for every token it has already processed, so the cache size grows linearly with length. Together, these factors make the cost of million-token contexts depend mainly on computation and GPU memory.
2. How Attention Reduces Cost
There are three common approaches.
The first is sparse attention. Each token attends to only a subset of positions, such as a local sliding window plus a small number of global positions. Longformer and BigBird both use this design. The computation can drop from n² to about n·k, where k is the number of tokens each position actually attends to.
The second is compression. The model merges a run of consecutive tokens into a smaller set of representations, and later attention operates on the compressed sequence. Compression reduces the number of entries involved in computation, but detail may be lost.
The third approach combines the two. Nearby content keeps full detail, while distant content is compressed or sampled sparsely. Most architectures designed for very long contexts fall into this category, and the exact rules vary by approach.
| Approach | Positions each query attends to | Computational complexity | Main risk |
|---|---|---|---|
| Dense attention | All n positions | O(n²) | Compute and memory become hard to sustain at long lengths |
| Sparse attention | Local window and global positions, about k in total | O(n·k) | Information outside the window reaches a query only indirectly, through global positions |
| Compression plus sparsity | Compressed representations plus local detail | Depends on the compression ratio and sparsity rules | Compression may discard detail, so evaluation on the target task is necessary |
3. What Training Must Address
As sequences grow longer, gradients travel along longer paths, which makes training more prone to instability. Common stabilization methods include learning rate warmup, gradient clipping, normalizing Queries and Keys (QK-Norm), and properly configuring residual connections and layer normalization. These are general techniques that have been validated in the public literature.
For the optimizer, AdamW remains the baseline for most large model training. It maintains first- and second-moment estimates for each parameter and decouples weight decay from the gradient update. When compression and sparsity are introduced, the gradient distribution across submodules changes, so hyperparameters such as the learning rate must be retuned. Settings from dense models cannot be reused directly.
To judge whether a training improvement works, compare validation loss at equal compute, along with results on long-context benchmarks. A smooth training curve alone does not show that a model is better.
4. Estimating Memory with Numbers
The following is an illustrative calculation. Assume a model with 80 layers, 8 KV heads (grouped-query attention, or GQA), a head dimension of 128, and a KV cache stored in FP16.
The KV cache size per token is 2 (K and V) × 80 layers × 8 heads × 128 dimensions × 2 bytes, which totals 327,680 bytes, or about 0.33 MB. For 1 million tokens, the cache is about 328 GB, which exceeds the memory of a single common GPU.
Two conclusions follow. First, reducing the number of KV heads (as in GQA), lowering cache precision (such as FP8 or INT8 quantization), or compressing the cache can each directly reduce memory use. Second, to determine whether memory is sufficient, calculate the KV cache first, then add model weights and intermediate activations. The numbers above do not describe any specific model. Before deployment, confirm the actual configuration in the model card or the official documentation.
5. Integrating and Selecting Models as a Developer
Long context changes some engineering practices, but it does not replace every design decision. Check the following items before integration.
- Confirm the context limit. Verify whether the documented window length includes output tokens, and whether limits differ across plans or pricing tiers.
- Estimate cost and latency. The number of input tokens directly affects billing and time to first token. Sending 1 million tokens with every request makes both cost and waiting time high. For codebases or documents used repeatedly, you can consider reusing a processed prefix, although support depends on the provider.
- Choose the model version. For tasks centered on complex reasoning or code modification, evaluate candidates on your target task and select the smallest version that meets quality requirements. For high-frequency, low-latency uses such as customer support or code completion, a lighter version is usually more suitable, but verify its accuracy with your own data.
- Structure your prompts. Provide a global summary and table of contents first, then guide the model to locate details. This produces more stable results than placing all content in one unstructured block.
- Build an evaluation set. Create tests from real questions, place the answers at the beginning, middle, and end of the context, and check whether the model misses information.
6. Limits and Risks
A longer context does not mean every position’s information is used equally well. Liu et al. (2023), in “Lost in the Middle,” found that many models recall information in the middle of a long context less reliably. Therefore, place key information near the instructions or at the end, and specifically test recall of middle-section information.
Compression and sparsity also introduce approximation error. For tasks that require precision, such as legal clauses or financial figures, keep the original text or let the model refer back to the source passage. Do not rely solely on compressed representations.
Claims such as “reducing memory by an order of magnitude” should be checked against the original paper or the official evaluation. Figures published without stated test conditions should not serve as the basis for model selection.
7. Outlook
The next steps for long-context capability may combine external memory with retrieval, and unify representations of multimodal tokens such as text, images, and audio. How far these directions can go depends on the fidelity of compressed information and on whether inference costs continue to fall. For developers today, the most reliable approach is to understand the computational and memory characteristics of attention, validate results on their own tasks, and then decide which parts of a workflow are worth depending on long context.
