Refactoring State Caching in Hybrid Architectures: The Critical Path to Faster Prefill

    This article explains why hybrid architectures that alternate full-attention and linear layers are becoming the default choice for long-context workloads, and why their caching is harder to manage than KV caching alone. It covers the properties of recurrent state, a two-layer design combining KV block caching with state snapshot caching plus an anchor mechanism, key optimizations such as adaptive anchor density and layered eviction, engineering recommendations, and the boundaries of the expected gains.

    1. Background: Why Hybrid Architectures Dominate Long-Context Workloads

    Over the past year or two, model architectures that alternate full-attention layers with linear layers have seen broad adoption. The motivation is straightforward: full-attention layers handle precise global information retrieval, while linear layers (state space models, linear attention, and similar designs) carry long-range history in a fixed-size state. Combining the two substantially reduces compute and memory-access overhead during decoding, and cache footprint no longer grows linearly with context length.

    For multi-turn, long-context workloads such as coding assistants and code completion tools, the appeal is even stronger. A single session often involves dozens of tool calls, file snippets fed back into the context, and intermediate reasoning results, pushing context length into the tens or even hundreds of thousands of tokens. With a pure attention structure, cache growth becomes the throughput bottleneck; a hybrid structure is inherently cheaper.

    But the problem that follows is this: the cache gets lighter, while managing it gets heavier.

    2. Why Prefix Caching Is Harder in Hybrid Architectures

    Prefix caching for pure attention models is relatively simple: each token maps to a set of key-value tensors, a prefix match is a hit, and entries are organized in blocks and evicted by reference count. Hybrid architectures introduce a second kind of state — the recurrent state of the linear layers — with three properties that differ fundamentally from the KV cache:

    1. The state is compressed. Linear layers compress history into a fixed-size state tensor. It cannot be sliced and reused per token the way KV entries can; it can only be reused as a whole, scoped by “layer + position range.”
    2. The state has strong sequential dependency. To obtain the state at token N, you must roll forward from a known anchor point; random access is not possible.
    3. The two caches have mismatched lifecycles. KV entries can be evicted at block granularity, while state reuse granularity is coarser. Using a single eviction policy for both easily produces partial hits — KV present but state missing — which triggers redundant computation instead of saving it.

    As a result, traditional prefix caching shows inflated hit rates but discounted real gains in high-concurrency multi-turn scenarios, and the prefill stage still repeatedly recomputes long prefixes.

    3. Redesign: Two-Layer Caching Plus Anchor Reuse

    The common approach on the inference-serving side is to split the cache into two layers, managed separately, and stitch them together with anchors:

    • Layer one: KV block cache, keeping block-based management and responsible for exact prefix matching.
    • Layer two: state snapshot cache, periodically persisting linear-layer state at key positions to form reusable “checkpoints.”
    • Anchor mechanism: record the token position and block index for each checkpoint so the two layers can cross-validate and partial hits are avoided.

    A schematic cache entry structure (expressing design semantics only, not a specific implementation):

    1. @dataclass
    2. class CacheEntry:
    3. prefix_hash: bytes # Prefix fingerprint, used for block-level matching
    4. kv_blocks: list[Block] # References to KV blocks
    5. state_snapshots: dict[int, StateTensor] # Position -> linear layer state
    6. ref_count: int
    7. last_access: float

    Hit determination follows the order “blocks first, then state, then anchor validation”:

    1. def lookup(entry, cur_pos):
    2. if entry is None or entry.prefix_hash != hash_prefix(cur_pos):
    3. return MISS
    4. snap = nearest_snapshot(entry.state_snapshots, cur_pos)
    5. if snap is None:
    6. return PARTIAL # Triggers incremental recomputation, not full recomputation
    7. return HIT(snap)

    The key point: downgrade “full recomputation” to “incremental recomputation from the nearest anchor” — this is the main source of prefill throughput improvement.

    4. Key Optimizations

    1. Adaptive anchor density. The longer the context and the denser the turns, the denser the anchors should be. Use “distance since last access + reuse frequency” to dynamically decide how many checkpoints to persist, so state snapshots do not themselves become a memory burden.
    2. Layered eviction. Evict KV blocks by block, and evict state snapshots by “reference count + anchor value.” Keeping the two queues separate reduces mutual interference.
    3. In-batch prefill alignment. Group requests that share a prefix into the same batch so one state snapshot is reused multiple times, amortizing the cost of a single prefill.
    4. Multi-tier storage coordination. Keep hot blocks and recent anchors in GPU memory, and let host memory or a distributed cache tier hold warm and cold data. Cross-node reuse requires anchor metadata and state tensors to be addressable and migratable.
    5. Observable partial hits. Track the PARTIAL ratio and average incremental recomputation length as core metrics; otherwise optimization gains are hard to attribute.

    5. Engineering Recommendations

    • Measure before optimizing: separately track KV hit rate, state hit rate, partial-hit ratio, and average recomputation length to locate the real bottleneck.
    • Plan capacity in tiers: prioritize anchors and hot blocks in the GPU memory budget, use host memory for session-level warm data, and use a distributed cache for cross-node sharing.
    • Couple scheduling with caching: session-affinity routing significantly improves state reuse and prevents a single session from being spread across nodes.
    • Load-test with realistic traces: replay real multi-turn tool-call traces rather than single-turn long-text benchmarks, otherwise the true cost of state management stays hidden.

    6. Gains and Boundaries

    Under real multi-turn long-context workloads, the gains from this kind of redesign show up in two places: the prefill stage avoids full recomputation, improving throughput by several times, and the long tail of time-to-first-token is noticeably flattened. The boundaries should also be clear: gains depend heavily on prefix reuse rate and session affinity. If the workload consists mostly of many short sessions that share nothing, the benefit of state caching narrows sharply, and attention should shift to scheduling and batching strategy rather than cache-layer changes.

    For teams running inference services on Baidu AI Cloud compute and container platforms, incorporating layered caching, anchor reuse, and affinity routing into service design is a viable path to better long-context experience without changing the model architecture.