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:
| Type | Weights per block | Bytes per block | Bits per weight |
|---|---|---|---|
| Q8_0 | 32 (8 bits each) + one 16-bit scale | 34 | 8.5 |
| Q4_K | 256 (4 bits each) + scales for 8 groups of 32 | 144 | 4.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:
| File | Bytes | Prefill t/s | Decode t/s | Perplexity | Same top token as fp16 |
|---|---|---|---|---|---|
| fp16 | 1,266,425,696 | 7,810 | 184 | 14.18 | (itself) |
| Q8_0 | 675,710,816 | 7,630 | 271 | 14.21 | 98.5% |
| Q4_K_M | 491,400,032 | 6,992 | 284 | 14.83 | 91.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:
| MiB | Weights | KV cache | Compute buffers | Total |
|---|---|---|---|---|
| fp16 | 1,201 (942 on the GPU + 259) | 96 | 326 | 1,624 |
| Q4_K_M | 462 (373 + 89) | 96 | 326 | 885 |
| fp16, 8-bit KV cache | 1,201 | 51 | 326 | 1,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 32768this 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.