Eyuboglu, Ehrlich, Arora et al. — Stanford, Caltech, UB — 2025

Cartridges: Self-Study

Train a tiny KV cache offline that replaces 100K tokens of in-context learning. 38.6x less memory, 26.4x higher throughput — no quality loss.

Prerequisites: Transformer attention + KV cache basics + Knowledge distillation
10
Chapters
5+
Simulations

Chapter 0: The Problem

You are building a coding assistant. A developer pastes their entire repository — 80,000 tokens of source code — into the prompt, then asks: "Where is the authentication bug?" The model reads everything, reasons over it, and gives a perfect answer.

Now a hundred developers do the same thing, each with their own codebase. Every single one needs a full KV cache — the key-value pairs that attention computes over the context. For LLaMA 8B at 128K tokens, that cache alone is ~10 GB per user. On a single H100 with 80 GB of VRAM, you can serve maybe 4–6 users simultaneously.

And it gets worse. As the context grows, throughput collapses. LLaMA 8B's peak throughput drops by 77x when increasing context from 1K to 120K tokens. Long context is not just expensive — it is the primary bottleneck of modern LLM serving.

The core tension: In-context learning (ICL) is incredibly powerful — the model can answer any kind of question about the corpus (factual, creative, mathematical, structural). But the KV cache that makes ICL work grows linearly with context length. Memory is the wall.

What if you could pre-compute a much smaller KV cache that captures everything the model needs to know about a corpus? Train it once offline, store it, and load it for every future query — no matter what the user asks. That is exactly what a Cartridge is.

KV Cache Memory vs. Context Length

Drag the slider to increase context length. Watch how KV cache memory grows linearly — and how a Cartridge stays flat.

Context tokens (K) 100K
Why is long-context ICL expensive to serve?

Chapter 1: The Key Insight

Here is the observation that makes Cartridges possible: in most real deployments, many different queries reference the same corpus. A legal team sends dozens of questions about the same filing. Developers ask different questions about the same codebase. A doctor queries the same patient record repeatedly.

If the corpus is shared, the cost of preparing its representation can be amortized across all future queries. Standard ICL computes the KV cache from scratch on every request (or caches it, but still stores the full thing). Cartridges take a different path: spend more compute once, offline, to train a much smaller KV cache that captures the corpus's information.

Standard ICL
Corpus (100K tokens) → Prefill → Full KV cache (~10 GB) → Decode response. Every query pays the full cost.
↓ vs.
Cartridge
Corpus → Offline Self-Study (~30 min) → Trained KV cache (~0.25 GB). Every query loads this tiny cache and decodes immediately.
The key trade-off: Cartridges spend more compute upfront (training takes ~30 minutes on 8xH100 for LLaMA 8B) but produce a KV cache that is 38.6x smaller. Since the corpus doesn't change between queries, you train once and serve forever. The more queries you serve, the more the upfront cost pays for itself.

But there's a catch. You can't just train the small KV cache by having the model predict the next token of the raw corpus. That approach memorizes the text but fails to answer diverse questions. The solution — Self-Study — is what makes Cartridges actually work. We'll get there in Chapter 4.

Why can the cost of training a Cartridge be amortized?

Chapter 2: What Is a Cartridge?

A Cartridge is a trained set of key-value vectors that you prepend to the model's KV cache at inference time. Think of it as a virtual prefix — the model "sees" it as if those tokens were at the start of the context, even though they were never real tokens. The model's own weights are completely frozen; only the Cartridge's key-value vectors are trained.

The Shape

For a Transformer with L layers, a Cartridge Z has shape:

Z ∈ RL × 2 × p × d

Where L is the number of layers, 2 is for keys and values, p is the number of virtual tokens (the Cartridge size — typically 128 to 8192), and d is the head dimension times the number of heads. The memory footprint is exactly that of a KV cache for a prompt with p tokens.

How It Plugs In

In standard ICL, the KV cache looks like this:

(k[1],v[1]), ..., (k[nC],v[nC]), (k[nC+1],v[nC+1]), ...

The first nC pairs are the corpus. The rest are the query. With a Cartridge, you replace those nC pairs with just p trained pairs:

(zk[1],zv[1]), ..., (zk[p],zv[p]), (k[1],v[1]), ...
Analogy: A Cartridge is like a study guide. Instead of reading the entire 500-page textbook every time (ICL), you study it once and distill it into a 20-page cheat sheet (the Cartridge). The cheat sheet is much smaller, but it captures what you need to answer exam questions.

Initialization Matters

Random initialization of the Cartridge's key-value vectors leads to unstable training and poor results (29.9% accuracy on LongHealth vs. 55.3% with proper init). The authors initialize Z with the KV cache of the first p tokens of the corpus. This gives the optimizer a sensible starting point — real key-value vectors from actual tokens — and converges much faster.

Cartridge vs. ICL KV Cache

Drag the slider to set corpus length. The visualization shows the KV cache layout for ICL (top) vs. Cartridge (bottom). Notice how the Cartridge stays small.

Corpus tokens (K) 100K
Cartridge size (p) 2048
What is a Cartridge, concretely?

Chapter 3: Why Naive Training Fails

The most obvious way to train a Cartridge is next-token prediction (NTP) on the raw corpus. You freeze the model, prepend the trainable KV cache Z, feed in the corpus tokens, and backpropagate the language modeling loss into Z's key-value vectors. This is essentially prefix-tuning with the corpus text as the training objective.

The result? The Cartridge memorizes perfectly. Given the trained Cartridge, the model can regurgitate the corpus with near-zero perplexity. It uses 107x less memory than ICL while doing so. Sounds great, right?

Wrong. Try asking a question the Cartridge wasn't trained on — "Summarize this filing" or "Compute the D&A margin for FY15" — and performance collapses. The NTP-trained Cartridge is a one-trick pony: it can complete the corpus text, but it cannot reason about the corpus.

Why does this happen? NTP on the corpus teaches the Cartridge to represent the surface form of the text — the exact sequence of tokens. But answering diverse queries requires representing the information content: facts, relationships, numerical values, document structure. These are different things. The NTP loss never forces the model to organize information for retrieval. It only forces memorization of a specific token sequence.

On the GenConvo benchmark (diverse questions about AMD's 10-K filing), the NTP-trained Cartridge matches ICL only on "memorization" queries (complete-the-passage tasks). On factual questions, synthesis, creative tasks, and mathematical reasoning, it falls far behind.

Query TypeICLNTP CartridgeSelf-Study Cartridge
MemorizationGoodGoodGood
Factual Q&AGoodPoorGood
SynthesisGoodPoorGood
CreativeGoodPoorGood
Math reasoningGoodPoorGood
Data structuringGoodPoorGood
The lesson: Memorizing text and understanding text are different capabilities. A KV cache trained to reproduce the corpus is not the same as a KV cache trained to answer questions about the corpus. We need a training objective that teaches retrieval and reasoning, not just reproduction.
Why does next-token prediction on the raw corpus produce a Cartridge that fails on diverse queries?

Chapter 4: Self-Study

Self-Study is the training recipe that makes Cartridges actually work. The idea is beautifully simple: instead of training on the raw corpus, make the model quiz itself about the corpus and train the Cartridge on those synthetic conversations.

Step 1: Chunk the Corpus

The corpus C may be hundreds of thousands of tokens — far longer than the context window. So we first split it into chunks of 512–4096 tokens. Each chunk becomes a subcorpus that fits in context.

Step 2: Pick a Seed Prompt

We randomly sample one of five seed prompt types. These are generic — the same five prompts are used for every corpus, whether it's medical records, legal filings, or code:

Step 3: Generate a Synthetic Conversation

Two participants A and B (both are the same model) have a conversation. A gets the subcorpus plus the seed prompt in context. A generates a message (e.g., a question). B gets the subcorpus plus A's message and generates a response. This produces a synthetic query-response pair grounded in the corpus.

The algorithm:
algorithm
# Self-Study Data Generation
Input: C (corpus), F (model)
Output: {a1, b1, ..., ak, bk} (conversation)

c_tilde = chunk(C)           # get subcorpus that fits in context
s = get_seed_prompt()      # random from {structuring, summary, ...}
for i = 1 to k:
  ai ~ F(. | c_tilde + s + a1 + ... + bi-1)  # A asks with seed
  bi ~ F(. | c_tilde + a1 + ... + ai)        # B answers with corpus
return {a1, b1, ..., ak, bk}
Why Self-Study works: By generating diverse Q&A pairs about the corpus, we create training data that forces the Cartridge to represent information in a way that supports retrieval. The model is not just memorizing text — it is learning to answer the kinds of questions users will actually ask. Different seed prompts ensure the training covers factual recall, synthesis, reasoning, and creative tasks.

Step 4: Train with Context Distillation

We don't just do next-token prediction on the synthetic conversations. Instead, we use context distillation (covered in the next chapter). The teacher is the model with the full subcorpus in context. The student is the model with only the Cartridge. We minimize the KL divergence between their output distributions.

Self-Study Pipeline

Click "Generate" to simulate the Self-Study pipeline. Watch how the corpus is chunked, a seed prompt is selected, and a synthetic conversation is generated. Each "Step" button advances one phase.

Click "Next Step" to begin.
What are the two critical design decisions in Self-Study data generation?

Chapter 5: Context Distillation

Self-Study generates synthetic conversations. But how do we train the Cartridge on them? The answer is context distillation — a technique from the model distillation literature adapted to this setting.

Teacher and Student

The teacher is the model F with the full subcorpus in context. Given a synthetic conversation x and the subcorpus that generated it, the teacher computes:

F(· | c̃ ⊕ x[:i])   ← teacher distribution at position i

The student is the same model F augmented with the Cartridge Z (no corpus in context). It computes:

FZ(· | x[:i])   ← student distribution at position i

The teacher "knows" the answer because it has the actual text. The student must learn to produce the same answers using only the Cartridge.

The Loss

We minimize the KL divergence between the teacher's and student's next-token distributions, summed over all positions in the synthetic conversation:

arg minZ(x,c̃)∈Di=1|x| DKL( F(·|c̃⊕x[:i]) || FZ(·|x[:i]) )

Only Z (the Cartridge's key-value vectors) is updated. The model's weights are completely frozen.

Why distillation, not NTP? Next-token prediction on the synthetic data gives a hard target — the single correct next token. Context distillation gives a soft target — the full probability distribution over all tokens. The soft distribution carries richer information: which tokens the teacher considers plausible, how confident it is, what alternatives exist. This lets the Cartridge learn a more nuanced representation. On MTOB (translation), distillation improves chrF by 8.6 points over NTP on the same synthetic data.

What Gets Updated

This is worth emphasizing: the only trainable parameters are the key-value vectors in Z. That is p × d values per layer, per head, for both keys and values. For a Cartridge with p=2048 on LLaMA 8B (32 layers, GQA with 8 KV heads, dh=128):

Parameters = 32 layers × 2 × 8 heads × 2048 × 128 = 134M

That is 134 million parameters — about 1.7% of LLaMA 8B's 8 billion parameters. And these parameters are stored as a KV cache, so existing inference servers already know how to manage them.

Context Distillation Loss

The teacher (with corpus) and student (with Cartridge) produce distributions over the vocabulary. Drag the slider to adjust how well-trained the Cartridge is. Watch the KL divergence shrink as the student's distribution approaches the teacher's.

Training progress 0%
In context distillation for Cartridges, what is the teacher and what is the student?

Chapter 6: Results

The authors evaluate Cartridges on three challenging long-context benchmarks, each pairing a large corpus (100K–484K tokens) with diverse queries:

Claim 1: Matches ICL at 38.6x Less Memory

On LongHealth and QASPER with LLaMA 3B, Cartridges trained with Self-Study match or exceed ICL quality while using dramatically less KV cache memory. Compression baselines like DuoAttention degrade rapidly beyond 2x compression. Cartridges achieve 10–100x compression without quality loss.

Claim 2: Extends Effective Context

On MTOB, the full Kalamang textbook is 484K tokens — far beyond LLaMA 8B's 128K window. ICL simply cannot use the full book. But Self-Study's chunking strategy lets a Cartridge train on the entire 484K text. The resulting Cartridge outperforms ICL on the first 130K tokens by 11.0 chrF points and matches ICL on the hand-curated 60K subset.

Claim 3: Composable Without Retraining

Two independently trained Cartridges (e.g., one for AMD's 10-K, one for Pepsi's 10-K) can be concatenated at inference time. The model can then answer questions requiring information from both documents — without any joint training. This composition outperforms both single-Cartridge and truncated-ICL baselines on multi-document questions.

The headline numbers: 38.6x less memory — 26.4x higher throughput — Matches ICL quality. Training cost: ~30 minutes on 8xH100 for LLaMA 8B. This cost is paid once per corpus and amortized across all future queries.
Quality vs. KV Cache Size

Compare methods across different KV cache sizes. Cartridges maintain quality at much smaller cache sizes, while compression baselines degrade rapidly.

What is the most surprising result about Cartridge composition?

Chapter 7: Applications

Cartridges enable a new class of context-aware applications where the corpus is large but relatively static, and many queries reference it over time.

Codebases

An entire repository (50–200K tokens) is trained into a Cartridge. Every developer query — "find the auth bug," "explain the payment flow," "write tests for the API" — runs against the same pre-trained Cartridge. No need to stuff the entire repo into every prompt.

Legal Documents

SEC filings, contracts, and regulatory texts are perfect Cartridge candidates: they are long, queried many times by different analysts, and rarely change. A 10-K filing (~100K tokens) becomes a tiny Cartridge that any analyst can query instantly.

Medical Records

A patient's full medical history (labs, imaging reports, clinical notes) can be compressed into a Cartridge. Doctors can query it from different angles — drug interactions, lab trends, surgical history — without re-processing the entire record each time.

Chat Histories

Long conversational histories (months of messages) can be distilled into a Cartridge, giving the model persistent memory without an ever-growing context window.

RAG Replacement

For corpora where the full text is available and relatively static, a Cartridge can replace Retrieval-Augmented Generation entirely. Instead of retrieving chunks and hoping you got the right ones, the Cartridge captures all the information holistically.

The sweet spot: Cartridges are most valuable when (1) the corpus is large (100K+ tokens), (2) it is queried many times, and (3) it changes infrequently. When the corpus changes often, the ~30-minute training cost becomes a bottleneck.
In which scenario would a Cartridge be LEAST useful?

Chapter 8: Scaling & Analysis

How does Cartridge quality change as we adjust its size and training compute? The ablations reveal clear scaling patterns.

Cartridge Size (p)

The authors test p ∈ {128, 512, 2048, 8192}. Across all benchmarks, larger Cartridges perform better — but with diminishing returns. Going from p=128 to p=512 gives a large jump. Going from p=2048 to p=8192 gives a smaller improvement. The sweet spot for most tasks is p=2048, which achieves ICL-matching quality with ~12.5x compression.

Training Compute

Performance scales steadily with the number of training steps. The authors train with batch size 64 and max sequence length 1024. No synthetic data is reused (one epoch). Across all Cartridge sizes, more steps = better quality, with no sign of overfitting in the regime tested.

Prefix-Tuning vs. LoRA

The authors compare Cartridges parameterized as a KV cache (prefix-tuning) vs. as LoRA adapters. Key finding: prefix-tuning wins on both in-domain and out-of-domain tasks. Critically, LoRA causes catastrophic forgetting — MMLU accuracy drops from 54.7 to 45.3 as LoRA rank increases. Prefix-tuning barely touches MMLU (54.7 to 54.3), because it only adds virtual tokens without modifying the model's weights.

Why prefix-tuning over LoRA? LoRA modifies the model's linear projections, which inevitably shifts the model's general capabilities. Prefix-tuning only adds key-value pairs to the attention context — it is additive, not multiplicative. The model's weights remain perfectly intact. This also means Cartridges work with existing inference infrastructure that manages per-user KV caches — no custom LoRA serving needed.

Seed Prompt Diversity

Using 5 diverse seed prompts vs. a single generic prompt: +4.8 accuracy on LongHealth, +7.9 chrF on MTOB. The diverse prompts force the synthetic data to cover different query types, which translates directly to better generalization.

Distillation vs. NTP on Synthetic Data

Holding the synthetic data constant, context distillation outperforms NTP by +3.7 accuracy on LongHealth and +8.6 chrF on MTOB. The soft targets from distillation carry more information than hard next-token labels.

Cartridge Size vs. Quality

Drag the slider to set the Cartridge size (p). The bar chart shows relative quality on LongHealth and MTOB, plus memory usage. Watch the diminishing returns as p grows.

Cartridge size (p) 2048
Why does prefix-tuning preserve general capabilities (MMLU) better than LoRA for Cartridges?

Chapter 9: Connections

Cartridges sit at the intersection of several active research threads. Here is how the ideas connect.

Relation to Prefix Caching

Modern inference servers already cache KV states for shared prefixes (e.g., system prompts). Cartridges take this further: instead of caching the exact KV cache from prefill, they train a compressed one. Cartridges are drop-in compatible with prefix caching infrastructure.

Relation to RAG

Retrieval-Augmented Generation retrieves relevant chunks and puts them in context. Cartridges compress the entire corpus into the KV cache, avoiding the retrieval step entirely. RAG risks missing relevant information; Cartridges represent everything (at the cost of offline training).

Relation to KV Cache Compression

Methods like DuoAttention, H2O, and SnapKV drop or merge KV pairs at inference time with minimal compute. They achieve 2–4x compression before quality degrades. Cartridges use much more compute (offline training) to achieve 10–100x compression. These approaches are complementary — you could even apply KV compression to a Cartridge.

Relation to Knowledge Injection

LoRA-based knowledge injection (e.g., Plug-n-Play Knowledge Modules) also stores corpus information in parameters. Cartridges use prefix-tuning instead, which avoids catastrophic forgetting and integrates with standard serving infrastructure.

Relation to Test-Time Training

Architectures like Titans and TTT use gradient descent at test time to compress context into a fixed-size memory. Cartridges apply the same principle (gradient-based compression) but to standard Transformers without architectural changes — any pre-trained model works.

MethodCompressionCompute CostQuality at High CompressionInfrastructure
Full ICL1xPrefill onlyBaselineStandard
KV Compression2–4xMinimalDegradesCustom kernels
RAGVariesRetrievalRetrieval qualityVector DB
LoRA InjectionHighTrainingGood, but forgettingCustom serving
Cartridges10–100x~30 min trainMatches ICLStandard KV cache
Limitations: Training takes ~30 minutes per corpus (unoptimized). If the corpus changes frequently, this becomes expensive. Self-Study also requires generating synthetic data, which itself costs compute. For single-use queries on rapidly changing corpora, standard ICL or RAG may still be preferable.

"What I cannot create, I do not understand." — Richard Feynman. Cartridges embody this: instead of passively reading the corpus at inference time, they actively learn it through self-quizzing and distillation.

What is the key advantage of Cartridges over standard KV cache compression methods?