State Cache Refactoring for Hybrid-Architecture LLMs: A Practical Guide
This article explains why hybrid architectures that alternate full-attention and linear layers complicate prefix caching, and how to refactor state caching to reduce prefill cost in coding-agent workloads. It covers unified prefix-block addressing, state checkpoints, a three-tier GPU/host/remote cache, safe partial-hit boundaries, transfer-compute overlap, and cross-node reuse, along with the metrics to validate the design.
1. Why Hybrid Architectures Complicate Prefix Caching
Recent model designs increasingly adopt a hybrid architecture that alternates full-attention layers with linear layers. The motivation is straightforward: full-attention layers preserve precise modeling of long-range dependencies, while linear layers (various linear attention designs, gated state-space structures) trade a constant-size state for higher decoding efficiency and a significantly smaller cache footprint.
The catch is that this benefit is obvious for single-turn short requests but reverses under coding-agent workloads. A typical agent loop reads repository files, retrieves code snippets, runs commands, observes output, and issues the next round of edits. Every round resends the entire prior context to the model, producing an extremely long and highly overlapping prefix. At that point the dominant cost is no longer decoding but prefilling: recomputing thousands of historical tokens.
Prefix caching semantics are relatively simple for pure attention models: each token maps to one key-value entry, and block-level hashing gives exact hit detection and reuse. Hybrid architectures add a second kind of cached data — the state maintained by linear layers, a fixed-size structure that evolves as the sequence advances. It does not correspond one-to-one with individual tokens; it is bound to an entire prefix segment that starts at one position and ends at another. This introduces three new problems:
- Granularity mismatch: key-value cache can be partially hit block by block, whereas state can often only be hit or recomputed as a whole segment.
- Inconsistent lifecycle: state for a short prefix is small; state for a long prefix is still fixed-size, but recomputing it is very expensive, so eviction policies must treat the two differently.
- Position coupling: state is a position-dependent intermediate result, so it becomes invalid as soon as the prefix is truncated or concatenated.
2. Locating the Bottleneck: What Actually Slows Down Prefill
Optimization starts with decomposing the cost. The prefill cost of one agent request can be approximated as:
T_prefill ≈ Σ(uncached tokens × per-layer compute cost) + state rebuild cost + cache transfer cost
The first term is the compute bottleneck, the second is the extra overhead specific to hybrid architectures, and the third is often overlooked: once the cache spills from GPU memory to host memory or even remote storage, bandwidth rather than compute becomes the limiting factor.
This yields three optimization tracks: raise the block-level hit rate to reduce recomputation, reuse state together with the prefix wherever possible, and overlap transfer with computation. The rest of the design follows these three points.
3. Core Design: Orchestrating Key-Value Cache and State Cache Together
3.1 Unified Addressing: Prefix Blocks as the Single Identifier
Compute a content hash for every fixed-length token block to form a chained identifier (each block hash includes the hash of preceding blocks), and let both the key-value cache and the state cache share the same identifier scheme. A single lookup then answers whether a given prefix has been fully computed, avoiding the ambiguous hit decisions that arise when the two caches maintain separate indexes.
def block_id(prev_id, tokens):return hash((prev_id, tokens)) # chained hash guarantees prefix uniqueness
3.2 State Checkpoints: Persist Fixed-Size State in Segments
Do not save state only at the end of the sequence. Checkpoint the linear-layer state at fixed intervals (for example, every few hundred tokens) and record the corresponding block identifier alongside it. On a hit, restore from the most recent checkpoint and recompute only a small tail of tokens. The checkpoint interval is a tunable knob: smaller intervals mean less recomputation but higher cache occupancy and write amplification.
3.3 Tiered Caching: GPU Memory, Host Memory, Remote Storage
Organize the cache in three tiers — hot, warm, cold. Keep recently active prefixes in GPU memory; push historical rounds down to host memory; place stable prefixes shared across sessions and nodes (repository skeleton, system prompts, specification documents) in remote storage. On eviction, prefer dropping entries that are “cheap to recompute and unlikely to be hit” rather than applying plain LRU, because recomputation cost varies widely across entries in a hybrid architecture.
3.4 Safe Boundaries for Partial Hits and Concatenation
Block-level partial hits require state to be concatenable. The safer engineering choice is: allow partial hits for the key-value cache, but reuse state only at complete prefix boundaries; if a prefix is truncated, restart from the most recent complete checkpoint. This constraint looks conservative, yet it prevents silent quality degradation caused by misaligned state — a class of problem that is extremely costly to diagnose.
3.5 Overlapping Transfer with Computation
Prefill is a batched, parallel phase that is relatively insensitive to latency, which makes it a good fit for overlapping with data movement. The implementation uses a prefetch pipeline: while the GPU computes the current batch, asynchronously pull the state and key-value blocks needed by the next batch from host memory or remote storage, using double buffering to hide transfer latency.
batch i: [compute] [compute]transfer: [prefetch i+1] [prefetch i+2]
4. Distribution and Cross-Node Reuse
Agent workloads are often driven by many concurrent sessions that share large common prefixes. Once the state cache is pooled, state computed by node A can be loaded directly by node B, provided the routing layer performs affinity scheduling by prefix identifier so that requests with the same prefix land on the same node or the same cache shard.
Three engineering points matter here. First, the metadata service must support fast lookup from prefix identifier to cache location. Second, cross-node transfer must control granularity to avoid frequent transfer of small objects. Third, a consistency convention is required that binds state to the model version and the parallelism partitioning scheme; on any version mismatch, the state must be invalidated and rebuilt.
5. Where the Gains Come From and How to Validate
Replaying real agent traces on a single high-end accelerator card, this kind of design offers several times the prefill throughput of a general-purpose high-throughput inference framework, with a substantial drop in p90 time-to-first-token. The gains persist after attaching a host-memory cache on the order of hundreds of gigabytes, which indicates the bottleneck has shifted from compute to cache hit rate and bandwidth scheduling.
For in-house validation, track four metrics: block-level hit rate, state checkpoint hit rate, average recomputed tokens, and p90 time-to-first-token. If throughput improves but p90 does not, the checkpoint interval for long-tail requests is usually too large; if the hit rate is normal but bandwidth is saturated, increase the compression ratio or adjust tier capacities.
6. Rollout Recommendations
- Quantify the workload first: measure the distribution of common prefix lengths in historical requests before choosing block size and checkpoint interval.
- Roll out in small steps: enable block-level key-value reuse first, then introduce state checkpoints, and finally turn on cross-node sharing.
- Ensure observability: bring hit rate, recomputation volume, and transfer wait time into monitoring, alerting, and logging.
- In a cloud environment such as Baidu AI Cloud that provides container platforms, object storage, and monitoring and alerting capabilities, the cache pooling components and tiered storage can be deployed decoupled, making it easier to scale elastically with the workload.
