Back to paper library
Paper notesarXiv 2024WWW Companion 2025

CAG

Memorize More, Score More

Original paper

Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks

Paper authors

Brian J Chan · Chao-Ting Chen · Jui-Hung Cheng · Hen-Hsen Huang

Publication
WWW Companion 2025Conference
First submitted to arXiv
arXiv:2412.15605
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{retrievalaugmentedgenerationcag2024,
  title = {{Don't Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks}},
  author = {Brian J Chan and Chao-Ting Chen and Jui-Hung Cheng and Hen-Hsen Huang},
  year = {2024},
  eprint = {2412.15605},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2412.15605}
}
On this page

This paper is titled, with some attitude, “Don't Do RAG.”

RAG—Retrieval-Augmented Generation—has become the standard way to connect language models to external information. A user asks a question; the system finds a few relevant passages in a knowledge base, puts them before the question, and asks the model to answer from them. Internal documents, product FAQs, and customer-support records often reach chatbots this way.

The workflow is useful, but things can go wrong at every stage.

If the retriever selects the wrong passage, the model has the wrong material to work with. If it finds the right material but only half of it, the answer is incomplete. Splitting documents, building indexes, tuning top-k, and choosing an embedding model all add maintenance work.

By 2024, open-source models had context windows exceeding a hundred thousand tokens. The authors therefore ask:

  • If the entire knowledge base already fits, why retrieve first?

Defining the Problem

Putting an entire knowledge base into a prompt is not particularly new. The problem is its cost.

Suppose our knowledge base contains 85,000 tokens. Every question sends those 85,000 tokens plus the question to the model. The model must read from the first token through the entire reference before it can begin writing the answer.

The next question arrives. The information has not changed at all, but the model reads it from the beginning again.

This prompt-reading stage is called prefill. Longer prompts take longer to prefill, increasing the user's wait for the first output token: TTFT, or time to first token.

So the question the authors want to address is:

  • If the information stays unchanged, can we read it just once?

To answer that, we need to know what the model retains after “reading.”

Solving the Problem

What Remains After the Model Reads?

Most current language models are decoder-only Transformers. Self-attention at each layer projects every token into Query, Key, and Value vectors.

When generating the next token, its new Query is compared with the Keys of all preceding tokens, then used to weight the Values of all preceding tokens.

The Keys and Values of those earlier tokens never change once computed.

Implementations therefore save them for the next step. This is the KV cache, already used during ordinary token-by-token generation to avoid repeated computation.

CAG—Cache-Augmented Generation—extends this reuse from “within one question” to “across all questions”:

  • Read the entire knowledge base once and save its KV cache. Every later question only needs to continue from there.

The paper compares the two workflows below. Pink marks components used at inference time:

RAG versus CAG: RAG retrieves knowledge through an IR Model at inference time; CAG preloads knowledge into a Context Cache offline and processes only the question at inference
Figure 1 from the paper, excerpted from page 2 of the v2 PDF. RAG is above and CAG below; pink components run during online inference.

In the upper RAG workflow, every question goes through an IR Model to retrieve information. The resulting Context and question qq are then passed to the LLM.

In the lower CAG workflow, “Offline Preloading” turns the knowledge base into a Context Cache. Only question qq is pink at inference time. The retriever has disappeared entirely.

Three Steps

The authors describe three steps.

Step 1: Preload knowledge. Organize the document collection D={d1,d2,… }\mathcal{D}=\{d_1,d_2,\dots\} and let the model read it once, producing a KV cache:

CKV=KV-Encode(D)C_{KV}=\text{KV-Encode}(\mathcal{D})

The cache can remain in memory or be saved to disk. The document-reading cost is paid once, regardless of how many questions follow.

Step 2: Inference. Load CKVC_{KV} and append the user's question qq:

r=M(D⊕q)=M(q∣CKV)r=\mathcal{M}(\mathcal{D}\oplus q)=\mathcal{M}(q\mid C_{KV})

The left side concatenates the documents and question for the model. The right side gives the model its cache and reads only the question. The computation gives the same result; the document portion simply avoids being reread.

Step 3: Reset the cache. Answering the first question appends question and answer tokens to the KV cache. Remove those additions before the second question, or it will see the first conversation.

Since the cache is append-only, remember its length after reading the knowledge base and truncate everything after that position. There is no need to reload it from disk.

Calculating the Actual Size

“Save the KV cache” sounds abstract. Let's calculate what it looks like for the paper's Llama 3.1 8B model.

According to Table 3 of the Llama 3 paper, the 8B model has 32 layers, hidden dimension 4096, and 32 attention heads, but only eight Key/Value heads through grouped-query attention. Each head has 4096/32=1284096/32=128 dimensions.

At each layer, the Key tensor stored for one token therefore has shape:

[batch, kv_heads, seq_len, head_dim]=[1, 8, 1, 128][\text{batch},\ \text{kv\_heads},\ \text{seq\_len},\ \text{head\_dim}]=[1,\ 8,\ 1,\ 128]

The Value has the same shape. Across all layers, one token requires this many stored numbers:

2 (K and V)×32 (layers)×8 (head)×128 (dimensions)=65,5362\ (\text{K and V})\times 32\ (\text{layers})\times 8\ (\text{head})\times 128\ (\text{dimensions})=65{,}536

At 16 bits, or two bytes, per number, that is 128 KiB per token.

The largest HotPotQA setting contains about 85k tokens:

85,000×128 KiB≈11.1 GB85{,}000\times 128\ \text{KiB}\approx 11.1\ \text{GB}

The model weights themselves occupy about 16 GB at 16-bit precision. The cache is already almost 70% of that.

With the tensor shape in mind, the reset step in the official code is easy to understand:

python
def clean_up(kv: DynamicCache, origin_len: int):
    """
    Truncate the KV Cache to the original length.
    """
    for i in range(len(kv.key_cache)):
        kv.key_cache[i] = kv.key_cache[i][:, :, :origin_len, :]
        kv.value_cache[i] = kv.value_cache[i][:, :, :origin_len, :]

From kvcache.py in hhhuang/CAG, MIT license.

kv.key_cache[i] is the Key tensor at layer ii, with shape [1, 8, seq_len, 128]. The slice [:, :, :origin_len, :] operates along the third dimension, sequence length, retaining only the knowledge-base portion.

When preloading finishes, origin_len records the cache length after the knowledge base has been read. Before each later question, the cache is cut back to that length. The entire “reset” consists of two slices per layer across 32 layers.

Why Put Everything In Together?

At this point you might ask: if caching works so well, why not cache each document separately, then concatenate the caches of whichever documents are retrieved?

The problem is in the earlier callout. A token's Key and Value depend on all preceding text and on its position in the sequence. When Document B is computed alone, it knows nothing of Document A before it, and its positions start from the beginning. Joining those caches directly differs from actually reading A followed by B.

The introduction mentions TurboRAG, which precomputes passage-level KV caches and needs additional position-ID rearrangement to operate properly. CAG takes a blunter approach and, if the knowledge base is fixed, reads the whole thing together. Both retrieval and the cache-joining problem disappear.

The price is that changing any text in the knowledge base requires recomputing the cache after that position.

Discussion

How Are the Experiments Set Up?

The authors use two QA datasets:

  • SQuAD 1.0: Answers are spans in a passage, leaning toward locating information in one passage.
  • HotPotQA: Answers combine multiple documents and require multi-hop reasoning.

To study growing knowledge bases, they create small, medium, and large subsets of each dataset. For HotPotQA small, for example, they sample 16 documents, concatenate them into a long reference, and select only questions related to those documents.

DatasetSizeDocumentsTokensQuestions
HotPotQASmall1621k1,392
HotPotQAMedium3243k1,056
HotPotQALarge6485k1,344
SQuADSmall321k500
SQuADMedium432k500
SQuADLarge750k500

Compiled from Table 1 of the paper.

All systems answer with Llama 3.1 8B, running on eight Tesla V100 32GB GPUs. The comparisons are two RAG implementations built with LlamaIndex:

  • Sparse RAG: BM25, ranking through keyword matching and term frequency.
  • Dense RAG: An OpenAI embedding index, ranking through semantic similarity.

Both try retrieving the top 1, 3, 5, and 10 passages.

Scoring uses BERTScore, measuring semantic similarity between the model's answer and the reference answer.

Accuracy: Mostly Ahead, with Exceptions

Table 2: BERTScore for Sparse RAG and Dense RAG at top-1, 3, 5, and 10, and CAG across small, medium, and large HotPotQA and SQuAD settings
Table 2 from the paper, excerpted from page 4 of the v2 PDF. HotPotQA is on the left, SQuAD on the right; bold marks the highest score in each setting.

Start with the “CAG (Ours)” row at the bottom of each group.

CAG scores highest on both datasets in the Small and Medium settings. For HotPotQA small, for example, CAG gets 0.7951, while the best RAG result is Sparse top-5 at 0.7676.

Now look at Large. CAG's 0.7734 still leads on SQuAD. On HotPotQA, however, the bold score belongs to Sparse RAG top-5 at 0.7535. CAG gets only 0.7407, below Sparse top-3's 0.7463 and nearly identical to Dense top-3's 0.7409.

The authors also note in the prose that CAG's advantage shrinks as the data grows, citing research on degradation with very long inputs.

Another detail deserves attention. The introduction cites RULER and gives Llama 3.1 8B an effective context length of 32K. HotPotQA large, at about 85k tokens, is well beyond that. This might help explain CAG's loss there, although the paper does not isolate the cause; it is our interpretation of the table.

The table also shows that BM25 is the highest-scoring RAG configuration in five of the six settings. Only SQuAD medium gives Dense top-10 a narrow 0.0009 win. The authors themselves suggest the datasets may be easy enough that keyword matching finds most of the required information. In other words, the RAG baselines here never hit a problem that only semantic retrieval could solve.

Speed: The Saving Comes from Avoiding Rereading

Now consider time.

Table 3: retrieval and generation times for RAG configurations, CAG, and In-Context Learning across the three HotPotQA sizes
Table 3 from the paper, excerpted from page 4 of the v2 PDF. Units are seconds. Retrieval is retrieval time; Generation is generation time.

The table includes an additional baseline called In-Context Learning. It sends the full reference and question directly to the model and computes the KV cache anew for every question, which is the “read everything from the beginning” approach discussed earlier.

Comparing this row with CAG isolates what preloading saves:

HotPotQA sizeReread every questionCAGSpeedup
Small (21k)9.32 s0.85 sAbout 11×
Medium (43k)26.37 s1.41 sAbout 19×
Large (85k)92.08 s2.26 sAbout 41×

The larger the knowledge base, the more expensive rereading becomes, and the greater the benefit of preloading.

Compare CAG with Sparse RAG, though, and the picture changes. In the Large setting, BM25 top-3 takes only 0.0008 seconds for retrieval and 0.67 seconds for generation, under one second in total. CAG takes 2.26 seconds. BM25 gives the model just three short passages, so the context it processes is already short.

CAG's own time also increases with knowledge-base size: 0.85, 1.41, and 2.26 seconds. Caching avoids rereading, but attention still scans the entire 85k-token cache for every generated token.

The table does not list how long the cache takes to build. Table 3 counts only per-question inference after preloading. The official code records preload time, but the paper does not report it. For a knowledge base updated daily, that number matters.

Questions This Paper Leaves Open

The Limitations section states directly that all relevant documents must fit into the model's context. The method suits bounded settings such as a small company's internal knowledge base, FAQs, or a support center, and becomes impractical for much larger datasets.

The earlier derivation also suggests several engineering concerns:

  1. Frequent document updates. The cache after the edited position must be recomputed. The paper does not measure update costs.
  2. Different users see different documents. One cache contains the entire knowledge base; different permissions may require separate caches for different document combinations. This is our inference, not a topic discussed in the paper.
  3. The cache is tied to the model. A KV cache is an intermediate state computed by a particular model version. Changing models requires rebuilding it.

Conclusion

CAG, the method this paper proposes, has the model read a fixed knowledge base once when it fits in the context window, store the KV cache, and then read only the question each time.

In the paper's experimental setting:

  • It is much faster than rereading everything for each question. HotPotQA large falls from 92.08 to 2.26 seconds, about a 41× speedup.
  • Accuracy is mostly comparable to or better than RAG. CAG leads in both Small and Medium settings; in Large, it still leads on SQuAD but loses to BM25 top-5 on HotPotQA.
  • Lightweight BM25 can be faster than CAG. RAG using just three short passages takes under one second in total.

These results come from a single 8B model, knowledge bases of at most about 85k tokens, and BERTScore as a semantic-similarity metric.

The title says “Don't Do RAG,” but the paper's answer is gentler, suggesting that when a knowledge base is small, stable, and queried repeatedly, you can consider skipping retrieval and memorizing it first.

If it is too big to memorize, you will still have to look things up.