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

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.