KV Cache in Hybrid Attention Models: Why a Prefix Hit Doesn't Mean It's Usable
Prefix cache hit rate is often treated as a proxy for correctness, yet in hybrid attention models running million-token contexts with cross-request reuse, a hit no longer guarantees a usable result. This article explains why "computed before" and "usable now" stop being equivalent once layers mix full-history compression, sliding windows, and sparse routing. It breaks down the five cache states a serving layer must track explicitly (compressed KV, uncompressed tail, SWA window, indexer state, and on-disk prefix), and lays out four layers of validation plus four consistency rules that decide whether a prefix hit can be reused directly. It closes with practical guidance on layered recomputation, an "effective hit rate" metric, and consistency testing.
Bottom line first: a hit is not correctness
After an inference engine upgrade exposed a new attention implementation, online monitoring showed the prefix cache hit rate climbing steadily while output quality regressions in long-context scenarios grew more frequent. Problems like this rarely surface as errors or crashes. Instead, the same input produces different results on the “cold start” path versus the “cache hit” path, and they are often hard to reproduce.
The root cause can be stated in one sentence: a prefix cache hit only answers “was this token history computed before,” and cannot answer “can the computed result be used directly right now.” In traditional global attention models, the two answers are essentially equivalent. Once different layers adopt full-history compression, sliding windows, and sparse routing, and once you stack on million-level context, they are no longer equivalent.
This article aims to answer three questions:
- Why does this divergence appear?
- Which cache objects, and which combinations of them, turn a “hit” into “unusable”?
- How should inference serving validate, constrain, and measure this?
Throughout, five names refer to the cache objects that must be tracked explicitly: compressed KV (full-history compressed representation), uncompressed tail, SWA window (sliding window), indexer state (indexer/routing state), and on-disk prefix.
The root cause: the gap between “computed” and “usable”
2.1 Why the default assumption holds
The representative paged caching mechanism—slicing token history into fixed-size blocks and mapping them to physical KV blocks through a page table—is widely adopted because it rests on a strong equality:
KV(block) = F(tokens in the block, all tokens before the block, the block’s position in the sequence)
The meaning is: as long as the token content, the preceding context, and the position all match, each block’s KV is deterministic, regardless of which request computed it, when, or how. Prefix reuse then simplifies to three steps:
- Compute a block-level hash of the token sequence;
- On a hit, point the page table entry to the existing physical block;
- Read KV according to the page table.
The allocator’s main job is simply to pick free physical blocks for new tokens.
This mechanism has run in existing inference frameworks for years. It carries three implicit assumptions: KV is stored as per-token key/value; attention covers all history; and layers are structurally homogeneous. Hybrid attention challenges the first two at the same time.
2.2 Hybrid attention: a “block” is no longer a complete semantic unit
Hybrid attention lets different layers in the same model use different attention structures. Three common types are:
- Full-history layers: attention over the compressed full history. Cheap, but whether the representation is accurate depends on the compression strategy—and the compression strategy determines whether “computed” equals “usable.”
- Sliding window layers: attention over only the most recent W tokens. Cheap and naturally bounded, but KV outside the window is no longer used at that layer, and the window’s boundary depends on how far the request has progressed.
- Sparse routing layers: a lightweight indexer selects a few historical tokens for the current token to attend to. Compute is controllable, but “which history to look at” depends on the current token, so it is bound to the query content.
As a result, the same logical block maps to three different objects across three cache groups:
| Cache group | Cached object | Lifespan | Recoverable as a whole? |
|---|---|---|---|
| Full-history layer | compressed KV + uncompressed tail | Rolling updates with the compression strategy | Conditional: depends on whether compression is chunkable |
| Sliding window layer | SWA window | Invalidated as the window slides | No: only valid within the window |
| Sparse routing layer | indexer state (swapped out/in together with the on-disk prefix) | Invalidated on swap out/in | No: must be rebuilt |
KV(block) in the original equation is no longer a single object but a Cartesian product of “block × layer type,” where every cell has its own lifespan and recovery path. “Same prefix → direct reuse” therefore breaks down.
2.3 Million-level context: pushing state beyond VRAM
Even with compression, full-history layers still produce KV that grows linearly with context. For requests with speculative decoding, the draft model additionally maintains its own KV. Add high concurrency, and at million-token context lengths a single GPU can no longer hold all the KV. The system can only store it in tiers:
- GPU VRAM: hot data;
- Host memory: warm data;
- Local disk or a cold tier such as object storage: swapped in and out on demand.
Layering adds three things to caching:
- Swap in/out: each block may be “logically present but physically absent” at any moment.
- Serialization: different cache groups have different object layouts, dtypes, and lengths, so serialization rules must be defined per group.
- Hot/cold imbalance: the most recent tokens change most frequently, forming an “active zone” where compression, tail, and sliding window overlap; the older the history, the more stable it is, yet it sits in the coldest tier.
More critically, swap in/out amplifies TOCTOU problems (see 3.3). The same prefix that was in VRAM when computed may still be migrating back the next time it is reused.
2.4 Cross-request reuse: state must be migratable
System prompts, few-shot examples, retrieved documents, and multi-turn conversations cause many requests to share the same prefix. Sharing is only valid if the prefix’s state can migrate losslessly to a new request:
- In multi-turn conversations, each turn appends new input/output after the existing KV, so KV advances turn by turn;
- Different users may share the same knowledge-base document prefix;
- Forked sampling within the same request shares the entire prefix via copy-on-write.
Migration must handle three kinds of boundaries:
- Partial block boundaries: only complete blocks participate in matching;
- Position offsets: if the prefix is trimmed or repositioned, position encoding must be recomputed accordingly;
- Lateral effects: both sliding windows and sparse routing require that the context boundaries carried over during reuse match those of the original request exactly.
The token hash in the original equation does not cover these states. “Same prefix” is therefore a necessary but not sufficient condition.
KV cache: the prefix hits, but the cache state may not be correct
3.0 Five states at a glance
Figure 1: KV cache states and validation relationships in hybrid attention models
- Left | Trigger conditions (three input scenarios):
- The three hybrid attention layer types used together;
- A 1M context that exceeds GPU capacity;
- Cross-request reuse;
- All three together push cache state beyond what any single rule can cover.
- Middle | Five states and recovery paths (the serving layer must track them explicitly):
- compressed KV → re-compress;
- uncompressed tail → fill the tail;
- SWA window → trim or recompute;
- indexer state → rebuild the index;
- on-disk prefix → migrate back and validate.
- Right | Four validation layers: whole block, kernel ABI, multi-cache-group state intersection, and byte-level hardware alignment. Together they decide whether a prefix hit can directly continue computing.
- Bottom | Four consistency rules (the allocator state machine must never violate them):
- admission cap;
- five-state routing;
- TOCTOU and state_data_ptrs;
- CUDA Graph static topology.
A common misconception is: as long as the physical block is still there and the hash matches, it can be reused. A library analogy helps:
- In a traditional global attention model, a call number is enough. There is exactly one book on the shelf, its content is fixed, and anyone retrieving it at any time gets the same book.
- In a hybrid attention model, each “call number” corresponds to five interrelated books:
- compressed KV: a standard edition under continuous revision, so you must confirm you are citing the same version;
- uncompressed tail: unbound loose pages—if they are lost, they must be reprinted;
- SWA window: a borrowing valid for only the most recent W pages, where expired pages can no longer be cited;
- indexer state: a table-of-contents card set that is constantly rearranged as new chapters arrive—if it is not updated, you will turn to the wrong page;
- on-disk prefix: a bound volume stored in a remote warehouse that no one may open until it is retrieved.
Only when all five books are in place, version-consistent, and the index is synchronized is the “hit” truly usable.
3.1 Five states, one by one
3.1.1 compressed KV: only “chunkable” compression can be reused as a whole
- What it is: full-history layers attend over the compressed history, and the original token sequence no longer resides item by item.
- Lifespan: the same as the full-history layer, but it changes with the compression strategy’s version or refresh cycle.
- Hit determination: the hash must include the compression strategy and version identifier, not just the token hash.
- Recovery condition: compression must decompose into “a per-token transform + a rolling update along the causal direction,” so each block’s compressed representation depends only on its own tokens and the context before them. If compression mixes in future tokens, or re-normalizes at refresh points, it cannot be recovered as a whole and must be re-compressed from the original tokens. This is why partial recomputation must be prevented from producing a “partially new, partially old” compression state.
- Typical error: comparing only the token hash while ignoring that the compression version has been upgraded.
3.1.2 uncompressed tail: the hit is the old prefix, the missing part is the latest tokens
- What it is: to control compression error and preserve precision for the most recent content, the last several tokens always keep their original KV and are not compressed.
- Lifespan: new tokens are generated as generation advances; old tokens are either compressed and folded into compressed KV, or evicted.
- Hit determination: the tail length and boundary must match the original request.
- Recovery condition: the tail must be backed by the original token sequence or original KV. Missing parts can only be recomputed, and they must connect correctly to the current compression state, so that the same token is neither both compressed and counted as-is.
- Typical error: treating the “hit prefix length” directly as the “reusable length,” when this prefix’s tail state has already changed.
3.1.3 SWA window: the same prefix, different positions, different availability
- What it is: sliding window layers keep only the KV of the most recent W tokens; outside the window, tokens no longer participate in attention at that layer.
- Lifespan: entries expire as the window slides past, and expired blocks can be reclaimed.
- Hit determination: the effective usable length along the sequence—after taking the minimum across groups—is the intersection of the “shared prefix” and the “sliding-window usable range.”
- Recovery condition: the window boundary must align precisely with the request’s current processed length. For blocks that are valid only within the window, parts outside the boundary cannot rely on the hit and must be trimmed or recomputed.
- Typical error: a cache group can only be reused up to the k-th token, yet it is let through by the full prefix length.
3.1.4 indexer state: an “additional cache” bound to the query position
- What it is: sparse attention usually has a lightweight indexer produce scores and then attend over the top-k historical tokens. The indexer keys tied to this history, and the metadata the index relies on (position-numbering scheme, chunking or compression mapping), belong to this state.
- Lifespan: the same as the corresponding KV block; once the KV is swapped out/in, it must be rebuilt accordingly.
- Hit determination: you must confirm the index coverage includes the complete prefix.
- Recovery condition: indexer keys are computed from token content and naturally migrate with the KV, whereas index metadata depends on the load path. If indexer scores are not restored after swap in/out, the index will be missing or misaligned, ultimately routing to the wrong historical tokens—and this kind of error usually does not raise an error.
- Typical error: reusing only the KV while dropping or mismatching the index.
3.1.5 on-disk prefix: a hit does not mean it is present
- What it is: an entire prefix that has been swapped out to disk or a cold tier.
- Lifespan: it resides in the cold tier until it is swapped back or evicted.
- Hit determination: you must distinguish “logical presence” from “physical presence.”
- Recovery condition: it must first be migrated back, then pass a checksum validation and a byte-level alignment check, and finally complete the page table update; only after all three steps may reads proceed.
- Typical error: issuing the hit before migration completes. The result is either reading stale or uninitialized data, or stalling mid-run on a swap-in, which shows up as pronounced long-tail latency.
3.2 Allocator: from “finding empty blocks” to “maintaining a state machine”
Once cache objects become heterogeneous, the allocator’s job changes. Traditional allocation only answers “where is a free block,” but now it must also answer “what form is each token segment currently in.” Otherwise, this failure chain occurs:
- The hash lookup that runs parallel to prefix matching in the cache manager reports a hit by token hash;
- The allocator treats it as an ordinary free block;
- At the actual read, it turns out the tail, the sliding window, or the index is missing;
- The generated output is wrong—and often no error is raised.
Therefore, each cache segment must explicitly record at least:
- cache group;
- form (one of the five, or a combination);
- physical location;
- version number;
- alignment attributes.
// Illustrative pseudocode: for concept explanation onlyenum class CacheKind { kCompressed, kTail, kSwa, kIndexer, kOnDisk };struct SegmentMeta {uint64_t prefix_hash; // token content hashCacheKind kind; // current formuint32_t group_id; // owning cache groupuint64_t block_id; // logical block numberuint32_t phys_idx; // physical location indexuint64_t version; // increments on every state changeuint32_t reserved_len; // number of tail tokensuint32_t win_left; // sliding window left boundarybool aligned; // whether byte-level alignment passed};// State machine: every form change must atomically update metadata and increment the versionvoid transition(SegmentMeta& s, CacheKind next, uint32_t phys_idx) {s.kind = next;s.phys_idx = phys_idx;s.aligned = check_align(phys_idx);s.version++; // basis for TOCTOU validation}
The four consistency rules (admission cap, five-state routing, TOCTOU and state_data_ptrs, CUDA Graph static topology) are constraints the state machine must never violate. The four validation layers are covered in 3.3, and the four consistency rules in 3.4.
3.3 Four validation layers: can a prefix hit directly continue computing?
| Layer | Validation target | Handling on failure |
|---|---|---|
| 1. Whole block | Whether the match falls on a complete token block boundary | Truncate to a complete block, recompute the tail |
| 2. Kernel ABI | Layout, dtype, and head split match the executing kernel | Reject reuse, rebuild with the current kernel |
| 3. Multi-cache-group state intersection | Available length along the sequence for each cache group | Take the shortest usable length, recompute the rest |
| 4. Byte-level hardware alignment | Start address, length, and cross-rank split | Reject reuse, or align first and then reuse |
Layer one: whole block. The prefix match must fall on a complete token block boundary; an incomplete tail block does not participate because it changes as generation proceeds. Just as important is a consistent “block size.” If the same history is written with two different block sizes (say A uses 16 and B uses 32), it cannot be reused even if the tokens are identical, because the boundaries for compression, indexing, and sliding windows all change with block size. For the same reason, the tokenizer version, model version, and parallel splitting scheme (tensor parallel degree, number of pipeline stages) must also be consistent.
Layer two: kernel ABI. The “same logical block” can be a completely different byte sequence in the eyes of different execution kernels. Global attention typically stores key/value separately per head; MLA-style compressed attention projects key/value into a low-rank latent and stores it uniformly, with only one entry per token and a different shape. If the kernel that writes the cache and the kernel that reads it have different layout conventions but share the same physical memory, the reader will interpret the latent’s bytes according to the key/value shape. The result is usually not a crash but a silent numerical error.
This is not caused by new models; it stems from a capability inherent to the paged mechanism: physical blocks can be reused by any request, and therefore by kernels of different structures. The same reasoning applies when the modality, quantization format (fp16/bf16/fp8), or parallel splitting changes.
Layer three: multi-cache-group state intersection. Under hybrid attention, hits are usually determined per cache group. But the length that can truly be reused is:
reusable length = min(available length across all cache groups)
And it must satisfy two conditions:
- the token-to-block mapping of each cache group corresponds one-to-one;
- all cache groups’ sliding window boundaries (if any) match the request position.
Taking the minimum is because, under hybrid attention, the most fragile layer determines the overall usable boundary. For example, if an SWA-type cache group keeps only the most recent W tokens while the compression group keeps the entire history, then the upper bound on reusable length is W.
Layer four: byte-level hardware alignment. Moving KV ultimately lands on hardware paths such as memory, PCIe, the NIC, and SSDs. A swap in/out can use zero-copy or batched DMA only when:
- the start address is aligned;
- the length is aligned;
- the cross-rank split is aligned.
A common constraint is that “the transfer size is an integer multiple of some byte count.” If a cache group moves only one head’s KV at a time, and that head’s KV byte count is not an integer multiple of the alignment unit, it triggers many small transfers, forcing either per-token movement or wasted prefetch. These issues usually do not raise errors; they simply show up as slower swap in/out. So alignment is not a performance optimization but part of correctness: an unaligned read may cross into an adjacent physical block or read uninitialized bytes.
// Illustrative pseudocodebool can_reuse(const Req& r, const Block& b) {// 1) whole blockif (r.matched_len % BLOCK_TOKENS != 0) return false;// 2) kernel ABIif (b.layout != current_kernel_layout()) return false;// 3) multi-cache-group state intersectionuint32_t usable = r.matched_len;for (auto& g : r.groups) usable = std::min(usable, g.usable_len(r));// 4) byte-level hardware alignmentfor (auto& seg : r.segments_of(usable))if ((seg.addr % kAlign != 0) || (seg.bytes % kAlign != 0)) return false;return true;}
3.4 Four consistency rules
Rule one: admission cap
- Purpose: cap the total KV resident at once, avoiding the “higher hit rate, more swap in/out” thrashing.
- Key points: the admission decision must consider VRAM, host memory, and the cold-tier budget together, as well as migration bandwidth. A million-context request may occupy tens of GB of KV; if several such requests are admitted at once, swap in/out crowds out compute bandwidth and P99 latency actually worsens.
Rule two: five-state routing
- Purpose: different forms take different recovery paths.
- Key points: compressed KV → re-compress; uncompressed tail → fill the tail; SWA window → trim or recompute; indexer state → rebuild; on-disk prefix → migrate back and validate.
- Forbidden: collapsing all five into a single “hit means use” judgment.
Rule three: TOCTOU and state_data_ptrs
- Purpose: prevent “valid at check time, changed at use time.”
- Key points: prefix matching happens at the admission stage, while the actual read happens at the execution stage; between them lie scheduling, batch assembly, swap in/out, and compression updates. The page table pointers in the allocator or cache manager (referred to here as state_data_ptrs) may already have been swapped out or remapped after the check.
- Approach:
- re-validate the version number on the read path;
- reference-count or pin blocks that are about to be reused;
- on validation failure, degrade to partial recomputation rather than using them directly.
Rule four: CUDA Graph static topology
- Purpose: ensure semantics are unchanged during replay after addresses are fixed during capture.
- Key points: some inference engines use CUDA Graph to capture each step’s scheduling and kernel launches into a static graph, where addresses, shapes, and dependencies are all fixed at capture time. If a cache group’s page table is updated after capture, or swap in/out changes a physical address, the replay uses the old address.
- Approach:
- fix the physical location and metadata layout of all reusable blocks before graph capture;
- during capture, do not allow swap out, compression updates, or form changes;
- if that cannot be guaranteed, run that step in non-graph mode, or re-capture.
3.5 Self-check list
| Check item | Pass criteria |
|---|---|
| Cache key | Includes tokenizer version, model version, block size, compression strategy version, and parallel splitting scheme |
| Partial block | Incomplete tail blocks do not participate in matching |
| Block size | Globally consistent, no mixing allowed |
| Kernel ABI | Write and read layouts and dtypes match |
| Multi-cache group | Usable length is the intersection, and the token-to-block mapping is one-to-one |
| Sliding window boundary | Matches the request’s current length |
| Indexer | Coverage is complete, metadata restored together with the KV |
| Swap in/out | Hit is issued only after migration completes and validation passes |
| Byte alignment | Address and length satisfy hardware constraints |
| TOCTOU | Version number re-validated before the read |
| CUDA Graph | Addresses stay stable during capture |
Practical recommendations
1. Replace “hit and use” with “layered recomputation.” Judge the hit prefix segment by segment per cache group, and recompute only the parts that fail validation. For example, when the compression group hits but the sliding window group misses, you only need to compute the sliding window layer for tokens within the window range. This is far cheaper than recomputing the entire prefill.
2. Make “effective hit rate” a core metric. Hit rate only reflects the lookup stage. At a minimum, add three metrics:
- Effective hit rate: tokens actually reused and validated / tokens theoretically reusable;
- Swap in/out ratio: number of swap in/outs triggered per 1000 output tokens;
- Cold-start vs hit-path output consistency (under greedy decoding, the log probs should match token by token).
3. Cover state changes with consistency tests. Four case types are recommended, all comparing output across the “pure cold start” and “hit” paths:
- Prefix extended turn by turn;
- Multi-turn conversation;
- Prefix trimming and repositioning;
- Simulated swap in/out.
4. Layered hosting for cloud deployment. When deploying inference services on cloud platforms such as Baidu AI Cloud, you can host by hot/cold tiering:
- Hot data stays in GPU and host memory;
- Warm and cold prefixes can use an object storage’s batch loading and version-management capabilities;
- The container platform scales elastically with load;
- A monitoring and alerting service sets thresholds for effective hit rate, swap in/out ratio, and end-to-end P99 latency.
Note that these are only general product-category capabilities; the specific capability boundaries should follow the documentation of the products you actually use.
5. Move consistency validation forward into CI. During model version upgrades, compression strategy changes, or inference engine upgrades, automatically run the “cold start vs hit” consistency cases. These regressions are usually not performance problems but correctness problems, and they are the hardest to catch through monitoring.
Summary
The effectiveness of a prefix cache depends on whether “computed” can be converted into “usable.” Three trends—hybrid attention, million-level context, and cross-request reuse—together push cache state into a situation that no single rule can cover:
- the allocator must maintain a state machine;
- matching must pass four validation layers;
- consistency must be backed by four rules.
In practice, a suggested order is:
- First establish state visibility: make the five states observable;
- Then establish a consistency baseline: add the output consistency cases;
- Finally optimize hit rate: use the effective hit rate as the core metric.
This improves performance in high-compression, heavy-offload scenarios while keeping output predictable.
