How to Make Million-Token Context Work: A Practical Guide to Long-Sequence Optimization

    Scaling a model's context window from a few thousand tokens to the million-token level is a multi-layered engineering effort, not a single parameter change. This guide walks through the core redesign work behind long context: sizing the KV cache, choosing attention architectures, tuning stability details, adapting data and training, and scaling the infrastructure. It explains why traditional attention becomes infeasible at million-token scale, how compressed sparse attention and heavy-compression attention divide the work, and how to verify that long-context capability is genuinely usable.

    Introduction: Million-Token Context Is Not “Just a Bigger Parameter”

    The most direct way to grow a context window from thousands of tokens to the million-token level is to increase the maximum position-encoding length so the model “accepts” longer inputs. But a larger window limit is not the same as real context capability. Putting information into a long window is only the first step; whether the model can accurately locate, integrate, and reason over information inside an extremely long sequence is what long-context capability actually means.

    From an engineering standpoint, extending context touches several parts of both inference and training at once:

    • Self-attention compute grows quadratically with sequence length.
    • Every generated token must scan the historical cache, so inference shifts from being compute-bound to bandwidth-bound.
    • Optimizer states, activations, and parallelism strategies all need to be redesigned around sequence length.

    Because of this, landing million-token context usually proceeds along three goals:

    1. Memory-feasible: the KV cache footprint stays within what the hardware can hold.
    2. Compute-feasible: long-sequence prefill and per-token decoding are acceptable in both time and cost.
    3. Quality-feasible: the model can locate, aggregate, and reason over information within an extremely long input.

    The sections below organize the core long-context redesign ideas across five dimensions—cache management, attention architecture, detail optimization, data and training, and infrastructure—around these three goals.


    1. Where the Bottleneck Starts: Sizing the Context Cache

    1.1 The cache-footprint formula

    Standard self-attention must store a set of keys (K) and values (V) for every token. In a simplified setting that ignores batch size and paged management, with context length L_ctx, number of model layers N_layers, number of KV heads N_kv_heads, and key/value vector dimensions d_k and d_v, the cache footprint in BF16/FP16 precision (2 bytes per value) can be estimated as:

    1. KVCache = L_ctx × N_layers × N_kv_heads × (d_k + d_v) × 2 bytes

    The table below compares magnitudes using a set of illustrative parameters. Assume: a single sequence, 1M (roughly one million) context, N_layers = 60, d_k = d_v = 128, BF16 storage. Memory figures are estimated in decimal GB and are used only to illustrate the order-of-magnitude differences.

    Scheme KV bytes per token per layer Full model per token 1M context, single sequence
    Standard MHA (128 KV heads) 65,536 ≈3.93 MB ≈3932 GB
    Grouped-query attention (8 shared KV heads) 4,096 ≈245.8 KB ≈245.8 GB
    Multi-query attention (1 KV head) 512 ≈30.7 KB ≈30.7 GB
    Low-rank latent compression (576-dim latent per layer) 1,152 ≈69.1 KB ≈69.1 GB
    Compressed sparse attention (block size 64, local window 2048, 1 KV head) 768 + 2,048 ≈2.75 MB ≈2750 GB (resident compressed cache ≈31 GB)
    Heavy-compression attention (compression ratio 512, 1 KV head) 1 ≈60 B ≈60 MB

    A few observations:

    • Standard MHA: at million-token context, it approaches 4 TB. Even if the model weights fit fully on one machine, the cache cannot be held.
    • Shared-KV-head approaches: grouped-query and multi-query attention compress the footprint to a few hundredths, but K/V is shared across all query heads, so the loss in expressiveness must be compensated during training.
    • Low-rank latent compression: the footprint is independent of head count and depends only on the latent dimension, so it becomes more resilient as the model grows.
    • Compressed sparse attention: the resident cache is only a small part; the bulk is on-demand raw K/V.
    • Heavy-compression attention: the footprint can drop to tens of MB, small enough to “fit” inside each attention compute unit for on-demand use.

    1.2 Refining the formula for real systems

    The formula above is only the starting point for capacity planning. Real systems need the following adjustments:

    • Batching and concurrency: when multiple requests share memory, cache usage scales roughly with “number of concurrent sequences × average length,” so long context sharply reduces achievable concurrency.
    • Precision and alignment: KV quantization (e.g., FP8, INT8), internal fragmentation from paged management, and temporary operator buffers all change actual usage.
    • Structural coupling: low-rank latent compression caches also include a decoupled position-encoding component; compressed sparse structures need extra index mapping to maintain the compressed cache alongside the raw cache.

    So for capacity planning, it is best to first estimate the order of magnitude with the formula, then calibrate with a small-scale measurement on the target hardware.

    1.3 How the three attention variants differ in role

    The numbers above also explain the role each of the three KV-compression approaches plays in long context:

    • Query-head sharing: degrades from “each query head stores its own K/V” to “multiple heads share one copy,” reducing the number of cache copies.
    • Low-rank compression: compresses K/V into a lower-dimensional latent space and reconstructs it at inference, reducing the storage dimension per token.
    • Compressed sparse: reduces the “resident cache” itself—the vast majority of historical tokens exist only as compressed summaries, with raw K/V fetched back on demand.

    The first two solve “can we store it,” while the third further solves “can we compute it affordably.” They are not mutually exclusive; real designs often combine them.


    2. Architecture Core: Coordinating Compressed Sparse and Heavy-Compression Attention

    2.1 Two main threads: compression and sparsity

    Redesigning attention for long context fundamentally revolves around two questions:

    • Compression: can a small number of summary vectors represent a segment of history?
    • Sparsity: does the current query really need to attend to all history?

    Compression: replace per-token storage with summaries

    The basic idea of compression is to aggregate a contiguous segment of tokens into one or a few “summary vectors.” Common methods include pooling, learnable linear projections, or another low-rank decomposition within the segment. Compression can be used on its own (uniformly compressing all history) or serve only as the “index” for sparse retrieval.

    Sparsity: precise interaction with only a few segments

    The key to sparsity is having a cheap “filter” that first decides which historical segments are relevant to the current query. Filtering signals can come from:

    • similarity between compressed summaries;
    • query/key vectors projected by a shared linear layer;
    • a lightweight scoring module.

    After a few candidates are selected, full attention is computed over the candidates.

    2.2 Why both threads are necessary: the tension between compression ratio and retrieval fidelity

    Compress without sparsifying, and once the compression ratio is turned up, summaries lose information. Sparsify without compressing, and the filter itself still has to scan all history, an overhead that cannot be ignored at million-token context. Worse still, when the compression ratio is pushed to the point where “the summary is small enough,” the compressed representation lives in a different numerical space from the raw K/V, so taking an inner product directly between a summary and the query easily causes scoring distortion.

    This is why the two threads must complement each other:

    • high-quality compression guarantees “can we store it”;
    • layered retrieval guarantees “can we find it accurately”;
    • precise attention over candidate segments guarantees “can we compute it in detail.”

    2.3 Compressed sparse attention: coarse filtering, fine filtering, and precise attention

    A typical three-stage design looks like this (illustrative pseudocode; parameters are examples only):

    1. def compressed_sparse_attention(q, K, V,
    2. block_size=64, # tokens covered by each summary block
    3. window=2048, # local precise window
    4. pool_top=32, # number of compressed blocks kept by coarse filter
    5. fine_top=256): # number of raw tokens kept by fine filter
    6. # 1) Chunk raw K/V and compress into one summary vector per block
    7. # The compressed cache stays resident in memory, using only 1/block_size of the raw cache
    8. Kc = compress(K, block_size) # [S/block_size, d]
    9. # 2) Coarse filter: score over compressed summaries, keep the top-scoring blocks
    10. pool_scores = score(q, Kc)
    11. cand_blocks = topk(pool_scores, pool_top)
    12. cand = gather_uncompress(K, V, cand_blocks) # fetch raw K/V on demand
    13. # 3) Fine filter: re-score within candidate tokens to narrow the range further
    14. fine_scores = score(q, cand.K)
    15. selected = topk(fine_scores, fine_top)
    16. # 4) Precise attention: local window + selected tokens computed together
    17. keys = concat(K[-window:], selected.K)
    18. values = concat(V[-window:], selected.V)
    19. return scaled_dot_product_attention(q, keys, values)

    Several design points in the pseudocode are worth noting:

    1. A local window preserves recency precision: nearby tokens usually have the most direct and most subtle influence on the current generation, so a stretch of “raw window” is kept without any compression.
    2. The two filtering stages divide work at different granularities: coarse filtering runs over compressed blocks—low cost, recall-first; fine filtering runs over candidate raw tokens—high cost, precision-first. They serve different goals and sit at different depths.
    3. Raw K/V stays out of the resident cache: what actually stays resident is only the compressed cache plus a little metadata; raw K/V typically lives in the memory/storage tier and is loaded on demand. This turns a memory bottleneck into a memory-bandwidth and I/O problem, which must be offset with prefetching and cache hits.
    4. Scoring must share the query’s space: compressed summaries should ideally be produced by a projection shared with the query, so that coarse-filter scores remain meaningful.

    2.4 Heavy-compression attention: letting summaries “live inside” the attention compute

    The compressed sparse approach still keeps a resident cost: one summary vector per historical block. If the compression ratio is raised by another one to two orders of magnitude on top of that (illustratively 512:1), the summaries for million-token context amount to only about 2,000 vectors (about 0.5 MB with 1 KV head). This magnitude is small enough to reside directly inside each compute unit, read along with attention, with no need for extra memory management.

    But its cost is also obvious: the summary granularity is extremely coarse, and it cannot complete precise retrieval on its own. So heavy-compression attention usually does not bear the responsibility of “searching all history” alone; instead it acts as a coarse-grained, long-range “global awareness” channel, working with modules responsible for precise localization.

    A more common practice is layered heterogeneity:

    • most layers handle local modeling using sliding-window attention;
    • a few layers keep full global attention;
    • the heavy-compression channel supplements them, providing a global overview at extremely low cost.

    This avoids the quadratic cost of “every layer querying all history” while still ensuring information can propagate across long ranges.


    3. Detail Optimization: The “Small Changes” That Decide Long-Context Stability

    3.1 Local normalization: keeping attention scores from drifting numerically

    As context grows, the variance of attention scores (inner products of queries and keys) tends to amplify as it accumulates over sequence length, making the softmax distribution overly sharp. When the output concentrates on very few tokens, the information flow gets “cut off,” and training shows loss spikes or even divergence.

    Inserting normalization after the query and key projections and before scoring (in the spirit of “query-key normalization”) can hold the inner-product scale within a controllable range, preventing extreme values in individual dimensions from dominating the scores. Typical engineering practice:

    • apply root-mean-square normalization along the feature dimension per token, then multiply by a learnable scale;
    • skip mean-centering for cheaper computation;
    • combine with learning-rate warmup and gradient clipping to further reduce numerical risk in early long-sequence training.

    3.2 Partial rotary position encoding: balancing extrapolation and resolution

    Rotary position encoding (RoPE) injects relative position information by applying position-dependent rotations to query and key vectors. In standard RoPE, each dimension pair corresponds to a different rotation frequency: high-frequency dimensions distinguish neighboring tokens, while low-frequency dimensions encode long-distance positions.

    The problem: when input length far exceeds the training length, the rotation angles of high-frequency dimensions undergo periodic “wrapping,” and positional distinctiveness drops sharply; low-frequency dimensions can extrapolate smoothly but can barely distinguish the exact order.

    A common improvement is partial rotation: rotate only a subset of dimensions, leave the rest unrotated, and let those unrotated dimensions be passed only through the low-rank latent path. This way:

    • the rotated dimensions carry the “relative position” signal;
    • the non-rotated dimensions act as a position-independent “content channel” that stays stable over extremely long distances.

    On top of this, combining with interpolation-style position scaling (such as linear interpolation or NTK-aware scaling) can further extend the supported context length.

    3.3 Sliding window: pressing quadratic complexity down to linear

    Sliding-window attention restricts each token to seeing only the most recent w tokens, reducing per-token compute from “proportional to total length” to a constant. Its drawback is that information cannot interact across windows directly, so it is typically used together with a global branch.

    One practical point is aligning the window with the block size. If window boundaries do not line up with compressed-block boundaries, some blocks become only partially visible and fragmented, wasting compute or losing information. Setting the window to an integer multiple of the block size is simpler to implement and better for kernel optimization.

    3.4 Attention sinks: softmax’s “mass absorbers”

    The softmax output always sums to 1. When a token has low similarity to all visible tokens, softmax still forces probability mass onto some tokens. During training, the model spontaneously learns to concentrate this “nowhere-to-go” probability mass onto a few tokens (such as a special token at the sequence start). This is called an attention sink, and it works like a “trash can.”

    Sliding-window attention introduces a new problem: the further along the sequence, the easier it is for the sink token to slide out of the window. As a result, the model suddenly loses its outlet for absorbing redundant probability mass, and perplexity can jump by an order of magnitude—especially noticeable in streaming inference.

    There are two general solutions:

    1. Always-visible sink tokens: no matter how the window slides, always allow attention to see a few tokens at the sequence start.
    2. Learnable sink logits: add a learnable “virtual key” to each attention head that participates in the softmax denominator but does not correspond to any real value vector—effectively giving the model an explicit “attend to nothing” option.
    1. # Illustration: add a learnable sink logit to each head
    2. sink = nn.Parameter(torch.zeros(num_heads))
    3. # scores: [batch, heads, q_len, kv_len]
    4. scores = concat([sink.view(1, -1, 1, 1).expand(...), scores], dim=-1)
    5. probs = softmax(scores, dim=-1)
    6. out = matmul(probs[..., 1:], V) # drop the output at the sink position

    4. Data and Training: Making the Model Actually “Use” Long Context

    4.1 Length curriculum: gradually extend from short to ultra-long sequences

    Training directly at million-token length from scratch is extremely expensive and tends to converge poorly because long-range dependency signals are sparse. A common industry strategy is “progressive extension”:

    • complete the bulk of pretraining at shorter lengths (e.g., 4K/32K);
    • then extend the window in stages (e.g., 128K → 512K → 1M);
    • at each stage, combine position-encoding interpolation with a short learning-rate warmup so the model adapts smoothly to the new position distribution;
    • in the final stage, keep a high proportion of long samples so the model does not “forget” long-range capability.

    4.2 Data mix: weight by tokens, not by documents

    Long documents make up a very low proportion of raw corpora. If you sample by “document count,” long samples get diluted to almost no influence. Common practices:

    • raise the sampling weight of long documents so the average proportion of long sequences in a training batch stays stable;
    • construct “same-topic concatenation” samples (such as multiple files from the same repo, or multi-turn discussions within the same project) so long-range dependencies arise more naturally;
    • fill gaps with synthetic data: chunk a long document and generate questions that require cross-chunk integration, or generate “multi-hop QA” samples.

    4.3 Evaluation: don’t just test “finding a needle in a haystack”

    “Finding a specific string in a long document” only verifies localization ability, not reasoning and integration ability. A layered evaluation set is recommended:

    Evaluation dimension Capability in focus Typical form
    Precise retrieval Can it locate a unique segment? Point retrieval of specified information
    Multi-hop reasoning Can it combine several scattered segments? Cross-section causal/comparative questions
    Middle-section use Is information in the middle actually used? Placing key info in the middle
    Extrapolation stability Does it degrade beyond training length? Inputs longer than the training window
    Long-output consistency Does a long output contradict itself? Long-document generation plus self-check

    A special note: positional effects are very pronounced in long context, and it is common to score high when key information sits at the start or end but low when it sits in the middle. Evaluation should treat “position” as a controlled variable rather than a random one.


    5. Infrastructure: Actually Running Million-Token Context

    5.1 Training side

    • Sequence parallelism: shard the long sequence across multiple GPUs and exchange K/V with ring communication, computing attention at block-level parallelism and overlapping communication with computation.
    • Expert-parallel communication pressure: as sequences grow, all-to-all communication volume rises and must be scheduled jointly with sequence parallelism to avoid communication becoming the bottleneck.
    • Recomputation and offloading: trade memory for recompute on intermediate activations such as attention, and, when necessary, offload some states to host memory or the storage tier.
    • Optimizer memory: in the long-context phase, combine parameter sharding with low-precision optimizer states to ease per-GPU memory pressure.

    5.2 Inference side

    • Chunked prefill: split a very long prompt into blocks computed block by block, avoiding a single prefill monopolizing resources for a long time and allowing per-token output to start sooner.
    • Prefill/decode disaggregation: the two phases have very different resource profiles (the former is compute-intensive, the latter bandwidth-intensive), so deploying them separately makes independent scaling easier.
    • Prefix caching: reusable prefixes such as system prompts and long documents skip redundant computation after a cache hit.
    • Length-bucketed scheduling: route very long requests and short requests to different queues to avoid long requests blocking the queue.
    • KV quantization and paged management: push the resident cache to lower precision and allocate it page by page to reduce fragmentation.

    5.3 Observability

    After launching long-context capability, monitor at least the following:

    • per-request KV usage and the distribution of context lengths;
    • the number of prefill chunks and queueing time;
    • time-to-first-token (TTFT) and per-token output latency;
    • memory watermark and OOM trends;
    • cache hit rate.

    These metrics are both the basis for capacity planning and the entry point for diagnosing “long-context stalls.”


    6. Implementation Advice and Common Pitfalls

    6.1 Implementation advice

    1. Do the math first: use the formula from Section 1 to estimate cache usage at the target context length and determine the hardware feasibility boundary.
    2. Design in layers: allocate the three module types—“local window / compressed sparse retrieval / heavy-compression global awareness”—across layers rather than making every layer do the same thing.
    3. Leave no gaps in the details: local normalization, partial rotation, sink handling, and window/block alignment—missing any one of them can surface problems on long sequences.
    4. Weight data by tokens: ensure the proportion of long samples in each training batch stays stable.
    5. Advance the length curriculum gradually: combine with position-encoding interpolation and extend the window stage by stage.
    6. Scale infrastructure in step: adjust parallelism strategy, scheduling strategy, and monitoring metrics together with context length.

    6.2 Common pitfalls

    • Treating “supported length” as “supported capability”: a window limit is only capacity; whether it can actually be used is another matter.
    • Looking only at compression ratio and not retrieval quality: a very high compression ratio that still fails to recall is a waste of compression.
    • Ignoring positional effects: not controlling position in evaluation systematically overestimates model ability.
    • Ignoring communication bottlenecks: as sequences grow, the bottleneck often shifts from compute to communication and bandwidth.

    Conclusion

    Landing million-token context is not the result of a single-point optimization but the coordination of five threads: cache management, attention architecture, detail fixes, data mix, and infrastructure. Starting from sizing the KV cache, this article explains why traditional attention is infeasible at million-token context; it then breaks down the division of labor between compressed sparse attention and heavy-compression attention, along with the motivations and costs of details such as local normalization, partial rotary position encoding, sliding windows, and attention sinks; finally, it offers supporting advice on training data and inference infrastructure.

    For developers, the most valuable methodology is: first quantify the bottleneck with formulas, then make architectural trade-offs along the “compress–sparsify–layer” line, and finally verify with a layered evaluation set whether long-context capability is genuinely usable. Note that the above is a general technical overview, all parameters are illustrative, and for specific implementation details please refer to the corresponding public technical documentation and code.