Hybrid State Cache Optimization and Throughput Improvement for Hybrid-Architecture LLMs

    This article explores state cache optimization for large language models that combine full-attention layers with linear sequence modeling layers. As LLM applications shift from simple Q&A to agentic workflows, inference bottlenecks increasingly revolve around how historical states are cached, reused, and updated. The article explains the two types of states in hybrid architectures, why unified cache structures waste memory and add scheduling overhead, and how layered state management, block-based storage, prefix reuse, incremental prefill, and consistency control can improve prefill throughput, time-to-first-token latency, and end-to-end task completion time. It also covers evaluation metrics and practical engineering recommendations for production deployments.

    As large language model applications move from “question answering” toward “agents,” the bottlenecks of inference performance are changing. Traditional models typically rely on full attention, which can directly access historical context. However, as sequence length grows, the key-value cache keeps expanding, and memory footprint, memory bandwidth, and scheduling costs rise with it. Another class of models combines full-attention layers with linear sequence modeling layers, reducing long-sequence processing pressure while retaining some global modeling capability.

    This hybrid architecture is not simply a matter of stacking two types of layers together. Different layers preserve historical information in different ways: attention layers typically need to cache keys and values, while linear layers prefer to maintain a compressed state that can be updated recursively. If a unified cache structure is still used, the efficiency advantages brought by the model architecture may be canceled out by inefficient data organization and scheduling. Therefore, redesigning the hybrid state cache is key to improving agent prefill throughput and overall inference efficiency.

    1. Why Agent Scenarios Depend More on Cache Optimization

    Ordinary conversation is usually “one input, one output,” while agent tasks typically involve multiple consecutive stages:

    1. Reading the user’s goal;
    2. Analyzing the task and forming a plan;
    3. Calling retrieval, databases, or external tools;
    4. Injecting tool results back into the context;
    5. Continuing to reason and generating the final answer.

    Throughout this process, historical context may be read repeatedly. Especially when the tool-call chain is long, each newly added piece of information accounts for only a small fraction of the total context, yet the system may repeatedly perform large amounts of identical prefill computation.

    The prefill phase mainly processes existing input; it is compute-intensive and highly parallel. The decode phase typically generates one or a few tokens at a time; it is memory-bandwidth-intensive and latency-sensitive. Agent systems also switch back and forth between the two phases repeatedly, so caching affects not only memory footprint but also throughput, time to first token, and tool-call responsiveness.

    With a well-designed cache, previously processed historical states can be reused, and only the newly added content requires incremental computation. With a poorly designed cache, the following problems may occur:

    • Historical states are recomputed repeatedly;
    • All layers use a unified cache format, wasting memory;
    • Small batches frequently trigger cache movement;
    • Under long contexts, cache access becomes a bandwidth bottleneck;
    • Multiple rounds of tool calls keep expanding the invalidation scope of the cache.

    2. The Two Types of States in Hybrid Architectures

    2.1 Key-Value States of Full-Attention Layers

    In the attention mechanism, historical tokens are mapped into keys and values, which participate in the computation of subsequent tokens during generation. To avoid recomputing historical content at every step, inference systems typically cache these keys and values.

    The basic characteristics are:

    • The state size is related to the historical sequence length;
    • Each new token usually requires appending a new key and value;
    • Reading historical states may involve accessing a long context range;
    • Memory demand grows approximately linearly with sequence length.

    Full attention is good at precisely accessing any historical position and handles cross-paragraph associations well. But in ultra-long-context and high-concurrency scenarios, the KV cache creates significant memory pressure.

    2.2 Recurrent States of Linear Layers

    Linear sequence modeling layers usually do not store the complete history. Instead, they aggregate historical information into a fixed-size or relatively stable state. When processing a new token, the system computes a new state from the current input and the old state, then passes it to the next step.

    The main characteristics of this type of state are:

    • No need to store complete keys and values for all historical tokens;
    • State size typically does not grow directly with context length;
    • Decoding can update the state recursively;
    • State updates are sensitive to computation order and numerical precision.

    Linear states help reduce the storage cost of long-sequence inference, but they are not equivalent to “no cache needed.” On the contrary, to achieve efficient incremental inference, the recurrent state of every relevant layer must be accurately preserved, and the state update order must remain consistent with a full recomputation.

    3. Why a Hybrid State Cache Is Needed

    If the system treats all layers as full-attention caches, two problems arise. First, linear layers do not need to store complete historical keys and values, so unified storage wastes memory. Second, linear layers have a different computation path from attention layers, and forcing them into the same data layout adds state conversion and scheduling overhead.

    A more reasonable approach is a layered, type-aware cache system:

    • Attention layers cache historical keys and values;
    • Linear layers cache recurrent states;
    • Layers share unified metadata describing position, length, and version;
    • State creation, update, reuse, and release are managed according to the request lifecycle.

    An abstract cache entry might contain the following information:

    1. CacheEntry {
    2. request_id
    3. layer_type
    4. sequence_range
    5. state_location
    6. state_shape
    7. precision
    8. version
    9. reference_count
    10. }

    Here, layer_type distinguishes attention states from linear states; sequence_range describes the context range the state corresponds to; version prevents reading stale content during concurrent updates. Real systems may not adopt exactly these fields or structures; this is only meant to illustrate the design idea.

    4. Optimization Priorities in the Prefill Phase

    The goal of the prefill phase is not simply to “finish computing the input,” but to generate reusable states as efficiently as possible. For hybrid architectures, optimization can proceed in the following directions.

    4.1 Organize Computation by Layer Type

    Treat attention layers and linear layers as two different kinds of computation tasks, each using data layouts and kernels suited to itself. For attention layers, focus on optimizing matrix multiplication, normalization, and KV writes; for linear layers, focus on state updates, reduction operations, and contiguous memory access.

    This reduces unnecessary data conversion and lets hardware compute units make fuller use of parallelism.

    4.2 Block-Based State Management

    Long contexts should not be managed as one large contiguous object, but split into multiple logical blocks. Block-based management offers several benefits:

    • Easier reuse of shared prefixes;
    • Lower cost of cache expansion and release;
    • State sharing across different requests;
    • When only a small amount of content is appended, only the new blocks need updating.

    Attention states can be partitioned by token ranges; linear states can be partitioned by computation stage or state snapshots. The two do not need to use identical block sizes.

    4.3 Prefix Reuse and Incremental Prefill

    In agent systems, system prompts, tool definitions, role constraints, and task templates are often highly repetitive. The cache system can reuse stable prefixes and place dynamic content in later ranges.

    However, prefix reuse must satisfy strict conditions:

    • The model version is identical;
    • Sampling or inference configuration does not affect the state;
    • The prefix text and special tokens match exactly;
    • The cached state has not been incorrectly modified;
    • Isolation mechanisms exist between different tenants or permission domains.

    For attention layers, prefix reuse typically means reusing the corresponding KV blocks; for linear layers, it means reusing the corresponding recurrent state snapshots. The validation methods for the two state types cannot simply be treated as equivalent.

    4.4 Overlapping Computation and Data Movement

    Prefill performance is often limited not only by compute power but also by memory read/write bandwidth. Through pipelining, the system can prepare or move some states in advance while other layers compute the current block, reducing idle time of compute units.

    That said, the degree of concurrency in data movement must be controlled. Too many asynchronous tasks can cause contention for memory bandwidth and ultimately reduce throughput. Dynamic adjustment based on batch size, sequence length, state size, and device topology is therefore necessary.

    5. State Updates in the Decode Phase

    The decode phase generates only a few tokens per step, so performance usually depends on the efficiency of per-step state access.

    For attention layers, the system reads historical keys and values and appends the state corresponding to the newly generated token. For linear layers, it reads the old recurrent state, performs the state transition, and writes back the new state. The two operations have different memory access patterns and cannot use identical scheduling strategies.

    Engineering approaches include:

    • Grouping requests with similar state layouts into the same batch;
    • Avoiding frequent changes to state addresses;
    • Applying different batching strategies for short and long requests;
    • Releasing states promptly for requests that are about to finish;
    • Freezing the states of paused requests or those waiting for tool results to avoid wasted computation.

    For tool-calling scenarios, the system should also distinguish between “ready to continue generating” and “waiting for external results.” During the waiting period, the request should not continuously occupy compute resources, but whether its cache is retained should be decided based on expected waiting time, memory pressure, and the value of subsequent reuse.

    6. Cache Consistency and State Recovery

    The most easily overlooked problem in hybrid state caching is correctness. Once a cache mismatch occurs, the model may still generate text, but the output will contain subtle errors that are hard to diagnose.

    The following consistency relationships must be guaranteed:

    1. The token positions a state corresponds to must be accurate;
    2. Attention key-values and linear recurrent states must come from the same context version;
    3. When truncation, retry, or branch generation occurs, the state must roll back to the correct snapshot;
    4. Concurrent requests must not accidentally read each other’s caches;
    5. After cache eviction, the state must be safely recomputable.

    Agents often produce branching paths—for example, executing Plan A first and switching to Plan B after a failure. If the system directly overwrites the original state, it cannot quickly roll back. A more robust approach is to use versioned snapshots or copy-on-write: a new branch only records incremental changes, the original state remains unchanged, and the branch is merged only after it is confirmed.

    7. How to Evaluate Whether the Optimization Works

    You cannot judge solely by single-run generation speed. Hybrid state cache optimization should be evaluated across at least the following metrics:

    7.1 Prefill Throughput

    Measures the number of input tokens processed per unit time. This metric is suitable for observing compute efficiency in long-context and large-batch scenarios.

    7.2 Time to First Token

    The time from request arrival to the generation of the first output token. Agents are sensitive to this metric because the first result often determines how quickly the next tool call can start.

    7.3 Per-Step Decode Latency

    Used to observe cache reads, state updates, and scheduling overhead. Even if prefill throughput is high, slow per-step decoding can drag down total task time.

    7.4 Cache Hit Rate and Reuse Gains

    Attention states and linear states should be tracked separately rather than summarized with a single overall hit rate. The more stable the prefix reuse, the more recomputation is eliminated.

    7.5 Per-Request Memory Footprint

    Beyond averages, you should also observe peaks under long-tail requests, concurrency spikes, and cache fragmentation. In production, peaks are more likely than averages to cause failures.

    7.6 End-to-End Task Completion Time

    What agents ultimately care about is the total time to complete a task, including model inference, tool calls, waiting, and state recovery. Cache optimization must demonstrate value on this metric.

    Claims of “several-fold throughput improvement” should be interpreted cautiously. Actual gains are affected by context length, the proportion of repeated prefixes, batch size, hardware bandwidth, the ratio of layer types, tool-call frequency, and cache hit rate. Any performance conclusion should be validated with a unified dataset, fixed precision, clearly defined concurrency, and a complete end-to-end pipeline, rather than being generalized beyond its test conditions.

    8. Engineering Recommendations for Implementation

    First, build observability. Record prefill time, decode time, cache hit status, state size, eviction count, and recomputation count for every request.

    Second, decouple cache logic from model computation logic. The cache manager handles lifecycle, versioning, and resource allocation, while the model executor handles the actual computation, making it easier to swap data layouts and scheduling strategies later.

    Third, prioritize stable prefixes and high-frequency workflows. For requests with highly dynamic content and very low reuse rates, complex caching mechanisms may not pay off.

    Fourth, establish correctness regression tests. Cover at least multi-turn conversations, long contexts, tool calls, request cancellation, branch rollback, cache eviction, and concurrent access.

    Fifth, dynamically adjust strategies based on memory pressure. When cache resources are abundant, retain more states to reduce recomputation; when resources are tight, prioritize retaining states with high reuse probability and high recomputation cost.

    Overall, the value of hybrid architectures lies not merely in reducing one type of cache, but in allowing different kinds of historical information to be stored and updated in different ways. Through layered state management, block-based storage, prefix reuse, incremental prefill, and consistency control, systems can achieve better throughput and responsiveness in long-context and agentic workflows. A truly effective solution must balance computational efficiency, memory footprint, scheduling complexity, and result correctness—rather than chasing any single benchmark metric in isolation.