Cache Redesign for Hybrid Architecture Models: Accelerating Agent Prefill

    Hybrid architectures combine full attention and linear layers to reduce KV cache size and decoding latency, but they complicate prefix caching for coding agents. This article explains why pure Transformer prefix caching is simpler, outlines the main challenges in hybrid models, and describes checkpoint, tiered-storage, eviction, scheduling, external-cache, and distributed-reuse strategies for improving prefill hit rates and TTFT.

    1. Background: Why Hybrid Architectures Became Mainstream

    Standard Transformer attention layers must retain the Key and Value of every historical token during decoding, which is the KV Cache. The longer the context, the more GPU memory the KV Cache consumes, and the more data must be read to generate each token. Linear attention and similar recurrent structures maintain only a fixed-size state, so read overhead is largely independent of context length.

    Hybrid architectures combine a small number of full attention layers with a large number of linear layers. The full attention layers preserve global retrieval capability, while the linear layers compress historical information. As a result, overall cache size and decoding latency drop significantly. Multiple mainstream open-source and commercial models have adopted this approach, showing that it has moved from experimentation into production.

    Hybrid architectures bring inference benefits, but they also change how the serving side manages caches. If cache design follows the pure Transformer approach, long-context scenarios can suffer from low hit rates, wasted GPU memory, or incorrect results.

    2. Workload Characteristics of Coding Agents

    A typical coding agent workflow includes reading a codebase, calling tools, receiving tool output, modifying files, and reasoning again. Each round of request concatenates the previous system prompt, user input, model replies, and tool results into the context. This workload has three characteristics:

    1. Fast context growth. Content from earlier rounds appears repeatedly in every later round, and a single request can reach tens of thousands of tokens or more.
    2. Long shared prefixes between adjacent requests. Consecutive requests in the same session share most of their input; only a small amount of new content is appended at the end.
    3. Irregular request intervals. User thinking time and tool execution time can both be long, and cache entries may be evicted before the next round arrives.

    The prefill stage must compute all input tokens. If the prefix cache hits, the system only needs to compute the newly added part. Therefore, the prefix hit rate directly determines time to first token (TTFT) and overall prefill throughput.

    The following example shows how the input changes across three rounds in a typical session:

    1. Round 1: [system prompt][user question]
    2. Round 2: [system prompt][user question][assistant reply][tool result A]
    3. Round 3: [system prompt][user question][assistant reply][tool result A][assistant reply][tool result B]

    The input of each round uses the full input of the previous round as its prefix. If the serving side can reuse the previous round’s computation results, the third round only needs to compute the last two segments.

    3. Why Prefix Caching Is Relatively Simple in Pure Transformers

    In a pure attention model, the KV of token i depends only on tokens 0 through i. In other words, the computation result of a prefix is independent of later content and can be truncated and reused at any token boundary.

    In engineering implementations, KV is usually split into fixed-size blocks, such as several tokens per block. A hash is computed for each block, and a “prefix block chain” is used as the index. During lookup, matching starts from the longest prefix and proceeds block by block; a hit is reused. Because each block’s data can be retrieved independently, the system can precisely reuse prefixes of any length and release GPU memory at block granularity during eviction.

    This design is simple and general, and it is the baseline used by most inference engines.

    4. Cache Challenges in Hybrid Models

    The linear-layer state in a hybrid model is fundamentally different from the KV of pure attention, mainly in the following ways.

    4.1 Linear State Cannot Be Truncated Arbitrarily

    The linear-layer state is obtained by recursively compressing the entire input history. The state at step t depends on all inputs from step 0 through step t. Unlike KV, it cannot be extracted as a segment by position. The system can only obtain the complete state ending at a specific position, and it cannot derive the state for the first n tokens from one state.

    Therefore, linear state can only be reused at positions where it was explicitly saved. If the shared prefix of a request falls between two checkpoints, the system must either roll back to an earlier checkpoint and recompute or pay extra computation cost.

    4.2 Snapshot Placement Requires Trade-offs

    The size of the linear state is fixed, but the saving frequency determines total storage. Saving more frequently gives finer hit granularity and less recomputation, but it increases storage overhead. Storage pressure can be estimated with the following approximation:

    1. total snapshots ≈ total tokens / checkpoint interval
    2. single snapshot size ≈ number of linear layers × per-layer state dimension × bytes per value

    Both variables affect final GPU and host memory usage. The interval must be chosen based on typical session length and available capacity.

    4.3 The Two Cache Types Have Inconsistent Lifecycles

    Full attention KV grows with sequence length, while linear-layer state remains fixed in size. Both are shared by the same request, but their eviction policies must be considered separately. If eviction relies only on a unified last-access time, a case may arise where KV is retained but the corresponding state is lost, making that prefix unreusable. Cache management must treat the two types of data as a single entry and evict or retain them together.

    4.4 Block Boundaries and Checkpoint Boundaries Must Align

    Full attention KV is stored and accessed in blocks, while linear state is stored and accessed in checkpoints. If the two boundaries do not align, a hit may provide some data while other data is missing. In practice, checkpoint positions are usually aligned with block boundaries, meaning checkpoints are placed only at integer multiples of the block size.

    4.5 Distributed Reuse Requires Serialization and Consistency Guarantees

    Cross-node reuse requires state to be serialized, transferred, and deserialized. During transfer, data precision, layout, and version must remain consistent. If the cache key omits the model weight version, tokenizer version, or quantization configuration, incompatible state may be reused incorrectly, producing output deviations that are difficult to diagnose.

    5. Design Approach: State Checkpoints and Tiered Caching

    A relatively complete solution for the challenges above usually includes the following components.

    5.1 Checkpoint Strategy

    Save linear state snapshots at key request boundaries. Common boundaries include:

    • Fixed token intervals, such as every aligned block;
    • The end of a request, meaning the end of one interaction round, because the next round is most likely to use it as a prefix;
    • Before and after tool calls, because an agent’s input often changes structurally at these points.

    Checkpoints at request end provide the highest benefit, because the next request in a multi-turn conversation almost always uses it as a prefix. Fixed-interval checkpoints provide a fallback for more flexible prefix matching.

    5.2 Tiered Storage

    The cache is divided into two tiers:

    • Hot tier: Placed in GPU memory and serving currently running or recently active sessions;
    • Cold tier: Placed in host memory or an external cache pool, with larger capacity and higher access latency.

    When data migrates between tiers, decisions should consider access frequency, prefix sharing, and remaining capacity. Prefixes shared by multiple branches should be retained in the hot tier first.

    5.3 Eviction Strategy

    During eviction, a composite score can be calculated for each cache entry, considering the following factors:

    • Last access time, reflecting recency;
    • Reference count, reflecting how widely the entry is shared;
    • Recomputation cost, meaning how much computation time is needed if the prefix is evicted; higher cost should favor retention;
    • Storage size, so that under equal benefit, larger entries are evicted first.

    Entries with the lowest scores are evicted first. Note that KV and the corresponding linear state must be evicted together as one entry.

    5.4 Lookup and Reuse Flow

    The following pseudocode describes the basic lookup and prefill flow. It is intended only to illustrate the approach and does not correspond to any specific framework interface:

    1. function lookup_prefix(input_tokens, cache):
    2. for each aligned checkpoint boundary b from largest to smallest:
    3. key = hash_prefix_block_chain(tokens[0:b]) plus model version and quantization configuration
    4. if key exists in cache:
    5. return (b, corresponding entry)
    6. return (0, empty)
    7. function prefill(input_tokens, cache):
    8. (start, state) = lookup_prefix(input_tokens, cache)
    9. (KV, new_state_set) = compute_from(start, state, tokens[start:])
    10. for each newly produced checkpoint boundary b:
    11. cache.write(key(tokens[0:b]), state corresponding to b in new_state_set)
    12. return KV

    There are three key points in this flow: lookup starts from the longest prefix; the key includes version information to prevent incorrect reuse; and new checkpoints are produced during computation according to the rules for later requests.

    6. Scheduling and Reuse Strategy

    Cache design must work with the scheduler to be effective.

    • Cache-aware scheduling: When forming batches, prioritize grouping requests with high prefix hit rates, while setting an upper bound on waiting time to prevent long-tail requests from being delayed indefinitely.
    • Session affinity: Route subsequent requests from the same session to the node that holds their cache whenever possible. If routed to another node, the system must pay the cost of loading or recomputation.
    • Prefetching: Agent tool calls often have predictable follow-up patterns. The system can load potentially needed state in advance while a tool is executing.

    Scheduling policies should tune parameters based on real workloads, avoiding over-optimization for one class of requests at the expense of overall fairness.

    7. External Cache and Distributed Reuse

    When GPU memory cannot hold all active sessions, host memory or an external cache pool can extend capacity. The benefit of external storage depends on the comparison between load time and recomputation time. The following rule can decide whether to enable loading:

    1. if snapshot_size / effective_transfer_bandwidth + deserialization_time < time_to_recompute_prefix_from_scratch:
    2. load cache
    3. else:
    4. recompute

    This rule means that external caching is meaningful only when transfer cost is lower than computation cost. For long prefixes, recomputation is usually expensive, so external caching is often worthwhile; for short prefixes, direct recomputation may be faster.

    Cross-node reuse also requires attention to the following points:

    1. The cache key must include the model weight version, tokenizer version, numeric precision, and quantization method. If any item is inconsistent, the cache must not be reused.
    2. State should undergo integrity verification before transfer, such as attaching a checksum, to prevent silent errors caused by data corruption.
    3. When a node fails, the cache should be safely invalidated, and the system should fall back to recomputation rather than returning incomplete results.

    8. Evaluation Methods

    When evaluating a cache design, use workloads that are close to real traffic rather than randomly generated synthetic requests. A recommended approach is to replay real agent session traces while preserving request order, intervals, and length distribution.

    Recommended metrics include:

    • Prefill throughput, measured as input tokens processed per second;
    • Time to first token (TTFT), with particular attention to p50, p90, and p99.