Refactoring State Caching for Hybrid Architectures: 3x Prefill Throughput

    This article explains why hybrid model architectures, which combine linear state layers with full attention, break traditional prefix caching, and how to refactor the cache to handle both state types. You will learn the semantic differences between addressable key-value caches and path-addressed recurrent states, four design principles for a unified state cache, and how these changes deliver roughly 3x prefill throughput. The article also covers tiered caching, distributed reuse, observability, and a phased adoption path for inference and Agent platforms.

    1. Why Hybrid Architectures Complicate Prefix Caching

    Over the past year, open-source LLM architectures have been diverging rapidly. Beyond the traditional stack of full attention layers, linear attention and state space layers are now appearing frequently in model descriptions, including mechanisms such as gated delta updates, incremental linear attention, and structured state spaces. Their shared selling point is that the decode stage no longer requires a key-value cache that grows linearly with context length. Instead, they maintain a fixed-size recurrent state, while lowering the compute cost of each decoding step and saving memory during long-text inference.

    As a result, one hybrid structure has become a mainstream choice: most layers use linear state updates, while a small number of layers retain full attention. This design is attractive from an engineering standpoint. It captures the memory advantage under long contexts while preserving the ability of full attention on precise retrieval tasks.

    The problem is what comes next. Agent workloads, exemplified by intelligent coding tools, are characterized by “multi-turn, long-prefix, frequent branching.” The same repository context is reused repeatedly, with each turn appending tool call results, retrieved snippets, and diff content. Retries and parallel subtasks also occur often. The performance bottleneck for these workloads is the prefill stage, the process of computing a long prefix into a cache in one pass.

    For pure attention models, the semantics of prefix caching are clear: the cache is a set of per-layer key-value tensors. A hit skips computation for the corresponding positions, and a miss resumes computation from a given position. A hybrid model’s prefix cache must manage two types of state at once: a key-value cache that can be indexed by position and truncated at any point, and a fixed-size recurrent state that evolves layer by layer in sequence and cannot be “cut” from the middle. Their lifecycles, eviction policies, and transfer granularities are completely different. Managing them with the same logic leads to incorrect hit detection, redundant computation, cache fragmentation, and wasted bandwidth.

    2. The Core Conflict: A Semantic Gap Between Two State Types

    To understand why refactoring is necessary, start by laying out the fundamental differences between the two state types:

    • Different addressability. The key-value cache is “position-addressed”: the cache for the k-th token maps to a definite tensor slice. The recurrent state is “path-addressed”: it is the result of the prefix sequence passed through all layers recursively, produced only by a complete prefix, and cannot be assembled from arbitrary sub-segments of the prefix.
    • Different invalidation propagation. Once a prefix is modified in the middle, the key-value cache only needs to discard the portion after that position. The recurrent state is invalidated entirely and must be recomputed from the start, at a much higher cost.
    • Different transfer and storage granularity. The key-value cache is suited to swapping in and out at block granularity. The recurrent state is one fixed-length tensor per layer, suited to whole-layer transfer; block-level slicing adds extra metadata overhead.
    • Different coupling with attention layers. The full attention layers retained in a hybrid model still need long key-value history, so the “memory savings” occur only on some layers, and the cache budget must be allocated uniformly across both state types.

    The traditional approach often treats the recurrent state as a “non-cacheable temporary value,” recomputing it recursively every turn, or crudely discarding it entirely. Under long-prefix, multi-turn scenarios, this means repeatedly performing the most expensive computation, which naturally chokes prefill throughput.

    3. The Refactoring Approach: Making State Caching a First-Class Citizen

    An effective refactoring direction can be summarized in four design principles.

    First, unified addressing and versioning. Assign a content hash identifier to each prefix segment, and record version numbers for both state types. Hit detection should not only check whether the token sequence matches, but also verify the state version, avoiding silent errors where “the sequence is identical but the state comes from a different branch.” A sample metadata structure can be written as:

    1. @dataclass
    2. class PrefixEntry:
    3. token_hash: bytes # Content fingerprint of the prefix
    4. kv_blocks: list[int] # Block indices for full attention layers
    5. state_layers: dict[int, bytes] # Fixed-length state handles for linear layers
    6. version: int # State version, incremented on branch writes
    7. ref_count: int

    Second, hybrid layer and block management. Full attention layers continue to use block-based allocation and reference counting; linear layers use the “layer” as the minimum unit for whole swap-in and swap-out, with metadata recording the prefix length they depend on. This avoids fragmentation from fine-grained slicing and allows eviction to proceed by layer priority.

    Third, copy-on-write and branch friendliness. Agent scenarios are naturally tree-structured calls: a main branch, retry branches, and parallel sub-branches share the same long prefix. Applying copy-on-write to the recurrent state, using read-only references when shared and copying a layer’s state only when a fork occurs, can significantly reduce repeated recursion.

    Fourth, local continuation and incremental repair. When newly appended content does not change the existing prefix, only continue the recursion of linear layers from the hit position and compute key-values for the newly added tokens in full attention. When a middle modification occurs, prefer reusing the nearest ancestor version, compressing the recomputation range to the minimum.

    4. Why Prefill Throughput Can Multiply

    Stringing these mechanisms together, the gains stack from three sources:

    First, repeated prefixes are genuinely skipped. In multi-turn conversations, the historical prefix often accounts for far more than the newly added content. Once the state cache hits, the most expensive long-sequence recursion is eliminated, and prefill shifts from “full computation every turn” to “incremental every turn.”

    Second, scheduling overlaps with memory transfer. Fixed-length state transfer is predictable and can be pipelined. Combined with batched transfer of block-based key-values, this saturates bandwidth while compute units wait for data, reducing idle cycles.

    Third, the cache budget is planned uniformly. Both state types share the same GPU and host memory budget, dynamically allocated by hit rate and recomputation cost, avoiding the imbalance where “the key-value cache is sufficient but the state is recomputed repeatedly.”

    In public technical discussions, this kind of refactoring performs impressively on real Agent trajectory replays: prefill throughput can reach about three times that of the original implementation, and p90 time-to-first-token latency can drop by more than eighty percent. When a host memory cache at the hundreds-of-gigabytes level is introduced as a second tier, the gains hold and further support cross-node state reuse. Note that the specific multipliers are strongly correlated with hardware model, model structure ratio, and prefix reuse rate; engineering evaluation should be based on your own workload.

    5. Tiered Caching and Distributed Scaling

    When a single machine’s GPU memory cannot hold the composite state of a long prefix, a second-tier cache is needed: GPU memory holds hot data, host memory holds warm data, and if necessary it sinks to a persistent layer based on object storage or a distributed file system, with a unified caching service handling metadata management and lifecycle reclamation. Cross-node reuse requires attention to three points: state handles must be globally addressable; compress and verify before transfer to avoid bandwidth being consumed by metadata; and the scheduler must be aware of which node holds the state, preferentially routing requests to cache-affine instances, otherwise cross-node transfer cancels out the hit gains.

    Observability is equally indispensable. At minimum, instrument: hit rate (distinguishing the two state types), recomputation length distribution, cache eviction reasons, state transfer time, and p50/p90 TTFT. Without these metrics, it is hard to tell which layer the optimization actually lands on.

    6. Adoption Recommendations

    If you are building an inference service or Agent platform, you can proceed along a progressive path: first add content fingerprints and version numbers to prefixes to fix hit detection; then bring linear layer states into the cache with whole-layer swap-in and swap-out; then introduce copy-on-write to support branching and parallelism; and finally connect host memory and distributed caching with affinity-aware scheduling. For a cloud implementation, you can combine a container platform to host inference instances, object storage to hold cold states, a message queue to broadcast cache invalidations, and logging and monitoring/alerting services to observe TTFT and hit rate. Baidu AI Cloud offers corresponding product categories for these general capabilities, which you can select as needed.

    Hybrid architectures will not revert to pure attention, and state caching will no longer be an afterthought. Whoever can schedule both state types as a single resource pool will secure a definite prefill advantage in multi-turn, long-context workloads.