Heterogeneous KV Cache: Prefix Hits and State Restoration

    This article explains why a prefix cache hit does not guarantee that KV data can be reused directly when different layers use different attention mechanisms. It reviews the three assumptions behind page-based KV caching, defines five heterogeneous cache states, and describes state tracking in the allocator, four-layer hit validation, consistency constraints, and engineering practices for correct prefix reuse.

    1. Why a Prefix Hit Does Not Mean Direct Reuse

    In large model inference services, prefix caching commonly uses the hash of a request prefix as an index. When two requests share the first several tokens, the service attaches already computed KV cache blocks to the new request and avoids repeated prefill computation. This mechanism relies on one premise: the same prefix produces KV data in the same form at every layer, so the data can be read block by block as-is.

    Models with a uniform attention architecture generally satisfy this premise. When different layers of the same model use different attention methods, the premise no longer holds. For example, some layers keep the full history and compress it, some attend only to a recent sliding window, and others use an indexer to sparsely select historical positions. In this case, a hash hit only means the token sequence is the same. It does not mean the data required by every layer is available.

    Prefix hit rate measures performance benefit. It cannot prove that generated results are correct. A high hit rate only means there are more reuse opportunities. If reused data is incomplete, output will be wrong, and such errors usually do not surface as exceptions.

    2. Three Assumptions Behind Traditional Page-Based Caching

    Mainstream inference frameworks generally use page-based KV caching. Each request’s token history is split into fixed-size pages, and a page table maps logical positions to physical GPU memory blocks. Requests with the same prefix can share the same physical blocks, and a new request only needs to increase the reference count.

    This design implicitly makes three assumptions:

    1. Each block’s content has only one form: a complete copy of the KV vectors for that layer.
    2. Whether a block is usable depends only on whether it exists.
    3. The allocator only needs to pick a free block for a new token and write data into it.

    Once cache objects become heterogeneous, all three assumptions fail. The allocator needs to record the current form of each token segment, and prefix matching must also check whether that form can satisfy subsequent computation.

    3. Five Types of Heterogeneous Cache State

    The following five states each have an independent lifecycle, restoration condition, and hit decision rule.

    1. Compressed KV: a representation of historical tokens after compression. Restoration requires confirming that the compressed result has been generated and that compression parameters match the current model.
    2. Uncompressed tail: the most recent tokens that have not yet filled a compression unit. They are usually stored in GPU memory at original precision, and if missing, they cannot be reconstructed from the compressed result.
    3. SWA window: the KV of recent tokens within a sliding window. During restoration, the window boundary must align with the current position; otherwise the attention range will be misaligned.
    4. Indexer state: the index structure used for sparse routing. If the index and KV are out of sync, the model will access the wrong historical positions.
    5. On-disk prefix: a prefix that has been offloaded to a slower storage tier. It can be hit, but it cannot participate in computation before being read back. Scheduling should treat read-back as a restoration step.

    The five states do not share a unified dependency order. A prefix may have a complete compressed result, a missing window, and an index already written to disk. The prefix can resume computation only after all five states are restored.

    4. The Allocator Moves from “Finding Free Blocks” to “Recording State”

    In a heterogeneous design, the cache manager has at least two parallel actions: alloc allocates blocks for new tokens and writes data, and prefix match finds reusable prefixes by hash. Both must share the same state record.

    A practical approach is to maintain a state record for each token segment, including:

    • which state types the segment contains;
    • whether each state type is currently online, offloaded, or writing;
    • the version number or sequence number associated with each state type.

    The following code only illustrates the data structure and does not correspond to the interface of any specific framework:

    1. from dataclasses import dataclass, field
    2. from enum import Enum
    3. class StateKind(Enum):
    4. COMPRESSED_KV = 1
    5. TAIL = 2
    6. SWA_WINDOW = 3
    7. INDEXER = 4
    8. OFFLOADED = 5
    9. @dataclass
    10. class SegmentRecord:
    11. token_range: tuple[int, int]
    12. # Example values: "online" | "offloaded" | "writing"
    13. states: dict[StateKind, str] = field(default_factory=dict)
    14. def can_reuse(segment: SegmentRecord, required: set[StateKind]) -> bool:
    15. """A segment counts as a valid hit only when all required states are online."""
    16. return all(segment.states.get(kind) == "online" for kind in required)

    Prefix match calls a check such as can_reuse before returning a hit result. Only prefixes that pass the check count as truly available hits.

    5. Four-Layer Hit Validation

    After a hash hit, a prefix must pass four layers of validation before it can be confirmed as directly resumable.

    Layer 1: Block alignment. Different states may have different block granularity. For example, the length of a compression unit may differ from that of a raw token page. The least common multiple of the two determines the boundary at which safe splitting is possible. The hit length must fall on this boundary; otherwise a half compression unit will remain.

    Layer 2: Compute kernel interface constraints. The data layout, stride, and alignment required by the kernel must match the layout stored in the cache. When layouts do not match, even complete data cannot be passed in directly.

    Layer 3: State intersection across multiple cache groups. Different attention types each occupy a cache group. The hit length should be the intersection of the available lengths across groups. If any group is missing, the overall hit length must fall back.

    Layer 4: Byte-level hardware alignment. The start address and length of a cache block must satisfy hardware access alignment requirements. Otherwise reads incur extra overhead or, in severe cases, fail with an error.

    The four validation layers can run from coarse to fine: first truncate by block boundary, then filter by layout, then intersect states, and finally check byte alignment.

    6. Consistency Constraints That Must Always Hold

    The allocator state machine must not violate the following four rules at any time.

    1. Admission cap: The state occupancy of a new request must not exceed the safe threshold of available capacity. Above the threshold, swap-in and swap-out during generation may fail.
    2. State routing: The processing path of each token segment is determined by its current form. It cannot be uniformly treated as full KV.
    3. Time-of-check to time-of-use (TOCTOU) consistency: After a prefix check passes and before the actual read, a background task may evict or overwrite the state. The version number should be revalidated before reading, or a data pointer snapshot should be recorded during the check and compared before use.
    4. Fixed static graph topology: If inference uses static graph capture to reduce scheduling overhead, the tensor addresses and shapes at capture time must remain unchanged. State should be written into preallocated fixed buffers, updating content only and not addresses. Dynamic layout adjustments invalidate captured results.

    7. Engineering Practice Recommendations

    When implementing heterogeneous KV caching, proceed in the following order.

    • Establish a correctness baseline first. For the same set of requests, disable and enable prefix reuse separately, and compare whether generated results are consistent. If outputs differ, first check whether state restoration is complete.
    • Track hit rate and correctness separately. Hit rate is used to evaluate cache effectiveness, while correctness is confirmed through comparison tests and sampled validation.
    • Set up independent monitoring for each state type. Metrics include restoration latency, read-back count from the offload tier, and validation failure count, making bottlenecks easier to locate.
    • Stress test the offload path. Focus on concurrent requests during read-back and whether they read state that has not yet completed.
    • Log state changes. Each change should record the token range, state type, and version number for later tracing.

    8. Summary

    A prefix hit is only the starting point for reuse. Under heterogeneous attention structures, a cache object is a composite object made up of multiple state types. An inference service needs to explicitly track the form of each state type, validate each item during hit determination, and maintain consistency under concurrency and graph capture. Only then can prefix reuse improve performance while preserving correct generation results.