Hierarchical Sparse Attention for Million-Token Contexts: Managing the KV State Lifecycle

    This article examines why million-token context is limited by the full lifecycle of historical KV state—storage, bandwidth, retrieval, and cache-boundary costs—rather than by attention compute alone. It presents a layered architecture that combines cross-head KV sharing, compressed sparse attention (CSA), heavily compressed attention (HCA), sliding-window attention (SWA), layer interleaving, and native sparse training, and it outlines capacity planning and evaluation considerations.

    1. Problem Restatement: The Long-Context Bottleneck Is Not Only Compute but the Entire Lifecycle of Historical State

    When discussing million-token contexts, most analysis stops at the quadratic complexity of attention computation. In real systems, however, the heavier burden comes from the full lifecycle of historical state (KV), from creation to retirement: every historical token leaves behind its key-value state, and every subsequent new token must read, retrieve, move, cache, reuse, and when necessary restore that state.

    As sequence length grows from thousands to millions, four cost curves rise at the same time:

    • Storage cost: KV grows linearly with length and must be multiplied by layers, KV heads, and precision factor.
    • Bandwidth cost: during decoding, every generated token requires moving relevant historical state from GPU memory to compute units; bandwidth, not compute, becomes the ceiling.
    • Retrieval cost: if sparse selection is introduced, the index itself must scan history, and index overhead grows with length.
    • Cache-boundary cost: paged caching, prefix reuse, and cross-request sharing all depend on state layout. Once the layout is replicated per head, boundary efficiency drops immediately.

    Therefore, the core proposition of long-context architecture can be summarized in one sentence: accept an acceptable loss of resolution in exchange for simultaneous reductions in historical-state storage, bandwidth, and retrieval costs.

    2. Cost Decomposition and Layering Principles

    By expanding historical state along two dimensions—distance and resolution—we get a clear responsibility allocation table:

    History range Required resolution Main cost pressure Corresponding mechanism
    Recent window token-level detail bandwidth sliding-window attention (SWA)
    Medium-distance relevant segments block-level, retrievable retrieval + bandwidth compressed sparse attention (CSA)
    Very distant history document-level summary storage heavily compressed attention (HCA)
    Reusable prefix request-dependent repeated computation prefix state sharing

    There are three layering principles: share what can be shared first; compress overly long token-level history before retrieval; and keep only low-resolution global memory for very distant history, covering content that “cannot be lost but does not need fine-grained inspection” at low cost.

    3. Step One: KV Should Not Be Stored Redundantly per Head

    In a million-token context, as long as each group of query heads still stores its own set of keys and values, storage and read bandwidth will be amplified by “layers × KV heads × length,” and the constant factor directly becomes system cost. The three common sharing approaches in the industry compare as follows:

    Type Relationship between query heads and KV State cost Expressiveness
    MHA independent K/V per query head scales with number of heads highest
    GQA a group of query heads shares one set of K/V balanced good
    MQA all query heads share one set of K/V lowest relies on query heads and output projection to compensate

    On this basis, mainstream long-context approaches also add low-rank compression: each token caches only one low-dimensional latent state, which is expanded to each head when used. It differs from a single-set KV main path in that the latter further converges the KV view of the main path to one set; multi-view expressiveness is carried mainly by query heads and output projection rather than by replicating state.

    It is important to emphasize that KV sharing only solves “how many times the same history is stored,” not “there are too many history entries.” The latter requires compression and sparse selection.

    4. CSA: Compress First, Then Select Among Compressed Entries

    Compressed sparse attention works in two steps. First, historical KV is compressed into a significantly smaller number of compressed entries, with each entry aggregating a continuous segment of history. Second, a lightweight indexer scores the set of compressed entries and selects the blocks most relevant to the current query, performing full attention only on those blocks.

    The benefit is composite: fewer entries directly reduce index scanning and bandwidth overhead, and “compress first, then index” avoids the problem that index cost grows linearly with length when top-k selection is performed at raw token granularity. In engineering practice, the indexer is usually placed on a low-precision side path, responsible only for ranking and not participating in the main output, so that extra overhead is kept within an acceptable range.

    5. HCA: Cover Very Distant Context at Extremely Low Resolution

    For history beyond the coverage of CSA, continuing to retain block-level detail is not cost-effective. Heavily compressed attention compresses longer history to a lower resolution, forming a low-cost global memory so that the model can still obtain document-level and topic-level information at very distant positions. Its role is not precise recall but a fallback: ensuring that distant content does not disappear completely while adding almost no storage or bandwidth pressure.

    6. SWA: Preserve Token-Level Resolution for the Recent Window

    Compression and summarization inevitably lose local detail, and the precision of the most recent tokens is especially critical for language modeling. Sliding-window attention preserves uncompressed token-level KV within the recent window, specifically filling the gap in near-end resolution left by CSA/HCA. Window size is an explicit trade-off: too small harms local modeling, while too large reintroduces bandwidth pressure.

    7. Layer Interleaving: Let Different Layers Carry Different Resolutions

    The mechanisms above do not need to be fully enabled in every layer at the same time. A common approach is layer interleaving: some layers retain higher-resolution local and block-level views, while others use only the compressed global path. Since different layers already have different functional roles, interleaving can further lower average state cost while keeping overall quality essentially unchanged.

    1. # Illustrative pseudocode: dispatch historical-state paths by context distance
    2. def hybrid_attention(q, kv_recent, csa_entries, hca_summary, cfg):
    3. o_swa = sliding_window_attention(q, kv_recent, cfg.window) # near-end detail
    4. idx = indexer(q, csa_entries, topk=cfg.csa_topk) # low-precision side path
    5. o_csa = sparse_attention(q, csa_entries, idx) # medium-distance relevant blocks
    6. o_hca = compressed_attention(q, hca_summary) # very distant low resolution
    7. return combine(o_swa, o_csa, o_hca)

    8. Native Sparsity During Training and Engineering Budgets

    If the sparse branch is introduced only at inference time, the state distribution during training and inference will be inconsistent, and long-context extrapolation can easily degrade. A more robust approach is therefore to let the sparse path participate natively in the forward and backward passes during training, so that the model adapts during training to which blocks it should read.

    Capacity planning can be grounded with a simplified estimation formula:

    1. def kv_bytes(layers, kv_heads, head_dim, tokens, dtype_bytes, shared=False):
    2. per_token = layers * (1 if shared else kv_heads) * head_dim * 2 * dtype_bytes
    3. return tokens * per_token

    By plugging in whether sharing is enabled, entry compression ratio, and window size as adjustable parameters, one can compare order-of-magnitude differences in memory and bandwidth across configurations at million-token length. If state must be reused across requests or persisted to disk, it can be handled by general infrastructure capabilities—for example, object storage for prefix state, container platforms for inference instances, and monitoring and alerting for cache hit rates and bandwidth levels.

    9. Evaluation Priorities and Common Pitfalls

    • Perplexity alone is insufficient: evaluate long-range retrieval, local detail reconstruction, and robustness to irrelevant history separately.
    • Higher compression ratio is not always better: over-compression can degrade global memory into noise; observe the inflection point in the quality-versus-compression-ratio curve.
    • Monitor index recall separately: missed index recall may not show up immediately in perplexity, but it will surface in retrieval-style tasks.
    • Do not ignore cache boundaries: if state layout is unfriendly to paging and sharing, theoretical compression gains can be consumed by data movement overhead.

    10. Conclusion

    Architecture competition at million-token context is fundamentally competition in managing the lifecycle of historical state. A viable path is layering: the main path reduces duplicate storage through cross-head sharing and low-rank compression; CSA performs affordable sparse retrieval over compressed entries; HCA covers very distant history at extremely low resolution; SWA preserves near-end detail; and layer interleaving plus native sparse training ensure overall consistency and trainability. Accounting for these five pieces on the same memory and bandwidth budget sheet is a reliable way to judge whether a long-context design is sound.