State Caching and Prefill Optimization for Hybrid Attention Architectures

    Agent workloads feature many interaction rounds and growing context, making prefill the main bottleneck. This article explains how hybrid attention architectures split work between full-attention and linear layers, why their two types of state require separate caching strategies, and how to design prefix-based state caching, scheduling, and memory management to improve prefill throughput, time to first token, and cache hit rate.

    1. Background: Why Agent Workloads Drive Architectural Change

    Agent applications differ from simple question answering in the number of interaction rounds. After each tool call, the system must reassemble tool outputs, conversation history, and planning records into the context. A single task often involves dozens of requests, with input length growing continuously while the newly generated output in each round stays short. This workload makes the compute and memory cost of the prefill stage the dominant pressure; the decode stage is no longer the only bottleneck.

    In a standard full-attention architecture, every token interacts with all previous tokens, so prefill compute grows quadratically with sequence length. Meanwhile, to support subsequent decoding, every layer must store keys and values, i.e., the KV cache. The KV cache size is proportional to sequence length, number of layers, number of heads, and data precision. As context grows, GPU memory fills up with cache first, and concurrency drops as a result.

    Linear attention and similar recurrent structures offer another path. They compress historical information into a fixed-size state matrix, so compute grows roughly linearly with sequence length and state size is independent of it. The trade-off is that this compression loses some precise retrieval capability. Hybrid architectures strike a balance between the two: a small number of full-attention layers handle exact recall, while the majority of linear layers handle efficient information transfer.

    2. The Basic Structure of Hybrid Architectures

    The core of a hybrid architecture is layer-level division of labor. A common approach interleaves the two layer types at a fixed ratio—for example, keeping one full-attention layer every several layers, with the rest being linear layers. The ratio and placement must be determined experimentally. Full-attention layers are typically placed deeper in the network to support global information integration at higher levels, while shallow linear layers handle local patterns and sequence compression.

    This design produces two direct results. First, fewer full-attention layers means a significantly smaller total KV cache, because only those layers need to store keys and values per token. Second, linear-layer states are fixed in size: no matter how long the context gets, each layer occupies the same amount of state space.

    The proportion of full-attention layers cannot be reduced without limit. With too few, the model’s ability to handle cross-paragraph dependencies, precise reference, and long-range retrieval degrades. Engineering teams need to weigh accuracy benchmarks against efficiency metrics rather than pursuing only one of them.

    3. Differences Between the Two Types of State

    Before designing a cache, you need to understand the nature of the two state types.

    Dimension Full-attention KV cache Linear-layer recurrent state
    Size vs. length Grows linearly Fixed
    Supported operations Exact retrieval at any position Sequential updates, hard to backtrack
    Prefix reuse Splittable by token, naturally truncatable Recoverable only at specific checkpoints
    Main cost GPU memory and memory bandwidth Compute for state updates

    The KV cache can be sliced by token position. If two requests share the first N tokens, the keys and values at those N positions can be reused directly. A recurrent state is different: it is a compressed result of history and can only be captured at a specific position. To reuse the linear-layer state of a prefix, a full snapshot must be saved at that exact position, and the snapshot must correspond strictly to the prefix content.

    Therefore, caching for hybrid models cannot simply copy the pure-Transformer approach. The two state types must be managed separately and linked through a unified prefix index.

    4. Why Prefill Becomes the Bottleneck

    Prefill is the process in which the model processes the input context in one pass and produces the intermediate states of every layer. In agent scenarios, prefill input usually contains large amounts of repeated content, such as system instructions, tool definitions, and conversation history. The system could compute only the newly added portion, provided the prefix states can be found and correctly restored.

    When measuring prefill performance, focus on three metrics:

    1. Prefill throughput: input tokens processed per unit time, reflecting compute utilization.
    2. Time to first token (TTFT): the time from request arrival to the first output token, which directly affects the interactive experience.
    3. Cache hit rate: the proportion of input covered by reusable prefixes, determining how much computation can be skipped.

    The three must be observed together. Pursuing throughput alone can push TTFT up; with a low cache hit rate, throughput gains are limited too.

    5. Designing a Hybrid State Cache

    A practical cache design can be divided into four parts.

    (1) Prefix chunking. Split the input into fixed-size blocks, such as 256 or 512 tokens each. Block boundaries serve as both snapshot positions and the granularity of the cache index.

    (2) State snapshots. At each block boundary, save both the KV fragments of the full-attention layers and the recurrent states of the linear layers. Since linear-layer states are fixed in size, snapshot cost is predictable.

    (3) Prefix indexing. Compute a hash of the block content and combine it with the model version, tokenizer version, and precision configuration to form a unique key. A change in any of these should invalidate the old cache.

    (4) Restore and resume. When a new request arrives, look up the snapshot of the longest matching prefix, restore both state types, and continue computing from after the matched position.

    The following code illustrates the flow only; function and method names are fictional:

    1. def prefill_with_cache(tokens, cache, model, block=512):
    2. key = model.signature()
    3. # Look up the longest cached prefix
    4. pos, state = cache.longest_prefix(tokens, block, key)
    5. if state is None:
    6. pos, state = 0, model.init_state()
    7. for start in range(pos, len(tokens), block):
    8. chunk = tokens[start:start + block]
    9. state = model.forward_chunk(chunk, state)
    10. cache.save(tokens[:start + len(chunk)], state, key)
    11. return state

    The key point of this flow: snapshots are saved only at complete block boundaries, and each state is bound one-to-one with its corresponding prefix. If a linear-layer state were saved mid-block, there would be no guarantee on restore that the state matches the prefix content.

    6. Scheduling and Memory Management

    Hybrid caching requires two memory strategies. KV data for the full-attention part suits paged allocation: fixed page sizes, little fragmentation, and dynamic growth and shrinkage per request. Linear-layer states are fixed in size and suit pre-allocated fixed slots, with the slot count determined by the concurrency cap.

    Chunked prefill is another important technique. Long inputs are split into segments and interleaved with decode requests in scheduling, preventing a single long request from occupying compute for an extended period and thereby keeping other requests’ TTFT from spiking.

    The eviction policy determines how much history the cache can retain. Least-recently-used is simple to implement, but in agent scenarios the prefixes of the same session are reused repeatedly. You can combine session priority with access time: keep in-progress tasks longer and release ended sessions sooner.

    The allocation ratio of the GPU memory budget matters as well. If the full-attention cache takes too much, concurrency suffers; if too much is reserved for snapshots, the prefix hit rate drops. This ratio…