Hybrid Architecture Cache Refactoring: Doubling Prefill Throughput

    This article explains why hybrid architectures that alternate full-attention and linear state layers are becoming the default for agent workloads, and why conventional KV Cache designs fail under them. It breaks down the three state types involved, identifies prefill bottlenecks in state management rather than compute, and presents three refactoring directions: tiered state caching, checkpoint placement with verifiable compression, and cache-aware prefill scheduling. Engineering pitfalls and expected gains are also covered.

    1. Why Hybrid Architectures Are Becoming the Default for Agent Workloads

    Over the past two years, a hybrid architecture that alternates full-attention layers with linear state layers has been widely adopted. The motivation comes from the real characteristics of agent workloads: a single task often carries a long system prompt, tool definitions, multi-turn history, and retrieved snippets, pushing input lengths to tens of thousands or even hundreds of thousands of tokens, while outputs stay relatively short. Under a pure full-attention design, the key-value cache (KV Cache) grows linearly with context length, and both memory footprint and memory bandwidth quickly become the bottleneck. Linear state layers (state space models, linear attention, and similar designs) carry history in a recurrent state of fixed size, sharply reducing memory traffic during decoding.

    Hybrid architectures aim to capture the strengths of both: linear layers compress long-range history at low cost, while a small number of full-attention layers provide precise recall of critical details. The structure also introduces a new engineering problem, however: the cache is no longer a single shape but a hybrid of full-attention key-value tensors plus linear-layer recurrent states, and the two differ enormously in lifecycle, portability, and compressibility. When agent scenarios demand frequent reuse, branching, and rollback of context, conventional KV-Cache-centric designs break down.

    2. How Hybrid State Caches Differ Fundamentally from Traditional KV Caches

    Understanding the optimization space starts with separating three kinds of state:

    • Full-attention key-value cache: proportional to sequence length, can be truncated precisely and reused by prefix, semantically clear but large.
    • Linear-layer recurrent state: fixed size, independent of sequence length, but it is compressed history and cannot be sliced and reused per token.
    • Intermediate activations and metadata: position offsets, layer normalization statistics, sampling state, and so on. Small in size, but they affect correctness.

    Traditional caching systems assume that “a cache entry is a key-value sequence reusable at any prefix.” That assumption no longer holds under hybrid architectures. A linear state can only be restored as a whole from a checkpoint: sparse checkpoints force large prefixes to be recomputed, while dense checkpoints inflate the number of cache entries and index overhead. This is the root cause of stalled prefill throughput: the scheduler cannot accurately determine what to reuse, what to recompute, and at what cost.

    3. Locating the Bottleneck: Prefill Is Stuck on State Management, Not Compute

    In long-context agent scenarios, the prefill stage typically shows three traits. First, a high proportion of repeated prefixes: the same system prompt and tool descriptions are submitted repeatedly across a session. Second, frequent branching: one tool call result spawns multiple candidate reasoning paths. Third, a long-tailed length distribution: a few very long requests consume most of the compute.

    If the cache can only hit the full-attention portion, the linear state still has to be advanced from scratch and the actual savings are minimal; conversely, caching only the linear state while ignoring the key-value portion leaves the attention layers to be recomputed. The real optimization goal is therefore to let both state types be reused cooperatively under one indexing and scheduling framework, and to turn “recompute cost” into an estimable, sortable scheduling parameter.

    4. Refactoring Direction 1: Tiered and Layered State Caching

    Split the cache into three tiers with different lifecycles:

    1. Session-level hot cache: holds both state types for stable prefixes such as system prompts and tool definitions, resident in high-bandwidth storage.
    2. Task-level warm cache: holds checkpoints taken after a given tool call, indexed by task identifier and reclaimed when the task ends.
    3. Rebuildable cold cache: holds only lightweight metadata and sparse checkpoints, recomputing local segments on demand after a hit.

    The key to tiering is recording a “rebuild cost” estimate for each entry, so the scheduler can order by benefit instead of simply evicting by least recent use. A sketch of the entry structure:

    1. @dataclass
    2. class StateEntry:
    3. prefix_hash: str # Prefix fingerprint for exact matching
    4. kv_blocks: list[int] # Full-attention key-value block indices
    5. ssm_state: bytes # Linear-layer recurrent state snapshot
    6. length: int # Number of tokens covered
    7. rebuild_cost: float # Estimated recomputation cost
    8. level: str # hot / warm / cold

    5. Refactoring Direction 2: Checkpoint Strategy and State Compression

    Because linear state cannot be reused per token, checkpoint placement determines reuse granularity. In practice, a hybrid strategy works well: force checkpoints at fixed intervals, and add extra checkpoints at semantic boundaries such as tool calls and inserted retrieval results, so common branch points are guaranteed to hit.

    For compression, recurrent states can be stored with low-rank or quantized representations, and key-value blocks can be block-quantized and sparsified, but a verification mechanism with bounded error is required: after restoration, sample a few positions and compare output distributions, falling back to recomputation if the deviation exceeds a threshold. This kind of verifiable compression is more robust than chasing compression ratios alone.

    6. Refactoring Direction 3: Cache-Aware Prefill Scheduling

    The scheduler should take cache state as a decision input, with the core being a comparable score for “hit benefit / recompute cost”:

    1. score = (hit_tokens * unit_prefill_cost) / (rebuild_cost + transfer_cost + eps)

    On top of this, three things can be done: prioritize high-scoring requests to amortize memory transfer overhead; use chunked prefill for very long requests, writing completed block states to the warm cache promptly to avoid a full rollback; and batch concurrent requests that share the same prefix, so one forward pass serves multiple branches. In cross-node settings, state migration should overlap with computation, using pipelining to hide transfer latency.

    7. Implementation Notes and Common Pitfalls

    Four points deserve attention. First, fingerprints must include the model structure version and quantization configuration, otherwise cross-version reuse produces silent errors. Second, cache capacity must be tied to the memory budget, with room reserved for defragmentation to avoid degradation over long runs. Third, observability is not optional: record hit rate, average rebuild length, queueing latency, and peak memory to close the tuning loop. Fourth, correctness takes priority over throughput, and any compression or reuse must have a fast fallback path.

    Common pitfalls include caching only the key-value portion while ignoring linear state, which yields far less benefit than expected; checkpoints that are too sparse, so a hit still requires long-segment recomputation; treating the cache as a pure memory problem while ignoring bandwidth and fragmentation; and managing entries with vastly different lifecycles under a single eviction policy.

    8. Platform Capabilities That Support These Optimizations

    The approach above places clear demands on infrastructure: high-throughput distributed caching and messaging channels to carry state migration, a container platform providing an elastically scaling inference instance pool, object storage for cold checkpoints, and logging plus monitoring and alerting to continuously observe hit and latency metrics. In Baidu AI Cloud’s product portfolio, these general capabilities can be combined as needed to build the caching, scheduling, and observability loop, without binding to a specific model architecture.

    9. Expected Gains and Future Directions

    Once the two state types are reused cooperatively, checkpoints cover real branch points, and scheduling orders by benefit, the main prefill cost shifts from “repeatedly advancing history” to “necessary attention computation and state transfer,” with the largest gains on agent workloads that have a high proportion of repeated prefixes. Future directions include cross-session state sharing with sanitization, heterogeneous cache pools spanning multiple models, and adaptive strategies that tune checkpoint density from online feedback. Overall, the performance ceiling of a hybrid architecture depends not only on the structure itself but on whether state caching is designed as a first-class citizen.