State Cache Refactoring and Prefill Acceleration for Hybrid Architecture LLMs

    This article explains why hybrid LLM architectures—which combine full attention layers with linear attention or state space layers—complicate cache management, and how to redesign state caching and prefill scheduling accordingly. It covers the semantic differences between attention caches and fixed-size recurrent states, a two-stage prefix-tree hit detection scheme with state closure tracking, tiered memory and eviction strategies, prefill pipelining techniques, and the metrics needed to validate throughput, latency, and output quality. The intended audience is teams building or operating inference services for long-context agent workloads.

    1. Why Hybrid Architectures Complicate Cache Management

    Over the past year, open-source LLM architectures have been diverging rapidly. Beyond standard full-attention layers, linear attention and state space layers—such as various gated delta rules and structured state recurrence schemes—are being introduced extensively, producing hybrid structures where some layers perform global attention while others perform linear recurrence. The motivation is straightforward: the inference cost of linear layers does not grow linearly with context length, decoding consumes less compute, and cache footprint is smaller.

    But these gains are not unconditional. A pure attention model has only one cache form: key-value pairs organized by token, written in append mode, matched by prefix, and evicted by block—a single, simple semantic. A hybrid model has at least two kinds of state: an attention cache that grows with the sequence, and a fixed-size recurrent state (a matrix or vector). The two differ in lifecycle, reuse granularity, and serialization format, so prefix cache hit detection, swap-in/swap-out, and cross-node transfer all need to be redesigned. In scenarios like AI coding tools, a single session often contains dozens of tool calls and code re-reads, with very long shared prefixes and many branches, which further amplifies the complexity of cache management.

    2. Semantic Differences Between the Two State Types

    To understand where the optimization headroom lies, start by classifying the states.

    • Attention cache: strongly bound to position, appended token by token, supports reuse from any prefix truncation, and grows linearly with context.
    • Linear state: equivalent to a single “compressed summary” of the prefix, constant in size, reusable only as a whole, and cannot be sliced from an intermediate position.
    • Position encoding and offsets: hybrid structures are sensitive to absolute/relative positions, so the position baseline must be corrected in sync when reusing a cache; otherwise silent quality degradation occurs.

    The key conclusion: correctness of linear state reuse depends on the prefix being exactly identical, whereas an attention cache can be reused on a partial match. If a scheduler applies one uniform policy to both, it either wastes GPU memory or produces incorrect hits.

    3. Hit Detection and Prefix Tree Refactoring

    Traditional prefix matching only needs token blocks as nodes. Under a hybrid architecture, each node must simultaneously maintain an attention block index and the corresponding linear state snapshot, and explicitly record whether the node is “state-closed” (i.e., the recurrent state has been fully computed up to that position).

    A sketch of the data structure:

    1. class HybridNode:
    2. tokens: bytes # Token fingerprint of this block
    3. kv_blocks: list[int] # Attention cache block IDs
    4. state_ref: int | None # Linear state snapshot reference; None means not closed
    5. position_base: int # Position baseline used on reuse
    6. ref_count: int

    Matching should be two-stage: first find the deepest reusable node by token prefix, then check whether that node carries a complete linear state. If the state is missing, fall back to the nearest state-closed ancestor; the attention blocks in between can still be reused, but the linear layers must be recomputed. In practice, it is advisable to enforce “closure per block” on the write side to avoid a large number of partial hits at runtime.

    4. Memory Tiering and Swap-In/Swap-Out Policy

    Fixed-size states are small individually, but numerous and frequently updated; attention blocks are large but have good access locality. A sensible approach is to tier by access heat: keep hot data in GPU memory, warm data in host memory, and cold data in a distributed cache or object storage. For eviction, attention blocks can use approximate LRU combined with reference counting, while linear states should be weighted by “session activity + branch depth,” because losing one state often means recomputing an entire prefix—far more expensive than losing a single attention block.

    Cross-node reuse requires additional attention to serialization cost. A linear state is a dense tensor and suits batched transfer; attention blocks are better streamed block by block to overlap computation and communication.

    5. Scheduling and Batching: Turning Prefill into a Pipeline

    The prefill bottleneck is usually not compute but queuing and fragmentation. Practical measures include:

    1. Priority scheduling: requests that hit the cache enter prefill first; requests that miss and have extremely long contexts are deprioritized so long requests do not block the queue.
    2. Chunked prefill: split long sequences into chunks and interleave them with decode requests in the same batch to smooth the long tail of time-to-first-token.
    3. State prefetching: predict the next states likely to be reused from the prefix tree and pull them from host memory or a remote cache ahead of time.
    4. Pipelining position baseline correction: overlap position rewriting with attention computation to reduce synchronization waits.

    6. Measuring and Validating the Impact

    Evaluating this kind of optimization cannot rely on average throughput alone. Three metric groups are recommended: prefill throughput, time-to-first-token at p50/p90/p99, and cache hit rate together with state recomputation rate. Replaying real multi-turn coding session traces is more meaningful than synthetic load tests, because branching and tool return contents determine the prefix reuse pattern. Quality regression is also mandatory: verify output consistency for the same prompt with cache reuse on and off, to guard against hidden degradation caused by position baseline or state closure errors.

    7. Implementation Recommendations

    For teams that want to build their own inference service or run hybrid architecture models on general-purpose capabilities from Baidu AI Cloud (such as container platforms, object storage, and monitoring/alerting), a progressive path is recommended: first implement a single-node dual-structure cache of “attention blocks + state snapshots” and measure the hit gains; then introduce tiered storage and prefetching; finally extend to cross-node state reuse and distributed caching. Throughout, stay metrics-driven and continuously calibrate eviction and scheduling parameters with real business traces—only then can you reliably obtain both prefill throughput and latency gains under long-context agent workloads.