Overview

13 Context compression and pruning

Long context in retrieval-augmented generation can make systems both slower and less accurate, even when the right document has been retrieved. As prompts grow, attention gets diluted, useful information can end up “lost in the middle,” and the model may read past the evidence and fall back on its own priors. The result is a mix of extraction failures, higher latency, and rising token costs, so the chapter argues that the real task is not simply retrieving more text, but handing the generator a smaller, cleaner context that preserves what matters.

The chapter traces context compression as an evolution of increasingly aligned scoring methods. Early heuristics like TF-IDF or BM25 were cheap but blind to the user’s question. Proxy perplexity improved things by using a small language model to score tokens, and LongLLMLingua made this practical by introducing contrastive perplexity, which keeps tokens that become more informative when the question is included. It then layers in coarse document filtering, reordering to exploit positional bias, fine-grained token pruning, and recovery for fragmented entities. AttentionRAG goes one step further by reading the generator’s own attention weights, reducing the mismatch between a proxy scorer and the model that will actually answer.

Beyond these runtime pruning methods, the chapter shows that stronger compression can come from trained synthesis methods such as RECOMP and CORE, which rewrite or select content to better support the downstream task, and from systems integration patterns like query-aware post-processors and recursive retrieval. It emphasizes that extractive compression is best when factual spans must be preserved, while abstractive compression is better for multi-hop or summarization tasks, though it adds hallucination risk. The main practical lesson is that compression ratio must be tuned to the task, the documents, and the deployment constraints: too little compression wastes money and attention, while too much can destroy meaning and flip the answer.

The LongLLMLingua Pipeline.
The two obstacles to reading attention, and the answer hint prefix that resolves them. Long sequences dilute softmax mass; multi-token queries scatter focal points. Reformulating the query as a fill-in-the-blank prefix forces a single focal token whose attention concentrates on the context that informs the prediction.
The AttentionRAG pipeline. Stage 1 retrieves chunks for the user's query. Stage 2 builds the answer hint prefix from the same query using a lightweight LLM. Stage 3 feeds each chunk and the prefix to the small open-weight pruning model and reads the attention from the chunk's tokens to the prefix's blank token, summed across all transformer layers; the highest-scoring sentences become the compressed context. The final generator can be any model, including a closed-source API.

Summary

  • Long contexts make models reason worse: Attention spreads thin, and position starts to matter more than content.
  • Contrastive perplexity finds what the question actually needs: Comparing a token's surprisal with and without the question conditioned on it separates relevant text from filler.
  • LongLLMLingua budgets per document and reorders them: The best passage goes first and the second-best last, because models read the ends of a prompt and lose the middle.
  • AttentionRAG reads the model's own attention: Framing the query as next-token prediction extracts the signal directly, with no proxy model to train or serve.
  • Abstractive compression writes new text and can invent: Extractive pruning only deletes, which is the safer default when the output is going to be cited.
  • Compression helps until it does not: Moderate ratios improve accuracy by removing distractors, and past roughly 6x the meaning goes with the tokens.
  • KV-cache eviction is the other half: It shrinks the decoder cache rather than the prompt, so it pays off on long generations where prompt compression does nothing.

FAQ

Why does long context hurt RAG performance?Long contexts increase cost and latency, but they also hurt extraction quality. As the prompt grows, attention gets spread across more tokens, so the relevant passage can be missed, especially when it appears in the middle of the context. This is the “lost in the middle” effect.
What is context compression in retrieval-augmented generation?Context compression is the process of shrinking retrieved text before it reaches the generator. The goal is to remove irrelevant or low-value tokens so the model sees a shorter, denser prompt that is cheaper, faster, and easier to reason over.
What are the main types of context compression methods?The chapter groups compression methods by scope and access mode. Scope can be token-level, sentence-level, document-level, or cache-level. Access mode can be black-box, which works with closed APIs, or white-box, which requires access to an open-weight model’s internals.
How does LongLLMLingua decide which tokens to keep?LongLLMLingua uses contrastive perplexity. It scores tokens once with the question absent and once with the question present. Tokens that become much more predictable when the question is added are considered relevant and are kept.
Why is absolute perplexity not enough for prompt compression?Absolute perplexity is query-agnostic. It can discard tokens that look ordinary in general language even when they are exactly what the user asked for, such as a legal clause or a key number. Contrastive perplexity fixes this by making the score depend on the question.
What steps are in the LongLLMLingua pipeline?The pipeline has four stages: coarse document ranking, reordering to exploit prompt-edge bias, iterative token pruning with contrastive perplexity, and a recovery pass that repairs fragmented entities or other broken spans in the output.
When should you use AttentionRAG instead of LongLLMLingua?Use AttentionRAG when you can host an open-weight model and want pruning signals that come directly from the generator’s own attention weights. It is a good fit when alignment between the scoring model and the answering model matters more than using a closed-source API.
What is an answer hint prefix in AttentionRAG?An answer hint prefix turns the query into a fill-in-the-blank statement, such as converting “where is Daniel?” into “Daniel is in the ___.” This creates a single focal token that helps the model produce cleaner attention scores for relevance pruning.
What is the difference between extractive and abstractive compression?Extractive compression keeps selected original sentences or spans, while abstractive compression rewrites multiple documents into a shorter synthesized passage. Extractive methods are better for factual recall; abstractive methods are better when the answer must combine facts across documents.
How do you choose a compression ratio without losing important meaning?Start around 4x compression and validate on a held-out set. If accuracy holds, increase compression; if it drops, reduce it. Also force-keep domain-critical terms like names, article numbers, drug names, or negations, because small token losses can completely change the meaning.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Retrieval Augmented Generation, The Foundational Ideas ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Retrieval Augmented Generation, The Foundational Ideas ebook for free