State Cache Refactoring for Hybrid LLMs: Block-Aligned Prefix Reuse

    This article explains why KV cache reuse breaks in hybrid architectures that mix global attention layers with linear attention or state space layers, and how to refactor caching around it. Because recurrent states are fixed-size and cannot be split or concatenated by position, token-only prefix keys force repeated prefill computation. The proposed design separates caching into two layers, matches prefixes on fixed-size block boundaries via a block tree, restores recurrent states incrementally from block-end snapshots, and shares read-only prefixes across branches with copy-on-write. It also covers multi-dimensional eviction scoring, asynchronous prefetching for agent workloads, and practical concerns such as block size tuning, snapshot precision, observability, and cache-affinity-aware scheduling.

    1. Background: Hybrid Architectures Make Cache Management Harder

    Recent open-source LLM designs increasingly combine linear attention and state space layers—gated incremental attention variants, structured state space sequence layers, and similar designs—into a hybrid structure where some layers perform global attention and others perform linear recurrence. The payoff is clear: per-step compute and memory access during decoding stay close to constant, cache footprint drops substantially for long contexts, and end-to-end decoding gets faster.

    The problem appears once the workload shifts from single-turn Q&A to agentic coding tools and multi-turn conversational agents. These workloads have extremely long contexts, many turns, and only a small amount of new content appended at the end of each turn, while the vast majority of the prefix—system prompts, repository snippets, prior trajectories—stays stable. Ideally, that stable prefix should be reused in full and only the new tokens computed. Hybrid architectures make reuse far more complicated than in pure attention models.

    2. Why the Two Cache Types Are Fundamentally Different

    In a pure attention model, the cache is a sequence of key-value pairs with two useful properties: it can be split by position and concatenated by position. On a prefix hit, you attach the newly computed portion to the head of the cached sequence and the result is semantically equivalent.

    Linear and state space layers in hybrid architectures behave differently. They maintain a fixed-size recurrent state that compresses the entire history so far into a matrix or vector. Three consequences follow:

    1. The state cannot be split by position. You cannot take “the first half” of a state, because it is the result of cumulative compression.
    2. State updates are sequential recurrences, so intermediate timesteps cannot be accessed randomly.
    3. State and attention cache operate at different semantic granularities: one is aligned per token, the other per compressed summary.

    As a result, keeping a cache key design that matches only token prefixes leads to a situation where the prefix text is identical yet the linear layers are still recomputed. Prefill gets bogged down in repeated computation and throughput cannot improve.

    3. Refactoring Approach: From a Single Prefix Cache to a Layered State Cache

    The core changes come down to four points.

    First, split the cache into layers. The attention layer cache stays organized in token blocks and handles exact matching; the recurrent state layer cache is organized as snapshots at block boundaries, with the state at the end of each block explicitly persisted. Matching first aligns block boundaries, then restores layer by layer.

    Second, block-aligned prefix matching. Use a fixed-length block (for example 128 or 256 tokens) as the minimum unit of reuse, and maintain a root-to-leaf block tree in which each node records a hash, a parent pointer, and a reference to the state snapshot at the end of that block. Matching then reduces to a longest common prefix lookup on the tree.

    A sketch of the structure:

    1. class BlockNode:
    2. __slots__ = ("hash", "parent", "kv_ref", "state_ref", "children")
    3. def __init__(self, h, parent, kv_ref, state_ref):
    4. self.hash = h
    5. self.parent = parent
    6. self.kv_ref = kv_ref # attention layer cache block
    7. self.state_ref = state_ref # recurrent state snapshot
    8. self.children = {}
    9. def match_prefix(root, tokens, block=128):
    10. node, matched = root, 0
    11. for i in range(0, len(tokens) - block + 1, block):
    12. h = hash_block(tokens[i:i + block])
    13. child = node.children.get(h)
    14. if child is None:
    15. break
    16. node, matched = child, i + block
    17. return node, matched

    Third, incremental restoration from state snapshots. After a block node is hit, there is no need to replay the full history: load that node’s state snapshot and run one forward pass over the remaining tokens. Snapshots can be retained selectively—keep shallow, frequently reused nodes resident, and use compressed storage or write-then-read-back for deeper nodes.

    Fourth, copy-on-write and sharing. Multi-turn conversations and multiple branch attempts against the same repository often share a long common prefix. Creating a branch with copy-on-write, while the shared prefix’s state and attention cache are read-only shared, substantially reduces GPU and host memory pressure.

    4. Eviction and Prefetching Strategy

    Eviction for a hybrid cache cannot rely on LRU alone. A multi-dimensional score is recommended: reuse frequency, block depth (shallower is more valuable), reconstruction cost (snapshots at greater depth are more expensive to rebuild), and session activity. In practice a tiered policy works well—shallow blocks stay resident, middle blocks are evicted by frequency, and deep blocks keep only a hash index so they can be rebuilt quickly.

    Prefetching matters just as much. The next request in an agent workload is often predictable: the follow-up call to the same tool, the adjacent snippet from the same file. Asynchronously precomputing state snapshots for candidate prefixes while the previous request wraps up hides that wait inside the user’s thinking time.

    Pseudocode example:

    1. def evict(cache, budget):
    2. scored = sorted(cache.values(), key=score, reverse=True)
    3. keep, freed = [], 0
    4. for node in scored:
    5. cost = node.memory_cost()
    6. if freed + cost > budget:
    7. freed += node.drop() # deep nodes keep only the index
    8. else:
    9. keep.append(node)
    10. return keep
    11. def score(node):
    12. return 3 * node.depth_weight() + 2 * node.hit_count() - node.rebuild_cost()

    5. Engineering Considerations

    Block size tradeoff. Blocks that are too small cause metadata and snapshot counts to explode; blocks that are too large make matching coarse and waste recomputation. Tuning usually starts at 128.

    State precision. Some implementations allow lower-precision snapshot storage in exchange for capacity, but the cumulative effect on generation quality must be evaluated. Validate on an offline evaluation set before shipping.

    Observability. Instrumentation is mandatory: prefix hit rate, average matched length, state load latency, snapshot hit rate, and rebuild counts. Without these metrics there is no way to tell whether the optimization is actually working. A dashboard can be built on general-purpose logging and monitoring with alerting.

    Coordination with scheduling. Cache affinity affects request routing: requests that share a prefix must be scheduled to the same instance for hit rates to rise, which requires session stickiness policies from the container platform.

    6. Benefits and Limits

    For multi-turn, long-context workloads with a high proportion of shared prefixes, a layered state cache turns large amounts of repeated forward computation into a single load plus a small incremental computation, improving prefill throughput by several times and lowering time to first token. The gains have limits: if request prefixes are highly fragmented with almost no sharing, or if block size is configured poorly, hit rates will be low, and falling back to the baseline strategy is better than forcing the optimization.

    Overall, cache design for hybrid architectures starts from accepting that recurrent state cannot be split, then uses block alignment, snapshots, and copy-on-write to turn indivisible state into objects that are addressable, shareable, and incrementally restorable. The same approach applies to self-hosted inference services built on container platforms and object storage on Baidu AI Cloud, and it is a key part of cost optimization for long-context agents.