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

How LLM Inference Works: a Deep Dive with llama.cpp

Tested 2026-11-29 on macOS 26.6.2, MacBook Pro, Apple M4 Pro, 48 GB; llama.cpp on the GPU (Metal, MTL0) · with llama.cpp v1.1.0 (build b12774, macOS arm64 release), Qwen2.5-0.5B-Instruct GGUF (fp16, Apache-2.0), Python 3.9.6 (macOS), WikiText-2 raw test set (CC BY-SA) · by Vivek Sahu (@viv1) · CC BY 4.0

You type a question into a chat assistant and press Enter.

Before any model sees it, your question has become 36 numbered pieces of text: tokens.

A model of 630 million fixed numbers then runs once and scores all 151,936 tokens it knows as the possible next one. Even this easy question doesn’t make it sure: given The capital of France is, its favourite, Paris, gets a probability of 0.395.

One token is picked, appended, and the whole thing runs again, until the model picks its end token: the one-sentence answer took 8 passes. Everything else you have noticed about chat models (the streaming, the different answer each time, the confident mistakes, the cost per token) follows from that loop.

This deep dive opens that loop on your own Mac, with llama.cpp and a small open model, and measures each part. You need to be able to program a little and to have used a chat assistant; nothing about how models work is assumed.

By the end you’ll be able to:

  • explain what a model computes at each step, and count the tokens a text costs
  • choose sampling settings (temperature, top-k, top-p, min-p, seed) knowing what each does to the probabilities
  • explain why the prompt is processed fast and the answer slowly, and how much memory the KV cache takes
  • quantize a model yourself and measure what it costs in quality and gains in size and speed
  • recognise and fix the classic failures: a missing chat template, a sampler set to produce noise, a context too large for memory

How it works

Each lesson starts with a problem you recognise, shows the mechanism in an animation you step through, and puts the production-level detail in Go deeper boxes. In the practicals you work in your own terminal: tasks with requirements, a hint, a hidden solution, a prediction to make before you look, something to break on purpose, and ./lab check pN to check your work (./lab setup pN fetches what isn’t the topic, ./lab reset pN starts you over). You need a Mac with Apple Silicon, Python 3 (the first time you run python3, macOS may offer to install its Command Line Tools: accept, it takes a few minutes) and a few GB free on disk (the model is 1.27 GB; the capstone adds smaller copies of it).

Path

LessonPracticalYou’ll be able to
1 · What happens when a model answerssay what one forward pass computes
2 · Picking each token: the loop and sampling0 · Your llama.cpp, token by tokencount tokens, see each step’s candidates, set the sampler
3 · Prefill and decode, and the KV cacheexplain time to first token, tokens per second and the cache’s size
4 · In production: quantization and fitting a model in memory1 · Your inference report card (capstone)quantize, measure and pick a model for a memory budget
What your folder will look like
 ~/llm-inference-deep/
 ├── lab            the lab script: ./lab setup|check|reset pN, ./lab stop
 ├── lab.log        every command the lab script ran, with its output
 ├── llama/         llama.cpp b12774 (llama-cli, llama-tokenize, llama-server, ...)
 ├── models/        qwen2.5-0.5b-instruct-fp16.gguf (1.27 GB), and the ones you quantize
 ├── data/          Practical 1: WikiText-2's test set, for llama-perplexity
 ├── report/        Practical 1: your measurements, report.py and your pick
 ├── tokens.sh      Practical 0: counts tokens
 └── probs.py       Practical 0: each step's top candidates

1 · What happens when a model answers

In one sentence: a language model only ever guesses the next small piece of text, a token, and an answer is that guess repeated in a loop, each new token added to the input for the next.

The problem

You ask a chat assistant a question and the reply doesn’t arrive all at once: it appears a few letters at a time, as if someone were typing. Sometimes it starts well and then states something false with total confidence. Ask again and the wording changes. None of that makes sense if you picture the model as a program that looks up an answer and prints it.

It makes sense once you see what the model actually computes. It never writes an answer. It produces one small piece of text at a time, and the reply is that step repeated.

The idea: guess the next piece, then repeat

Think of the autocomplete on a phone keyboard: it looks at what you typed so far and suggests the next word. A language model does the same, with three differences: its pieces are smaller than words, it gives a score to every possible piece, and instead of waiting for you it takes one of its own suggestions, appends it, and asks itself again.

 "The capital of France is"  ──>  model  ──>  " Paris" (0.395)  ──┐
 "The capital of France is Paris"  ──>  model  ──>  "." (0.531)  <─┘  ──┐
 "The capital of France is Paris."  ──>  model  ──>  " It" (0.200)  <──┘   ... and so on

Each arrow through the model is one forward pass: one full run of the model’s calculation. One pass, one new piece. A 12-piece reply is 12 passes.

The words you need

Token. The piece of text the model works with. A tokenizer cuts text into tokens using a fixed list built before training: common words are one token, rare words are split into parts. Each token in the list has a number, and those numbers are all the model receives:

llama/llama-tokenize -m models/qwen2.5-0.5b-instruct-fp16.gguf -p "The capital of France is" --log-disable
   785 -> 'The'
  6722 -> ' capital'
   315 -> ' of'
  9625 -> ' France'
   374 -> ' is'

Five tokens, and the space before a word belongs to the word’s token. unbelievably is 3 tokens (un, belie, vably); Hello is 1.

Vocabulary. The fixed list of tokens. This course’s model, Qwen2.5-0.5B-Instruct, has 151,936 of them.

Weights (or parameters). The numbers the model learned in training and never changes while answering. This model has 630.17 million of them, stored at 16 bits (2 bytes) each, which is why its file is 1.17 GiB (the name says 0.5B; llama.cpp counts 630.17 million).

The model as a function. Put the whole picture together and a model is one fixed function: tokens in, one score for each of the 151,936 vocabulary entries out. The scores become probabilities (lesson 2 shows how), and here are the five highest after our prompt:

 1  chose ' Paris'     ' Paris' 0.395 | ' ______' 0.096 | ':\n' 0.058 | ':\n\n' 0.047 | ' __' 0.047

Paris wins with 0.395. Second place is ______, a blank to fill in, as on a quiz sheet. The model doesn’t know an answer; it knows what text tends to come next.

The loop, run for real

Here are 12 passes, always picking the most likely token. Each line is one pass: the token chosen and the top 5 candidates.

 1  chose ' Paris'     ' Paris' 0.395 | ' ______' 0.096 | ':\n' 0.058 | ':\n\n' 0.047 | ' __' 0.047
 2  chose '.'          '.' 0.531 | ',' 0.251 | '.\n' 0.070 | ' and' 0.057 | '.\n\n' 0.052
 3  chose ' It'        ' It' 0.200 | ' The' 0.131 | ' Paris' 0.091 | ' Which' 0.048 | ' In' 0.041
...
 6  chose ' largest'   ' largest' 0.370 | ' most' 0.132 | ' capital' 0.075 | ' oldest' 0.065 | ' seat' 0.062
 7  chose ' city'      ' city' 0.732 | ' and' 0.172 | ',' 0.029 | ' metropolitan' 0.024 | ' French' 0.007
 8  chose ' in'        ' in' 0.792 | ' of' 0.087 | ' and' 0.061 | ' by' 0.032 | ',' 0.009
 9  chose ' Europe'    ' Europe' 0.403 | ' France' 0.270 | ' the' 0.257 | ' both' 0.017 | ' western' 0.009
...
12  chose ' second'    ' second' 0.224 | ' third' 0.215 | ' fifth' 0.077 | ' largest' 0.075 | ' most' 0.058

The reply reads Paris. It is the largest city in Europe and the second. Fluent, and false: Paris is not Europe’s largest city. Every step picked a likely continuation; nothing checked the claim. That is also why replies stream in: each token exists only after its pass, so the program shows it as soon as it has it.

How a chat fits in: the template

A chat model was trained on conversations written in a fixed layout, so your question is wrapped in that layout, the chat template, before tokenizing. For this model, “What is the capital of France?” becomes:

<|im_start|>system
You are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant

The bare question is 7 tokens; wrapped, it’s 36. <|im_start|> (151644) and <|im_end|> (151645) are single special tokens. The model then continues after assistant, and when it picks <|im_end|> itself, the program stops: that is how an answer ends.

Try it on your Mac

Practical 0 · Your llama.cpp, token by token, after lesson 2: you install llama.cpp, count tokens and watch these probabilities yourself.

Go deeper: how the tokenizer picks its pieces

The vocabulary is built before training by byte-pair encoding (BPE): start from single bytes, then repeatedly merge the pair of pieces that occurs most often in a large sample of text, until the list has the size wanted. Frequent words end up as one token; rare ones are left in parts. Because it starts from bytes, any text can be tokenized, even a character the list never saw as a whole. You can see both effects here:

 30124 -> 'Sch'
 21140 -> 'aden'
 24716 -> 'fre'
   793 -> 'ude'
   220 -> ' '
    16 -> '1'
...
    23 -> '8'
 25125 -> ' �'
   243 -> '�'

Schadenfreude 12345678 ☕ is 15 tokens: the German word in four parts, a lone space, then each of the 8 digits as its own token (this model’s tokenizer splits numbers into digits), and ☕, 3 bytes in UTF-8, as two tokens that each hold part of those bytes (printed � because neither is a whole character).

Token counts are what context limits and API prices are measured in, so a number or a rare word costs more of them than a common word of the same length.

The Hugging Face course explains BPE step by step: Byte-Pair Encoding tokenization.

Go deeper: what is inside one forward pass

llama.cpp prints the model’s shape when it loads it (-v):

0.00.077.940 I print_info: n_embd                = 896
0.00.077.940 I print_info: n_layer               = 24
0.00.077.959 I print_info: model params          = 630.17 M
0.00.077.960 I print_info: n_vocab               = 151936

Each token’s number first picks a row of 896 numbers, its embedding. Those vectors then pass through 24 layers; in each one, every token’s vector is updated from the vectors of the tokens before it (attention) and then on its own (a small feed-forward network).

After the last layer, the last token’s vector is multiplied against the whole vocabulary to give 151,936 scores, the logits. Every pass reads all the weights, whatever the length of the reply so far: lesson 3 measures what that costs, and why the work for earlier tokens isn’t redone each time.

The model was trained with up to 8192 tokens of text at once (n_ctx_train): its context. The architecture is described in the Qwen2 technical report.

Common misunderstandings

  • “The model writes the whole answer, then the app shows it slowly.” The answer doesn’t exist yet: each token is computed after the one before it is chosen.
  • “A token is a word.” Often it’s part of a word, a space plus a word, a single digit, or part of a character’s bytes.
  • “It answered Paris, so it knows geography.” It gave Paris 0.395 because that text is likely there; the same loop started a falsehood five tokens later ( largest, step 6).

Check yourself

1. A reply of 200 tokens: how many times did the model run its full calculation?

About 200 forward passes, one per new token. The first one also reads your whole prompt and gives token 1 (lesson 3 shows the prompt is done in one go).

2. An API charges per token. Why does an invoice number like 20261129 cost more than the word "Hello"?

This tokenizer splits numbers into single digits: 8 digits are 8 tokens, while Hello is 1. Rare words are split too (unbelievably is 3).

3. You send "Hi" to a chat model and the request reports 30-odd prompt tokens. Where did they come from?

The chat template: the system message and the <|im_start|>/<|im_end|> markers wrap your text. Here the bare question was 7 tokens and the wrapped one 36.

Next: 2 · Picking each token: the loop and sampling.

2 · Picking each token: the loop and sampling

In one sentence: the model gives a probability to every possible next token, and a separate step, the sampler, reshapes those probabilities with settings such as temperature and top-p and then draws one.

The problem

Ask the same question twice and you get two different answers. Turn “temperature” up and the text gets creative, then strange; set it to 0 and the answers repeat word for word. The model is the same in every case: what changes is how one token is chosen from its scores, at every step of lesson 1’s loop.

The idea: the model proposes, the sampler picks

Sometimes one token clearly leads ( city had 0.732 in lesson 1). Often none does. After Once upon a time, there was a, the top 10 are:

' young'       0.075
' man'         0.057
' little'      0.040
' group'       0.034
' farmer'      0.025
' very'        0.025
' king'        0.024
' boy'         0.024
' small'       0.021
' big'         0.018
sum of listed: 0.344  (10 candidates)

The ten best hold only 0.344 together. Think of a raffle where each token holds tickets in proportion to its probability: the sampler redistributes the tickets (or takes some away), then draws one.

From scores to probabilities: softmax

The model’s raw output is a score per token, a logit, any number, positive or negative. Softmax turns them into probabilities: raise e to each score and divide by the total, so every result is between 0 and 1 and they add up to 1. Bigger score, bigger share, and differences between scores become ratios between probabilities.

Temperature T divides every score before softmax. T below 1 stretches the differences, so the leaders take more of the tickets; T above 1 squeezes them, so the long tail gets more. T = 0 can’t divide, so it means greedy: take the top token, no draw at all.

The settings, measured

These are the same step’s probabilities after each setting, from llama.cpp’s server (it can report the probabilities after sampling when a request sets "post_sampling_probs": true). The temperature rows were measured with the cuts off (top-k 0, top-p 1, min-p 0):

Settingyoungmanlittlethe 10 shown add up towhat it does
none (temperature 1, cuts off)0.0750.0570.0400.344the model’s own probabilities
temperature 0.5, cuts off0.3260.1870.0910.859sharpens: the leaders gain
temperature 1.5, cuts off0.0170.0140.0110.098flattens: the tail gains
top-k 30.4370.3320.2311.000only the 3 best can be drawn
top-p 0.90.0830.0630.0440.382keep the fewest tokens that add up to 0.9
min-p 0.10.1650.1250.0870.759drop tokens under a tenth of the leader

After each cut, the tokens left are rescaled to add up to 1: top-k 3 keeps 0.075 + 0.057 + 0.040 = 0.172 and divides by it, so young gets 0.437.

Top-p 0.9 kept a long list here (young rose only to 0.083), because no few tokens stand out. Top-p adapts to the step: few tokens when the model is sure, many when it isn’t. Min-p does the same relative to the leader: with 0.1, the cut-off here is 0.1 × 0.075 = 0.0075.

A high temperature with the cuts off is where text goes wrong: the 151,926 tokens nobody wants get a real chance together, and one bad draw derails every step after it, since each token becomes part of the input for the next. The cuts are the guard: in Practical 0, temperature 1.5 with the default cuts still gave readable text.

What llama.cpp does by default

llama-completion --help and the server’s /props give this build’s defaults:

SettingDefaultOff with
--temp0.80--temp 0 (greedy)
--top-k400
--top-p0.951.0
--min-p0.050.0
--seed-1 (a random seed each run)a fixed number

They run as a chain, in this order: top_k, typ_p, top_p, min_p, xtc, temperature (after a few samplers that are off by default: the penalties, dry and top_n_sigma). So the cuts are made on the model’s own probabilities, and temperature reshapes what is left.

Seeds: why “random” can repeat

The draw uses random numbers from a generator started by a seed. Same seed, same settings, same prompt: the same draws, so the same text. Five runs of Once upon a time, 30 tokens each, gave three texts:

RunSettingsText begins
a, b--temp 0, there was a young man named John who lived in a small village. (both identical)
a, b--temp 0.8 --seed 1 in 16th century, the main player in the game was a mouse. (both identical)
c--temp 0.8 --seed 2, I went to a place where I could buy any item I wanted for a price.

A chat app usually picks a new seed per request, which is why the same question gets a different answer.

When the loop stops

The loop ends when the model picks its end token (<|im_end|>, lesson 1’s template), reported by an OpenAI-style API as "finish_reason":"stop", or when the length limit (max_tokens, -n) comes first: "finish_reason":"length", the text cut wherever it was. Asked for the capital of France “in one word”, the model answered Paris in 2 tokens (the word, then the end token); with max_tokens 1 the same Paris came back marked length: the end token never got its turn.

Try it on your Mac

Practical 0 · Your llama.cpp, token by token: install llama.cpp, count tokens with your own script, print each step’s candidates, and break the sampler on purpose.

Go deeper: the arithmetic, checked against the measurements

Softmax with temperature: pi = ezi/T / Σj ezj/T (softmax). Halving T doubles every score, which squares every ratio between two probabilities. Check it on the table: at temperature 1, young / man = 0.075 / 0.057, and squared that is 1.73; at temperature 0.5 the measured ratio is 0.326 / 0.187 = 1.74.

Top-p is nucleus sampling (Holtzman et al., The Curious Case of Neural Text Degeneration): sort, add up from the top until the sum reaches p, drop the rest. Here young’s rescaling tells you what was kept: 0.075 / 0.083 = 0.904, just over 0.9. Min-p (Nguyen et al., 2024) keeps tokens with p ≥ min_p × ptop; here the kept tokens added up to 0.075 / 0.165 = 0.455.

llama.cpp lists every sampler and its flag in the server README and the completion README; --samplers changes the order.

Go deeper: what production APIs do with these settings

The settings belong to each request, not the model: the same server answers a temperature: 0 request from a classifier and a temperature: 1 one from a writing tool side by side.

Greedy is repeatable on one machine and build, but not promised across them: other hardware or another build may round the arithmetic differently, and a near-tie between two tokens can then go the other way, changing all the text after it. This course checked repeatability on one machine and build only.

A length limit doesn’t make an answer shorter; it cuts it. To get short answers, ask for them in the prompt (the model then picks its end token sooner) and keep max_tokens as a safety net, checking finish_reason for "length".

Common misunderstandings

  • “Temperature 0 makes the model more accurate.” It makes it repeatable. In lesson 1, greedy picking stated that Paris is Europe’s largest city.
  • “Top-k 40 always leaves 40 choices.” It leaves at most 40, and top-p and min-p, run after it, can cut further.

Check yourself

1. You run with --temp 5 --top-k 1. Will the text be gibberish?

No. Top-k 1 leaves one token before temperature runs, so there is nothing to choose between: it’s greedy. You’ll check this in Practical 0.

2. With top-p 0.9, one step's leader has probability 0.95. How many tokens can be drawn?

One: the leader alone already reaches 0.9, so top-p keeps only it, and the step is greedy. A step with no clear leader, like Once upon a time, there was a, keeps a long list instead.

3. A test compares a model's output to a saved answer and fails randomly. What two settings make it repeatable?

Greedy (temperature 0), or a fixed seed with fixed settings. Both only hold on the same build and hardware.

Next: Practical 0 · Your llama.cpp, token by token, then lesson 3 · Prefill and decode, and the KV cache.

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.

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

In one sentence: quantization stores each weight in fewer bits, a small block of weights sharing one scale, which makes the file smaller and decode faster for a small loss in quality; what must fit in memory is the weights, plus the KV cache for the context you ask for, plus working buffers.

The problem

The model you want doesn’t fit: its file is bigger than your free memory, or it fits but leaves no room for a long context. And lesson 3 showed that every new token reads all the weights, so a big file is also a slow one. You can’t change how many weights the model has. You can change how many bits each one takes.

The idea: fewer bits, one scale per block

Rounding 0.1197 to 0.12 keeps the meaning; most weights don’t need 16 bits of precision. Quantization cuts a row of weights into small blocks, stores one scale per block, and replaces each weight with a small whole number that, multiplied by the scale, gives the weight back approximately. The animation runs this on eight made-up weights:

weights: [0.12, -0.4, 0.03, 0.27, -0.08, 0.35, -0.19, 0.01]
scale d = 0.00315
stored q: [38, -127, 10, 86, -25, 111, -60, 3]
read back: [0.1197, -0.4, 0.0315, 0.2709, -0.0787, 0.3496, -0.189, 0.0094]
largest error: 0.0015

That is Q8_0, llama.cpp’s 8-bit type: the scale is the block’s largest weight (ignoring its sign) divided by 127, and each weight becomes a whole number from −127 to 127.

The types, as stored

From the block definitions in ggml’s source:

TypeWeights per blockBytes per blockBits per weight
Q8_032 (8 bits each) + one 16-bit scale348.5
Q4_K256 (4 bits each) + scales for 8 groups of 321444.5

The scale is why “8-bit” is 8.5 bits. Q4_K_M is a mix, not one type: Q4_K for most tensors, and the 6-bit Q6_K for the ones llama.cpp’s rules say are most sensitive (some of the attention value and feed-forward output weights, and the output layer).

Quantizing this course’s model takes llama-quantize under a second:

llama/llama-quantize models/qwen2.5-0.5b-instruct-fp16.gguf models/qwen2.5-0.5b-instruct-q4_k_m.gguf Q4_K_M
llama_model_quantize_impl: model size  =  1202.09 MiB (16.0018 BPW)
llama_model_quantize_impl: quant size  =   462.96 MiB ( 6.1628 BPW)
llama_model_quantize_impl: WARNING: 145 of 291 tensor(s) required fallback quantization

6.16 bits per weight, not 4.5-and-a-bit: half of the tensors fell back to another type. The reason is in the log:

warning: blk.9.ffn_gate.weight                - ncols    896 not divisible by 256 (required for type    q4_K) -> falling back to    q5_0

A Q4_K block is 256 weights of one row, and these tensors’ rows are 896 long, 3.5 blocks. All 145 fallbacks were rows of 896: 133 went to 5-bit Q5_0, 12 to Q8_0. The file ended up with 133 Q5_0, 13 Q8_0, 12 Q6_K and only 12 Q4_K tensors, plus 121 small ones left in 32-bit floats. The name of a quantization is a recipe; the file you get depends on the model’s shape.

What it changes: size, speed, answers

One llama-bench run over the three files, and two quality measures, on the GPU of the Mac this course was written on:

FileBytesPrefill t/sDecode t/sPerplexitySame top token as fp16
fp161,266,425,6967,81018414.18(itself)
Q8_0675,710,8167,63027114.2198.5%
Q4_K_M491,400,0326,99228414.8391.2%
  • Size: Q8_0 is 53% of fp16, Q4_K_M 39%.
  • Decode gets faster as the file shrinks, as lesson 3 expects of a step that reads every weight.
  • Prefill doesn’t follow size: it is arithmetic, not reading (lesson 3). Between files it moves up to 10% either way on the GPU, more on the CPU.
  • Perplexity measures how surprised the model is by real text (here, 20,480 tokens of Wikipedia articles, WikiText-2): lower is better. Q8_0 is 0.2% higher than fp16, Q4_K_M 4.6%.
  • Same top token: how often the quantized model’s most likely next token is fp16’s, over those same tokens.

On one greedy question, In two sentences, why is the sky blue?, all three files answered the same on this GPU:

The sky is blue because it reflects sunlight, which contains colors such as red, orange, yellow, green, blue, and indigo. [end of text]

On the CPU, Q4_K_M’s changed a few words in: a tiny arithmetic difference changes one greedy pick, and all that follows. So speeds, perplexity’s second decimal and answers vary by machine; sizes don’t. The answer is wrong (the reason is scattering, not reflection): a 0.5B model makes plausible text at any precision, as in lesson 1.

The memory budget

llama.cpp prints what it allocated (-v, the last memory breakdown it prints). At -c 8192:

MiBWeightsKV cacheCompute buffersTotal
fp161,201 (942 on the GPU + 259)963261,624
Q4_K_M462 (373 + 89)96326885
fp16, 8-bit KV cache1,201513261,579

Parts are rounded; a total is llama.cpp’s GPU total plus its Mac-memory total (1,350 + 274 for fp16).

Weights + cache + buffers is the budget, and each part has its lever: quantize the weights, size -c to what you need (12 KiB per token here), or store the cache in 8 bits:

llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf -c 8192 -fa on -ctk q8_0 -ctv q8_0 -p Hi -n 1 -no-cnv -v

-ctk/-ctv set the key and value types; 96 MiB becomes 51. The value cache in 8 bits needs flash attention, which the default (-fa auto) turned on here: the same command without -fa runs too. Turn it off (-fa off) and:

0.00.181.730 E llama_init_from_model: quantized V cache requires flash_attn to be enabled
0.00.181.732 E llama_completion: error: unable to create context

Flash attention computes attention in tiles, without storing every token-to-token score at once.

Three classic failures, briefly

  • A context too large for memory. At -c 32768 this model’s cache (384 MiB, reserved at start) is nearly as big as its Q4_K_M weights (462). The capstone has you hit the limit.
  • A context beyond training. This file says it was trained on 8,192 tokens; ask for more and llama.cpp warns, then runs anyway:
    0.00.184.191 W llama_context: n_ctx_seq (32768) > n_ctx_train (8192) -- possible training context overflow
    
  • A wrong chat template. Practical 0’s break-it task: without the template, the model continues your text instead of answering it.
Go deeper: perplexity and "same top token"

Perplexity is e raised to the average negative log-probability the model gave each real next token of the text. A model that always gave the right token probability 1 would score 1; one guessing evenly among n tokens scores n. So 14.18 is “as unsure as choosing among about 14 tokens”. llama-perplexity scored 40 chunks of 512 tokens of the WikiText-2 test set (Merity et al., 2016).

Perplexity can hide changes that cancel out. --kl-divergence compares the quantized model’s whole probability list with fp16’s at every token: the mean KL divergence was 0.00072 for Q8_0 and 0.029 for Q4_K_M, about 40 times more, and the “same top token” figures come from the same run. The tool and its options: perplexity README.

Go deeper: where the formats are defined

The blocks are C structs in ggml-common.h (block_q8_0, block_q4_K, block_q6_K, 210 bytes per 256 weights), and the arithmetic of Q8_0 in ggml-quants.c: d = amax / ((1 << 7) - 1), then roundf of each weight divided by d. Q4_K stores a minimum as well as a scale per group of 32, each in 6 bits, so a group needn’t be centred on zero.

Which tensor gets which type in a _M mix is llama_tensor_get_type_impl in llama-quant.cpp; llama-quantize --help lists every type. Flash attention: Dao et al., 2022.

Common misunderstandings

  • “Q4 means 4 bits per weight.” Q4_K is 4.5 with its scales, Q4_K_M mixes in 6-bit tensors, and this model’s Q4_K_M came out at 6.16.
  • “Quantization only trades quality for size.” It also changes speed: decode got 1.54 times faster with Q4_K_M here.

Check yourself

1. A Q8_0 block's largest weight is 0.8. What is its scale, and what number is stored for a weight of 0.2?

d = 0.8 / 127 = 0.0063; 0.2 / 0.0063 rounds to 32 (exactly, 0.2 / 0.8 × 127 = 31.75).

2. A model needs 1,624 MiB at -c 8192 and you have 1,000 free. What two changes from this page fit it?

Q4_K_M weights (885 MiB in total here) and, if you need more room, a smaller -c or an 8-bit KV cache with flash attention on (the default here).

3. A quantized file's perplexity is only 0.2% above fp16's. Will its answers be word for word the same?

Not necessarily: that is Q8_0, which picks fp16’s top token 98.5% of the time, not always, and one different greedy pick changes all that follows. On the sky question it matched; on another it might not.

Next: Practical 1 · Your inference report card (the capstone): quantize, measure and compare the model yourself, from an empty folder.

Practical 0 · Your llama.cpp, token by token

Goal: llama.cpp and the course’s model running on your Mac; a script of yours that counts tokens and one that prints, for each generated token, the candidates the model weighed; and a sampler you broke on purpose.

Time: ~45 minutes, plus the download. Where: everything in ~/llm-inference-deep/ on your Mac, in your own terminal. Read lesson 1 and lesson 2 first.

Task 1 · Get llama.cpp and the model

Make the workspace and get the lab script:

mkdir -p ~/llm-inference-deep && cd ~/llm-inference-deep
curl -fo lab http://localhost:8800/llm-inference-deep/tools/lab && chmod +x lab

The model is one 1.27 GB file. On a slow connection (at 100 KB/s that’s about 3.5 hours), start its download yourself first, in its own terminal; if it stops, run the same command again and it carries on where it was:

cd ~/llm-inference-deep && mkdir -p models
curl -fL -C - -o models/qwen2.5-0.5b-instruct-fp16.gguf \
  https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-fp16.gguf

The model is Qwen2.5-0.5B-Instruct by the Qwen team, under the Apache-2.0 licence: free to use, change and share, no account needed. Then:

./lab setup p0
  ✓ macOS on Apple Silicon (arm64)
  downloading llama.cpp b12774 for macOS arm64 (17 MB)
  ✓ llama.cpp 1.1.0-dev (build 12774) in llama/ (checksum matches the release)
  models/qwen2.5-0.5b-instruct-fp16.gguf is already there: checking its SHA-256 (a few seconds)
  ✓ models/qwen2.5-0.5b-instruct-fp16.gguf: 1.27 GB, checksum matches, kept as it is

ready for p0. Next: task 2, then ./lab check p0

That is with your own download done first. Without it, setup fetches the model itself (and also carries on if stopped), and its two model lines read instead:

  downloading Qwen/Qwen2.5-0.5B-Instruct-GGUF (1.27 GB, licence Apache-2.0); a run that stops can be started again and carries on
  checking its SHA-256 (a few seconds)
  ✓ models/qwen2.5-0.5b-instruct-fp16.gguf: 1.27 GB, checksum matches
What setup did
  • Downloaded llama.cpp b12774 (the build of release v1.1.0; newest release: github.com/ggml-org/llama.cpp/releases), the official prebuilt macOS arm64 archive (17 MB), checked its SHA-256 against the release, and unpacked it into llama/. The archive stays in downloads/. Nothing is installed anywhere else: delete the folder and it’s gone.
  • Checked the model file’s SHA-256 against the one Hugging Face publishes (or downloaded it with curl -C -, which resumes).
  • Logged every command and its output in lab.log. Running setup again keeps what’s there.

The file is GGUF, llama.cpp’s format: the weights plus the tokenizer’s vocabulary and the chat template, in one file. fp16 means each weight is a 16-bit floating-point number.

Task 2 · Count tokens

Predict first: how many tokens is 12345678? And unbelievably?

Write tokens.sh yourself:

  • ./tokens.sh "some text" prints the number of tokens the course’s model splits that text into, the number alone, on the last line.
  • It uses llama/llama-tokenize and the model in models/, found from the script’s own folder.
Hint

llama/llama-tokenize --help lists -m, -p, --show-count (its last line is Total number of tokens: N) and --log-disable (hides the loading messages). tail -n 1 and awk '{print $NF}' keep the last word of the last line. $(dirname "$0") is the script’s folder.

Solution
#!/bin/bash
# tokens.sh TEXT: prints how many tokens the course's model splits TEXT into
here="$(cd "$(dirname "$0")" && pwd)"
"$here/llama/llama-tokenize" -m "$here/models/qwen2.5-0.5b-instruct-fp16.gguf" -p "$1" \
  --show-count --log-disable | tail -n 1 | awk '{print $NF}'

Then chmod +x tokens.sh.

for t in "Hello" "The capital of France is" "unbelievably" "Schadenfreude 12345678 ☕"; do ./tokens.sh "$t"; done

You should get 1, 5, 3 and 15. To see the pieces, run llama-tokenize without --show-count; try your name, a line of code, a sentence in another language.

Task 3 · Greedy, then sampled

Predict first: you run the same command twice at --temp 0. Same text? And twice at --temp 0.8 --seed 1?

llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf -p "Once upon a time" -n 30 \
  -no-cnv --no-display-prompt --temp 0 2>/dev/null
FlagWhy
-n 30the length limit: 30 tokens
-no-cnvplain completion of your text, no chat (no template, no waiting for your input)
--no-display-promptprint only the new tokens
2>/dev/nullhide the loading log, which goes to stderr

Run it again, then twice with --temp 0.8 --seed 1 and once with --seed 2. Greedy repeats exactly; the same seed repeats exactly; another seed gives another story.

Task 4 · See every step’s candidates

Start llama.cpp’s server in a second terminal and leave it running:

cd ~/llm-inference-deep
llama/llama-server -m models/qwen2.5-0.5b-instruct-fp16.gguf --host 127.0.0.1 --port 8811 -c 2048

Why: --host 127.0.0.1 keeps it reachable from your Mac only; -c 2048 is the context it makes room for (lesson 3 is about what that room costs). It’s ready when its log shows listening on http://127.0.0.1:8811. Port 8811 taken? Stop what uses it, or use another port and set LLAMA_URL=http://127.0.0.1:<port> for the script.

Write probs.py yourself (Python 3, standard library only):

  • python3 probs.py PROMPT [N] [TEMPERATURE] generates N tokens (default 5) at that temperature (default 0) by POSTing to the server’s /completion.
  • It prints one line per generated token: the token chosen, then the 5 most likely candidates with their probabilities between 0 and 1, most likely first.
  • The server’s address comes from LLAMA_URL, default http://127.0.0.1:8811.
Hint

Send JSON {"prompt": ..., "n_predict": N, "n_probs": 5, "temperature": T}. The answer has a list completion_probabilities, one entry per token, each with token and top_logprobs, a list of {token, logprob}. A logprob is the natural log of the probability: math.exp turns it back.

Solution
# probs.py PROMPT [N] [TEMPERATURE]: N tokens, and the top 5 candidates at each step
import json
import math
import os
import sys
import urllib.request

url = os.environ.get("LLAMA_URL", "http://127.0.0.1:8811")
prompt = sys.argv[1]
n = int(sys.argv[2]) if len(sys.argv) > 2 else 5
temperature = float(sys.argv[3]) if len(sys.argv) > 3 else 0.0

body = {"prompt": prompt, "n_predict": n, "n_probs": 5, "temperature": temperature}
req = urllib.request.Request(url + "/completion", data=json.dumps(body).encode(),
                             headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as r:
    answer = json.load(r)

for i, step in enumerate(answer["completion_probabilities"], 1):
    top = " | ".join(f"{c['token']!r} {math.exp(c['logprob']):.3f}" for c in step["top_logprobs"])
    print(f"{i:2}  chose {step['token']!r:12} {top}")
python3 probs.py "The capital of France is" 12
 1  chose ' Paris'     ' Paris' 0.395 | ' ______' 0.096 | ':\n' 0.058 | ':\n\n' 0.047 | ' __' 0.047
 2  chose '.'          '.' 0.531 | ',' 0.251 | '.\n' 0.070 | ' and' 0.057 | '.\n\n' 0.052
...

Lesson 1’s 12 steps, on your Mac. Look for the steps with no clear leader (3 and 5) and the near-tie at step 12 ( second 0.224, third 0.214; a third decimal can differ from lesson 1’s run), where a sampled run could branch.

Predict first: at temperature 1.5, will the probabilities printed change, or only the tokens chosen?

python3 probs.py "Once upon a time, there was a" 8 1.5
 1  chose ' man'       ' young' 0.075 | ' man' 0.057 | ' little' 0.040 | ' group' 0.034 | ' farmer' 0.025
 2  chose ' named'     ' named' 0.513 | ' who' 0.322 | ' with' 0.039 | ' and' 0.018 | ' called' 0.015
 3  chose ' David'     ' John' 0.067 | ' Bob' 0.018 | ' David' 0.018 | ' Tom' 0.017 | ' Jack' 0.015
...

Run it a few times. The probabilities are the model’s own, before the sampler reshapes them (lesson 2), so the first line’s are the same every run, while the chosen token is sometimes not the leader (here man, then David in third place); after that first pick the runs branch.

Task 5 · Break it

An absurd sampler. Turn the temperature up to 5 and switch the cuts off:

llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf -p "The capital of France is" -n 30 \
  -no-cnv --no-display-prompt --temp 5 --top-k 0 --top-p 1 --min-p 0 --seed 1 2>/dev/null
ﮮ דור anxiety dignity JAXB Déầu станетễn financ Hartfordacoesbirthdifficulty ويم grilled ymax하시는馒头比起烜 kö	filesヒוסףاي τ dispatch southwestern

Find the cause by changing one thing at a time: 1. put --top-k 1 back (keep --temp 5): the text is exactly the --temp 0 text, because one candidate leaves nothing to draw; 2. try --temp 1.5 with the defaults for top-k, top-p and min-p, and see how much the cuts protect you. Put the command back to the defaults when you’re done.

A missing chat template. Ask the server a question without the template, then through its chat endpoint, which applies it:

curl -s http://127.0.0.1:8811/completion -d '{"prompt":"What is the capital of France?","n_predict":40,"temperature":0}' | python3 -c 'import json,sys; a=json.load(sys.stdin); print(a["content"]); print("stop_type:", a["stop_type"], "tokens_predicted:", a["tokens_predicted"])'
curl -s http://127.0.0.1:8811/v1/chat/completions -d '{"messages":[{"role":"user","content":"What is the capital of France?"}],"temperature":0}' | python3 -c 'import json,sys; a=json.load(sys.stdin); print(a["choices"][0]["message"]["content"]); print("finish_reason:", a["choices"][0]["finish_reason"], "completion_tokens:", a["usage"]["completion_tokens"])'
 The capital of France is Paris. It is the largest city in Europe and the third largest city in the world by population. Paris is known for its rich history, beautiful architecture, and vibrant culture.
stop_type: limit tokens_predicted: 40
The capital of France is Paris.
finish_reason: stop completion_tokens: 8

Investigate in this order: 1. why it stopped: limit means the model didn’t pick its end token within the 40-token limit: it continued the text; 2. how many tokens it produced (40, the limit, against 8); 3. what the model was given: the server’s /apply-template prints the templated prompt, with the <|im_start|>assistant that tells the model a reply starts and that <|im_end|> ends it:

curl -s http://127.0.0.1:8811/apply-template -d '{"messages":[{"role":"user","content":"What is the capital of France?"}]}'

Check your work

With the server still running (if it isn’t, the check starts its own on port 8812 and stops it after):

./lab check p0

Then stop the server: Ctrl-C in its terminal, or ./lab stop.

To start this practical over, ./lab reset p0 moves your tokens.sh and probs.py into a new before-reset-<date>/ folder (it deletes nothing) and keeps llama/ and the model.

Next: lesson 3 · Prefill and decode, and the KV cache.

Practical 1 · Your inference report card

Goal: from an empty report/ folder, your own quantized copies of the model and one table, printed by a script you write, that puts each file’s size, prefill and decode speed, perplexity and answer side by side, with the KV cache’s cost at three context lengths. Then a context too large for memory, and a quantization too far.

Time: ~60 minutes. Where: ~/llm-inference-deep/, where Practical 0 left llama/ and models/. Read lesson 3 and lesson 4 first.

Every command runs from ~/llm-inference-deep, and everything you measure goes into report/. This is the capstone: the tasks give requirements, and you work out the commands from the lessons; the solutions are hidden.

Task 1 · Quantize the model yourself

cd ~/llm-inference-deep && ./lab update && ./lab setup p1
mkdir report

./lab setup p1 checks Practical 0’s files and downloads the text llama-perplexity scores in task 4 (WikiText-2’s test set, 4.7 MB, under CC BY-SA, the copy llama.cpp’s own get-wikitext-2.sh uses) into data/.

Predict first: from lesson 4’s bits per weight, how big will a Q8_0 copy of the 1.27 GB file be? A Q4_K_M one?

Make models/qwen2.5-0.5b-instruct-q8_0.gguf and models/qwen2.5-0.5b-instruct-q4_k_m.gguf from the fp16 file, then list models/ with their sizes.

Hint

llama/llama-quantize INPUT OUTPUT TYPE, as in lesson 4. ls -l models/ gives the bytes.

Solution
llama/llama-quantize models/qwen2.5-0.5b-instruct-fp16.gguf models/qwen2.5-0.5b-instruct-q8_0.gguf Q8_0
llama/llama-quantize models/qwen2.5-0.5b-instruct-fp16.gguf models/qwen2.5-0.5b-instruct-q4_k_m.gguf Q4_K_M
ls -l models/

Near its end, before the timings, each run prints the sizes (here Q4_K_M’s):

llama_model_quantize_impl: model size  =  1202.09 MiB (16.0018 BPW)
llama_model_quantize_impl: quant size  =   462.96 MiB ( 6.1628 BPW)

Q8_0 comes out at 638.74 MiB, 53% of fp16, close to 8.5 / 16. Q4_K_M is 39%, not 4.5 / 16 = 28%: many of its tensors were stored in bigger types (lesson 4).

Task 2 · Speed

Predict first: which of the three files decodes fastest? Which prefills fastest?

Measure prefill (512 prompt tokens) and decode (128 new tokens) of all three files in one llama-bench run, 3 repetitions each, and save its results as JSON lines in report/bench.jsonl.

Hint

llama-bench takes -m once per file. llama/llama-bench --help lists -p, -n, -r and -o (output formats: md, json, jsonl, …). JSON lines means one JSON object per line: one line per file and test.

Solution
llama/llama-bench -m models/qwen2.5-0.5b-instruct-fp16.gguf -m models/qwen2.5-0.5b-instruct-q8_0.gguf \
  -m models/qwen2.5-0.5b-instruct-q4_k_m.gguf -p 512 -n 128 -r 3 -o jsonl > report/bench.jsonl

head -1 report/bench.jsonl shows what each line holds; your script needs model_filename, n_prompt (512 for the prefill test, 0 for decode) and avg_ts, the mean tokens per second.

Task 3 · The KV cache at three context lengths

Save the line in which llama.cpp states the KV cache’s size, for -c 2048, 8192 and 32768, in report/kv-2048.txt, report/kv-8192.txt and report/kv-32768.txt.

Hint

-v prints the llama_kv_cache: size = ... line lesson 3’s table quotes; it appears twice (two load passes, as lesson 4 says of the memory breakdown): keep the last. One token (-p Hi -n 1 -no-cnv) is enough: the cache is reserved when the program starts.

Solution
for c in 2048 8192 32768; do
  llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf -p Hi -n 1 -no-cnv -c $c -v 2>&1 \
    | grep 'llama_kv_cache: size' | tail -n 1 > report/kv-$c.txt
done
cat report/kv-2048.txt report/kv-8192.txt report/kv-32768.txt
0.00.185.554 I llama_kv_cache: size =   24.00 MiB (  2048 cells,  24 layers,  1/1 seqs), K (f16):   12.00 MiB, V (f16):   12.00 MiB

24, 96 and 384 MiB: 12 KiB per token, the same with every one of your files, since the cache holds 16-bit keys and values whatever the weights are stored in.

Task 4 · Quality

Predict first: order the three files by perplexity. Will the three answers to one greedy question match?

  1. Score each file with llama-perplexity on data/wikitext-2-raw/wiki.test.raw, 40 chunks of 512 tokens as in lesson 4, and save its Final estimate line in report/ppl-fp16.txt, report/ppl-q8_0.txt, report/ppl-q4_k_m.txt.
  2. Save lesson 4’s question with its chat template in report/sky.txt, then save each file’s greedy answer (60 tokens at most, the answer only) in report/answer-fp16.txt, and so on.
Hint

llama-perplexity -m ... -f FILE -c 512 --chunks 40; its last line is Final estimate: PPL = .... For the question, printf writes the \ns of the template; llama-completion -f report/sky.txt reads the prompt from the file; -no-cnv --temp 0 -n 60 --no-display-prompt and 2>/dev/null keep only the answer.

Solution
for m in fp16 q8_0 q4_k_m; do
  llama/llama-perplexity -m models/qwen2.5-0.5b-instruct-$m.gguf -f data/wikitext-2-raw/wiki.test.raw \
    -c 512 --chunks 40 2>&1 | grep 'Final estimate' > report/ppl-$m.txt
done
printf '<|im_start|>user\nIn two sentences, why is the sky blue?<|im_end|>\n<|im_start|>assistant\n' > report/sky.txt
for m in fp16 q8_0 q4_k_m; do
  llama/llama-completion -m models/qwen2.5-0.5b-instruct-$m.gguf -no-cnv --temp 0 -n 60 --no-display-prompt \
    -f report/sky.txt 2>/dev/null > report/answer-$m.txt
done

Task 5 · One table: report/report.py

Write report/report.py (Python 3, standard library only). python3 report/report.py, run from ~/llm-inference-deep, prints:

  • a Markdown table with one row per models/qwen2.5-0.5b-instruct-*.gguf file, largest first, and the columns file (fp16, q8_0, …), MB (the file’s bytes / 1,000,000, rounded), prefill t/s and decode t/s (from bench.jsonl, rounded), perplexity (as in ppl-*.txt) and same answer as fp16 (yes or no);
  • under it, the KV cache’s size in MiB at each of the three -c, one line each (for example KV cache at -c 2048: 24.00 MiB).

A measurement that’s missing shows -, so the script works before task 6 adds a file.

Hint

glob.glob lists the models and os.path.getsize gives bytes; json.loads reads each line of bench.jsonl (os.path.basename(r["model_filename"]) names the file); re.search(r"PPL = ([\d.]+)", text) finds the perplexity, r"size =\s*([\d.]+) MiB" the cache.

Solution
# report.py: one table from the measurements saved in report/
import glob
import json
import os
import re

here = os.path.dirname(os.path.abspath(__file__))        # report/
ws = os.path.dirname(here)                               # ~/llm-inference-deep
prefix = "qwen2.5-0.5b-instruct-"


def name(path):
    """models/qwen2.5-0.5b-instruct-q8_0.gguf -> q8_0"""
    return os.path.basename(path)[len(prefix):-len(".gguf")]


def read(filename):
    path = os.path.join(here, filename)
    return open(path).read() if os.path.exists(path) else ""


speed = {}                                               # (file, "prefill" or "decode") -> tokens per second
for line in read("bench.jsonl").splitlines():
    r = json.loads(line)
    speed[name(r["model_filename"]), "prefill" if r["n_prompt"] else "decode"] = r["avg_ts"]

fp16_answer = read("answer-fp16.txt").strip()
print("| file | MB | prefill t/s | decode t/s | perplexity | same answer as fp16 |")
print("|---|---|---|---|---|---|")
files = sorted(glob.glob(os.path.join(ws, "models", prefix + "*.gguf")), key=os.path.getsize, reverse=True)
for path in files:
    n = name(path)
    ppl = re.search(r"PPL = ([\d.]+)", read(f"ppl-{n}.txt"))
    answer = read(f"answer-{n}.txt").strip()
    cells = [n, f"{os.path.getsize(path) / 1e6:.0f}"]
    cells += [f"{speed[n, t]:.0f}" if (n, t) in speed else "-" for t in ("prefill", "decode")]
    cells += [ppl.group(1) if ppl else "-", ("yes" if answer == fp16_answer else "no") if answer else "-"]
    print("| " + " | ".join(cells) + " |")

print()
for c in (2048, 8192, 32768):
    kv = re.search(r"size =\s*([\d.]+) MiB", read(f"kv-{c}.txt"))
    print(f"KV cache at -c {c}: {kv.group(1) + ' MiB' if kv else '-'}")

On the Mac this course was written on (GPU), with task 6’s Q2_K file already added:

| file | MB | prefill t/s | decode t/s | perplexity | same answer as fp16 |
|---|---|---|---|---|---|
| fp16 | 1266 | 7729 | 186 | 14.1759 | yes |
| q8_0 | 676 | 7556 | 272 | 14.2080 | yes |
| q4_k_m | 491 | 7078 | 285 | 14.8279 | yes |
| q2_k | 415 | 7464 | 318 | 16.2309 | no |

KV cache at -c 2048: 24.00 MiB
KV cache at -c 8192: 96.00 MiB
KV cache at -c 32768: 384.00 MiB

Sizes and KV lines should match exactly. Speeds, perplexity’s second decimal and so the answers and the yes/no column vary by Mac: on the CPU, two walks got 14.1747, 14.2517, 14.8644 and no for q4_k_m. Not a mistake. Compare the pattern: decode rises as the file shrinks, prefill doesn’t follow size, perplexity climbs slowly until Q2_K.

Pick one. With 1,100 MiB to spare and a need for -c 8192, which file is closest to fp16? Write your pick and why in report/README.md (the check wants a file’s name): that file is what the report is for.

Solution

Q8_0: about 639 + 96 + 326 ≈ 1,061 MiB from lesson 4’s parts, 1,060 measured on the GPU (908 + 152). It fits, 0.2% above fp16’s perplexity against Q4_K_M’s 4.6%; fp16’s 1,624 doesn’t.

llama/llama-completion -m models/qwen2.5-0.5b-instruct-q8_0.gguf -p Hi -n 1 -no-cnv -c 8192 -v 2>&1 | grep 'memory_breakdown'

Task 6 · Break it

A quantization too far. Make a Q2_K copy (Q2_K, nominally 2.625 bits per weight), measure it as in tasks 2 and 4 (add a fourth -m to the benchmark), then run report.py again.

Predict first: how much smaller than Q4_K_M will it be?

llama_model_quantize_impl: quant size  =   390.28 MiB ( 5.1953 BPW)
llama_model_quantize_impl: WARNING: 145 of 291 tensor(s) required fallback quantization

Only 16% smaller than Q4_K_M (415 MB against 491), because 145 of 291 tensors fell back here too (121 to Q4_0, 24 to Q5_0); yet perplexity rose 14% over fp16, and the greedy answer changed (yours may read differently):

The sky appears blue because it is a reflection of the sunlight, which is a color of the sun, which is a color of the blue part of the electromagnetic spectrum. [end of text]

Investigate in this order: 1. the bits per weight the quantizer printed, not the type’s name; 2. perplexity against fp16’s; 3. the answer on a question you know. Then put the report back to three files: rm models/qwen2.5-0.5b-instruct-q2_k.gguf report/*q2_k* (Q2_K’s lines in bench.jsonl can stay: report.py lists only the files in models/).

A context too large for memory. At 12 KiB per token, -c 4194304 asks for a 48 GiB cache. llama/llama-cli --list-devices shows what your GPU may use: here MTL0: Apple M4 Pro (45000 MiB, 44999 MiB free). This run needs about 56,000 with weights and buffers; if yours shows more, double -c until 0.012 MiB × -c is well above it.

llama/llama-completion -m models/qwen2.5-0.5b-instruct-fp16.gguf -p Hi -n 1 -no-cnv -c 4194304 -fit off
0.06.910.482 E ggml_metal_synchronize: error: command buffer 0 failed with status 5
0.06.910.521 E error: Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)
...
0.06.915.962 E cmn  common_promp: failed to eval

Investigate in this order: 1. the error: the GPU ran out of memory; 2. the arithmetic: -c × 12 KiB against free memory; 3. what you turned off: -fit is on by default (--help: “whether to adjust unset arguments to fit in device memory”).

Without -fit off the same -c ran here, slowly: loading took 6 to 9 seconds instead of 105 ms at -c 8192, and its one token about 150 ms instead of 7. The fix either way: ask for the context you need, here at most the 8,192 tokens the model was trained on.

Go deeper: what -fit did

With -v, llama.cpp says it needed 56,254 MiB on the GPU against 44,999 free, kept your -c (“context size set by user”), and put only 19 of the model’s 25 layers on the GPU, with their part of the cache. The other 6 layers and 12,288 MiB of cache stayed in the Mac’s memory, for the CPU. On the CPU alone (-dev none) there is no GPU limit to hit: there, too, it loaded slowly and ran.

Check your work

./lab check p1
checking p1
  PASS llama.cpp build 12774 in llama/
  PASS models/qwen2.5-0.5b-instruct-fp16.gguf
  PASS models/qwen2.5-0.5b-instruct-q8_0.gguf is a GGUF file, 50%-56% of fp16's size
...
  PASS python3 report/report.py prints a row for fp16, q8_0 and q4_k_m
...

22/22 passed

The last three lines check your rows against your own files and measurements.

That’s the course: you’ve followed one answer from tokens to probabilities to a sampled pick, timed its two phases, sized its cache, and shrunk the model yourself. ./lab reset p1 puts your workspace back to the start of this practical: it moves report/, your quantized files, tokens.sh and probs.py into a new before-reset-<date>/ folder (deleting nothing), then writes Practical 0’s two scripts from its solutions.