KV Cache Heterogeneous State Governance for Million-Token Contexts
This article explains why prefix cache hit rate is an efficiency metric rather than a correctness guarantee in long-context LLM inference, especially when hybrid attention is involved. It identifies five distinct KV cache object types, describes how the allocator must evolve from free-block search into a state machine, and details the four-layer hit validation and four consistency checks required to prevent silent errors. Readers will learn how to break hit rate into actionable observability metrics and how to plan capacity around memory, swap-in bandwidth, and policy mismatches.
1. Where the Problem Starts: Prefix Cache Hit Rate Is Not a Correctness Metric
In long-context inference serving, teams typically measure resource efficiency by prefix cache hit rate: the higher the hit rate, the less redundant computation occurs and the lower the time to first token. But this metric only describes how many requests are judged reusable at the hash level. It says nothing about whether the result is still correct after reuse. Once context length reaches the million-token range and the model internally mixes multiple attention patterns, hit rate and correctness decouple, and hit rate can even become a dangerously optimistic signal.
Common industry inference frameworks split token history into fixed-size pages and use a page table to map logical pages to physical GPU memory blocks. Requests with identical prefixes share those physical blocks, skipping redundant prefill. This mechanism has run for years on pure full-attention models, but it rests on a very strong implicit assumption: a token’s key-value representation is determined solely by the token itself and its causal history. Therefore, a token-by-token identical prefix is treated as equivalent to “this segment of KV cache can be reused as is.”
Hybrid attention breaks exactly that assumption. Different layers may handle history differently: some layers build a compressed representation over the full history, some keep only a fixed-length sliding window, and others use sparse routing to access only selected history segments. The same logical prefix then maps to cache objects of different forms in different layers, each with its own generation timing, invalidation conditions, and recovery cost. “Identical prefix” is only a necessary condition, no longer a sufficient one.
2. Five Cache Object Types: Lifecycles and Recovery Conditions
Explicitly naming heterogeneous caches is the first step toward governing them. In practice they fall into five categories, and the rest of this article uses this shared set of names.
- Compressed KV: a low-rank or downsampled representation produced by the compression mechanism. It covers the full history but is lossy. Recovery depends on the compressed block being fully persisted and not evicted; if any segment is missing, it cannot be reconstructed through local recomputation.
- Uncompressed tail: a short segment of high-precision keys and values near the current generation position, used to correct the bias introduced by compression. It is appended continuously as generation advances, and once the length threshold changes, the tail boundary must be realigned.
- Sliding window cache: retains keys and values only within the most recent fixed span, with history outside the window actively discarded. The window position is determined by the current sequence length, so the same prefix may be covered by different window ranges across requests.
- Index state: the index structure required by sparse routing, recording which history segments will be selected. It depends on routing parameters and the index configuration fixed during training; when the configuration differs, index results are not transferable.
- Remote prefix: history data swapped out to an external storage tier due to insufficient GPU memory, which must be explicitly swapped back in before it can participate in computation. A hit here only means the data exists, not that swap-in bandwidth and address mapping are ready.
The key difference among these five objects is this: the first four reside in GPU memory or a near tier, and their recovery is synchronous. The fifth crosses tiers, its recovery is asynchronous, and it shows obvious queuing and bandwidth jitter. Any “hit means reuse” implementation that validates only one of these categories will produce silent errors along the remaining dimensions.
3. Upgrading the Allocator from “Find a Free Block” to a State Machine
A traditional allocation action answers only one question: pick a free GPU memory block for the new token and write into it. Prefix matching is a separate action that runs in parallel with allocation: look up reusable blocks in the page table by hash. Decoupling the two is safe under a single cache form, but under heterogeneous forms they must be coupled again.
The allocator needs to record a current form label for each token segment and maintain invariants across state transitions. Illustrative pseudocode:
state = { form, valid_range, generation, backing_tier }on append(token):state = classify(layer_policy, position)block = alloc_empty()write(block, token)record(state, block)on prefix_match(hash):for seg in lookup(hash):if not recoverable(seg, request_policy):return MISS(seg.reason) # must not be counted as a hitreturn HIT(seg)
Here recoverable must check at least: whether the form matches the current request’s layer policy, whether the valid range covers the required span, whether the generation is stale, and whether the backing storage tier can be swapped back within budget. If any condition fails, the result should be downgraded to a miss and routed through recomputation, rather than reported as a hit and then failing downstream with a missing page.
4. Four-Layer Validation for Hit Decisions
To give “hit” executable semantics, complete four layers of validation before returning a hit, tightening at each layer.
- Block alignment validation: compression and page granularity must match, and no half block may appear at cross-block splice points; otherwise the boundaries of the compressed representation become misaligned.
- Compute kernel and binary interface consistency: attention kernels of different versions make different assumptions about cache layout, so the layout version number must match.
- Multi-cache-group state intersection: under hybrid attention, the same prefix involves multiple cache groups, and the intersection counts as a hit only when all groups simultaneously satisfy recovery conditions.
- Byte-level hardware alignment: the starting address, stride, and alignment requirements must match the device side, avoiding a post-swap-in rearrangement that would drive the benefit to zero.
The cost of the four-layer validation is far lower than the cost of recomputing and rolling back one erroneous generation, so it should be a mandatory path rather than an optional optimization.
5. Four Consistency Checks That Must Not Be Violated
- Admission limits: set caps on per-request cache occupancy and swap-in volume to prevent long-context requests from crowding out shared blocks.
- Five-way state routing: route each object type through independent reclamation and swap-in queues so that asynchronous swap-in does not block the synchronous path.
- Check-and-use ordering: the generation must be locked between hit validation and the actual read, preventing time-of-check-to-time-of-use errors caused by eviction in between.
- Static topology constraints: if graph-capture-style execution optimization is used, cache addresses and shapes must remain static, and dynamic changes must explicitly fall back to the normal execution path.
6. Observability and Implementation Recommendations
Break hit rate into three levels of metrics — hash hit, validation passed, and actual reuse — and separately track the distribution of missing reasons across the five object types. Only then can capacity planning distinguish insufficient GPU memory from insufficient swap-in bandwidth or inconsistent policy configuration. On the engineering side, container platforms can provide elastic scaling, object storage can carry the remote prefix, and logging services plus monitoring and alerting can close the loop. When deploying on Baidu AI Cloud, the same recommendation applies: integrate through a combination of general-purpose capabilities and keep the cache layer decoupled from the storage layer.
The conclusion is straightforward: long context and hybrid attention turn prefix caching from a “table lookup” into “state recovery.” Hit rate can continue to serve as an efficiency metric, but correctness must be guaranteed by an explicit state machine, layered validation, and consistency constraints.
