Rebuilding State Caching for Hybrid LLMs: A Practical Guide for AI Coding Workloads
This article explains why cache management becomes harder in hybrid LLM architectures that interleave full-attention layers with linear state layers. It contrasts token-appendable KV caches with fixed-size recurrent states, then presents a three-tier cache design (block-level KV cache, state snapshot cache, shared base), prefill scheduling strategies, and tiered memory pooling with distributed reuse. Readers will find metadata structures, scheduling pseudocode, and a staged rollout plan for improving prefill throughput and tail time-to-first-token.
1. Background: Hybrid Architectures Make Caching Harder
In open-source LLM architectures over the past two years, linear attention and state-space layers (for example, various gated incremental update mechanisms and structured state recurrence modules) appear with increasing frequency. They are usually stacked alternately with a small number of full-attention layers, forming a hybrid structure of “full attention + linear state layers.” The core motivation is clear: reduce the modeling cost for most tokens from “growing quadratically with context length” to “growing linearly with length,” significantly shrinking cache size during inference and improving decoding speed.
The engineering reality, however, is that the structure got simpler while cache management got more complex. The reason is that the state semantics of the two layer types are completely different.
- The full-attention cache is appended per token as key-value pairs; any prefix is reusable and can be trimmed precisely.
- The linear state cache is a fixed-size recurrent state that “compresses” the entire history into a matrix or vector; it cannot be split per token, nor can the last few tokens be dropped while keeping the semantics correct.
In workloads like AI coding tools, the problem is amplified further. Multi-turn conversations, repository-level long contexts, and frequent tool calls and file re-ingestion make the shared prefix across requests extremely long and highly overlapping, while the conversation branch points differ from request to request. Pure Transformer systems typically rely on “prefix block hashing + paged cache,” whereas hybrid models must handle both “splittable KV blocks” and “unsplittable fixed-size states.” This is the new source of complexity.
2. The Essential Differences Between the Two State Types
To design a correct caching system, start by making the differences clear.
2.1 Cache Shape and Growth
Full-attention part: cache size is proportional to the number of processed tokens; reads and writes are block-based, naturally suited to paging and block-level addressing.
Linear state part: whether the context is 4K or 256K, the state size is essentially constant. It behaves more like a “lossy summary”: writes are in-place updates, and reads take the whole block at once.
2.2 Reuse Granularity
A KV cache can do “hit the first N tokens and reuse the first N tokens.” A state cache can only do “hit a specific historical prefix and reuse the state snapshot taken at the end of that prefix.” This means the reuse unit for states is the conversation path, not a token range.
2.3 Invalidation and Rollback Semantics
If a request is preempted mid-generation, canceled, or needs to roll back to an earlier branch point, the KV cache only needs to truncate trailing blocks; the state cache must roll back to a historical snapshot. Otherwise, all subsequent recurrence results are skewed, and this skew does not converge on its own.
2.4 Compute and Memory-Access Characteristics
During prefill, the full-attention part is compute-intensive, while the linear state layers lean toward memory access and serial recurrence. When the two are interleaved, if the scheduler batches by a single resource dimension only, one class of operators can easily slow down the entire batch.
3. A Layered Redesign of the State Cache
Given the differences above, a practical general design is to split the cache into three separately managed layers.
The first layer is a block-level KV cache, continuing to use paged management, with fixed blocks as the unit of allocation and eviction. The block hash includes the parent block identifier, naturally expressing prefix-tree relationships.
The second layer is a state snapshot cache, keyed by “path node,” where each node stores the fixed-size state at the end of that prefix. It is not tied to token count but to branch points. In practice, snapshots should have an independent lifecycle, because they are small and have high reuse value, so they can be retained longer than KV blocks.
The third layer is a shared base, used to store common prefix states across sessions, such as system prompts, repository descriptions, and tool definitions. This content is nearly unchanged across all requests and is best kept resident long-term and shared across nodes.
A schematic metadata structure can be written as:
@dataclassclass StateSnapshot:path_id: str # Prefix tree node identifierparent_id: str | None # Parent node, used for rollback and locating branchesstate_tensor: bytes # Fixed-size recurrent statetoken_len: int # Context length corresponding to this snapshotlayer_ids: list[int] # Only linear state layers need snapshots@dataclassclass KvBlock:block_hash: str # Includes parent block hash to express prefix relationshipskv_pages: list[int] # Paged indicesref_count: int
The key design principle is: evict KV blocks by length, retain state snapshots by path, and keep the shared base resident by reference count.
4. Prefill Scheduling: Actually Realizing the Benefits
The caching system is only a prerequisite; throughput and latency gains come mainly from scheduling.
First, find the longest common prefix hit before starting prefill. The system needs to locate the deepest matching node in the prefix tree, retrieve the corresponding KV blocks and state snapshot, and compute only the unmatched suffix. The most error-prone part here is inconsistent hit lengths between the two cache types; you must align to the shorter one, otherwise the state and KV will not match.
Second, group batches by operator characteristics. Separate requests with long prefixes, pure suffixes, and no hits into different batches to avoid compute-intensive and memory-intensive requests interfering with each other; for no-hit requests, chunked prefill can be used to control batch size and stabilize tail latency.
Third, front-load branch points. When multiple candidate actions are predicted (for example, multiple tool-call branches), first complete prefill of the common prefix and write a state snapshot, then expand branches in parallel, avoiding repeated computation of the same history.
Fourth, prefer rolling back state over full recomputation on preemption. Treat snapshots as checkpoints; after preemption, resume from the nearest checkpoint, combined with KV block truncation, to minimize the recomputation range.
A simplified scheduling pseudocode:
def schedule(req):hit = prefix_tree.deepest_match(req.tokens) # Returns both kv hit and state hitn = min(hit.kv_len, hit.state_len) # Align the two cache typessuffix = req.tokens[n:]if len(suffix) > CHUNK:return chunked_prefill(req, n, CHUNK) # Control tail latencyreturn prefill_from(req, n, suffix)
5. Adding a Large Memory Pool and Distributed Reuse
When single-machine cache capacity is insufficient, cold data can be pushed down to a larger-capacity, higher-latency storage tier, forming a tiered cache of “GPU memory—host memory—remote storage.” There are three key points:
First, tiered promotion policy. State snapshots are small and have high hit rates, so they should be promoted to the fastest tier first; KV blocks are promoted by block热度.
Second, overlap transfer and computation. Load the next cache segment while computing the current one to hide transfer latency; otherwise the benefits of the large-capacity tier will be eaten by memory access.
Third, cross-node consistency. Distributed reuse requires strict correspondence among prefix identifiers, snapshot versions, and model weight versions; any weight or configuration change should invalidate old snapshots to avoid silent incorrect reuse.
6. Sources of Gains and Rollout Recommendations
Under workloads like real agent trajectory replay, the reason this kind of redesign can increase prefill throughput several times and substantially reduce tail time-to-first-token comes down to four points: eliminating repeated prefill across turns; turning the reuse of unsplittable states from “unusable” to “usable”; stabilizing long tails through chunking and grouped batching; and reducing preemption cost through checkpoint rollback.
For rollout, proceed in order: first unify the prefix identifier and cache metadata model, then implement state snapshot storage, access, and invalidation, then modify the scheduler’s hit determination and batching logic, and finally integrate tiered storage and cross-node reuse. If you deploy on a container platform, use object storage for cold data, and use logging and monitoring with alerting to observe hit rates and tail latency, you can locate bottlenecks faster. It must be emphasized that any performance numbers depend heavily on model structure, context length distribution, and hardware conditions; always measure a baseline on your own workload before deciding cache tiers and eviction policies.
