State Cache Optimization for Hybrid-Architecture LLMs in Agent Inference
This article explains why hybrid models that combine full attention with linear sequence modeling need different cache designs than standard KV Cache systems. It covers how multi-step agent workloads reuse context, which cache types and metadata to track, how checkpoints support branching and rollback, and how to evaluate prefill and decode performance.
Large language models are moving from architectures where every layer uses full attention to hybrid designs. Some layers keep full attention to model local and cross-segment dependencies precisely. Other layers use linear sequence modeling or recurrent states, which handle long sequences at a lower memory cost.
This change affects more than the model’s computation graph. It also changes cache design in inference systems. Traditional inference engines build the KV Cache around attention layers. A hybrid model has both attention caches and linear-layer states, and the two differ in data shape, update method, lifecycle, and reuse conditions. A single cache strategy often cannot take full advantage of a hybrid architecture.
1. Why Agent Scenarios Need Better State Caching
A regular question-answering request usually involves one input and one generation pass, so inference is relatively short. Agent tasks are different. They include multi-step planning, tool calls, observing results, and making new decisions. During this process, the model repeatedly processes similar context:
- The user’s goal stays the same across steps.
- The system prompt and tool definitions usually persist for the whole session.
- Tool results may keep being appended.
- Each generation step depends on earlier conversation and action history.
- Some branches roll back, retry, or explore in parallel.
If every request re-runs prefill over the full context, first-token latency increases and much of the matrix computation is repeated. For long-context agents, compute cost also rises quickly as the history grows.
Agent inference optimization therefore cannot focus only on single-pass decoding speed. It also needs to account for:
- Prefill throughput;
- First-token latency;
- Per-token cost during decoding;
- Cache memory usage;
- Reuse rate of multi-turn state;
- Rollback cost when branches are explored;
- Memory contention between concurrent requests.
2. How Hybrid Architectures Change Caching
In a full-attention model, each attention layer typically stores keys and values for later token computation. Cache size grows with input length. Its basic characteristics are:
- Cache entries map one-to-one to token positions;
- New tokens append new keys and values;
- Reading history requires accessing the corresponding positions;
- Multi-turn conversations keep expanding the cache.
Linear layers in a hybrid model usually maintain a recurrent state. This state does not necessarily store a full representation of every past token. Instead, it is updated continuously with compressed summary information. Its typical characteristics are:
- State size stays relatively stable or grows slowly;
- New input incrementally updates the existing state;
- Later computation depends on the current state rather than the full history;
- The state may not be readable by token position the way a KV Cache is.
A hybrid model therefore needs to manage at least two types of cache.
1. Attention Cache
The attention cache keeps precise local context, such as recent conversation, tool call arguments, code snippets, and content that must align token by token. Its advantage is high fidelity. Its drawback is that memory use grows with sequence length.
2. Linear-Layer State
Linear-layer state represents compressed information over longer ranges, which reduces storage pressure for long sequences. However, state updates depend on order. The state cannot simply be copied, concatenated, or read at random like a static KV block.
3. Metadata and Boundary Information
Beyond the tensors, the system also needs to store metadata such as layer type, sequence position, chunk boundaries, version tags, device location, and valid length. Without this information, the cache data may be correct but still cause state misalignment during branch reuse or cross-turn calls.
3. Main Problems with Traditional Cache Designs
1. Treating All Layers as One Cache Type
A common approach places attention caches and linear states in the same allocator. This is simple to implement, but it causes the two resources’ lifecycles to interfere with each other. Attention caches need dynamic appending. Linear states are better suited to in-place updates or checkpoint-based saving.
2. Using the Full Sequence as the Reuse Unit
If a cache can only be reused when the entire request matches, a small change in the prefix invalidates the whole cache. In agent workloads, tool results, timestamps, and intermediate observations often change, so full-sequence matching lowers the cache hit rate.
3. Ignoring Branching and Rollback
Agents often try several plans. If each branch copies the full cache, memory fills up quickly. If branches share mutable state directly, an update in one branch can corrupt another. A cache system therefore needs read-only sharing, incremental writes, and fast rollback.
4. Using the Same Scheduling for Prefill and Decode
Prefill usually has high parallelism and suits batched matrix operations. Decode works with small batches, strict ordering, and frequent memory access. Applying the same batching and memory policy to both often leaves prefill underutilized or makes decode scheduling overhead too high.
4. Core Ideas for Redesigning Hybrid State Caching
1. Manage Different States in Tiers
The cache can be split into three tiers:
- Hot state: requests currently generating, kept in high-bandwidth device memory;
- Warm state: prefixes or checkpoints likely to be reused soon, kept in a lower-cost, high-speed storage tier;
- Cold state: history that has not been accessed for a long time, restored when needed.
Different cache types should not use the same eviction policy. Attention cache can be managed in token blocks. Linear states are better managed by layer, checkpoint, or sequence stage.
2. Define a Unified State Descriptor
Each cache entry should contain at least the following fields:
StateEntry {request_idsequence_idlayer_groupstate_typeposition_rangeversiondevice_locationreference_countwritable}
state_type distinguishes attention cache from linear state. version detects stale state. reference_count allows multiple agent branches to share read-only state. Real systems can use different data structures, but the core principle is to tie each cache entry clearly to its lifecycle, writability, and origin.
3. Use Checkpoints for Low-Cost Branching
When an agent enters a planning, tool-call, or retry stage, the system can create a lightweight checkpoint of the current state. A checkpoint does not need to copy every tensor. It records:
- The current sequence position;
- The version of each layer’s state;
- Newly added cache blocks;
- Reference relationships to shared state.
When a branch updates state, use copy-on-write so that only the parts that actually change are copied. This substantially reduces the memory cost of parallel exploration and failure rollback.
4. Distinguish Exact Reuse from Approximate Reuse
Stable content, such as system prompts and fixed tool descriptions, can use exact prefix reuse. Linear states that are compressed or updated recurrently require stricter checks. The model version, layer configuration, position encoding state, and input boundaries must all match. Reuse cannot be decided from a text summary alone.
Any factor that could affect model output should be included in the cache key. Examples include:
- Model and weight version;
- Inference precision;
- Parallel layout;
- Position encoding configuration;
- Prefix content;
- State update version;
- Special token configuration.
5. Improving Prefill Throughput
The goal of prefill is to feed large batched inputs into compute units as continuously as possible while reducing unnecessary state write-backs.
First, organize computation by layer type. For attention layers, use chunked processing to avoid allocating overly large contiguous caches at once. For linear layers, update the state as the sequence is processed. This reduces repeated saving of intermediate results.
Second, compute shared prefixes once. When multiple agent requests share the same system instructions and tool definitions, prefill the common part first, then process each user input and tool result separately. Sharing is safe only when the prefix matches exactly and the state boundary is clear.
Third, pipeline state writes with computation. Compute threads generate new states, while cache threads organize and migrate them asynchronously. The two synchronize through version numbers or events, which avoids blocking memory copies after every layer.
When resources allow, group requests by length. Mixing long and short sequences in one batch causes padding waste and tail waiting. Bucketing by length usually improves device utilization.
6. Decode-Stage Optimization
Decode usually generates only a few tokens per step, so the bottleneck often shifts from compute to memory access and scheduling.
One effective approach is to keep frequently accessed states in contiguous memory and minimize pointer chasing. For attention cache, use fixed-size blocks to reduce dynamic allocation and fragmentation. For linear states, avoid unnecessary full copies. Prefer in-place updates or double-buffered updates.
Cache precision also needs control. Not every state must be stored at the highest precision. For intermediate states that have been verified as insensitive, lower-precision storage may be considered. However, offline evaluation must confirm the effects on generation quality, tool-call accuracy, and long-context stability.
For scheduling, waiting requests can be classified by cache hit status:
- Requests that hit the full prefix go to decode first;
- Requests that hit only part of the state fill in the missing parts first;
- Requests with no cache enter the prefill queue;
- Requests that need rollback restore the most recent checkpoint first.
This tiered scheduling reduces average latency more effectively than processing requests simply in arrival order.
7. Evaluation Should Not Rely on a Single Metric
Headline claims such as “several-fold throughput gains” usually depend on specific hardware, sequence lengths, concurrency, cache hit rate, and precision settings. They cannot be generalized to all scenarios. Engineering evaluation should cover at least the following metrics:
- Prefill token throughput;
- Single-request first-token latency;
- Per-token decode latency;
- Peak memory usage;
- Average cache hit rate;
- Branch rollback time;
- Tail latency under concurrent requests;
- Performance changes across different context lengths;
- Output consistency before and after cache optimization.
Tests should separate pure chat, long-document QA, tool
