Large Language ModelsInference & Performance Optimization
How does query-side adaptation enable recomputation-free position-independent KV-cache reuse in LLM serving?
Question 303 of 309 · Updated
On this page
- 1. The repeated-prefill problem in RAG and agent systems
- 2. Prefix caching versus position-independent caching
- 3. Why independently cached artifacts can lose quality
- 4. The key diagnostic: reading an artifact versus selecting among artifacts
- 5. What query-side adaptation changes
- 6. A simple numerical illustration
- 7. Training with full-context distribution distillation
- 8. Why low-rank query adapters are attractive
- 9. Worked architecture for a RAG service
- 10. ATTUNER's reported evaluation
- 11. How ATTUNER differs from other PIC approaches
- 12. Production evaluation checklist
- 13. Failure modes and safeguards
- 14. When should you use query-side adaptation?
- 15. Interview-ready summary
1. The repeated-prefill problem in RAG and agent systems#
A retrieval-augmented generation (RAG) request often combines a system instruction, conversation history, retrieved documents, and a new question. An agent may repeatedly load the same skills, code files, policies, or memory entries while the surrounding instructions and history change.
Ordinary prefix caching is useful when a new request begins with the same token prefix as an earlier request. But reusable documents are often not at the beginning of the prompt, and their preceding text can change. A document that appears after one conversation history may appear after a different history in the next request.
Position-independent caching (PIC) addresses this by encoding reusable artifacts independently and reusing their key-value (KV) cache states at different positions and behind different prefixes. The system can reuse a document's cached representation even when the surrounding prompt changes.
The challenge is that a Transformer normally processes the complete context jointly. A document's hidden representations and attention interactions can depend on what came before it and on which other segments are present. An independently computed artifact cache is therefore not always equivalent to the cache that full-context prefill would have produced.
A conventional repair recomputes selected tokens or adjusts positions. ATTUNER explores a different direction: keep the artifact KV cache fixed and adapt the queries that read it.
2. Prefix caching versus position-independent caching#
Consider two requests:
- Request A: system instructions + conversation A + policy document + question A.
- Request B: system instructions + conversation B + policy document + question B.
The policy document is identical, but the prefix differs. Strict prefix caching cannot generally reuse its KV state as a matching prefix because the document begins at a different location in the complete sequence.
With PIC, the policy document is encoded independently once. Its cache can be inserted into both requests without recomputing the document's full-context prefill.
This is particularly useful for:
- RAG systems that repeatedly retrieve the same documents.
- Coding agents that load recurring repository files or skills.
- Multi-agent systems that share common memory artifacts.
- Assistants that reuse long policy, product, or domain-reference material.
PIC is not semantic caching. It does not return a previously generated answer because a new question is similar to an old one. It reuses model-side attention state for reusable input content, after which the model still performs the task and generates a fresh response.
3. Why independently cached artifacts can lose quality#
A standard Transformer layer computes queries, keys, and values from its current hidden states:
Attention is:
Here, Q represents what the current token is looking for; K determines how cached positions are matched; V contains the information retrieved by attention.
During full-context prefill, a token in a document can attend to preceding instructions and context, subject to the model's causal and attention rules. When the document is encoded independently, those cross-segment interactions are absent. Its KV cache is generated without the complete context in which it will later be read.
Two kinds of mismatch are worth distinguishing:
- Positional mismatch: the artifact's independent position IDs may differ from the positions it occupies in the assembled prompt. Rotary positional embeddings and other position mechanisms can make this important.
- Contextual mismatch: the artifact's representations were created without the preceding context and interactions present during full prefill.
Correcting position IDs can address positional mismatch, but it cannot generally reconstruct all the missing contextual interactions. A cache can have plausible position alignment and still behave differently when the model must choose among several retrieved artifacts.
4. The key diagnostic: reading an artifact versus selecting among artifacts#
ATTUNER's analysis makes a useful distinction.
When a model is asked to read or use one supplied artifact, independently cached representations can remain relatively faithful. The larger quality problem appears when the model must select relevant information among multiple artifacts.
Imagine a prompt containing three cached documents:
- Document A: deployment instructions.
- Document B: incident history.
- Document C: database schema.
The user asks: "Which database field caused the deployment failure?"
The model must attend to the relevant portions of B and C and ignore unrelated information in A. Full-context prefill lets each token's representation reflect the joint prompt. Independently encoded caches do not contain all those interactions.
The model may therefore understand each document reasonably well in isolation but attend to the wrong document or passage when several are present together.
The ATTUNER paper reports an important diagnostic: replacing the PIC attention scores with scores from full-context prefill can recover performance while leaving the cached KV tensors unchanged. This suggests that, in the studied setting, the major failure is not necessarily that the cached artifact values have become unusable. The model's query-side reading behavior is misaligned with the full-context attention pattern.
That diagnosis motivates adapting queries instead of recomputing or rewriting cached keys and values.
5. What query-side adaptation changes#
ATTUNER inserts low-rank adapters into the query projections so that the model learns to read frozen artifact caches more like it reads artifacts during full-context prefill.
For a hidden representation h, the ordinary query projection is:
A low-rank adaptation can be written conceptually as:
where A and B are trainable low-rank matrices. The dimensions are chosen so that the additional trainable parameter count is much smaller than updating the full query projection.
The base model and artifact KV cache remain frozen. Only the small query-side adaptation parameters are learned.
This is a different intervention from:
- Recomputing selected artifact tokens.
- Re-encoding every document at its final prompt position.
- Training a new document encoder that changes cached K/V representations.
- Translating one model's KV cache into another model's cache.
The adapted query is intended to retrieve information from the independently encoded cache in a way that better matches the attention behavior of full-context prefill.
6. A simple numerical illustration#
Suppose a user asks a question over three independently cached documents. At a particular attention layer, a query token assigns the following illustrative attention weights:
| Document | Full-context attention | PIC attention |
|---|---|---|
| A: deployment guide | 0.10 | 0.42 |
| B: incident history | 0.25 | 0.18 |
| C: database schema | 0.65 | 0.40 |
The full-context model focuses most strongly on document C, which contains the relevant schema detail. The PIC model distributes too much attention to document A.
This is an illustrative example, not a measured ATTUNER result.
A query adapter can learn a transformation that moves the PIC attention distribution closer to the full-context distribution. For example, after adaptation, the weights might become:
| Document | Adapted PIC attention |
|---|---|
| A: deployment guide | 0.12 |
| B: incident history | 0.23 |
| C: database schema | 0.65 |
The cached keys and values have not changed. The query used to score them has changed, allowing the model to select the useful information more effectively.
In practice, attention operates over token positions and heads, not just three document-level weights. The table is a simplified way to understand the mechanism.
7. Training with full-context distribution distillation#
ATTUNER uses full-context prefill as a teacher signal during training.
For each training example, the system can construct two views:
- Teacher view: run the complete prompt through the original model and obtain the next-token distribution under ordinary full-context prefill.
- Student view: use independently cached artifacts and the query-adapted model to obtain a distribution from PIC.
The student is trained to match the teacher distribution. A common conceptual objective is:
The actual training objective can include implementation-specific details and additional terms; this expression illustrates the distribution-distillation idea.
The key is that the student learns how to read the frozen artifact cache in the presence of changing context. It does not need the full-context teacher at serving time.
This is an offline training cost. It should not be confused with online inference overhead.
8. Why low-rank query adapters are attractive#
Updating the entire model for PIC would be expensive and operationally intrusive. Low-rank query adaptation has several advantages:
- Small trainable footprint: the paper reports training fewer than 0.05% of model parameters.
- Frozen cache compatibility: artifact KVs remain in the ordinary model cache representation.
- No token recomputation at inference: the adapted model does not need to identify and re-encode selected artifact tokens.
- No full-context reference at inference: the teacher distribution is used for offline training, not required for each request.
- Simple serving integration: after merging or applying the query updates, the ordinary attention path can read the cached artifacts.
The small parameter count does not mean the whole deployment is free. Training still requires representative examples, full-context teacher computation, validation, and version management. Serving still has to retrieve, transfer, allocate, and assemble cached artifacts.
9. Worked architecture for a RAG service#
Consider a knowledge assistant with 10,000 reusable policy and technical documents.
Offline artifact construction
- Normalize each document into stable chunks.
- Encode each chunk independently using the pinned model and tokenizer.
- Store the per-layer KV tensors with document ID, chunk boundaries, model revision, positional metadata, and content hash.
- Train or load the query-side adapters for the target model.
- Validate cache reads against full-context prefill on representative retrieval tasks.
Online request
- Receive the user question and conversation state.
- Retrieve candidate documents using the ordinary retrieval system.
- Fetch their compatible cached KV chunks.
- Assemble the system prompt, dynamic conversation, and cached artifacts using the PIC layout.
- Run the model with adapted query projections.
- Generate a fresh answer and apply normal grounding, authorization, and output validation.
The benefit is that the service avoids repeatedly encoding the unchanged document content. It still processes the dynamic query, instructions, and any new context.
A production implementation should distinguish cache lookup time, remote transfer time, cache assembly time, and model prefill/decode time. An efficient query adapter cannot compensate for a slow artifact store or a congested network.
10. ATTUNER's reported evaluation#
The ATTUNER paper evaluates Qwen3-4B and Qwen3-8B across seven benchmarks covering skills, documents, memory, and code.
Its abstract reports:
- Query-side low-rank adapters train fewer than 0.05% of the model parameters.
- The method does not require cache recomputation or a full-context reference at inference.
- It substantially improves on prior PIC baselines in the reported in-domain and out-of-domain settings.
- It matches full-context prefill quality in the evaluated settings while providing up to 3.73× speedup.
These are paper-reported results, not a guarantee for every model, workload, cache layout, or deployment. The maximum speedup should not be interpreted as the expected gain for every request. Measure the actual workload's prompt composition, artifact reuse rate, cache transfer cost, and latency distribution.
The project's detailed results also report that, with query updates merged into projection weights, geometric-mean in-domain TTFT is only 1.8% and 0.5% higher than PIC on Qwen3-4B and Qwen3-8B respectively, while preserving reported speedups over full prefill. These figures are specific to the paper's experimental setup.
11. How ATTUNER differs from other PIC approaches#
EPIC: Efficient Position-Independent Caching improves PIC serving with its LegoLink algorithm, which mitigates the inappropriate attention-sink effect at document beginnings. It focuses on cache construction and serving behavior rather than adapting query projections to read frozen artifacts.
SemPIC: SemPIC trains a Writer to compile document KV representations through behavioral distillation while keeping the pretrained Reader unchanged. Adaptation occurs when constructing the artifact cache. ATTUNER instead adapts the reader's query projections.
CacheWeave: CacheWeave learns which contiguous token blocks to recompute for efficient PIC. It focuses on selective recomputation, block-aligned selection, and serving integration. ATTUNER aims to avoid artifact-token recomputation at inference by changing query-side behavior.
These methods address related PIC quality problems but intervene at different points:
- Cache construction and representation learning.
- Query-side reading behavior.
- Selective token or block recomputation.
- Serving and distributed cache placement.
They should be compared using the same model, workload, quality metric, and latency measurement rather than by comparing headline speedups across papers.
12. Production evaluation checklist#
A serious deployment should compare at least these configurations:
- Full-context prefill baseline.
- PIC without adaptation.
- PIC with position correction where applicable.
- PIC with query-side adaptation.
- A relevant recomputation-based PIC baseline.
Measure:
Quality
- Exact match, F1, or task-specific accuracy.
- Multi-document retrieval and evidence attribution.
- Answer faithfulness and citation correctness.
- Out-of-domain performance.
- Performance as the number of retrieved artifacts increases.
Latency
- Artifact lookup and fetch latency.
- Cache transfer and assembly time.
- Time to first token (TTFT).
- Inter-token latency (ITL) and output throughput.
- p50, p95, and p99 under realistic concurrency.
Resource use
- Cache storage size and hit rate.
- GPU memory and host memory.
- Adapter memory and execution overhead.
- Network bytes per request.
- Offline training and teacher-inference cost.
A useful comparison is quality at a fixed TTFT or TTFT at a fixed quality threshold. A system that is fast but selects the wrong evidence is not a successful cache optimization.
13. Failure modes and safeguards#
Artifact distribution shift. Adapters trained on short policy documents may not work equally well on long code files, tables, or unusual formatting. Build calibration and evaluation sets that reflect production artifacts.
Too many competing artifacts. Query adaptation may improve reading behavior but cannot guarantee that retrieval supplied the correct document or that the model can resolve contradictory sources. Retrieval ranking and evidence-grounding checks remain necessary.
Incorrect cache identity. Cache entries must be bound to the exact model, tokenizer, adapter, attention configuration, document content, and cache format. Never reuse an artifact KV cache across incompatible model revisions simply because the text is identical.
Position and boundary assumptions. PIC implementations have different positional handling and artifact-boundary behavior. Query adaptation should not be treated as a universal fix for every positional encoding or cache assembly method.
Long-context extrapolation. A model evaluated on a certain number of chunks may degrade when thousands of artifacts are assembled. Test the actual context length and artifact count.
Security and tenant isolation. Cache lookup must enforce document permissions before exposing cached state. A correct query adapter does not provide authorization. Cache keys, storage namespaces, and retrieval metadata must preserve tenant and access boundaries.
Adapter drift. Updating the base model, tokenizer, retrieval pipeline, or artifact compiler can invalidate the learned query behavior. Version the adapter with the full serving configuration and re-evaluate after changes.
Teacher cost. Full-context teacher inference can be expensive during training. Reuse a curated training set and track teacher compute separately from online savings.
14. When should you use query-side adaptation?#
ATTUNER-style adaptation is worth evaluating when:
- The same documents, skills, or memory artifacts recur across many requests.
- Their position and preceding prompt context change.
- Prefix caching misses much of the reusable content.
- PIC is already useful but suffers from multi-artifact selection errors.
- You can afford offline teacher-based training and maintain a model-specific adapter.
It is less compelling when:
- Requests rarely reuse the same artifacts.
- Prompts are short and prefill is not a meaningful bottleneck.
- Cache transfer and lookup dominate the request latency.
- The workload requires strict native-prefill equivalence that has not been validated.
- The serving stack cannot safely manage artifact-level cache identity and permissions.
15. Interview-ready summary#
Position-independent caching reuses independently encoded document or memory KV states even when those artifacts appear after different prefixes. This can save substantial prefill work in RAG and agent workloads, but the assembled prompt may behave differently from full-context prefill.
ATTUNER's key insight is that the cached artifact representations can remain useful while the model's attention queries select among them incorrectly. It therefore freezes the artifact KV cache and learns small low-rank adapters in the query projections, using full-context output distributions as an offline teacher.
At inference, the adapted model reads the cached artifacts without recomputing their tokens or requiring a full-context reference. The method is distinct from selective KV recomputation: it changes how the model reads the cache rather than repairing the cache contents. Validate quality, latency, artifact count, cache compatibility, and security on the actual production workload.
References
- 1.
- 2.EPIC: Efficient Position-Independent Caching for Serving Large Language Modelsproceedings.mlr.press
- 3.
- 4.
- 5.ATTUNER project page and detailed evaluationskycxh.github.io
Related questions
- How do distributed position-independent KV caches coordinate remote reuse, parallel prefill, and cluster-wide resource allocation?
- How does overlap-conditioned cache construction reduce boundary errors in position-independent KV reuse?
- How do hybrid-attention LLMs reuse cached segments when linear layers expose recurrent states instead of token KV?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents