Hybrid Architecture Model Cache Refactoring: Accelerating Prefill for Coding Agents

    As open-source large language models (LLMs) increasingly adopt hybrid architectures combining full-attention and linear layers, managing the KV cache has become more complex. This article explores the unique workload characteristics of coding agents and the core contradictions in caching for hybrid models. It outlines a design approach for hybrid state caching, covering block-based organization, checkpoint selection, longest prefix matching, tiered storage, and cross-node reuse. Additionally, it provides metrics for performance evaluation, best practices for engineering implementation, and future directions for optimizing prefill throughput and reducing latency.

    1. Why Hybrid Architectures Are Becoming Mainstream

    In recent years, open-source large models have widely adopted a hybrid structure combining “full-attention layers plus linear layers.” Full-attention layers retain the ability to precisely model long-range dependencies, while linear attention layers and state space layers compress historical information recurrently. After combining these two types of layers, the model only needs to maintain a smaller cache during the decoding phase. The memory footprint of the KV Cache is significantly reduced, and the number of requests that can be processed per unit of time increases accordingly.

    The cost of this structure lies in cache management. The KV Cache of a pure Transformer is appended token by token, allowing any prefix to be truncated and reused. The state of a linear layer, however, is a cumulative compression of the entire history; it only represents the overall information prior to a certain position and cannot be truncated to an arbitrary position like a KV. Hybrid models must therefore address how to align the two types of caches, where to save them, and how to search and evict them.

    2. Characteristics of Coding Agent Workloads

    The request patterns of coding agents differ significantly from those of ordinary chatbots, primarily in the following ways:

    • Multi-turn interactions: Each turn of requests carries the previous complete conversation, tool call results, and code modification records. New content typically accounts for only a small fraction of the total input.
    • Highly repetitive prefixes: System prompts, project structure descriptions, and historical file contents appear repeatedly within the same session. The prefix hit rate directly determines the prefill cost.
    • Continuous context growth: The longer the session, the longer the input, and the higher the proportion of prefill in the first-token latency.
    • Interleaved tool outputs: Content such as compilation logs and test results are continuously inserted into the context, making cache boundaries fragmented.

    Therefore, for these types of workloads, the ability to reuse cache is almost equivalent to inference efficiency itself.

    3. Core Contradictions in Hybrid Model Caching

    The caching model of a pure Transformer can be summarized as follows: each token corresponds to a set of KV pairs, and the cache for the prefix of N tokens is simply the first N sets of KV pairs. When a hit occurs, it is reused directly; when a miss occurs, computation starts from the first mismatched position.

    In hybrid models, the full-attention layer still adheres to this rule, but the linear layer does not. The state of a linear layer is a fixed-size vector or matrix representing the cumulative result from the beginning of the sequence to the current position. This introduces three constraints:

    1. States can only be saved at specific positions: If only the final state is saved, it is impossible to roll back to an intermediate prefix; if a state is saved for every token, the memory overhead becomes unacceptable.
    2. KV and state must be aligned to the same position: Only when both correspond to the same prefix length can the computation continue correctly.
    3. Cache lookup requires checking for “complete availability”: A position that has only KV but lacks the state cannot serve as a valid hit point.

    Understanding these three constraints is a prerequisite for designing hybrid state caching.

    4. Design Approach for Hybrid State Caching

    4.1 Block-based Cache Organization

    Divide the prefix into blocks of a fixed size, using each block boundary as a candidate checkpoint. Within a block, record the KV block index for that position, along with the linear layer state snapshot. The block size needs to be a trade-off between hit granularity and indexing overhead: smaller blocks yield more precise hits but generate more metadata.

    4.2 Selecting Checkpoint Positions

    Checkpoints do not need to cover every block; instead, they should fall at positions with the highest reuse value, such as:

    • At the end of the system prompt, which is the most stable throughout the session.
    • At the end of each user message, which is a common prefix boundary for the next request.
    • At the end of tool call outputs, which determines whether subsequent content can be reused.

    This strategy balances memory usage and hit rate.

    4.3 Longest Prefix Matching

    During lookup, the longest prefix that has both KV and state should be found. Below is a simplified illustrative implementation to explain the logic. In production environments, rolling hashes or prefix trees are typically used to reduce computational overhead.

    1. from dataclasses import dataclass
    2. from typing import Optional
    3. @dataclass
    4. class CacheEntry:
    5. kv_ready: bool # Whether full-attention layer KV is available
    6. state_ready: bool # Whether the linear layer state snapshot is available
    7. kv_ref: str # Storage reference for the KV block
    8. state_ref: str # Storage reference for the state snapshot
    9. class HybridPrefixCache:
    10. def __init__(self, block_size: int):
    11. self.block_size = block_size
    12. self.index: dict[str, CacheEntry] = {}
    13. def _prefix_key(self, token_ids: list[int]) -> str:
    14. # Hash the prefix content to avoid storing raw tokens directly
    15. return hash(tuple(token_ids)).__str__()
    16. def lookup(self, token_ids: list[int]) -> Optional[tuple[int, CacheEntry]]:
    17. best = None
    18. for end in range(self.block_size, len(token_ids) + 1, self.block_size):
    19. entry = self.index.get(self._prefix_key(token_ids[:end]))
    20. if entry and entry.kv_ready and entry.state_ready:
    21. best = (end, entry)
    22. return best # Return the reusable longest prefix length and its corresponding cache

    Upon a hit, the system continues computation from the end position, directly loading the KV and state for the covered part. This way, the prefill only needs to process the newly added tokens.

    4.4 Tiered Storage and Eviction

    The cache is typically divided into three tiers: GPU memory, host memory, and distributed storage. Hot prefixes are kept in GPU memory, warm data is placed in host memory, and cold data falls to distributed storage. The eviction strategy can combine the last access time with the number of reuses, prioritizing the eviction of entries that have large state snapshots and low hit rates.

    4.5 Cross-Node Reuse

    Cross-node reuse requires that state snapshots be serializable and accompanied by verification information, such as model version, weight hash, numerical precision, and chunking parameters. Only when these metadata match exactly can the snapshot be loaded by other nodes. Otherwise, the loaded state will silently produce incorrect results, which are much harder to debug than a cache miss.

    5. Performance Evaluation Methods

    When evaluating hybrid state caching, it is recommended to focus on the following metrics:

    • Prefill throughput: The number of input tokens processed per unit of time.
    • First-token latency: Focus on p50 and p90; tail latency has a greater impact on interactive experience.
    • Cache hit rate: Statistical distribution by prefix length, distinguishing between full hits and partial hits.
    • Memory and storage footprint: Total volume of KV pairs and state snapshots.
    • Result consistency: Compare with full computation results without caching to ensure the error is within an acceptable range.

    Evaluation should replay real multi-turn request trajectories as much as possible, preserving the request arrival times and prefix relationships. Using only randomly generated requests cannot reflect the reuse structure in real workloads. Comparative experiments must be conducted under the same hardware, same batch size, and same numerical precision, otherwise the conclusions are not comparable.

    Experimental results from public research show that in coding agent trajectory replays, this type of design can increase prefill throughput to about three times the baseline, with p90 first-token latency dropping by up to 88%. The specific gains depend on the prefix hit rate, hardware configuration, and request length distribution, and should be remeasured based on your own workload before actual deployment.

    6. Considerations for Engineering Implementation

    1. Prioritize correctness verification: Before going live, compare the outputs of the cache path and the full computation path, and perform regression testing on edge cases such as long sequences and multiple truncations/continuations.
    2. Include snapshot volume in capacity planning: A single state snapshot has a fixed size, but the denser the checkpoints, the higher the total footprint. The capacity model needs to estimate both the number of checkpoints and the number of concurrent sessions.
    3. Monitor hit rate and eviction rate: A drop in hit rate often indicates changes in prompt templates or session structure, requiring timely investigation.
    4. Isolation and security: The cache may contain user code, project paths, and other sensitive information. In multi-tenant environments, cache spaces should be isolated by tenant, persistent data should be encrypted, and clear expiration policies should be set.
    5. Version management: After model upgrades or chunking parameter adjustments, old caches should be invalidated. Using version numbers in index key generation can prevent the misuse of incompatible states.

    7. Future Directions to Watch

    Hybrid architectures are still evolving rapidly. Future directions to watch include whether linear layer states can be compressed or truncated at a finer granularity, whether automatic checkpoint selection can be learned based on historical access patterns, and how state snapshots transmitted across nodes can maintain low latency under bandwidth constraints. For teams currently building coding agents, a prudent approach is to first evaluate the current hit rate using real trajectories, and then decide on the checkpoint strategy and the scale of investment in storage tiering.