Large Language ModelsInference & Performance Optimization
How do hybrid-attention LLMs reuse cached segments when linear layers expose recurrent states instead of token KV?
Question 305 of 309 · Updated
On this page
- 1. Why ordinary position-independent caching breaks on hybrid models
- 2. Understand the two kinds of state in a hybrid stack
- Full-attention layer
- Linear or recurrent layer
- A simple contrast
- 3. HYPIC: cache the segment transition as well as its zero-start state
- Why this is not one universal-size matrix
- 4. Why naive addition of recurrent states is wrong
- 5. HYPIC's second challenge: repairing full-attention layers
- Why the boundary is special
- Seam width is a quality-latency knob
- 6. HYPIC's third contribution: parallelize cold segment prefill
- 7. End-to-end HYPIC request flow
- 8. LinearKV: a simpler initializer can be more robust than exact composition
- Why can exact algebra still produce a poor initializer?
- Reported LinearKV results
- 9. HYPIC versus LinearKV
- 10. A worked segment example
- 11. Production engineering considerations
- Cache identity
- Segment boundaries
- Transition storage and memory
- Seam-window policy
- Selector compatibility
- Parallel cold prefill
- Correctness and output quality
- Deployment and observability
- 12. What should an engineer choose?
- Conclusion
1. Why ordinary position-independent caching breaks on hybrid models#
Position-independent caching (PIC) reuses independently prefilled prompt segments even when they appear after different prefixes or at different positions. This is useful in retrieval-augmented generation (RAG), document workflows, and agents: a document, skill file, or tool result may recur even though the surrounding prompt changes.
In a conventional full-attention Transformer, each token has a key-value (KV) entry at every attention layer. A PIC system can concatenate cached token KV from several segments, then selectively recompute some token positions to repair cross-segment context. Methods such as CacheBlend and EPIC build on this token-indexed representation.
Hybrid-attention models change the representation. They interleave a minority of full-attention layers with recurrent or linear-attention layers such as Mamba-2, Gated DeltaNet (GDN), or Kimi-style linear attention. A recurrent layer compresses the processed prefix into a fixed-size state. After prefill, it typically retains the final state needed for decoding—not a separately addressable state for every token.
That breaks two familiar PIC operations:
- Splicing: there is no token-indexed recurrent KV sequence to concatenate for a linear-attention layer.
- Selective repair: recomputing an arbitrary token at a later full-attention layer may require the recurrent state immediately before that token, but that intermediate state was not retained.
The engineering challenge is therefore not simply caching fewer bytes. It is finding a valid way to initialize and advance recurrent state when independently cached segments are assembled into a new context.
Two research directions illustrate the design space: HYPIC caches a segment transition operator and composes states; LinearKV argues that a single cached segment state can be a more robust initializer in some architectures. Their results show why algebraic exactness and end-to-end model quality must be evaluated separately.
2. Understand the two kinds of state in a hybrid stack#
A hybrid model contains two distinct layer behaviors.
Full-attention layer#
For a sequence of tokens, a full-attention layer retains token-indexed keys and values:
At a given decoding step, attention can read selected historical entries. This is the familiar KV cache used by prefix caching and full-attention PIC.
Linear or recurrent layer#
A recurrent layer compresses the processed prefix into a state . A useful general form is:
Here transports or transforms the previous state, and is the update contributed by the current token. The exact form depends on the architecture.
For Mamba-2, a simplified state update is:
where is a learned decay factor.
For GDN, the transition can be direction-dependent:
where , , and are token-dependent quantities.
Unlike full attention, the recurrent layer does not need to keep every intermediate state for ordinary decoding. It needs the current accumulated state. That saves memory, but removes the token-level handles that conventional PIC assumes.
A simple contrast#
Imagine a prompt with three independent segments A, B, and C.
- At a full-attention layer, the cache can retain the token KV for A, B, and C, then assemble them in context order.
- At a recurrent layer, the cache may hold only the final state produced by A, the final state produced by B, and the final state produced by C.
Those three isolated end states are not generally interchangeable with the state obtained by processing A followed by B followed by C. The recurrent state for B was produced from an empty initial state, not from the state after A.
The missing information is how B transforms an arbitrary incoming state. HYPIC makes that transformation explicit.
3. HYPIC: cache the segment transition as well as its zero-start state#
HYPIC identifies a segment-cumulative transition operator as the missing primitive for recurrent-layer PIC.
For a segment , prefilled from a zero initial state, cache two objects:
- : the cumulative transition operator for the segment.
- : the segment's final recurrent state when its starting state is zero.
The segment then represents an affine transformation of any incoming state:
This is the crucial step. The zero-start state alone describes only what the segment contributes from an empty history. The transition operator describes how the segment transforms whatever state came before it.
For two segments A and B:
If the initial state , this becomes:
The same construction extends to multiple segments. With segments in context order:
The product order matters: later segments transform the state contributed by earlier ones.
This composition is constant with respect to the number of tokens in a segment once its transition and zero-start state have been cached. It avoids replaying every token merely to combine segment states.
Why this is not one universal-size matrix#
The storage and compute cost of depends on the recurrence family:
- Scalar transitions, as in simplified RetNet or Mamba-2 forms, can be represented by a scalar.
- Diagonal transitions can be represented by a vector.
- Dense transitions, as in GDN or DeltaNet-style recurrences, may require a matrix.
For the HYPIC paper's example dimensions and FP16, a dense transition is about 32 KB per head per layer. This is much smaller than retaining a full recurrent state at every token, but it is not free. The cache design must account for model architecture, number of heads and layers, segment count, and reuse frequency.
The transition can be accumulated during the first segment prefill. At reuse time, applying it to the current state costs work that is independent of the segment's token length, though dense transitions cost more than scalar or diagonal ones.
4. Why naive addition of recurrent states is wrong#
A tempting shortcut is to add the isolated end states:
This omits the effect of B on the state contributed by A. The correct expression includes .
A numerical scalar example makes the difference clear.
Assume:
- Segment A has transition and zero-start state .
- Segment B has transition and zero-start state .
- The initial state is zero.
After A:
After B:
Naive addition gives , which is wrong. The transition-aware composition gives 3.8.
The example is deliberately scalar. Real recurrent states are matrices or structured tensors, and the transition may be diagonal or dense. But the principle is identical: a cached segment must encode both its own contribution and how it transforms incoming state.
5. HYPIC's second challenge: repairing full-attention layers#
Even if recurrent states can be composed, a hybrid model still contains full-attention layers. Those layers need cross-segment context when cached segments are assembled.
In a pure full-attention model, selective recomputation can reconstruct a chosen token's hidden state and KV by reading the required preceding token KV. In a hybrid stack, that forward path may pass through recurrent layers. If only the final recurrent state was stored, the intermediate state needed for an arbitrary selected token is unavailable.
There are two unattractive alternatives:
- Store every token's recurrent state. This can be dramatically larger than ordinary KV storage and erase the memory advantage of linear attention.
- Re-run the recurrence from the beginning for every selected token. This can approach full-prefix recomputation and defeat the point of caching.
HYPIC observes a useful locality pattern: the largest full-attention KV deviations after segment assembly tend to concentrate near the beginning of each reused segment. It therefore uses a seam window at each segment boundary.
The seam window contains a small number of tokens at the start of a reused segment. Those tokens are recomputed through the hybrid stack so that the full-attention layers receive hidden states that account for the preceding segments. The remaining tokens reuse cached state.
This is a boundary-anchored approximation, not a claim that every token's representation is mathematically identical to a full recomputation. Its effectiveness depends on the observed localization of the error and the chosen seam width.
Why the boundary is special#
The first tokens of a segment were originally prefetched without the preceding segments that exist in the assembled request. Their hidden states therefore miss some cross-segment context. Later tokens within the same segment have already accumulated more local context, so their representations can be less affected by the missing prefix.
A seam window spends recomputation where the discrepancy is concentrated instead of storing every intermediate recurrent state or recomputing an entire segment.
Seam width is a quality-latency knob#
A narrow seam window reduces repair cost but may leave more boundary error. A wider window increases computation and can improve fidelity, but reduces the speedup. The right width should be measured by model, recurrence type, segment length, and workload.
A production system should evaluate:
- task quality against full prefill;
- TTFT and throughput at multiple seam widths;
- sensitivity to segment ordering and boundary placement;
- whether a small number of unusually important segments need wider repair;
- whether the seam window remains effective on new model revisions.
6. HYPIC's third contribution: parallelize cold segment prefill#
PIC is often described as a cache-hit optimization, but cache misses remain important. New documents arrive, low-frequency segments are evicted, and agent context changes.
A conventional serving system may prefill all cold segments of one request on a single instance. If a request contains cold segments of similar length , the work is approximately proportional to:
HYPIC exploits the fact that independent segments can be prefilled from their own tokens. It dispatches cold segments to multiple scatter workers and gathers their cached representations at a combine worker.
With workers and balanced segments, the compute portion can approach:
where represents transfer, assembly, and coordination overhead. This is not a guaranteed speedup formula: network transfer, queueing, imbalance, and the combine step can dominate.
The system uses a Longest-Processing-Time-first (LPT) policy to distribute larger cold segments first, helping balance worker load. It also pipelines computation with transfer so that the combine worker does not wait for every operation to finish serially.
This is related to, but not the same as, the distributed cache coordination in Question 304. Question 304 focused on cluster-wide PIC directory state, remote hits, PC/PIC cache allocation, and end-to-end scheduling. HYPIC's segment parallelism is specifically enabled by hybrid-model segment self-containment and the need to assemble recurrent state and full-attention KV correctly.
7. End-to-end HYPIC request flow#
A simplified request lifecycle is:
- The application supplies meaningful segment boundaries, such as document separators or agent-turn boundaries.
- The router identifies cache hits and misses for each segment.
- It chooses a combine worker.
- It dispatches cold segments to scatter workers.
- Each scatter worker computes the segment's full-attention KV plus recurrent-layer cache objects, including and .
- Cached segment objects are transferred or made available to the combine worker.
- The assembler concatenates full-attention KV in context order.
- It composes recurrent states using the cached transition operators.
- It recomputes seam windows to repair full-attention boundary context.
- It completes remaining query prefill and hands the assembled running state to decoding.
HYPIC separates reusable segment cache from the private running state of a particular request. Its public pool stores reusable segment objects; its private pool stores the request-specific assembled state used during decode. This separation prevents a request's composed state from being confused with a reusable isolated segment.
The implementation's cache identity must still include model revision, tokenizer, attention configuration, adapter, and representation metadata wherever these affect compatibility. Position independence does not mean model independence or tenant independence.
8. LinearKV: a simpler initializer can be more robust than exact composition#
HYPIC's transition composition is algebraically principled: it composes the affine operators represented by independently cached segments. But a later study, LinearKV, asks whether the resulting exact composition is always the best practical initializer for hybrid models.
LinearKV keeps the full-attention path unchanged: it concatenates cached full-attention KV and uses an existing PIC selector such as CacheBlend, EPIC, or ProphetKV to choose token positions for recomputation.
For each recurrent layer, it maps the matched segment states to one initial state:
It compares two choices:
Exact composition: compose every matched segment's cached transition and zero-start state in order, as HYPIC does.
Single-block initialization: choose one cached segment's local recurrent state as the initializer. The paper's default uses the last matched segment:
Then selected tokens are replayed in context order. The full-attention KV at selected positions is overwritten, and each recurrent layer advances its state through those selected tokens.
This is intentionally not the exact full-prefix recurrent state. It is an approximate starting point designed to be robust when exact composition of independently conditioned states becomes unreliable.
Why can exact algebra still produce a poor initializer?#
The composition formula is exact for the cached affine operators it receives. But those operators were computed while each segment was processed in isolation.
In a deep hybrid network, a segment's higher-layer inputs depend on the hidden states produced by lower layers. During isolated prefill, those lower-layer hidden states do not include the preceding segments that would exist in the assembled full context. The cached transition operator at a higher layer can therefore be conditioned on a different hidden trajectory from the one in full prefill.
Composing these isolated operators exactly does not necessarily reproduce the operator that the segment would have under full-context hidden inputs.
The paper describes accumulated error with a recurrence of the form:
where is the state error after segment , and is the fresh mismatch introduced by using an isolated segment operator instead of its full-context counterpart.
The transition family affects how error propagates. Scalar decays can retain and accumulate error; dense gated transitions can suppress or overwrite some directions. But the injected mismatch also depends on layer depth, hidden inputs, and architecture. It is therefore unsafe to assume that a mathematically exact composition of cached local operators guarantees the best served output.
Reported LinearKV results#
LinearKV evaluates three hybrid models: Granite with Mamba-2, OLMo-Hybrid with GDN, and Qwen3.6 with GDN. It uses three PIC selectors and evaluates LongBench and RULER at 8K–32K context lengths.
The paper reports that:
- On the two evaluated GDN models, single-block initialization and exact composition are broadly comparable.
- On the evaluated Mamba-2 model, exact composition performs poorly under the tested selectors; for EPIC, the reported full-quality recovery is 46.6% with exact composition versus 86.8% with single-block initialization.
- A random single block performs similarly to the default last block in the reported ablation, suggesting that the single-source construction, rather than the specific last block, drives the result.
- The single-state initializer avoids the extra transition composition overhead.
These results are not a theorem that single-block initialization is always superior. They are an empirical finding across a limited set of architectures, models, selectors, and tasks. The authors explicitly caution that the observed boundary is not yet a universal law for every hybrid architecture.
9. HYPIC versus LinearKV#
| Design question | HYPIC | LinearKV |
|---|---|---|
| Recurrent-layer initialization | Compose all segment transitions and zero-start states | Use one cached segment state as initializer |
| Full-attention KV | Concatenate and repair boundary regions | Concatenate and use existing selective recomputation |
| Hybrid-specific repair | Seam windows at segment beginnings | Existing selector's chosen token positions, replayed through recurrent states |
| Main objective | Near-exact state composition plus hybrid PIC and cold-segment parallelism | Test whether a simpler state initializer is more robust |
| Extra cached object | Segment transition operator | No transition required for single-block initialization |
| Main caveat | Transition storage and isolated-operator conditioning | Approximate initializer; evaluated evidence is architecture-limited |
They are not simply two interchangeable implementations of the same formula. HYPIC changes the cache representation to preserve the segment's affine transition. LinearKV changes the initialization policy and reuses existing PIC selectors. Their methods can be compared under matched model, segment, selector, and recomputation settings, but results should not be mixed without checking those experimental conditions.
A useful engineering approach is to benchmark both approaches on the actual hybrid architecture. Do not choose solely because one is more mathematically elegant or has fewer cached objects.
10. A worked segment example#
Suppose a RAG request is assembled from three documents:
- A: a 1,000-token policy document.
- B: a 700-token product specification.
- C: a 900-token troubleshooting guide.
All three were previously cached independently. The new request uses the order B, A, C and appends a 60-token question.
At full-attention layers, the serving system can retrieve the cached KV for B, A, and C and concatenate it in the new context order. It then repairs selected positions so that important tokens account for cross-document context.
At recurrent layers, it cannot simply concatenate three token-level KV sequences because there are no such sequences. HYPIC retrieves , , and , then composes them in B-A-C order.
If a simplified scalar recurrence had:
Starting from zero:
A naive sum of isolated states would produce , which does not represent the recurrence.
LinearKV instead chooses one of the cached local states as its recurrent initializer, then processes selected repair tokens in context order. This is not exact state composition, but the paper finds that this can be more robust for the tested Mamba-2 case.
The final question prefill uses the repaired hybrid state. This example illustrates the state-handling difference; the scalar numbers are hypothetical and are not measured results from either paper.
11. Production engineering considerations#
Cache identity#
A reusable object must be tied to the exact model and execution configuration that produced it. At minimum, assess model revision, tokenizer, adapter, layer layout, recurrent-state format, attention mode, dtype, quantization, and backend version. A mismatch should cause a cache miss, not a best-effort state composition.
Segment boundaries#
The application must define segments that are genuinely reusable. Arbitrary splitting can change the semantics of recurrent state and the cross-segment attention repair requirement. Record segment order and identity separately from their original absolute positions.
Transition storage and memory#
Dense matrices cost more than scalar or diagonal transitions. Estimate transition memory across all layers, heads, segments, replicas, and cache tiers. A transition that is cheap for one segment can become material when the cache holds millions of segments.
Seam-window policy#
Use a measured seam width rather than assuming a universal fixed number of tokens. Measure accuracy and TTFT across segment lengths and model revisions. Monitor whether errors remain localized at boundaries.
Selector compatibility#
LinearKV assumes the selector returns positions to recompute in context order. Verify that the selected positions are valid for both full-attention KV repair and recurrent-state replay. A selector designed for full-attention models may need careful integration and evaluation in a hybrid stack.
Parallel cold prefill#
Parallelism is useful only when transfer and combine overhead are lower than the saved queueing and compute time. Balance segments by predicted prefill cost, not merely token count if segment content or model behavior changes throughput. Include straggler and worker-failure handling.
Correctness and output quality#
Compare against full recomputation, not just a cache-hit metric. Use task-appropriate evaluation such as retrieval accuracy, answer F1, summarization quality, and long-context needle retrieval. A low state error norm does not necessarily guarantee the correct answer, and a strong first-token match does not guarantee identical continuation.
Deployment and observability#
Track cache hit rate, transition-cache hit rate, seam tokens recomputed, recurrent-state composition time, per-segment prefill time, transfer time, combine wait, TTFT percentiles, throughput, and quality. Separate cache misses from invalid or incompatible cache entries. Add a full-prefill fallback when a cache object fails validation or the expected speedup disappears.
12. What should an engineer choose?#
Use HYPIC-style transition composition when:
- The model's recurrent transition operators can be represented and composed efficiently.
- Exact affine composition is stable for the target architecture and layer stack.
- Transition storage and application costs are acceptable.
- The implementation can combine this with boundary repair and segment-parallel cold prefill.
Evaluate LinearKV-style single-state initialization when:
- Exact composition adds material runtime or cache overhead.
- The architecture's isolated segment operators produce poor end-to-end quality after composition.
- A selected-token repair pass can recover sufficient task quality from a simpler initializer.
- The target model resembles the tested recurrence family, but still verify on the exact model.
Use full prefill or a conservative prefix-cache path when:
- Segment boundaries are not trustworthy.
- Cache provenance is incomplete.
- The model or adapter has changed.
- Quality loss exceeds the product's tolerance.
- Transfer and repair cost erase the expected latency advantage.
The important design principle is to separate three questions: what state must be cached, how cached segments should initialize the recurrent path, and which tokens must be recomputed to restore useful cross-segment context. A solution to one does not automatically solve the others.
Conclusion#
Hybrid-attention models create a new obstacle for position-independent caching: full-attention layers expose token KV, while recurrent layers expose a compact state for the processed prefix. HYPIC addresses this by caching each segment's transition operator and zero-start state, composing them in context order, repairing full-attention boundaries with seam windows, and parallelizing cold segment prefill.
LinearKV adds an important caution. Exact composition of isolated segment operators can still be poorly conditioned by the hidden-state context in which those operators were created. In its evaluated models, a single cached state can be a more robust initializer, especially for the tested Mamba-2 model. The choice must be settled through model-specific end-to-end evaluation, not algebra alone.
For production LLM serving, hybrid PIC is therefore an architecture-aware cache design problem: preserve the right recurrent information, repair the right boundaries, parallelize only when it improves completion time, and always measure task quality against full recomputation.
References
- 1.
- 2.
- 3.
- 4.EPIC: Efficient Position-Independent Caching for Serving Large Language Modelsproceedings.mlr.press
- 5.
Related questions
- How does relative-position-dependent KV caching reuse ordered prompt segments across changing agent turns?
- How does query-side adaptation enable recomputation-free position-independent KV-cache reuse in LLM serving?
- How do distributed position-independent KV caches coordinate remote reuse, parallel prefill, and cluster-wide resource allocation?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents