Prefix Cache Validation for Heterogeneous KV Cache States

    This article discusses how prefix caching in large language model inference must handle heterogeneous KV cache states introduced by models with mixed attention mechanisms. It identifies five state types that require explicit tracking—compressed KV, uncompressed tail, sliding window content, indexer state, and on-disk prefix—and proposes a four-level validation scheme for prefix hit decisions, along with allocation state tracking and consistency constraints for practical implementation.

    Background: The Classical Assumption of Prefix Caching

    In autoregressive inference, each new token’s computation depends on the Keys and Values of all previous tokens, collectively referred to as the KV cache. When the same prefix is reused by multiple requests, inference frameworks cache this portion and directly reuse it for subsequent requests with the same prefix, skipping redundant forward computation. This is a core technique for reducing time-to-first-token and increasing throughput.

    A common practice is to divide the token history into fixed-size blocks and use a page table to map logical positions to physical GPU memory blocks. Requests sharing the same prefix map their logical blocks to the same physical blocks, so reuse becomes a simple table lookup. This design relies on an implicit assumption: the cache content for the same prefix is identical, and as long as the corresponding blocks are found, the cache can be used directly.

    In models where all layers use the same attention mechanism, this assumption largely holds. The cache content depends only on the token sequence, and block hit detection only needs to check whether a hash or index exists.

    Heterogeneous Cache Breaks the Single Rule

    When different layers of a model use different attention mechanisms, the assumption fails. Common forms include:

    • Full-history compression: compress earlier historical tokens and keep only a compact representation.
    • Sliding window attention (SWA): attend only to tokens within a recent window; KV outside the window is no longer used in computation.
    • Sparse routing: use an index structure to select a small number of relevant positions for each query, accessing only the KV of those positions.

    Each of these mechanisms stores different cache content. The lifecycle of compressed representations differs from that of sliding-window content, and sparse routing additionally relies on an index state. Thus, the same prefix may exist in multiple forms in the cache: some parts complete, some missing, some already swapped out to slow storage.

    Long-context scenarios amplify this problem. When context length exceeds the capacity of a single GPU’s memory, some cache must be offloaded to host memory or disk. During cross-request reuse, different requests may have different sampling parameters, window positions, or index versions, further exacerbating state divergence.

    At this point, simply checking whether a block exists is insufficient. Hit detection must answer: can every type of state for this prefix be restored to the point where computation can continue?

    Five State Types That Need Explicit Tracking

    Below we illustrate the recovery conditions for five state types, using generic names for discussion. Actual implementations vary by framework and model architecture.

    3.1 Compressed KV

    Compressed KV holds a compact representation of earlier history. Its recovery condition typically requires that the compressed blocks for the token range are fully written and that the compression parameter version matches the current model.

    The check must verify completeness, not mere existence. If compression was only partially completed, reading it directly will produce incorrect attention distributions.

    3.2 Uncompressed Tail

    Since compression is usually applied at fixed granularity, the trailing tokens that do not fill a complete compression unit are stored in raw KV form. This tail must be complete and its length aligned with the compression boundary.

    Missing tails are the most easily overlooked issue. The compressed portion may be intact, but if the KV for the last few tokens is not written, generation will diverge at the first new token.

    3.3 Sliding Window Content

    The sliding window state requires that all KV within the window range are accessible in the storage hierarchy. The window’s start and end positions depend on the current sequence length, so for the same prefix, the window position and availability differ across requests with different lengths.

    For recovery, if some blocks in the window reside in slow storage, they must be migrated back to faster storage before computation can proceed.

    3.4 Indexer State

    Sparse routing depends on an index structure. The index state must remain synchronized with the KV content—i.e., the positions recorded in the index correspond one-to-one with the current KV block contents.

    If KV is updated but the index is not yet synchronized, sparse routing will select incorrect positions, and the model’s output will deviate. The version numbers of the index and KV must be checked as part of the recovery condition.

    3.5 On-Disk Prefix

    When cache is swapped out to disk or remote storage, the prefix remains valid but cannot directly participate in computation. Recovery involves three steps: read, deserialize, and refill GPU memory.

    For disk-resident prefixes, the check must distinguish between “a record exists” and “is ready”. A record only indicates that the data is somewhere; it is not usable until refilled.

    The following table summarizes the key checks for the five state types:

    State Primary Recovery Condition Common Failure Mode
    Compressed KV Compressed blocks complete, parameter version matches Interrupted compression, reading partial results
    Uncompressed tail Tail tokens complete, aligned with compression boundary Tail not written
    Sliding window content All blocks in window accessible Window blocks still in slow storage
    Indexer state Synchronized with KV version Index stale, routing errors
    On-disk prefix Refilled to GPU and validated Only a record exists, data not ready

    State Forms the Allocator Must Track

    A traditional allocator’s job is simple: find free GPU memory for new tokens and write their KV. With heterogeneous caches, the allocator must also record which form each segment of tokens currently has. Otherwise, the prefix matching module reports a hit based on a hash, but at read time the tail or window may be missing, leading to errors.

    One workable approach is to maintain a state descriptor for each logical block. The following is a schematic data structure; field names are illustrative:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class BlockState:
    4. token_start: int # start token position covered by the block
    5. token_end: int # end token position covered by the block
    6. compressed_ready: bool # whether compressed KV is complete
    7. tail_ready: bool # whether uncompressed tail is complete
    8. window_ready: bool # whether sliding-window content is accessible
    9. indexer_synced: bool # whether index state aligns with KV
    10. location: str # "gpu" / "host" / "disk"
    11. version: int # model parameter or index version

    The allocator updates these fields on write and swap-out. During prefix matching, in addition to hash hit, these fields must be read to decide whether the hit can be used directly.

    Four-Level Validation for Hit Decisions

    After a prefix hit, we recommend a four-level validation, each level in sequence. If any level fails, fall back to recomputation or wait for migration.

    1. Block alignment: The hit length must be a common multiple of the granularities of all cache types. Different states may have different granularities (e.g., compression unit vs. paging block). In that case, use the least common multiple as the smallest reusable unit. Only fully aligned parts can skip computation.

    2. Kernel interface consistency: The computation kernel has fixed requirements on input layout. If the cache layout differs from what the kernel expects, the data cannot be read directly even if the numerical values are correct. The check must confirm that the layout version matches the kernel version.

    3. Intersection of multiple cache groups: A request may depend on multiple cache groups simultaneously. The reusable length should be the intersection of all groups that are ready. For example, compressed KV covers up to token 4096, while sliding-window content only covers up to token 4000. The directly reusable length is the smaller of the two, rounded down to block boundaries.

    4. Byte-level hardware alignment: Underlying storage and access instructions often require specific address alignment. The starting address and length of cache blocks must satisfy this requirement; otherwise, memory access errors or performance degradation may occur.

    Below is a schematic decision function illustrating the combination of these checks:

    1. def usable_prefix_len(groups, block_align, kernel_version):
    2. """Returns the prefix length (in tokens) that can be reused directly."""
    3. usable = min(g.ready_upto for g in groups) # intersection of group states
    4. usable -= usable % block_align # block alignment
    5. for g in groups:
    6. if g.kernel_version != kernel_version: # kernel interface consistency
    7. return 0
    8. if g.location != "gpu": # parts not migrated back
    9. usable = min(usable, g.gpu_upto)
    10. return usable - usable % block_align

    In the example, block_align can be the least common multiple of the granularities of the groups. If the function returns 0, the entire prefix must be recomputed.

    Consistency Constraints

    The allocator state machine should always satisfy the following constraints during runtime.

    6.1 Admission Limit

    The system must limit the total amount of cache resident in GPU memory. Admission checks must consider both the computational requirements of new requests and the occupancy of existing caches, to avoid new requests evicting blocks that are in use by running requests.

    6.2 State-Based Dispatching

    Blocks in different states should follow different handling paths. Missing tails need recomputation, blocks being migrated need waiting, stale indexer states need synchronization. Treating all anomalies uniformly as “miss” causes excessive unnecessary recomputation and conceals the real issue.

    6.3 Time Window Between Check and Use

    In a concurrent environment, there is a time gap between a hit check and the actual read. During this gap, a block may be swapped out, overwritten, or freed. This race condition is a classic time-of-check-to-time-of-use (TOCTOU) problem.

    Two common mitigation methods exist. One is to re-validate the block’s version number before reading; if it differs, abandon reuse. The other is to use reference counting to guarantee that a block is not reclaimed after the check passes until it is no longer in use. The two can be combined.

    6.4 Static Execution Graph Topology Fixation

    If inference uses a static graph capture, memory addresses and call structures are fixed after capture. In this case, the physical address of a cache block cannot change during runtime; state transitions can only change block content, not block location or count. Violating this constraint can cause the execution graph to read the wrong memory.

    Engineering Practice Recommendations

    When designing or debugging such a system, the following order is suggested:

    • First, enumerate the cache content of each attention type in the model, and list the lifecycle and recovery conditions for each state type.
    • Design state fields for each logical block, and ensure that write, swap-out, and migration paths update these fields.
    • The return value of prefix matching should include the usable length, not just whether a hit occurred.
    • Write unit tests for each of the four validation levels, covering alignment boundaries, version mismatches, and partial migration scenarios.
    • Construct stress tests with long sequences and high concurrency to verify consistency between check and use, and compare outputs between cached and uncached paths to confirm correctness.

    Prefix caching remains an effective way to reduce inference costs. Heterogeneous caches merely require the hit decision to upgrade from “does the block exist” to “is the state usable”. By implementing complete state tracking, validation, and consistency constraints, you can reuse caches while ensuring the correctness of generated results.