Optimizing Agent State Caching with Hybrid Attention Architectures
Hybrid attention architectures combining full-attention layers with linear state layers are reshaping how LLM inference systems manage state. This article explains why Agent workloads—with multi-turn conversations, tool calls, and continuously accumulating context—demand a redesigned caching strategy. It covers the roles of full-attention KV caches versus recurrent linear states, a three-part state management design, throughput optimizations for prefill, latency optimizations for decoding, state consistency around tool calls, evaluation metrics for throughput claims, and a phased engineering roadmap for production deployment.
In large language model inference, model architectures are evolving from pure full-attention designs toward hybrid schemes that combine full-attention layers with linear state layers. The goal is not simply to reduce one type of computation, but to lower cache footprint, memory bandwidth pressure, and decoding latency in long-sequence inference while preserving critical context modeling capability.
For ordinary Q&A requests, the benefits of hybrid architectures are already noticeable. But in Agent scenarios, the real complexity comes from multi-turn conversations, task planning, tool invocations, result write-backs, and continuously accumulating state. The model must not only understand the current input—it must repeatedly read historical messages, tool return values, intermediate reasoning results, and task execution state. At this point, how the cache is designed often matters more than simply adding compute.
1. Why Agents Demand a Rethink of Caching
Traditional Transformer inference splits attention computation into two phases: prefill and decoding.
The prefill phase processes user input, system instructions, and historical context. The model reads a long sequence in one pass and produces the key and value caches needed for subsequent decoding. The decoding phase then generates output token by token, and each new token requires access to all previously accumulated cache.
In a full-attention model, every layer must store keys and values for every historical token. Given sequence length L, N layers, and attention head dimension D, cache size grows approximately linearly with context length. For long-context tasks, this consumes GPU memory and creates significant memory bandwidth pressure.
Agent requests have several typical characteristics:
Long and unpredictably growing context. A single task may include multiple conversation turns, several tool results, and repeated state updates, making length hard to estimate.
Decoding consists of many short steps. The model may output a plan, invoke a tool, read the tool result, and continue generating. Each stage’s output may not be long, but historical state is accessed repeatedly between stages.
Large amounts of reusable content. System prompts, tool descriptions, workflow rules, and task constraints often remain unchanged across many requests.
Cache capacity becomes the bottleneck under concurrency. As per-request cache usage grows, the number of concurrently served requests drops, hurting overall throughput.
Therefore, Agent inference optimization cannot focus solely on single-request generation speed; it must simultaneously address cache capacity, state reuse, request scheduling, and concurrency isolation.
2. The Different Roles of Full Attention and Linear States
The strength of full-attention layers is their ability to directly associate the current token with any historical position, making them well suited for precise referencing, complex coreference, and cross-paragraph information retrieval. The cost is that a fairly complete history of keys and values must be retained.
Linear state layers typically compress historical information through recurrent updates. For each new token in the sequence, the model maintains a continuously evolving state rather than storing keys and values for every historical position. This reduces cache size and lowers bandwidth requirements when accessing long sequences.
A simple way to think about the two:
- Full-attention layers are like “randomly accessible historical records”;
- Linear state layers are like “a continuously updated summary state.”
The two are not substitutes for each other—they carry different responsibilities. Full attention is suited for preserving local or critical context that must be recalled precisely, while linear states carry continuous, compressible, and cumulative historical information.
The key to hybrid architecture is deciding which layers keep a full KV cache, which layers use recurrent state, and how the two types of state are updated cooperatively during inference.
3. A Basic Design for Hybrid State Caching
A general cache management scheme can divide inference state into three categories.
3.1 Full-Attention Cache
This portion stores the keys and values produced by full-attention layers, typically organized by layer, batch, sequence position, and feature dimension. It supports precise access to historical positions and underpins the model’s handling of critical context.
Engineering concerns include:
- How the cache is partitioned into blocks;
- Memory isolation between requests;
- Space reclamation for variable-length sequences;
- Cache expansion and eviction policies;
- The trade-off between data types and GPU memory usage.
Contiguous large memory blocks are simple to manage but prone to fragmentation; paged or block-based schemes suit dynamic-length requests better but make scheduling logic more complex.
3.2 Recurrent State of Linear Layers
Linear layers do not need to retain full keys and values for every historical token; instead, they maintain a state that updates as the sequence progresses. This state typically has a fixed or near-fixed size, so cache growth with longer context is significantly slower than in full-attention structures.
The management focus here is not “how many historical positions to keep,” but rather:
- Whether the state strictly corresponds to the current sequence;
- Whether it can be correctly restored after tool calls;
- Whether branching tasks require state copies;
- Whether multi-turn sessions support incremental updates;
- How to rebuild state after invalidation.
In Agent workloads especially, a single task may spawn multiple execution branches. Fully copying large states would negate the benefits of linear caching, so state sharing, copy-on-write, and checkpointing mechanisms are all worth incorporating into the design.
3.3 Request-Level Metadata
Beyond model state, the system must store metadata such as request position, processed token count, cache version, tool call boundaries, and termination reasons. Many inference errors do not originate from model computation but from mismatches between state and sequence position.
For example, after a tool result is inserted into the context, if the text is appended without synchronously updating each layer’s state, the model may read misaligned information. A reliable cache system should treat the “text sequence” and the “model state” as an inseparable, versioned object.
4. Improving Throughput in the Prefill Phase
Prefill is inherently more parallel and, in theory, easier to scale for high throughput via batching. But Agent inputs often vary greatly in length, and naively batching requests together can cause severe padding waste.
Optimizations can proceed along several lines.
4.1 Dynamic Batching by Length
Grouping requests of similar length into the same batch reduces wasted computation. For requests that share long fixed prefixes, the system can first identify the shared prefix and then process only the differing portions separately.
Note that batching decisions should not consider input length alone; they should also account for:
- How many full-attention layers are used;
- Whether linear states need initialization;
- How many tokens are expected to be generated;
- Whether the request involves tool calls;
- Current remaining GPU memory.
4.2 Reusing Stable Prefixes
System instructions, tool definitions, and fixed workflow descriptions typically repeat across many requests. For such content, the reusable prefix state can be retained after prefill, so subsequent requests only compute the newly added portion.
Prefix reuse, however, must meet strict conditions: the model version, weights, inference precision, positional encoding configuration, and related runtime parameters must all match. Any change to factors affecting hidden states can invalidate the old cache.
4.3 Reducing Unnecessary State Conversions
If full-attention layers and linear layers use different data layouts, frequent conversions introduce extra overhead. A unified memory layout should be established at initialization wherever possible, allowing compute kernels to read the adapted format directly.
The main bottleneck in prefill is often not raw compute but memory reads and writes, tensor rearrangement, and synchronization across batches. Fusing adjacent operators where appropriate helps reduce intermediate results being spilled to and reloaded from memory.
5. Core Optimizations in the Decoding Phase
The decoding phase processes only a few new tokens per step. Its compute is small, but it is highly sensitive to latency and memory access. This is where hybrid architecture advantages usually become most visible.
First, linear layers only need to read and update a fixed-size state, without scanning the full history. Second, full-attention layers can limit the data accessed at each step through windowing, tiered retention, or important-segment caching.
A common approach divides historical information into three categories:
- Recent context: retains a relatively complete attention cache to ensure continuous generation quality;
- Critical context: preserves important content such as system instructions, task objectives, entity definitions, and tool constraints;
- Low-value history: carried through summarization, compression, or linear states to reduce direct access cost.
This tiered strategy should not be understood as simply deleting history; it assigns different information to different storage forms. Whether to compress and how much to retain should be validated against task accuracy.
6. State Consistency Around Tool Calls
The most failure-prone point for Agent caching is the state transition before and after a tool call.
Before invoking a tool, the model may already have generated a task plan and parameters; after the tool returns, the new result must be appended to the context. At minimum, the following steps are required:
- Freeze the state version from before the tool call;
- Write the tool result into the sequence as a new input segment;
- Update the full-attention layer caches;
- Advance the linear layer recurrent states;
- Record the new sequence position and cache version;
- Isolate state for exception retries or branch execution.
If a tool call fails and triggers a retry, the original state must not be overwritten directly. A safer approach is to create a new branch from a checkpoint and commit it only after the new branch is confirmed valid. For high-concurrency systems, state lifecycles should also be enforced so that abnormal requests do not occupy cache indefinitely.
7. How to Evaluate “Throughput Improvements”
Performance claims of “several-fold improvements” are common, but actual results depend heavily on hardware, context length, batch size, model structure, precision, and request distribution. Evaluation should not focus on a single peak number; a complete metric system is needed.
At minimum, record:
- Time to first token;
- End-to-end latency per request;
- Output tokens per second;
- Prefill token throughput;
- Average cache footprint per request;
- Concurrency supported per unit of GPU memory;
- State restoration time before and after tool calls;
- Cache hit rate;
- Accuracy changes under long context;
- Rates of timeouts, cancellations, and state invalidation.
Prefill throughput and decoding throughput should be measured separately. The former reflects batching and matrix computation efficiency; the latter reflects memory access and scheduling efficiency. Relying only on average latency can mask long-tail requests and the real problems that appear under high concurrency.
8. Engineering Rollout Recommendations
In practice, deployment can proceed in three phases.
Phase one: implement cache observability. Record each request’s state size, lifecycle, hit behavior, and reclamation reasons to establish baseline data.
Phase two: introduce prefix reuse, dynamic batching, and block-based caching. These optimizations are minimally invasive to model structure and their benefits can usually be validated quickly.
Phase three: implement dedicated state management based on the model’s hybrid layer layout, including incremental linear state updates, state branching, tool call checkpoints, and tiered history retention.
At the same time, a fallback mechanism is essential. When cache validation fails, state versions mismatch, or memory pressure is too high, the system should fall back to full recomputation rather than continue using potentially incorrect old state. Performance optimization must be premised on correct results.
Conclusion
The value of hybrid architectures lies not only in reducing KV cache, but in redefining how state is managed in long-context inference. Full-attention layers handle precise access; linear layers handle continuous compression. Together, they let models process complex Agent tasks at a much lower cache cost.
But stable gains require simultaneous optimization of prefill, decoding, batching, state reuse, tool calls, and monitoring. Throughput improvement is never the product of a single operator—it emerges from the combined effect of model structure, cache layout, and service scheduling. For enterprise-grade inference systems, the most reliable path is to first build a cache system that is measurable, recoverable, and verifiable, and then progressively expand the scope of hybrid state optimization.
