Understanding Million-Token Context LLM Architecture: Memory Constraints and Hierarchical Compression

    This article breaks down the architecture of million-token context large language models, starting from the core engineering fact that context length is a memory budget problem rather than a pure algorithmic parameter. It explains KV cache estimation, compares compressed sparse attention with heavy compression attention, and covers low-rank KV compression, local window attention, attention sinks, partial positional encoding, selective normalization, and layer-wise differentiation. It also outlines data and training practices such as progressive length extension, long-dependency data mixing, retrieval-style synthetic tasks, and position consistency checks, followed by infrastructure considerations for parallelism, memory-compute balance, and inference cache management. Readers will find a practical capacity estimation example and selection advice centered on effect-cost tradeoffs.

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

    Before discussing any model capability, one engineering fact must be clear: context length is not a pure algorithmic parameter but a function of the memory budget. Standard self-attention needs to retain a set of Key/Value vectors for every token, and its usage can be approximated as:

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

    With Batch=1, a context length of 1,000,000, and BF16/FP16 at 2 bytes per number, a rough order-of-magnitude estimate shows that traditional multi-head attention (which keeps the full K/V for every head group of every token) would produce a KV cache on the order of hundreds of GB at million-token context. Neither a single GPU nor a single node can hold it. This is the starting point of all long-context work: the problem is not that computation is impossible, but that storage is insufficient.

    It is worth emphasizing that the formula above is only a lower-bound estimate. Real serving also includes framework reservations, communication buffers, activation recomputation ranges, and fragmentation, so capacity planning must leave headroom. In engineering practice, this usually follows three steps: first calculate the theoretical value with the formula, then multiply by an empirical coefficient, and finally calibrate with load testing.

    2. Architecture: From Full Retention to Hierarchical Compression and Sparse Retrieval

    2.1 Division of Labor Between Two Types of Compressed Attention

    Two complementary routes are common in long-context solutions, which can be abstracted as:

    • Compressed sparse attention: First perform structured compression on historical K/V to form a shorter “summary sequence”. The current query mainly interacts with this compressed representation, and only looks back at a small number of raw segments when necessary. It addresses the problem that “the vast majority of historical information does not need token-by-token precise access”.
    • Heavy compression attention: Push the compression ratio higher, using an extremely short representation to carry global semantics and serve a role similar to “global memory”, at the cost of reduced detail fidelity.

    The combined effect of the two is: global semantics are guaranteed by the heavy compression branch, while local details are filled in by the sparse branch. Compared with a single mechanism, this division of labor makes it easier to balance “needle finding” (precise retrieval) and “surveying” (global understanding) in long-context evaluations.

    2.2 Relationship to Low-Rank KV Compression

    The previous mainstream approach used low-rank projection to compress K/V into a smaller latent space, which is still essentially “one compressed vector per token” with linear growth in length. The change in the new approach is to extend the compression dimension from “per token” to “segment-level across tokens”, meaning compression is also performed along the sequence dimension. This is what makes million-level lengths feasible in terms of memory.

    2.3 Detail Optimizations That Should Not Be Overlooked

    What truly determines long-context stability is often these “small parts”:

    • Local window attention: Most layers perform precise attention only within a nearby window, reducing complexity from quadratic to linear;
    • Attention sinks: Retain a small number of “globally visible” positions to act as information aggregation points and gradient pathways, alleviating optimization difficulties in long sequences;
    • Partial positional encoding: Apply rotary positional encoding only to a subset of dimensions while keeping the remaining dimensions free of positional information, balancing length extrapolation and semantic stability;
    • Selective normalization: Apply normalization separately at specific positions (such as sinks and compression boundaries) to suppress numerical drift;
    • Layer-wise differentiated configuration: Not all layers need the same context horizon; shallow layers being more local and deep layers more global is a common tradeoff.

    Together these designs form one principle: restrict expensive precise computation to the positions that truly need it.

    3. Data and Training Paradigm: Length Is Trained

    Architecture only provides possibility; capability comes from data and training arrangements. More consistent industry practices include:

    1. Progressive length extension: Complete the main training on shorter contexts, then gradually lengthen the window in stages, avoiding paying quadratic costs from the start;
    2. Long-dependency data ratio: A certain proportion of long documents, code repositories, and structured records is needed; otherwise the model will only “see long” but not “use long”;
    3. Retrieval-style synthetic tasks: Construct supervised samples that require answering across large distances, directly aligning with the evaluation format;
    4. Position consistency checks: After extending the window, check whether the attention distribution at different positions degrades, preventing “middle collapse”.

    The most common mistake on the data side is: length goes up, but effective dependency signals are sparse, and the model degenerates to only looking at the beginning and the end.

    4. Infrastructure: Turning Feasibility into Usability

    The engineering constraints of million-token context concentrate in three areas:

    • Parallelism strategy: Splitting along the sequence dimension is almost unavoidable and must coordinate with expert parallelism and pipeline parallelism. Communication volume grows with length, so operator fusion and communication overlap are necessary;
    • Memory and compute balance: Activation recomputation, chunked forward passes, and the incremental computation of compression branches need unified orchestration; otherwise the saved KV memory will be consumed by activations;
    • Inference-side cache management: Paged caching, prefix reuse, and on-demand eviction are standard capabilities for long-context serving, typically carried by general cloud categories such as container platforms, object storage, log services, and monitoring and alerting.

    An example of a practical capacity estimation workflow:

    1. def kv_cache_gb(l_ctx, n_layers, n_kv_heads, d, bytes_per=2, batch=1):
    2. return l_ctx * n_layers * n_kv_heads * (2 * d) * bytes_per * batch / 1e9
    3. # After compression: change "one copy per token" to "one copy per segment"
    4. def compressed_kv_gb(l_ctx, seg, **kw):
    5. return kv_cache_gb(l_ctx // seg, **kw)

    5. Evaluation and Selection Advice

    Evaluating long context cannot rely on a single retrieval metric. It is recommended to cover at least four categories: cross-segment precise retrieval, multi-hop reasoning, global summarization, and long-form generation consistency. At the same time, record first-token latency, throughput per unit length, and peak memory to form a two-dimensional “effect-cost” view.

    For selection, three pieces of experience are offered: first, estimate before selecting—any solution must be able to answer “how much memory does million-token context require”; second, prefer implementations where compression and sparse mechanisms are configurable, making it easy to tune parameters by business length; third, include cache reuse capability in the evaluation, because in long-context scenarios prefix reuse often affects actual cost more than peak compute.

    Overall, million-token context is the result of the combined action of architectural compression, data construction, and engineering orchestration. Understanding its memory constraints and hierarchical compression logic is more valuable than memorizing any single module name.