State Cache Optimization and Throughput Improvement Practices for Hybrid Architecture LLMs
As large language models (LLMs) evolve from pure full-attention architectures into hybrid models combining full-attention, linear-attention, and state-space layers, traditional cache management strategies become inadequate. This article explores how to optimize state caching and improve inference throughput for hybrid architecture LLMs. By shifting the focus from fixed block-based allocation to identifying safe reuse boundaries across different layer types, it details the core data structures, resume point calculation, hierarchical storage design, and consistency validation. It also highlights the significant benefits of this approach for Agent workloads and provides practical engineering guidelines for implementation.
1. Why Hybrid Architectures Require Redesigned Cache Management
In recent years, the architecture of large language models has gradually evolved from a single full-attention structure to a hybrid form combining “full-attention layers + linear-attention layers” or “full-attention layers + state-space layers.”
Full attention mechanisms excel at precisely modeling relationships between arbitrary positions, but their inference process typically requires maintaining a large-scale Key-Value (KV) cache. As the context length increases, the pressure on cache capacity and memory bandwidth rises significantly. Linear attention, gated state update mechanisms, and state space models tend to compress historical information into a fixed-size or relatively stable recurrent state, thereby reducing the storage overhead during token-by-token decoding.
While this hybrid architecture offers better inference efficiency in standard conversational tasks, cache management becomes much more difficult in scenarios like coding agents, automated operations agents, and multi-turn tool calls. This is because such tasks usually involve the following characteristics:
- A single task generates multiple rounds of context;
- Each round may only append a small amount of content at the end;
- Different branches may share a very long historical prefix;
- Tool call results cause context branching;
- Different layers within the model use different historical representations.
For pure Transformer models, systems typically organize KV Cache by token position and use prefix matching to determine which content can be reused. However, in hybrid architectures, some layers rely on traditional KV Cache while others depend on recurrent or compressed states. Their recoverable positions, invalidation conditions, and storage formats are inconsistent. If the system still uses a unified chunking strategy, it often leads to a situation where “some caches can be reused, but the overall cache cannot be restored.”
Therefore, the key to a hybrid architecture inference system is not just reducing cache capacity, but accurately answering a more fundamental question:
In the current request, from which position can the model safely continue computing?
2. Shifting from “How to Block” to “Where to Reuse”
Traditional caching systems often define fixed-size blocks first, and then perform allocation, eviction, and restoration in block units. This method is simple to implement and suitable for models with uniform layer structures.
However, in hybrid architectures, the reuse boundary of the cache does not necessarily align with fixed block boundaries. Some layers may have already completed state computation up to a certain position, while others still need to re-execute from an earlier position. At this point, if the system only uses a unified token block as the restoration unit, two types of problems will occur:
- The restoration position is too early, leading to increased redundant computation;
- The restoration position is too late, causing state inconsistency and potentially affecting output correctness.
A more reasonable design approach is to first analyze the reusable range of each cache type and then reversely determine the restoration position.
Caches can be abstracted into three types:
1. Full Attention Layer KV Cache
This type of cache usually corresponds directly to historical token positions. As long as the prefix content is consistent, and the corresponding model configuration, positional encoding, and batch processing conditions are met, the relevant KV data can be reused.
2. Linear Attention Layer Recurrent State
Linear attention usually does not store the complete keys and values of all historical tokens; instead, it maintains a state that summarizes historical information. This state depends on strict input order. If a change occurs at an intermediate position, the subsequent state usually cannot be directly inherited.
3. State Space Layer Internal State
State space layers also feature recurrent updates. Their states may contain multiple tensors, and the state sizes and update methods may differ across layers. State restoration must ensure that the input positions corresponding to the state are exactly identical; otherwise, subsequent computation results will deviate.
Therefore, the cache system cannot simply treat all content as the same type of “historical cache.” It should establish a unified index oriented towards layer types and state dependency relationships.
3. Core Data Structure of Hybrid State Cache
A scalable hybrid state cache system needs to record at least the following information:
CacheEntry├── prefix_identity # Logical identifier of prefix content├── token_range # Corresponding token position range├── attention_cache # Full attention layer KV data├── recurrent_state # Linear layer or state space layer state├── layer_coverage # Covered layer range├── parent_reference # Parent prefix or shared node├── storage_location # GPU, CPU, or remote storage location└── validation_metadata # Metadata for consistency validation
Here, prefix_identity should not rely solely on a simple string hash; it should also consider the model version, tokenization method, inference configuration, and necessary positional information. For Agent tasks, the system can also divide system instructions, tool definitions, historical conversations, and tool return results into different logical segments to enable more precise reuse.
layer_coverage is particularly important. It indicates which layers a cache entry actually covers, rather than assuming all layers have the same completion position. For example, a cache node might already contain KV data for the first few layers, but only partial recurrent states. The scheduler can use this to calculate the optimal resume point instead of blindly restoring the entire cache block.
4. Calculation Method for the Resume Position
Hybrid cache restoration can be viewed as a constraint intersection problem.
Assuming the full attention layer can be reused up to position (p_a), the recurrent state layer up to (p_r), and the state space layer up to (p_s), the safe resume position usually cannot exceed the minimum of these boundaries:
[
p_{\text{resume}} = \min(p_a, p_r, p_s)
]
This is just the basic scenario. In a real system, you also need to consider whether the cache is complete, whether dependencies exist between different layers, whether positional encoding is continuous, and whether the request has branched.
If a certain type of state can be advanced from an earlier node to the target position through extra computation, the system can split the recovery process into two parts:
- Restore from the saved state position;
- Perform incremental prefill for the missing interval;
- Continue executing subsequent computation after reaching the common boundary.
The advantage of this approach is that it avoids complete recomputation from the start of the request while also preventing the erroneous use of incomplete states.
For multi-turn Agent tasks, the context can be represented as a prefix tree:
System Instructions│Task Description├── Tool Call Branch A│ └── Results and Subsequent Instructions└── Tool Call Branch B└── Results and Subsequent Instructions
Each node saves the cache state corresponding to its newly added content, and child nodes share the common prefix through parent node references. When a new request arrives, the system only needs to find the longest consistent prefix and check the recoverable boundaries of various states to decide where to continue execution.
5. Why Agent Scenarios Benefit the Most
In ordinary single-turn conversations, the number of cache reuses is limited, and the extra benefits of cache management may not be obvious. However, in coding agents and tool-calling tasks, the prefill phase often accounts for a large proportion.
A typical workflow might be:
- Read system rules and task objectives;
- Load code snippets or file contents;
- Generate a tool call;
- Receive tool return results;
- Continue analysis based on the results;
- Repeat the above process.
These rounds usually share a long historical prefix, while newly added content only accounts for a small portion of the overall context. If each round of requests executes prefill from scratch, the GPU will repeatedly process a large number of identical tokens, causing throughput degradation and increased Time to First Token (TTFT) latency.
Hybrid state cache can reuse:
- Fixed system prompts;
- Tool descriptions and parameter definitions;
- Already analyzed code context;
- Historical tool call records;
- Task backgrounds shared across multiple branches.
Especially when multiple agents concurrently process similar tasks, prefix caching can significantly reduce redundant computation. For scenarios requiring frequent switching between task branches, the prefix tree-based sharing method can also reduce VRAM and host memory usage.
6. Hierarchical Design: GPU, CPU, and Distributed Cache
Caches do not necessarily have to be entirely placed in GPU VRAM. A practical system usually adopts hierarchical storage:
GPU Layer
The GPU layer stores hot states for requests currently being executed or about to be executed, with the goal of reducing access latency. Due to limited VRAM capacity, lifecycle management and eviction strategies are required.
CPU Memory Layer
The CPU layer is used to store caches that are temporarily inactive but may be reused in the future. Its capacity is usually larger than that of the GPU, but data migration is affected by memory bandwidth and bus transfer speeds, so it needs to be combined with request scheduling for prefetching.
Remote Storage Layer
In multi-instance or multi-node deployments, distributed memory, object storage, or dedicated cache services can be used to store cold data. The remote layer is suitable for storing states with a low probability of reuse but a high cost of recomputation.
The key to hierarchical caching is not simply expanding storage capacity, but building a cost model. The system can decide whether to load a certain cache based on the following factors:
- Transfer time required to read the cache;
- GPU time required to compute from scratch;
- Probability of the cache being hit in the future;
- Current GPU and CPU resource load;
- Compression and decompression overhead of state data.
Restoring a cache is only practically beneficial when the “cost of loading the cache” is lower than the “cost of recomputing.”
7. Cache Consistency and Security Validation
State cache reuse must be predicated on correctness. It is recommended to record the following validation information in the cache metadata:
- Model structure and weight version;
- Tokenizer version;
- Position encoding related configurations;
- Quantization or precision configurations;
- Digest of the input prefix;
- Shape and data type of state tensors;
- Inference parameters used when generating the state.
If any key condition does not match, the cache should not be directly restored. For example, the same text might correspond to different token sequences after a tokenizer version change; after model weights are updated, old states can no longer be used.
Furthermore, the cache system needs to distinguish between “logically identical” and “byte identical.” For inference tasks requiring strict reproducibility, it is recommended to use stable content digests and structured metadata rather than relying solely on string prefixes to determine if sharing is possible.
8. Key Performance Evaluation Metrics
When evaluating hybrid state caches, you cannot just look at a single throughput metric. You should simultaneously observe at least:
- Prefill Throughput: Number of input tokens processed per unit of time;
- Time to First Token (TTFT): Time from request submission to the generation of the first output token;
- Cache Hit Rate: Proportion of requests that successfully reused existing states;
- Effective Reuse Length: Actual number of tokens for which computation was skipped;
- State Transfer Overhead: Data transfer time between GPU, CPU, and remote storage;
- Tail Latency: Especially P90, P95, or P99 latency in high-concurrency scenarios;
- VRAM Usage: Impact of cache policies on the number of concurrent requests;
- Correctness Metrics: Whether the output remains consistent before and after cache restoration.
Public experiments show that in real multi-turn coding agent trajectories, redesigning the cache organization for hybrid architectures can achieve several times the prefill throughput of traditional cache implementations, and TTFT tail latency can also be significantly reduced. However, actual gains will be affected by context length, prefix repetition ratio, cache hit rate, hardware bandwidth, and scheduling strategies, so a single test result should not be blindly applied.
9. Engineering Implementation Guidelines
If you want to introduce hybrid state caching into an inference service, you can implement it in the following order:
Step 1: Identify Model State Types
Clarify which layers use KV Cache and which use recurrent states, and record the shape, lifecycle, and dependencies of each state type.
Step 2: Build a Unified Cache Index
Incorporate token prefixes, layer ranges, state positions, and storage locations into the same index to prevent different cache modules from maintaining their own structures and failing to coordinate.
Step 3: Implement Longest Prefix Matching
Construct a prefix tree or similar index structure for Agent requests, prioritizing the search for the historical node with the longest reusable length.
Step 4: Calculate Safe Resume Points
Find the common reusable position based on the state boundaries of all relevant layers, and perform incremental computation for the missing intervals.
Step 5: Add Hierarchical Eviction Policies
The GPU side should prioritize keeping states with high hit rates and high recomputation costs, the CPU side should store larger-scale warm caches, and remote storage should be used for cross-process or cross-node sharing.
Step 6: Continuously Monitor ROI
Use metrics like hit rate, restored length, migration time, and tail latency to determine whether caching actually improved the system, rather than simply increasing memory usage and management complexity.
10. Conclusion
The advantages of hybrid architecture models come not only from a smaller KV cache but also from a more efficient compression and recurrent representation of historical information. However, if a fixed chunking strategy designed for pure Transformers is still used, it will be difficult to fully leverage these advantages.
A more reasonable approach is to treat the cache as a combination of multiple states, determine the resume position based on “which states can be safely reused,” and then reduce redundant prefill costs through prefix trees, hierarchical storage, and distributed sharing mechanisms.
For long-context, multi-turn dialogue, and coding agent workloads, this design can simultaneously improve prefill throughput, TTFT, and VRAM utilization. Future inference systems will no longer just manage a single KV Cache; they will need to unifiedly manage KV, recurrent states, state space states, and cross-device caches, truly integrating cache reuse capabilities into the core scheduling logic of model serving.
