Hybrid Architecture State Caching and Agent Inference Optimization

    As LLM agents move from single-turn Q&A to multi-turn planning, tool use, and code editing, inference bottlenecks shift toward context processing, cache reuse, and scheduling efficiency. This article examines hybrid architectures that combine full-attention layers with linear layers, explains why conventional prefix caching cannot directly cover recursive linear states, and presents a two-path cache design for attention KV blocks and linear state snapshots. It also covers reported prefill throughput and TTFT improvements, tiered GPU/CPU/distributed storage, cache consistency and invalidation, deployment metrics, and a three-stage implementation path for enterprise inference platforms.

    Hybrid Architecture State Caching and Agent Inference Optimization

    As large models move from single-turn Q&A toward multi-turn planning, tool calling, and code modification, the main bottleneck in inference systems is no longer just model parameter scale. It is also context processing, cache reuse, and scheduling efficiency.

    For coding agents, a single task typically includes requirement analysis, code retrieval, file modification, test execution, error fixing, and result summarization. Each turn carries a large amount of historical messages, tool results, and code snippets. If every request reprocesses the full context, the prefill phase repeatedly consumes compute, and time to first token (TTFT) rises quickly with context length.

    In recent years, hybrid architectures that combine full-attention layers with linear layers have attracted attention. They aim to preserve strong context modeling while reducing compute and KV cache size during generation. However, these architectures introduce a new engineering problem: different layers store historical information in different forms. Traditional prefix caching systems designed only around KV cache cannot directly cover the internal states of linear layers.

    1. Why Hybrid Architectures Fit Long-Horizon Agent Tasks

    Full attention can directly access relationships among historical tokens, making it suitable for code dependencies, instruction constraints, and complex reasoning. Its inference process usually needs to store key and value states, and the longer the sequence, the higher the cache footprint.

    Linear layers compress historical information through recursive updates. For a layer at position (t), let its state be (S_t) and its input be (x_t). This can be abstracted as:

    [
    St = F(S{t-1}, x_t)
    ]

    When generating the next token, the model only needs to read the current state and continue updating it, without explicitly accessing all historical tokens. This reduces memory access pressure during decoding and is especially suitable for long-context and continuous generation tasks.

    However, a linear state is not an ordinary token segment. It is usually an aggregated result produced by a series of recursive transformations and has a clear sequential dependency. If earlier inputs change, subsequent states may all be affected. Therefore, linear-state caching cannot simply concatenate or truncate arbitrary intervals in the same way as KV cache.

    2. Limitations of Conventional Prefix Caching

    Conventional cache systems often divide input into fixed-size blocks and use token-sequence hashes to decide whether a block can be reused. For pure attention models, this is relatively straightforward: as long as the prefix content is identical, the corresponding layer’s keys and values can be restored.

    Hybrid architectures introduce at least three differences.

    First, the cache objects differ. Attention layers need to store keys and values, while linear layers need to store recursive states. Their data structures, generation timing, and restoration methods are different.

    Second, the reuse granularity differs. Attention cache can often be reused by block, while linear states usually require recursion to continue from a definite historical boundary. If only an intermediate state is restored without guaranteeing the complete prefix corresponding to that state, the result may have semantic deviation.

    Third, the lifecycle differs. Context in agent tasks is not static text. Tool results may be appended, code files may be modified, and failed attempts may be replanned. The cache system must distinguish “fully stable prefixes” from “tails that may still change”; otherwise, it will create many invalid cache entries.

    Therefore, cache management for hybrid architectures can no longer be treated as simple GPU memory management. It should be designed as a scheduling system oriented around computation graphs and state dependencies.

    3. Core Design of Hybrid State Caching

    A more reasonable approach is to split the cache into two cooperating paths.

    3.1 Attention Cache Path

    Attention layers continue to use block-based KV cache. The system can generate a content fingerprint from the token prefix and map stable prefixes to corresponding key-value blocks. When a new request shares the same code, system instructions, or tool protocol as a historical request, the already computed blocks can be reused directly.

    This type of cache is suitable for high-frequency, repetitive content with clear boundaries, such as:

    • System prompts;
    • Fixed agent behavior specifications;
    • Tool definitions and parameter descriptions;
    • Project-level shared context;
    • Code files that change infrequently.

    3.2 Linear State Path

    Linear layers require additional state snapshots. A snapshot should not be bound only to a cache block. It should also record the corresponding prefix boundary, layer number, state version, and dependencies.

    When a new request hits a state snapshot, the system continues processing subsequent tokens from that position instead of recursing again from the beginning of the context. To avoid incorrect reuse, a state snapshot must satisfy two conditions:

    • The input sequence before the snapshot is exactly identical;
    • The incremental content after the snapshot continues to execute in the correct order.

    In engineering practice, an agent trajectory can be divided into semantic segments such as “user instruction,” “tool call,” “tool result,” “model plan,” and “code change.” Compared with fixed-length blocks, semantic segments better describe state boundaries and make it easier to establish stable checkpoints after tool calls complete.

    4. Why Prefill Throughput Can Improve Significantly

    The main work in the prefill phase is to process the input context in parallel and build caches for each layer. In long-context tasks, repeated computation often accounts for a large amount of time.

    If every agent request contains the same historical prefix, the system can divide computation into three parts:

    1. Attention KV cache hits;
    2. Linear state snapshot hits;
    3. Newly added text that has not yet been processed.

    The first two parts do not need to be executed again, so compute resources are concentrated on the third part. For tasks containing large amounts of historical code and tool results, this reduction can be significant.

    When replaying real coding-agent traces on high-performance accelerators, related research shows that after hybrid cache optimization, prefill throughput can reach up to roughly 3x that of a conventional inference service, with some tests showing about 3.14x. These numbers depend on model structure, request distribution, hit rate, context length, batching strategy, and storage bandwidth. They should not be understood as a fixed gain in all scenarios.

    5. Why Time to First Token Decreases

    The most visible metric to users is usually TTFT: the time from when a request reaches the system to when the model produces the first output token.

    In agent scenarios, TTFT is affected by three factors:

    • Waiting time for scheduling and batching;
    • Compute time required to prefill the context;
    • Time required to load cache and restore states.

    Hybrid state caching first reduces prefill computation and then allows the system to skip a large number of completed recursive state updates. If the cache is in local high-speed storage or GPU memory, restoration is usually faster than recomputation. Experimental results show that in some long-context tests, p90 TTFT can be reduced by up to about 88.4%.

    However, cache restoration is not free. If a cache hit requires reading a large amount of data from low-speed storage, or if the state format does not match the current execution batch, restoration cost may offset the compute savings. The system must therefore jointly optimize cache hit rate, data layout, read bandwidth, and scheduling strategy.

    6. Roles of CPU Cache and Distributed Storage

    GPU memory capacity is limited and cannot retain all agent trajectories for long periods. Moving some caches to CPU memory can expand cache capacity and is suitable for storing recent but inactive context that may be used again.

    A practical tiered structure can include:

    • GPU tier: stores the current batch and frequently accessed states;
    • CPU tier: stores KV blocks and linear state snapshots for recent tasks;
    • Inter-node shared tier: stores stable prefixes reused across instances;
    • Persistent storage tier: stores project-level caches with longer lifecycles.

    When cache scale reaches hundreds of GiB, the CPU tier can significantly improve the overall hit rate. Related experiments show that after adding about 512 GiB of CPU cache, hybrid state reuse can still maintain clear benefits.

    However, CPU cache does not mean unlimited expansion. The system still needs to consider memory bandwidth, NUMA topology, serialization overhead, and concurrent access conflicts. For cross-node reuse, network transfer, node failures, cache version consistency, and access permission isolation also need to be considered.

    7. Cache Consistency and Invalidation Strategies

    In agent tasks, cache invalidation is usually triggered by events such as:

    • System instructions change;
    • Tool definitions or parameter constraints change;
    • Project file contents are modified;
    • Model version or inference configuration changes;
    • Context concatenation order changes;
    • Sampling or control logic affects state semantics.

    Therefore, a cache key should not use only a text content hash. It should also include model identifier, layer configuration, state type, tokenizer version, and necessary runtime version information.

    For coding agents, a tiered invalidation strategy can be used. When project-level general instructions change, only related global prefixes are cleared. When a single file changes, only context segments that depend on that file are cleared. When a tool result changes, invalidation starts from the state boundary after the corresponding tool call.

    This localized invalidation is more efficient than clearing all caches at once and is better suited to multi-user, multi-project concurrent environments.

    8. Metrics to Monitor During Deployment

    When deploying a hybrid cache system, at least the following metrics should be monitored:

    • Attention KV cache hit rate;
    • Linear state snapshot hit rate;
    • Average number of reused tokens;
    • Prefill throughput;
    • p50, p90, and p99 TTFT;
    • GPU memory and CPU memory usage;
    • Cache read bandwidth;
    • State restoration failure rate;
    • Cache eviction rate;
    • Cross-node transfer latency.

    Hit rate alone is not sufficient. A cache may have a high hit rate, but if every restoration goes through a high-latency network, overall performance may still be unsatisfactory. More valuable metrics are “compute time saved per request” and “the ratio of cache restoration cost to recomputation cost.”

    9. Implementation Path for Enterprise Inference Platforms

    Enterprises can proceed in three stages.

    In the first stage, implement hybrid caching within a single node. First distinguish KV cache from linear states, establish unified cache metadata and invalidation mechanisms, and validate local GPU and CPU tiered storage.

    In the second stage, introduce agent trajectory-level reuse. Establish checkpoints around system prompts, tool protocols, project context, and stable code snippets, and optimize incremental processing in multi-turn tasks.

    In the third stage, extend to cross-node sharing. Through general object storage, distributed cache, or other shared storage capabilities, enable asynchronous migration of stable prefixes and state snapshots, and use monitoring and alerting systems to observe cache quality.

    In cloud inference environments such as Baidu AI Cloud, these capabilities can be combined with container platforms, object storage, monitoring services, and elastic compute resources. The specific architecture should still be evaluated based on model scale, request patterns, data compliance requirements, and network topology.

    Conclusion

    Hybrid architecture models reduce the compute and storage pressure of long-context inference, but they also turn cache management from a single KV reuse problem into a combined problem of “KV cache + recursive state + version consistency.”

    Effective optimization is not simply about adding more cache capacity. It is about identifying which context is stable, which states can be safely restored, which changes affect only a local scope, and how to design storage and scheduling strategies for different cache objects.

    For coding agents, multi-turn office assistants, and long-document analysis systems, hybrid state caching can reduce repeated prefill, improve resource utilization, and lower user waiting time. In the future, competition among inference systems will shift from raw model compute speed toward context reuse efficiency, state management capability, and distributed inference scheduling.