Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

3 · Prefill and decode, and the KV cache

In one sentence: a model reads your whole prompt in one wide pass (prefill), then writes one token per narrow pass (decode), and keeps every token’s keys and values in a KV cache so earlier work is never redone.

The problem

Paste a long document into a chat: nothing happens, then the answer streams at a steady pace. Two different waits, before the first word and between words. And a larger “context length” (-c in llama.cpp) takes more memory before you’ve typed anything. Why?

The idea: read everything at once, then write one token at a time

Lesson 1’s loop runs one pass per new token, but the prompt is known up front, so all of its tokens go through the model together, in one pass. Writing can’t work that way, since each new token depends on the one before. So there are two phases with two speeds.

Each pass also leaves notes behind: for every token, every layer stores what later tokens will need to look back at it. Those notes are the KV cache. The next token reads them instead of recomputing the whole text.

Prefill: the wait for the first word

The story in the animation is 487 tokens: prompt.txt. Save it in ~/llm-inference-deep, then run 64 new tokens, greedy, and read llama.cpp’s timing summary:

cd ~/llm-inference-deep
curl -o prompt.txt http://localhost:8800/llm-inference-deep/chapters/03-prefill-decode/prompt.txt
llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf --temp 0 -n 64 -f prompt.txt -no-cnv
0.00.617.967 I common_perf_print:    sampling time =       5.98 ms
0.00.617.969 I common_perf_print:        load time =      90.77 ms
0.00.617.969 I common_perf_print: prompt eval time =      66.47 ms /   487 tokens (    0.14 ms per token,  7327.05 tokens per second)
0.00.617.970 I common_perf_print:        eval time =     340.00 ms /    63 runs   (    5.40 ms per token,   185.29 tokens per second)
0.00.617.970 I common_perf_print:       total time =     413.58 ms /   550 tokens

prompt eval is prefill: 487 tokens in 66 ms. Its pass also gives the first new token, so this is the time to first token (TTFT), what a chat user feels as the pause. eval is decode: the other 63 tokens, 5.40 ms each, about 40 times slower per token than prefill.

Is prefill fast because the tokens go through together? llama.cpp takes the prompt in batches of up to 512 tokens (-ub). With one token per batch, prefill should drop to about decode’s speed:

llama/llama-bench -m models/qwen2.5-0.5b-instruct-fp16.gguf -p 512 -n 0 -ub 1

It drops from 7,901 tokens a second (pp512, batches of 512) to 251, still above decode’s 185; batches of 8 and 64 give 1,782 and 5,169: the bigger the batch, the faster prefill.

Decode: the speed the answer streams at

Decode can’t batch: each pass works on one token, yet still reads every weight from memory, all 1.17 GiB, for one token’s arithmetic. Your llama.cpp runs on the Mac’s GPU (Metal). On its CPU instead (-dev none), the two phases part ways:

llama/llama-bench -m models/qwen2.5-0.5b-instruct-fp16.gguf -p 512 -n 128 -r 3
llama/llama-bench -m models/qwen2.5-0.5b-instruct-fp16.gguf -p 512 -n 128 -r 3 -dev none
Tokens per secondGPU (the default)CPU (-dev none)
prefill, 512 tokens (pp512)7,9011,572
prefill, one token per batch (-ub 1)251241
decode, 128 tokens (tg128)185189

Your numbers will differ (runs here differ by 1-2%; lesson 4’s says 7,810 and 184). Compare the pattern: prefill several times faster on the GPU, decode about the same.

The GPU does arithmetic about 5 times faster, and prefill, which is mostly arithmetic, follows. Decode doesn’t move: both read the weights from the same memory. Decode is limited by memory bandwidth. If every token reads the whole 1.27 GB file, 185 tokens a second is about 235 GB of reads a second, near the 273 GB/s Apple specifies for the M4 Pro these numbers come from (look up your own chip’s).

A smaller file should then decode faster. Lesson 4’s 8-bit copy has 53% of fp16’s bytes and decodes 1.47 times faster: faster, but not 1.9 times. Reading the weights is most of a decode step, not all of it.

The KV cache: what it holds and what it costs

In every layer, each token’s vector is turned into a key (what this token offers to later tokens) and a value (what it passes on to a token that attends to it). A new token compares itself with the keys of all earlier tokens and takes a weighted mix of their values; that is lesson 1’s attention. Earlier tokens’ keys and values never change, so they are computed once and kept.

Their size follows from the model’s shape (-v prints it):

0.00.082.177 I print_info: n_layer               = 24
0.00.082.185 I print_info: n_head_kv             = 2
0.00.082.186 I print_info: n_embd_head_k         = 64
0.00.082.187 I print_info: n_embd_k_gqa          = 128

Per token: 2 (a key and a value) × 24 layers × 128 numbers × 2 bytes (16-bit) = 12,288 bytes, 12 KiB. And llama.cpp reserves a cell for every token of the context -c when it starts, whether you use it or not:

-c12 KiB × -cllama.cpp says
204824 MiBsize = 24.00 MiB ( 2048 cells, 24 layers, 1/1 seqs), K (f16): 12.00 MiB, V (f16): 12.00 MiB
819296 MiBsize = 96.00 MiB ( 8192 cells, ...)
32768384 MiBsize = 384.00 MiB ( 32768 cells, ...)

So Practical 0’s -c 2048 cost 24 MiB.

The cache saves recomputing, but reading it costs time too. Decode speed with tokens already in the cache (llama-bench -d):

Tokens in the cache051220484096
decode, tokens per second185184175171

Each new token reads all those keys and values, so decode slows as the text grows: by 8% at 4,096 tokens here. Without the cache, the token after 4,096 others would push all 4,096 through the model again: about 0.52 seconds at prefill’s speed, not 5.8 ms.

The same cache, across requests

llama-server keeps the cache after answering. cache.py sends it the story three times, the third with its last sentence changed, and prints the prompt tokens computed (prompt_n) and their time (prompt_ms). With Practical 0’s server running, in ~/llm-inference-deep:

curl -o cache.py http://localhost:8800/llm-inference-deep/chapters/03-prefill-decode/cache.py
python3 cache.py
1st same prompt {'prompt_n': 487, 'prompt_ms': 82.688}
2nd same prompt {'prompt_n': 1, 'prompt_ms': 6.619}
3rd, last sentence changed {'prompt_n': 12, 'prompt_ms': 9.119}

Only what differs from the cached start is computed again: prompt caching. A chat resending the whole conversation each turn pays prefill only for the new part. Your prompt_n should match, your times won’t.

Go deeper: why this model's cache is small (grouped-query attention)

The model has 14 attention heads per layer (n_head), each comparing tokens in its own 64-number space, but only 2 sets of keys and values (n_head_kv): every 7 query heads share one. This is grouped-query attention (GQA, Ainslie et al., 2023), which the Qwen2 report uses. With one set per head the cache would be 7 times larger. The general formula, per token:

2 × n_layer × n_head_kv × head_size × bytes per number
2 ×   24    ×     2     ×    64     ×        2          = 12,288 bytes

Lesson 4 changes the last factor: a cache stored in 8 bits instead of 16.

Go deeper: memory-bound and compute-bound

A step is memory-bound when the processor waits for data, compute-bound when it waits for arithmetic. Decode does little arithmetic per byte it reads (one token per weight), so memory sets most of its speed. Prefill does up to 512 tokens’ arithmetic per byte read, so reading matters far less to it. That’s why prefill speed is reported per prompt length (pp512) and decode per token generated (tg128) in llama-bench.

The read-rate sum gives less for lesson 4’s smaller files: about 183 GB/s for the 8-bit copy and 140 for the 4-bit one. The smaller the file, the more of each step is something other than reading weights.

Common misunderstandings

  • “A longer prompt makes every word of the answer slower.” Mostly it makes the wait before the first word longer. Decode slows too as the cache grows, far less than redoing the prompt would.
  • “The KV cache is filled as you type, so a small -c costs nothing until used.” llama.cpp reserves all -c cells at start.

Check yourself

1. A tool sends a 20-page contract and gets its first word after a long wait, then fast text. Which phase is the wait, and what helps when the next question is about the same contract?

Prefill. Keep the contract at the start of the prompt and let the server reuse its cached keys and values: the second question then pays prefill only for its own tokens.

2. You raise -c from 8192 to 32768 for this model. How much more memory does the cache take?

384 − 96 = 288 MiB more, reserved when the program starts.

3. With a model file at 53% of the size, decode got 1.47 times faster. What does that say about a decode step?

Reading the weights is most of its cost, not all of it: if it were all, the speed-up would have been 1.9 times.

Next: lesson 4 · In production: quantization and fitting a model in memory.