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 leftllama/andmodels/. 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?
- Score each file with
llama-perplexityondata/wikitext-2-raw/wiki.test.raw, 40 chunks of 512 tokens as in lesson 4, and save itsFinal estimateline inreport/ppl-fp16.txt,report/ppl-q8_0.txt,report/ppl-q4_k_m.txt. - 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) inreport/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-*.gguffile, largest first, and the columnsfile(fp16,q8_0, …),MB(the file’s bytes / 1,000,000, rounded),prefill t/sanddecode t/s(frombench.jsonl, rounded),perplexity(as inppl-*.txt) andsame answer as fp16(yesorno); - under it, the KV cache’s size in MiB at each of the three
-c, one line each (for exampleKV 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.