Optimizing LLM Agent Inference with Hybrid Architectures: Redesigning Mixed-State Cache Management

    This article explores the engineering challenges of prefix cache management in hybrid architecture large language models (LLMs) that combine full attention and linear attention layers. It analyzes the fundamental differences between token-level KV caches and fixed-size recurrent states, explaining why multi-turn agent workloads exacerbate prefix reuse complexity. To address this, the article proposes a systemic redesign that treats recurrent checkpoints as first-class cache citizens. Key strategies include dynamic checkpoint granularity, tiered storage hierarchies, and reuse-value-based eviction policies, all aimed at maximizing prefill throughput and minimizing time-to-first-token (TTFT) latency.

    Optimizing LLM Agent Inference with Hybrid Architectures: Redesigning Mixed-State Cache Management

    1. Background: Hybrid Architectures Becoming the Mainstream Choice

    In recent years, linear attention and state space model layers (such as various gated incremental mechanisms and recurrent state layers) have matured. An increasing number of open-source large models are adopting a hybrid architecture that alternately stacks “full attention layers + linear attention layers.” The motivations are clear:

    • Faster Decoding: Linear layers summarize the entire prefix using a fixed-size recurrent state. Generating each token only requires a constant-overhead update to the state, avoiding the standard attention’s full scan of the KV Cache.
    • Lower Memory Footprint: Unlike attention KV Cache, which grows linearly with context length, the state size of linear layers is fixed. The memory savings are especially pronounced in long-context scenarios.
    • Long-Window Friendly: Hybrid architectures can maintain long-window capabilities while offloading the pressure of modeling global dependencies to linear layers. Full attention layers only need to handle a small amount of local and precise retrieval tasks.

    However, these models face an engineering challenge that pure Transformer models do not encounter in real-world workloads—especially in multi-turn, long-context, high-reuse scenarios like Coding Agents: Prefix Cache management is far more complex than in pure attention models. If the cache layer is not redesigned, the decoding time saved by the hybrid architecture will likely be consumed by redundant computations during the prefill stage.

    2. Problem Analysis: Why Prefix Reuse is Difficult in Hybrid Architectures

    2.1 Two Fundamentally Different Types of Cache

    In pure Transformer models, the KV Cache is stored at token granularity. This means a prefix can be truncated at any position: as long as the KV for the first N tokens is cached, computation can resume from the (N+1)th token, or the tail can be discarded at any time to reuse a shorter prefix. This flexibility is the foundation of current prefix caching and session reuse technologies.

    Linear attention layers are completely different. Instead of saving per-token KV, they maintain a fixed-size recurrent state (e.g., a matrix used to accumulate the “key-value statistics” of the entire prefix). This design introduces two hard engineering constraints:

    1. Large State Block Memory Overhead: A single state block is significantly larger than a single token’s KV fragment in a single layer. Caching all of them directly will rapidly bloat the cache pool.
    2. Non-Rollbackable State: The recurrent state is a unidirectional recursive process. Holding the state at the 10,000th token, it is impossible to deduce the state at the 9,000th token. Any reuse that involves “shortening the prefix” is invalid for recurrent layers.

    2.2 Necessary Conditions to Resume Computation from Position p

    Based on the above analysis, to continue generating from position p in a hybrid architecture model, the inference engine must simultaneously satisfy two conditions:

    • The complete attention KV of the request’s prefix before position p (covering all full attention layers);
    • The recurrent checkpoint located exactly at position p (covering all linear layers; each linear layer must have its recurrent state).

    Both are indispensable: without KV, the attention layer calculations will be incorrect; without the checkpoint, the linear layer’s state will be inconsistent with the actual prefix. This is the essence of the “two-piece set” in hybrid architecture cache management and the starting point for all reuse strategies.

    2.3 Agent Workloads Amplify the Problem

    The typical workflow of a coding agent involves multi-turn interaction: each round of user messages is appended after the complete history of the previous round, which includes long texts such as code files and tool call results. Its characteristics are:

    • Extremely High Prefix Reuse Rate: The prefixes of adjacent requests are almost identical.
    • Extremely Long Context: The input of a single request can reach tens of thousands of tokens.
    • Latency Sensitive: Each round expects to get the first token quickly (low TTFT).

    In pure Transformers, these workloads can be easily digested via token-level prefix caching. In hybrid architectures, however, if the recurrent checkpoint is only saved once at the end of each request (i.e., only keeping the state at the “last token”), any branching continuation in the middle will require re-scanning the prefix from the previous checkpoint. The prefill computation volume will repeatedly accumulate as the number of rounds increases, severely degrading both throughput and TTFT.

    3. Solution Design: Redesigning the Cache System Around Checkpoints

    To address these challenges, the industry’s core approach can be summarized as: Treat recurrent checkpoints as first-class cache citizens alongside KV, and systematically design the granularity, scheduling, and storage around them. This primarily includes the following aspects.

    3.1 Checkpoint Granularity: Periodic Saving During Scanning

    The most direct optimization is to save recurrent checkpoints at fixed intervals during the prefill scan. The schematic logic is as follows:

    1. # Pseudocode: Checkpoint insertion during prefill
    2. CHECKPOINT_INTERVAL = 512 # Save checkpoint every N tokens
    3. def prefill_with_checkpoints(request):
    4. kv, state = lookup_cache(request.prefix) # Try to hit "KV + nearest checkpoint"
    5. start = request.prefix.committed_len
    6. for chunk in chunks(request.tokens, start):
    7. kv = attention_layers.update(chunk, kv)
    8. state = linear_layers.update(chunk, state)
    9. if chunk.end % CHECKPOINT_INTERVAL == 0:
    10. state_cache.put(request.prefix[:chunk.end], state)
    11. state_cache.put(request.prefix, state) # Terminal checkpoint

    The choice of granularity is a trade-off: the smaller the interval, the shorter the redundant scan from the checkpoint during continuation, but the greater the memory pressure and eviction pressure on the cache pool; larger intervals have the opposite effect. In practice, it is usually dynamically adjusted based on session branching frequency, context length distribution, and VRAM/memory budget. A tiered retention strategy can also be applied to checkpoints—for example, retaining dense checkpoints only for active sessions, while retaining only terminal checkpoints for cold sessions.

    3.2 Cache Tiering: Coordinating VRAM, Main Memory, and Distributed Storage

    Under hybrid architectures, the size ratio of KV to checkpoints differs from that of pure attention models, and a single VRAM cache pool is often insufficient. Common tiered designs include:

    • VRAM Layer: Accommodates the KV and hot checkpoints of currently active requests, serving low-latency continuation;
    • Main Memory Layer (CPU RAM): Takes in prefix blocks and checkpoints evicted from VRAM but still potentially reusable. Typical capacity can reach hundreds of GiB, paired with high-speed interconnects for asynchronous prefetching;
    • Distributed Storage Layer: Shares prefix caches across nodes, enabling hits on existing KV and checkpoints when the same session switches between instances or when multiple workers handle the same project, avoiding full recomputation.

    A key engineering challenge brought by tiering is consistency: KV is precisely aligned by token, while checkpoints are aligned by interval. During continuation, it is necessary to “round up” to the checkpoint position and then compute the small gap between the checkpoint and the target position. This gap computation logic must drive both the attention and linear layers simultaneously to ensure the two cache states are strictly synchronized.

    3.3 Scheduling and Eviction: Managing Cache by “Reuse Value”

    Unlike pure KV cache eviction based on byte size, hybrid architecture cache eviction requires additional considerations:

    • Pairing: KV prefix blocks and their corresponding checkpoints should be born and die together as much as possible, avoiding “half-disabled” caches where KV exists but the checkpoint does not;
    • Checkpoint Density ROI Evaluation: For sessions with frequent multi-turn continuations and branch exploration, the marginal benefit of retaining dense checkpoints is higher;
    • Eviction Cost: Checkpoints are large in volume and expensive to recompute if mistakenly evicted. Higher retention weights can be assigned to recent sessions.

    4. Results and Practical Recommendations

    In real-world agent coding trajectory replay tests, an inference engine that reconstructs the cache system around checkpoints can achieve multiple times the improvement in prefill throughput compared to a baseline system without mixed-state management. The tail percentile of Time-To-First-Token (TTFT) can also be significantly reduced. After integrating large-capacity main memory and distributed cache layers, the benefits remain significant in multi-node scenarios. This indicates that the decoding-end advantages of hybrid architectures can only be truly translated into end-to-end performance benefits when the cache management layer is designed equivalently.

    For teams planning to implement hybrid architecture models, it is recommended to proceed in the following order:

    1. Profile Workload Characteristics First: Calculate session prefix hit rates, average context length, and round distribution to determine the potential ROI ceiling of cache optimization;
    2. Implement Basic Checkpoint Mechanisms: Add periodic checkpoint saving to the prefill path and a joint “KV + checkpoint” hit logic;
    3. Introduce Tiered Caching: When VRAM is insufficient, prioritize expanding CPU-side cache before evaluating the need for cross-node distributed reuse;
    4. Continuously Monitor Recompute Overhead: Track the distribution between checkpoint hit positions and request positions, and dynamically adjust checkpoint intervals and eviction strategies.

    Hybrid architectures provide better decoding efficiency and a smaller memory footprint for long-context agents. To realize these advantages in multi-turn, real-world business scenarios, the key lies precisely in an easily overlooked aspect: mixed-state cache design. Managing attention KV and recurrent checkpoints as a unified whole is the necessary path for hybrid architecture inference systems to reach production-grade readiness.