KV Cache Reuse with Mixed Attention: What to Validate After a Prefix Hit

    In heterogeneous LLM architectures that mix full attention, sliding-window attention, and sparse routing, a matching prefix hash no longer guarantees that cached KV data is reusable. This article explains the five distinct cache states that must be tracked, the four validation layers required after a prefix hit, the consistency constraints the allocator must enforce, and practical engineering advice for keeping cache reuse correct—since silent quality degradation, not exceptions, is the typical failure mode.

    Why an Identical Prefix Does Not Guarantee Reuse

    LLM inference services typically store the Key and Value tensors of historical tokens in GPU memory, known as the KV cache. Paged management is the mainstream approach: the inference framework splits token history into fixed-size pages and maps them to physical KV blocks via a page table. If two requests share an identical prefix of tokens, the scheduler can reuse the already-computed blocks and skip redundant prefill computation. On standard full-attention models, this hash-based prefix matching mechanism has been stable in production for years.

    The problem arises when the model architecture changes. In heterogeneous models, different layers may use different attention forms: some layers retain full history with compression, some attend only to a sliding window, and others use sparse routing to select a small number of historical positions. As a result, the same prefix has different cache representations across layers. A hash match only proves the tokens are identical—it says nothing about whether each layer’s cache is in a readable state.

    An analogy helps here. In a standard model, finding a cache block is like looking up a shelf number in a library—you just take the book. In a heterogeneous model, after finding the block you must verify each item: does the compressed history still exist, has the recent uncompressed tail been written, is the data within the sliding window valid, is the index state in sync with the content, and has the prefix been swapped out to external storage? Only when all five checks confirm recoverability can computation proceed.

    Five Cache States and Their Recovery Rules

    Each state has a distinct lifecycle, recovery condition, and hit criterion, so they must be modeled separately.

    State Meaning Recovery condition Hit criterion
    Compressed KV Representation of long history after compression Compressed blocks are complete and match the current model version Compressed blocks cover the required prefix length
    Uncompressed tail Most recent tokens that have not yet filled a compression granularity Tail data is written and readable Tail length matches the current position
    SWA window Raw KV retained within the window Data within window boundaries is complete Window start matches the position required by the request
    Indexer state Index structure used by sparse routing Index is updated in sync with content blocks Index version matches content version
    On-disk prefix Prefix swapped out to slower storage Read-back completes and verification passes Counted as a hit only after read-back completes

    The on-disk prefix requires special handling. Its hash record still exists, but the data has not returned to GPU memory. The system should distinguish between “record exists” and “state is ready”—only ready prefixes may participate in computation.

    The Allocator Must Track State Forms

    A traditional allocation step only picks a free block for new tokens and writes to it. With heterogeneous caching, the allocator must also record the current form of each token segment: whether it is in compressed, tail, window, index, or on-disk state. Prefix matching is a separate action alongside allocation; it determines reusable length based on the hash. If matching looks only at the hash while reading lacks the tail, window, or index routing, generation results will be wrong. Such errors usually do not raise exceptions—they only manifest as degraded output quality, making them expensive to debug. Therefore, match results must pass state validation before being handed to compute kernels.

    Four Validation Layers

    After a hit, the system must pass four checks to confirm reuse is feasible.

    1. Block-length alignment: Different cache groups may have different block sizes. Use the least common multiple of block lengths as the alignment unit, and only reuse complete whole blocks.
    2. Kernel interface compatibility: The reused data layout must conform to the compute kernel’s interface contract, including dimension order and data types.
    3. Intersection of multi-group states: Every cache group must be in a usable state; the final match length is the intersection of usable lengths across all groups.
    4. Byte-level hardware alignment: The data’s starting address and length must satisfy hardware memory-access alignment requirements, otherwise illegal access or performance degradation may occur.

    Four Consistency Constraints

    The allocator’s state machine must never violate the following rules at any point.

    1. Admission limits: Before a new request is admitted, sufficient blocks must be reserved. Long-context requests must not crowd out other requests’ cache space, which would cause frequent swaps and read-backs.
    2. State-based routing: Each prefix enters the recovery path corresponding to its current state. Different states use their own read logic and must not share the same processing flow.
    3. Race protection: Between matching and reading, a cache block may be swapped out or rewritten. Before reading, snapshot key pointers and validate versions to guard against state changes between time-of-check and time-of-use.
    4. Static graph topology: If GPU static graph capture is used to reduce scheduling overhead, tensor addresses and shapes in the graph must be fixed. Cache pointer changes should be handled indirectly through pre-agreed slots, and the topology must not be modified while the graph is running.

    Illustrative Implementation

    The pseudocode below shows the matching flow. It is for illustrating decision order only, not a real interface from any framework.

    1. def match_prefix(request, cache):
    2. # 1. Find candidate prefix by token hash
    3. candidate = cache.lookup_by_hash(request.tokens)
    4. if candidate is None:
    5. return 0
    6. # 2. Check state per group, take the intersection of recoverable lengths
    7. length = candidate.length
    8. for group in candidate.state_groups():
    9. length = min(length, group.recoverable_length())
    10. if length == 0:
    11. return 0
    12. # 3. Align to the LCM of block lengths, reuse only whole blocks
    13. aligned = align_down(length, cache.block_lcm)
    14. # 4. Snapshot and validate version to prevent state changes during read
    15. snapshot = candidate.snapshot(aligned)
    16. if not snapshot.is_valid():
    17. return 0
    18. return aligned

    Engineering Recommendations

    • Split hit determination into two phases: “record exists” and “state is ready”. While on-disk data is being read back, do not count the corresponding prefix as a hit.
    • Set up independent metrics for each state type—for example, hit counts, read-back latency, and validation failure counts per state—to make troubleshooting easier.
    • Before deployment, compare outputs with caching enabled versus disabled using fixed inputs, confirming that reuse logic does not change results. Cache hit rate measures efficiency only; it does not prove correctness.