Large Language ModelsInference & Performance Optimization

How does relative-position-dependent KV caching reuse ordered prompt segments across changing agent turns?

Question 307 of 309 · Updated

On this page

The gap between prefix caching and position-independent caching#

An agent rarely sends the same prompt twice. A coding agent may keep its system instructions and repository context while inserting a new tool result. A memory agent may preserve a long conversation history while updating a short working window. A multi-step reasoning agent may retain several fixed sections but change the content between them on every turn.

The prompt therefore has structure:

[system instructions]
[updated working context]
[fixed memory segment A]
[new tool result]
[fixed memory segment B]
[current question]

Some sections are stable and worth reusing. Other sections change each turn. The difficulty is that the fixed sections may move to different absolute token positions as the updated sections grow or shrink.

Two familiar KV-cache strategies sit at opposite ends of this problem:

  • Position-dependent caching (PDC) reuses cached states only when the segment remains at the same absolute position. It is straightforward and can preserve exact positional assumptions, but it is restrictive when dynamic prompt sections change length.
  • Position-independent caching (PIC) tries to reuse a segment at arbitrary positions. This is more flexible, but moving a cached segment can change its positional encoding and the attention relationships represented by its cached keys and values. PIC systems may need to recompute selected tokens to recover quality.

The FAST 2026 paper CacheSlide: Unlocking Cross Position-Aware KV Cache Reuse for Accelerating LLM Serving identifies an intermediate pattern common in agent workflows: reusable segments often move in absolute position but retain their relative order. The authors call this Relative-Position-Dependent Caching (RPDC).

The key insight is that an agent prompt does not always need arbitrary segment reordering. If fixed segments A and B always appear in the order A-before-B, a cache can preserve that ordering while tolerating moderate shifts caused by updated content between them. This creates a different reuse opportunity from either strict prefix caching or unrestricted position-independent reuse.

What RPDC assumes—and what it does not#

RPDC assumes that a prompt can be divided into reusable fixed segments and dynamic segments, and that the relative order of the reusable segments is stable.

For example:

Turn 1: [System] [Update-1: 120 tokens] [Memory A] [Update-2: 40 tokens] [Memory B]
Turn 2: [System] [Update-1: 220 tokens] [Memory A] [Update-2: 15 tokens] [Memory B]

The absolute positions of Memory A and Memory B shift. Their order does not.

RPDC exploits this stable order. It aims to keep positional differences between cached and freshly computed representations small enough that attention within a fixed segment, and between fixed segments, can be reused with little error. The attention interactions between fixed and newly updated content still need to be recovered.

This is not a universal cache format for arbitrary prompt assembly. If the application swaps A and B, changes the meaning of their order, or inserts large unpredictable sections that destroy the learned positional pattern, the RPDC assumptions may fail. In those cases, the system should recompute, use another cache strategy, or fall back to full prefill.

Why absolute position drift matters#

In a transformer, a key is not just a content vector. It is used by attention together with positional information. With Rotary Position Embeddings (RoPE), position-dependent rotations are applied to queries and keys. If a fixed segment is cached at one set of positions and later appears at substantially different positions, the cached keys can differ from the keys produced by a fresh prefill.

CacheSlide calls this Positionally Misaligned KV Drift (PMKD). The paper measures key-cache similarity using CKSim, a cosine-similarity measure between cached and recomputed keys, averaged across attention heads. The corresponding value-cache similarity is reported to track the key similarity closely in the experiments.

The authors compare RoPE with Contextual Position Encoding (CoPE), where position increments are conditioned on learned semantic boundaries rather than simply assigning a unique index to every token. In their controlled experiment, as the prefix shift grows from 0 to 1,000 tokens, CKSim falls by more than 90% with RoPE, while it falls by 28% with CoPE. These are results from the paper's particular model and experimental setup, not a guarantee that CoPE always behaves this way for every model.

The practical lesson is not that RoPE is universally unsuitable. RoPE is widely used and works well in ordinary inference. The issue is that a cache created under one positional layout may be reused under another. If the serving workload repeatedly changes the lengths of prompt sections before fixed segments, the positional assumptions embedded in cached keys may become stale.

Why simply padding the changing section is not a robust fix#

One possible workaround is to reserve a fixed-size window for the dynamic section. If the updated content is shorter than the window, pad the unused space so later fixed segments retain their absolute positions.

This can reduce position drift, but it imposes a rigid capacity choice:

  • A window that is too small can truncate useful context.
  • A window that is too large can increase positional distance and waste prompt capacity.
  • A single fixed window is difficult to tune when tool outputs, memory updates, and reasoning steps vary widely in length.

In the paper's MemGPT experiment, 1K, 2K, and 3K token window-padding configurations produced substantially lower F1 than the unpadded baseline at the same reasoning rounds; the reported reduction exceeded 78.1%. This result is specific to the paper's tested setup. It illustrates that forcing a prompt into fixed-length update slots can damage the information available across turns rather than solving the underlying reuse problem.

RPDC takes a different route: preserve the relative order of fixed sections and reduce the positional mismatch without forcing every dynamic section into an oversized fixed window.

CacheSlide: three cooperating components#

CacheSlide implements RPDC with three major components:

  1. Chunked Contextual Position Encoding (CCPE) makes the positional treatment of reusable chunks more stable.
  2. Weighted Correction Attention (WCA) recovers interactions between reusable and updated chunks while limiting recomputation to selected tokens.
  3. SLIDE manages KV loading, writes, relocation, and storage spill so the correction work does not become blocked by cache I/O.

These pieces solve different parts of the same problem. CCPE addresses positional consistency. WCA addresses attention interactions that changed because dynamic content changed. SLIDE addresses the systems overhead of loading and updating KV pages.

1. Chunked Contextual Position Encoding (CCPE)#

CCPE first partitions the prompt into chunks and classifies them as either reusable or recomputed. The partition is guided by the application's prompt structure or task template.

For example:

Chunk 0: system instructions       -> reuse
Chunk 1: current working update    -> recompute
Chunk 2: persistent memory A       -> reuse
Chunk 3: latest tool result        -> recompute
Chunk 4: persistent memory B       -> reuse

CacheSlide instantiates CCPE using CoPE. During task-specific pretraining, it collects the CoPE position patterns associated with prompts of that task and identifies a frequent encoding pattern. That pattern is then used to assign position ranges to reusable chunks.

At inference time, the prompt is split using the same task structure. If a reusable chunk is found in the cache, its KV states are loaded. If it is missing, the chunk is prefetched and stored. Dynamic chunks are processed using the positions assigned by the current prompt's encoding.

The objective is to reduce the difference between the positional representation stored in the cache and the representation expected in the current prompt. The paper describes this as making the positional discrepancy small, not eliminating all differences.

Why preserve order?#

Suppose Memory A and Memory B were cached in that order. If their relative order remains unchanged, the model can preserve much of the positional relationship between those fixed segments even when a dynamic section between them changes length.

If the application reorders the memories, that assumption no longer holds. A cache system should therefore treat segment order as part of the cache compatibility contract rather than assuming that content hashes alone establish reusability.

Task-specific patterns are an operational dependency#

CCPE relies on the task structure and positional patterns learned during its preparation phase. A deployment with several unrelated prompt templates may need separate patterns or a fallback. A prompt that changes structure unexpectedly should not be forced through a stale chunk map.

In practice, version the template, chunk boundaries, encoding configuration, and model revision together. A cache hit should mean that the cached representation is compatible with the current execution contract, not merely that a text chunk has the same hash.

2. Weighted Correction Attention (WCA)#

Even if the positional representation of fixed chunks is aligned, the full prompt has changed. A fixed memory segment may now interact with a new tool result or a different working context. The cached KV states cannot automatically contain those new cross-attention effects.

WCA addresses this by recomputing a selected subset of tokens and combining their fresh and cached KV states.

The paper's method works in two broad stages.

Stage A: identify candidate tokens#

At the first layer, the system compares recomputed and cached keys for tokens in the relevant segments. It calculates a deviation score based on the difference between the two representations and ranks the candidates.

A selected top-k set receives more expensive correction in subsequent layers. This is intended to focus computation on tokens whose cached representations differ most from the current computation.

The paper reports a recommended top-k proportion near 0.26 in its evaluated workloads. That value is a study-specific tuning result, not a universal constant. Different models, prompt structures, and accuracy targets may require a different selection budget.

Stage B: similarity-gated weighted fusion#

For selected tokens in later layers, WCA recomputes the relevant KV states and fuses them with the cached values using deviation-aware weights. Conceptually:

LaTeX

The same idea is applied to values. The weight reflects the discrepancy between the cached and recomputed representation.

WCA periodically checks CKSim. Every four layers in the described algorithm, it uses a similarity threshold to decide whether a selected token has converged sufficiently. Tokens that meet the criterion can leave the active correction set, while other candidates with larger remaining discrepancies can be promoted.

The paper reports a threshold near 0.12 alongside the top-k proportion near 0.26 as effective in its experiments. These should be treated as starting points for reproduction, not hard-coded production defaults.

Why this is different from recomputing a fixed percentage once#

A fixed recomputation budget can spend work on tokens that no longer need correction while missing tokens whose errors remain important. WCA combines deviation ranking with layer-wise similarity checks, allowing the active set to change as representations evolve through the network.

The authors motivate this design partly through observed similarity between KV representations in adjacent deeper layers. That observation supports their correction strategy in the tested models; it should not be generalized into a theorem that all transformer layers converge in the same way.

What is being recovered?#

The intended target is the interaction between fixed and updated chunks. If two fixed chunks retain their relative order and their positional encodings remain similar, much of their intra-segment and fixed-to-fixed attention can be reused. WCA focuses correction on the relationships affected by the new dynamic content.

This distinction is central to RPDC. The method does not blindly recompute every cached token, nor does it assume that positional alignment alone restores the full prompt computation.

3. SLIDE: making correction compatible with the KV storage path#

WCA creates a systems problem. At each transformer layer, the serving engine must load cached KV pages and write corrected KV states. If the implementation serializes loading and writing, the correction path can stall while waiting for cache I/O.

Storage pressure adds another problem. Corrected tokens may occupy scattered positions in otherwise reusable KV pages. Evicting those pages with a simple LRU policy can cause small, fragmented writes to SSD, increasing write amplification.

CacheSlide's SLIDE manager combines three ideas:

  • Spill awareness: distinguish clean pages from pages containing corrected tokens.
  • Load-write decoupling: overlap cache loading with recomputation instead of making one wait for the other.
  • Dirty-page eviction: choose pages to spill in a way that encourages coalesced writes.

Load-write decoupling#

At the beginning of a layer, SLIDE starts recomputation while loading the corresponding cached KV data. If recomputation finishes before loading, the corrected KV states can be written into newly allocated pages rather than blocking on the load. The page mapping is then updated.

If loading finishes first, the writes can use the updated mapping directly. During decoding, the system can overwrite original KV slots where appropriate, reducing the need to retain duplicate pages.

The key is to avoid a strict load-before-write dependency on the critical path.

Clean-first and dirty-aware spilling#

SLIDE marks a page dirty if it contains one or more corrected token states. It also tracks how many selected tokens each dirty page contains.

When storage pressure forces eviction, it first spills clean pages. If dirty pages must be evicted, it prioritizes pages containing more selected tokens. This ordering is designed to group corrected data and reduce fragmented write-back.

The approach is not simply a new global LRU replacement policy. It uses knowledge of which pages have been modified by WCA to improve the I/O behavior of cache correction.

The authors implement SLIDE by extending vLLM 0.8.5. The paper's results therefore demonstrate a particular implementation and hardware/software setup, not a guarantee that the same speedups will appear in every vLLM release or storage configuration.

A concrete agent-turn example#

Consider a coding agent that sends the following prompt on each turn:

[System rules]
[Current task and latest test output]
[Repository architecture notes]
[Latest tool result]
[Persistent debugging history]
[Next action request]

The architecture notes and debugging history remain useful across turns. The current task and tool result change.

A conventional prefix cache may reuse the system rules but not the later fixed segments because dynamic content appears before them. A PIC method can reuse those later segments at shifted positions, but it must deal with positional mismatch and changed attention relationships. RPDC can exploit the fact that the architecture notes still precede the debugging history.

A CacheSlide-style execution could proceed as follows:

  1. Split the prompt into stable and dynamic chunks using the coding-agent template.
  2. Look up the reusable chunks by content identity and compatible metadata.
  3. Apply the task-specific contextual position pattern to preserve the order of the reusable chunks.
  4. Recompute dynamic chunks.
  5. Use WCA to identify and correct selected tokens in fixed chunks whose interactions with the dynamic content changed.
  6. Use SLIDE to overlap cache loads with correction writes and manage dirty pages under storage pressure.
  7. Continue decoding with the updated page mapping.

If the agent changes its prompt template, moves the debugging history before the architecture notes, or changes the model revision, the previous cache should not be reused blindly. The safe fallback is a compatible cache variant or full prefill.

How CacheSlide differs from nearby cache techniques#

The names are similar, but the methods solve different constraints.

  • Prefix caching / PDC: reuse is tied to the same absolute position, often a common prefix. It is simple when the stable content stays at the front.
  • PIC (for example, EPIC): reusable chunks can move more freely, but position and context mismatch may require boundary or token recomputation.
  • CacheBlend: fuses cached RAG chunks by recomputing selected tokens to recover contextual interactions in the assembled prompt.
  • Transition Overlap: changes cache construction by temporarily prepending context to a segment, then stores the original segment's KV states. It focuses on reducing isolated-segment boundary mismatch.
  • RPDC / CacheSlide: assumes reusable chunks preserve relative order while absolute positions shift. It combines a position strategy, selective correction, and cache I/O management.

The distinction from Transition Overlap is especially important. Overlap-conditioned construction improves the local left boundary of an independently cached segment. RPDC instead targets a multi-segment prompt structure in which several reusable chunks retain their order while dynamic chunks between them change. CCPE manages positional alignment across those fixed chunks, WCA repairs fixed-to-updated attention, and SLIDE manages the resulting page traffic.

What the evaluation actually establishes#

CacheSlide is evaluated on Mistral-7B, MPT-30B, and Llama-3 70B using HotPotQA, Multi-Session Chat, and SWE-Agent-Bench. The paper reports experiments on NVIDIA A100 80 GB GPUs, with two A100s for the 70B model, plus 500 GB host DRAM and 2 TB NVMe SSD storage.

The authors report:

  • Across the three models and datasets, CacheSlide reduces TTFT by approximately 2.4–3.3× compared with ContextCache while maintaining near-baseline accuracy in their reported comparisons.
  • Compared with CacheBlend, the paper reports 1.21–2.11× lower TTFT and 1.97–2.28× better accuracy in the plotted comparisons.
  • Compared with PromptCache, it reports 1.12–2.45× lower TTFT and 1.41–3.95× better accuracy.
  • In parallel inference, its advantage over the best baseline grows from about 1.2× at batch size 2 to 2.3× at batch size 6 in the reported MemGPT setting.
  • The SLIDE component reduces layer-wise parallel latency by 26.7–51.5% as batch size increases from 2 to 6, and reduces SSD write amplification by 3.11–3.62× in the reported SWE-Agent workloads.
  • The paper also reports 1.63–1.9× lower GPU storage use than PromptCache in its tested configurations.

The paper's abstract summarizes broader gains of 3.11–4.3× latency reduction and 3.5–5.8× throughput improvement. These headline figures should be read in the context of the paper's evaluated workloads and baselines; the more detailed comparisons above show why one should not quote a single multiplier as a universal production expectation.

There are important limitations to keep in mind:

  1. Task structure matters. CCPE learns positional patterns for a task. An unstructured prompt or a new task may not match the trained pattern.
  2. Relative order is a hard assumption. Reordering reusable chunks can invalidate the reuse relationship.
  3. WCA still recomputes. The method is not zero-compute cache reuse; it spends compute on selected tokens and updated context.
  4. Thresholds are workload-dependent. Top-k and CKSim settings influence both quality and throughput.
  5. The implementation is version-specific. The reported implementation extends vLLM 0.8.5 and uses particular A100/DRAM/NVMe hardware.
  6. Encoding adaptation has a cost. The paper uses adapter-based continued pretraining to add CoPE support while preserving backbone weights. This is more involved than enabling an ordinary cache flag.
  7. Benchmark gains are not a substitute for application evaluation. Agent success, code patch correctness, and multi-turn consistency should be measured on the target workflow.

How to decide whether RPDC fits your serving workload#

RPDC is a strong candidate when all of the following are true:

  • The prompt has multiple large reusable segments.
  • Their relative order is stable across requests or turns.
  • Dynamic content between them changes length or content.
  • Prefix-only caching leaves substantial reuse opportunities untapped.
  • Unrestricted PIC has unacceptable quality or correction overhead.
  • The system can define and version task-specific prompt chunk boundaries.

It is a weaker fit when prompt sections are frequently reordered, the reusable content is small, requests rarely repeat, or dynamic sections dominate the context. In those cases, the complexity of task-specific positional patterns and selective correction may outweigh the saved prefill work.

Production rollout checklist#

  • Define a prompt schema with explicit reusable and dynamic chunk boundaries.
  • Record the ordered sequence of reusable chunk identities.
  • Include model revision, tokenizer, positional-encoding configuration, adapter revision, chunk-template version, and cache dtype in cache compatibility metadata.
  • Reject a cache hit when reusable chunks appear in a different order.
  • Version task-specific CCPE patterns and monitor prompt-template drift.
  • Tune WCA's selected-token budget and CKSim threshold on representative workloads rather than copying paper defaults.
  • Track TTFT, output quality, correction-token count, cache hit rate, storage reads/writes, write amplification, and GPU memory.
  • Validate parallel requests and beam search separately because they increase KV storage pressure.
  • Keep a full-prefill fallback for incompatible cache metadata, changed templates, and quality-sensitive requests.
  • Compare end-to-end task success, not only KV similarity or cache-hit latency.

Key takeaway#

Position-dependent caching is too rigid for many multi-section agent prompts, while position-independent caching can pay a quality and correction cost when segments move. Relative-Position-Dependent Caching identifies a useful middle ground: when reusable segments retain their relative order, preserve that structure and manage the smaller positional shifts rather than treating every segment as arbitrarily movable.

CacheSlide turns that idea into a serving design. CCPE stabilizes the positional treatment of reusable chunks, WCA selectively restores attention between fixed and updated content, and SLIDE keeps cache loading, correction writes, and SSD spilling from becoming the next bottleneck. The result is a workload-specific strategy for multi-turn agents—not a universal replacement for prefix caching, PIC, or full prefill.

Related questions

Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents