Long-Context LLM Inference at Million-Token Scale: Engineering a Tiered KV Cache Runtime

    This article breaks down what actually bottlenecks million-token LLM inference and how to engineer around it. It explains why KV cache capacity and bandwidth, not parameter count, become the binding constraint at long context, and why mixed attention (sliding window, block-compressed, and sparse global) forces the runtime to treat KV state as a heterogeneous, multi-pool resource with different eviction rules. It then covers a two-level logical-to-physical pool mapping, shadow indexes for prefix caching that stay compatible with CUDA Graph, pipelined compression and lightweight TopK selection to cut memory movement, isolating speculative decoding state from committed prefix cache, PD disaggregation with block-aligned context parallelism, and the observability metrics and capacity formulas needed to tune such a system.

    1. Reframing the Problem: The Bottleneck Is Not Bigger Parameters

    As context length grows from tens of thousands of tokens into the million-token range, the pressure points in an inference system shift. Parameter count determines the resident cost of weights in GPU memory, while context length determines the per-request state space and the memory-access intensity of attention computation. A pattern widely observed in the industry is that in long-context scenarios, the capacity and bandwidth cost of the KV cache tends to become a constraint before compute does. The scheduler has to answer three questions at once: where state lives, how much of it is reused, and when it gets compressed.

    The new generation of sparse and compressed attention schemes discussed in the source material essentially reduce state size at the model-structure level. But structural changes propagate to the runtime immediately: an inference engine can no longer treat the KV cache as a homogeneous resource with “one raw K/V tensor per layer.” It must manage it as a heterogeneous resource with multiple pools, multiple granularities, and multiple lifetimes. That is the main thread of this article.

    2. State Space Tiering Under Mixed Attention

    A typical long-context model mixes three types of attention across different layers and different token ranges:

    • Sliding window attention (local attention): attends only to a fixed recent window of tokens. State is reclaimable, but it requires precise ring or physical pool mapping.
    • Block-compressed attention: compresses consecutive tokens into low-rank or mean representations, forming a “coarse-grained pool” that significantly lowers the cost of long-range access.
    • Hierarchical/global attention (sparse global): performs high-precision interaction on a small set of global anchors to keep long-range information from being lost.

    One fact has to be accepted in engineering: these three kinds of state have different eviction rules. Local state is evicted as the window slides, compressed state is rebuilt on block boundaries, and global anchors are almost always resident. Applying a single LRU-style eviction causes both fragmentation in the local pool and repeated computation in the compressed pool. A workable approach is a two-level mapping from “logical coordinates to physical pools”: the logical side keeps full-token coordinates to support prefix reuse and positional-encoding consistency, while the physical side allocates per pool type.

    A sketch of the pool management abstraction:

    1. class KVStateManager:
    2. def __init__(self):
    3. self.full_coord = {} # token logical coordinates
    4. self.swa_pool = RingPool() # local window physical pool
    5. self.c4_pool = BlockPool(block=4)
    6. self.c128_pool = BlockPool(block=128)
    7. self.index_pool = IndexPool()
    8. self.compress_state = CompressStatePool()
    9. def admit(self, seq_id, token_pos):
    10. # Register the logical coordinate first, then place it into
    11. # different physical pools by layer type
    12. self.full_coord[(seq_id, token_pos)] = self._alloc_by_layer(token_pos)

    3. Prefix Caching: From Prefix Trees to Shadow Indexes

    The core benefit of long-context serving comes from prefix reuse: system prompts, long documents, and multi-turn history are often highly repetitive. The problem with a traditional prefix tree at million-token context is node-count explosion and degraded matching. A more robust idea is to maintain a “shadow index”: the real KV stays in the tiered pools, while the index side stores only compressed fingerprints and block-level summaries. Matching first queries the summary, then verifies, then loads on demand. This drops matching complexity from token level to block level and naturally tolerates compressed-pool rebuilds.

    One engineering constraint deserves emphasis: the shadow index must be compatible with CUDA Graph (or an equivalent computation-graph capture). If the index structure changes at every step, graph capture fails repeatedly. In practice, a “fixed capacity plus generation markers” approach folds structural changes into a static shape that can be captured.

    4. Compression and Sparsity: Turning “Compute Less” into “Move Less”

    The value of compressed attention is not only fewer computations, but more importantly less data movement over HBM and interconnect bandwidth. Three implementation points:

    1. Pipeline compression with computation: the compressor incrementally updates block summaries on a background thread or stream, and the main attention consumes only summaries that are ready, avoiding synchronous waits.
    2. Lightweight indexing for TopK selection: global sparsity needs to select top-k anchors. Scoring everything every time gives the gains back; use a two-stage strategy of approximate scoring over a low-dimensional index followed by exact reranking.
    3. Coordinate compressed state with offload: when cold blocks are pushed down to host memory or remote storage, compressed summaries should be retained first, since they are the smallest and cheapest to restore.

    5. Scheduling Coupling of Multi-Token Prediction and Expert Parallelism

    Speculative decoding (predicting several tokens and then verifying) pays off notably at long context, but it amplifies the burstiness of state writes. Mixture-of-experts parallelism (data, tensor, and context parallelism) introduces cross-rank state consistency costs. The coupling point between them: temporary state within the speculative window must not pollute the committed prefix cache. The engineering answer is isolation via a “staging area plus commit point”: verification failure rolls everything back, and success merges in one shot.

    On deployment shape, separating prefill from decode (PD disaggregation) has become a common approach. The prefill cluster consumes compute and long-sequence memory access, the decode cluster consumes memory capacity and low-latency scheduling, and the two are bridged by block-level state transfer. Context parallelism is used to split a single ultra-long sequence across multiple GPUs; the split boundaries should align with compression block boundaries, otherwise substantial cross-GPU recomputation appears.

    6. Observability and Capacity Planning

    The tuning space of a long-context system is enormous, and without observability it will not converge. At minimum, collect: hit rate and fragmentation rate per pool, number of compressed-block rebuilds, speculative acceptance rate, volume of cross-rank state transfer, and number of graph-capture failures. For capacity planning, estimate the lower bound of GPU memory as “peak concurrency × average context × state bytes per token,” then add the compression ratio and offload ratio to arrive at the actual configuration.

    7. Conclusion

    Shipping million-token long context is not a matter of swapping in a larger model. It means unifying mixed attention, tiered caching, compressed sparsity, speculative decoding, and parallel deployment into a single observable, tunable runtime. In its own inference service practice, Baidu AI Cloud likewise emphasizes the coordination of tiered caching and elastic parallelism, which can serve as a general reference for architecture design.