Hybrid Architecture State Cache Optimization: Tripling Prefill Throughput
This article explains why traditional caching strategies break down in hybrid architectures that alternate full-attention layers with linear or state-space layers, and how a layered state cache addresses the problem. It covers the three distinct state types and their lifecycles, copy-on-write branching for tree-shaped Agent workloads, tiered compression and approximate reuse, and scheduling techniques such as prefix-aware routing, chunked prefill, and state prefetching. It also lists four metrics for honest evaluation, common pitfalls to avoid, and a layered approach to deploying the design on Baidu AI Cloud.
1. Background: Hybrid Architectures Are Mainstream, but Cache Management Is the New Bottleneck
Over the past year or two, a hybrid architecture that alternates full-attention layers with linear or gated state layers has been widely adopted in model design. Intelligent coding tools, multimodal assistants, and general-purpose chat models in the industry all use this approach to gain two direct benefits: lower computation per step during decoding, and a significantly smaller cache footprint than a pure full-attention structure.
However, once such models are placed in Agent scenarios, the problem surfaces quickly. A typical Agent behavior is to read the environment, call tools, concatenate long context, and then generate a decision, over and over. Each round may send tens of thousands or even hundreds of thousands of tokens of history back to the model. At this point the real cost center is no longer decoding but prefill—the process of building state in one pass over the input sequence.
The cache in a hybrid architecture is no longer a single homogeneous block of key-value tensors, but an assembly of several state types:
- Full-attention layers: store conventional key-value pairs that grow linearly with sequence length;
- Linear/state-space layers: store a fixed-size recurrent state that is independent of length but cannot be rolled back once updated;
- Some designs also include convolution or short-range caches that must be maintained per window.
The three state types differ completely in semantics, lifecycle, and compressibility, so managing them with a unified policy inevitably wastes resources.
2. Why Traditional Cache Strategies Fail on Hybrid Architectures
The conventional approach treats the cache as “contiguous memory indexed by token,” where a hit means reusing the prefix. Under a hybrid architecture, three of these assumptions no longer hold.
First, states cannot be simply concatenated. Key-values in full-attention layers can be split and concatenated by position, whereas a recurrent state is “compressed history”; adding or chaining two states directly is not mathematically equivalent to the result of continuous input.
Second, eviction costs are asymmetric. Dropping an old key-value entry causes a local and gradual loss, while overwriting or resetting a recurrent state produces an error that keeps being amplified across all subsequent time steps.
Third, reuse patterns in Agent workloads are tree-shaped rather than linear. Multi-branch sampling, tool retries, and plan rollbacks all produce a structure of shared prefix plus diverging suffix, and a linear cache can only hit the trunk.
3. Redesign: Layered State Cache
The core design principle is to group homogeneous states together and address, evict, and transfer each according to its own physical characteristics.
CacheNamespace├── kv_block_pool # Full-attention layers, allocated by block, prefix-shareable├── recurrent_state # Linear layers, fixed length, managed by branch version└── window_state # Short-range convolution/sliding window, reused as a ring per window
The three pools share the same logical prefix identifier, but their physical layouts are independent. Logically it is still a prefix tree node; physically, each layer holds its own handle.
class PrefixNode:key: bytes # Prefix fingerprint (chained hash)kv_blocks: list[BlockId] # Reference counted, shareablerec_state: StateId # Copy-on-writewindow: RingBufferIdchildren: dict[int, PrefixNode]
The key point is copy-on-write: on a fork, only the fixed-length recurrent state and the window buffer are copied, while key-value blocks are shared through reference counting. Since fixed-length states are typically on the order of tens to hundreds of KB, the copy cost is far lower than recomputing the entire prefix.
4. State Compression and Approximate Reuse
Where a minimal precision loss is acceptable, the cache can be compressed in tiers:
- Key-value quantization: compress cache entries from high-precision floats to a low-bit representation, significantly reducing memory bandwidth pressure—and bandwidth is often the real prefill bottleneck.
- Low-rank projection of states: store the recurrent state as a low-rank approximation and reconstruct it at use time.
- Importance-based eviction: prioritize keeping high-contribution entries based on cumulative attention weights or state norms.
Engineering discipline must be emphasized: any approximation needs a rollback switch and per-layer error monitoring, to avoid error accumulation in long-chain Agent tasks that eventually affects decision correctness.
5. Scheduling: Actually Saturating Prefill
The cache is only a necessary condition; throughput gains also depend on scheduling:
- Prefix-aware routing: compute the longest matching prefix when a request arrives, and batch requests with the same prefix together to maximize sharing.
- Chunked prefill: slice very long inputs and interleave them with decoding requests, avoiding decode stalls caused by a long request monopolizing compute.
- State prefetch: asynchronously pull the parent node’s state before a branch is created, hiding copy and transfer latency.
- Pool capacity watermark control: set a separate watermark for each of the three pools, and evict on trigger following a “recompute-first” principle—discard the parts that are cheapest to recompute first.
def schedule(req):node = trie.longest_prefix(req.hash_chain)if node and node.rec_state.remote:prefetch(node.rec_state) # Async prefetchchunks = split(req.tokens, CHUNK) # Chunkingreturn Batch(chunks, shared=node)
6. Where the Gains Come From and How to Evaluate
The claim of “several times more prefill throughput” in a general engineering context usually comes from three effects stacking up rather than a single optimization: higher prefix hit rate, which eliminates repeated computation; lower cache bandwidth, where quantization and compression let more tokens be processed per unit time; and higher in-batch parallelism, where chunking and mixed scheduling reduce idle cycles.
It is advisable to fix four metrics to avoid fooling yourself:
| Metric | Meaning |
|---|---|
| Prefix hit rate | Share of input tokens served from cache |
| Prefill tokens/s | Number of input tokens processed per unit time |
| Time to first token P50/P99 | Directly affects the Agent interaction experience |
| State memory usage | Determines how many branches can run concurrently |
Be sure to compare under the same hardware, the same input distribution, and the same precision tolerance, and report the two sets of data with approximation strategies enabled and disabled separately.
7. Deployment Suggestions on Baidu AI Cloud
To implement the above in a cloud environment, you can build it up along general capability layers: use a container platform to host inference services and elastic scaling; use object storage to keep shareable prefix state snapshots; use a message queue for request sharding and priority scheduling; use logging and monitoring/alerting services to track hit rate, latency percentiles, and state pool watermarks. These general-purpose capabilities offered by Baidu AI Cloud can serve as the foundation for the engineering implementation; specific parameters should be based on your own load test results.
8. Common Pitfalls
- Treating the recurrent state as an ordinary cache and applying LRU, causing error accumulation;
- Doing a full deep copy on fork, canceling out the sharing benefit;
- Optimizing only memory capacity while ignoring bandwidth, with no throughput improvement;
- Approximate compression without monitoring, causing silent degradation on long tasks;
- Prefix fingerprints that omit the model version and configuration, causing false hits across versions.
9. Summary
The benefit of hybrid architectures is faster decoding and a smaller cache, but the cost is heterogeneous state and complex management. Only by rebuilding the cache from “a single contiguous memory” into “layered, addressable state,” combined with copy-on-write, tiered compression, and prefix-aware scheduling, can prefill throughput genuinely be pushed up under high-reuse, long-context workloads like Agents.
