Mixed-Architecture Agent Prefill Optimization: Redesigning KV and State Caches
This article examines prefill optimization for hybrid full-attention/linear architectures in coding-agent workloads. It explains why KV-only prefix caching is insufficient, outlines four constraints for unified mixed-state caches—precise state boundaries, versioned cache keys, prefix-tree branching, and tiered/distributed reuse—and presents design principles, a request workflow with pseudocode, performance measurement considerations, and engineering boundaries.
1. Background: Why Hybrid Architectures Depend More on Caches Under Agent Workloads
Hybrid architectures that combine full-attention layers with linear layers or state-space layers usually have a clear goal: retain the long-range dependency modeling of full attention while using linear layers to reduce decoding-time computation and KV cache overhead, thereby achieving faster generation and lower memory usage. These architectures show clear advantages in single-turn question answering. In multi-turn, long-context, tool-heavy workloads such as coding agents, however, the system bottleneck shifts from single-step decoding to prefill and cache reuse.
Typical coding-agent requests are not one-off. System prompts, tool definitions, codebase context, conversation history, tool results, code diffs, and test outputs accumulate continuously and are repeated heavily across turns. Ideally, the inference service should reuse the cache of an existing prefix and prefill only the newly added suffix. But prefix caching for hybrid architectures is much more complex than for pure Transformers: full-attention layers can maintain a KV cache per token, while linear layers maintain a recurrent compressed state that is not a simple token-by-token truncatable structure. On a cache hit, the system must restore not only KV data but also the linear state, and it must ensure that the state matches the exact prefix boundary, positional encoding, and model version.
As a result, cache management for hybrid architectures cannot simply follow the KV-block reuse logic of pure attention models. It requires unified modeling of both KV cache and linear state cache. This is the core motivation for redesigning mixed-state caching.
2. Problem Breakdown: Four Key Constraints for Mixed-State Caches
2.1 State Boundaries Must Be Exact
KV data in full-attention layers can be split by token position. After a partial prefix hit, computation can usually continue from a token boundary. The state of a linear layer is a recurrent compression of historical information. Although it saves space, it cannot be arbitrarily truncated, concatenated, or partially merged like KV data. A state snapshot must correspond to an exact token prefix, position offset, and intra-layer recurrence boundary. If the boundary is misaligned, subsequent prefill will continue from incorrect history, making output quality unpredictable.
2.2 Cache Keys Must Be Versioned
The validity of a mixed-state cache depends on model weights, layer configuration, precision settings, positional encoding scheme, linear-layer recurrence implementation, and other factors. A change in any of these can invalidate an old snapshot. A cache key cannot be determined only by the token sequence. It should include metadata such as model version, configuration fingerprint, precision, tokenizer version, and state layout version. Otherwise, the system may encounter a subtle failure where it hits an old state even though the model has been updated.
2.3 Prefix Branching Requires Tree-Based Management
Agent workloads are naturally multi-branching: under the same system prompt, different tool calls produce different outputs; parallel subtasks explore different code modifications; and after a user interruption, a new question may start from a historical node. These requests share long prefixes but branch at some point. The cache system needs to organize snapshots as a prefix tree and support longest-prefix matching, reference counting, copy-on-write, and benefit-based eviction. Keying by complete request alone would waste many reusable prefixes.
2.4 Tiered and Distributed Reuse Introduces New Overhead
GPU memory is suitable for holding hot prefixes, large CPU memory is suitable for holding mid-term snapshots, and distributed object storage or file systems are suitable for cold snapshots. However, cross-tier loading, compression and decompression, network transfer, and state verification all have costs. Caching is beneficial only when the total cost of snapshot restore plus incremental prefill is clearly lower than recomputing from scratch. Distributed cross-node reuse must also handle consistency, permission isolation, tenant isolation, and failure fallback.
3. Design Principles: Unified Abstraction, Immutable Snapshots, Tiered Reuse
First, unify the cache object. A mixed cache entry should describe the token-prefix fingerprint, full-attention KV blocks, linear-layer state, positional metadata, model version, verification information, and tenant identifier. This allows the scheduler to query, restore, and evict through one interface instead of maintaining two separate sets of logic for the two state types.
Second, use immutable snapshots and reference counting. Once a snapshot is created, it is not modified in place. When branching occurs, a new entry is created through copy-on-write. Reference counting determines which snapshots are still referenced by active requests or prefix-tree nodes, preventing eviction of a state that is being restored.
Third, build a prefix-tree index. When a request arrives, compute its prefix fingerprint, perform longest-prefix matching in the prefix tree, find the nearest restorable snapshot, and then incrementally prefill the suffix from that boundary. Partial hits are more valuable than complete misses, especially with long system prompts and stable codebase context.
Fourth, use tiered placement and cache-aware scheduling. Keep hot snapshots in GPU memory, move mid-term snapshots down to CPU memory, and place cold snapshots in distributed storage. The scheduler should route requests that share the same long prefix to the same node or GPU where possible to reduce cross-node transfer, and it should limit concurrent loads to prevent a restore storm from crowding out compute resources.
4. Workflow and Illustrative Code
A typical workflow is as follows: after a request arrives, compute the prefix fingerprint and query the prefix tree; check the GPU hot cache first, then CPU cache and distributed storage; after loading a snapshot, verify the version and checksum; restore KV and linear state; continue prefilling the new suffix from the snapshot boundary; during generation, asynchronously write back new snapshots and update metadata. If verification fails or loading times out, fall back to prefill from scratch to preserve availability.
def handle_request(req):key = fingerprint(model_version, tokenizer_version,precision, req.prefix_ids, state_layout_version)node = prefix_tree.longest_match(key)entry = cache_lookup(node, tenant=req.tenant)if entry and entry.valid():states = entry.restore()elif node.has_snapshot():states = load_from_lower_tier(node)verify(states, node)else:states = empty_states()out = prefill(states, req.suffix_ids)new_entry = snapshot_immutable(out, key, req.tenant)prefix_tree.attach(new_entry)async_writeback(new_entry, tiers)return decode(out)
This pseudocode highlights three points: the cache key includes version information; verification is required before restoration; and writeback is asynchronous to avoid blocking the critical path. A production system also needs backpressure, timeouts, compression, encryption, and observability metrics.
5. Performance Benefits and Measurement
Public evaluations show that when replaying real coding-agent traces on high-end GPUs, the mixed-state cache redesign can increase prefill throughput by up to 3.14x over a general-purpose inference engine baseline and reduce p90 time to first token by up to 88.4%. With a 512GiB-class CPU cache, the benefits remain significant and support distributed storage and cross-node mixed-state reuse. The essence is to reduce repeated prefill computation and replace long-prefix recomputation with lower-cost state restoration. The clear p90 latency improvement indicates that long-tail requests benefit more from caching.
Evaluation should focus on cache hit rate, state restore latency, cross-tier bytes transferred, compute saved from avoided recomputation, p50/p90 TTFT, and end-to-end throughput. The size of the benefit depends on workload prefix repetition, branching degree, network bandwidth, snapshot size, and model update frequency. Benefits narrow for short requests, low-repetition workloads, or scenarios with frequent model changes.
6. Engineering Practice and Applicable Boundaries
In production, freeze model and state layout versions, canary-release new versions, and retire old snapshots; isolate multi-tenant prefixes to avoid cross-tenant hits; encrypt sensitive content such as tool outputs at rest; cap concurrent restores and provide timeout fallback; and monitor hit rate, restore failure rate, and transfer overhead. Mixed-state caching is not a case of “the more, the better.” It requires a dynamic tradeoff among hit benefit, restore cost, and storage cost. For coding agents with long contexts, multi-turn tool calls, and highly reused prefixes, it is key infrastructure for improving prefill efficiency. For short requests and low-repetition workloads, its complexity and benefits should be evaluated carefully.
