Skip to main content

AI and machine learning · Intermediate · 22 min

Serve a quantised GGUF model with llama.cpp

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · llama.cpp v1.1.0 (build b12774)

You will build llama.cpp v1.1.0 for CPU, compare a Q4_K_M and a Q8_0 copy of the same small model for size, memory and speed, and answer chat requests from its OpenAI-compatible server behind an API key.

On this page

llama.cpp is a C and C++ engine that runs language models on ordinary hardware, CPU first, with optional GPU back ends. Tools such as Ollama and LM Studio build on it or on its file format. Using it directly gives you control over three things those tools decide for you: which build you run, which exact model file you load, and how the server is started and secured.

Models for llama.cpp come as GGUF files. One GGUF holds the weights, the tokeniser and the chat template in a single file, and the weights are usually quantised: stored with fewer bits than the original 16, so the file is smaller and faster to read from memory, at some cost in accuracy.

In this tutorial you build llama.cpp v1.1.0 from source on Ubuntu 26.04, download two quantisations of SmolLM2-135M-Instruct, measure what the smaller one saves, and then serve it on an OpenAI-compatible API that any OpenAI client library can call. The model is tiny (135 million parameters) so that everything runs on a laptop CPU in seconds. Its answers are often wrong; it is here to learn the plumbing, and every step works the same with a larger GGUF.

If your data is metered or slow, the downloads are small by model standards: a shallow clone of the source and two model files of about 101 MB and 139 MB. Each download command can be run again to resume after a dropped connection.

Step 1 · Install the build tools

llama.cpp needs a C++ compiler, CMake and git. OpenSSL lets its tools fetch over HTTPS. curl downloads the models, jq reads JSON, and the time package gives you a command that reports peak memory:

Bash
sudo apt update
sudo apt install -y build-essential cmake git libssl-dev openssl curl ca-certificates jq time

Check it worked

Bash
cmake --version | head -n 1
g++ --version | head -n 1
test -x /usr/bin/time && echo "GNU time present"

You see a CMake version line, a g++ version line and GNU time present.

Step 2 · Build llama.cpp v1.1.0 for CPU

Clone only the v1.1.0 release tag, without history, into a throwaway demo folder:

Bash
mkdir -p ~/llama-demo
cd ~/llama-demo
git clone --depth 1 --branch v1.1.0 https://github.com/ggml-org/llama.cpp.git

Git warns that you are in a "detached HEAD" state. That is expected for a tag checkout.

Configure a release build, then compile only the two programs this tutorial uses, with one job per CPU core. The full project has dozens of tools; building two of them saves several minutes:

Bash
cd ~/llama-demo/llama.cpp
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release -j "$(nproc)" --target llama-server llama-bench

On a four-core machine the build takes something like 5 to 15 minutes. CMake detects your CPU's vector instructions (AVX2 and similar on x86, NEON on ARM) and builds the CPU back end with them, which is why a build on your own machine is a good default.

A source build is not updated by apt. To upgrade later, clone the newer tag into a fresh folder and build again.

Using the release archive instead

The project also publishes prebuilt CPU archives for each build. v1.1.0 is build b12774, with archives for x86-64 (ubuntu-x64) and ARM64 (ubuntu-arm64). If you prefer not to compile, download the one for your machine, unpack it and use the binaries in the folder it creates in place of build/bin:

Bash
cd ~/llama-demo
curl -L -o llama-bin.tar.gz https://github.com/ggml-org/llama.cpp/releases/download/b12774/llama-b12774-bin-ubuntu-x64.tar.gz
tar -xzf llama-bin.tar.gz

The rest of this tutorial uses the binaries you built.

Check it worked

Bash
cd ~/llama-demo/llama.cpp
ls build/bin/llama-server build/bin/llama-bench
./build/bin/llama-server --version 2>&1 | tee ../version.txt

Both paths are listed, and the version output names the commit 1715275, which is the commit the v1.1.0 tag points at. The build number in that line is low because a shallow clone has no history to count; the commit hash is the part that identifies the release.

Step 3 · Download the model in two quantisations

The model is SmolLM2-135M-Instruct from Hugging Face, released under the Apache 2.0 licence, which allows commercial use as long as you keep the licence and notices. The GGUF conversions come from the bartowski/SmolLM2-135M-Instruct-GGUF repository, under the same licence. Check the licence of any model before you use it; GGUF files of other models carry many different terms.

The URLs below pin a specific revision of the repository, so the files cannot change under you:

Bash
mkdir -p ~/llama-demo/models
cd ~/llama-demo/models
REV=09816acd5d99df7be770d85ea30822623dab342c
BASE=https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/$REV
curl -L --retry 5 -C - -o SmolLM2-135M-Instruct-Q4_K_M.gguf "$BASE/SmolLM2-135M-Instruct-Q4_K_M.gguf"
curl -L --retry 5 -C - -o SmolLM2-135M-Instruct-Q8_0.gguf "$BASE/SmolLM2-135M-Instruct-Q8_0.gguf"

Now confirm the files are exactly what the repository published. A partial or corrupt download fails this check:

Bash
cd ~/llama-demo/models
cat > SHA256SUMS <<'EOF'
2e8040ceae7815abe0dcb3540b9995eaa1fa0d2ca9e797d0a635ae4433c68c2d  SmolLM2-135M-Instruct-Q4_K_M.gguf
5a1395716f7913741cc51d98581b9b1228d80987a9f7d3664106742eb06bba83  SmolLM2-135M-Instruct-Q8_0.gguf
EOF
sha256sum -c SHA256SUMS
ls -lh *.gguf

Check it worked

sha256sum prints OK for both files, and ls -lh shows the Q4_K_M file at about 101M and the Q8_0 file at about 139M.

What the two names mean

Each name describes how the weights are stored:

  • Q8_0 keeps every weight as an 8-bit integer, in blocks of 32 weights that share one scale factor. It is close to the original model in quality and about half the size of the 16-bit original.
  • Q4_K_M uses llama.cpp's "K" formats: most weights get 4 bits, grouped into larger super-blocks with their own small scales and offsets, which works out to about 4.5 bits per weight for those tensors. The M (medium) mix keeps some tensors that matter most for quality at higher precision.

Fewer bits means each weight can take fewer distinct values, so the model's numbers drift further from the originals. The trade is file size, memory and speed against accuracy: on most models, Q4_K_M loses a little quality compared with Q8_0, and that loss grows as you go to 3 bits and below. Small models feel it more than large ones.

Here the Q4_K_M file is about three quarters of the Q8_0 file, not half. A 135M model spends a large share of its weights on the token embedding table, which is kept at higher precision, and some of its tensor shapes do not fit the 4-bit block size, so those fall back to larger formats. On a 7B or 8B model, Q4_K_M is usually a little over half the size of Q8_0.

Step 4 · Compare size, memory and speed with llama-bench

llama-bench loads a model and times two things separately: reading a prompt (-p 64, 64 prompt tokens) and generating new tokens (-n 32, 32 tokens), repeating each test (-r 3) and reporting the average. Wrap each run in /usr/bin/time to record the peak memory of the process:

Bash
cd ~/llama-demo
for q in Q4_K_M Q8_0; do
  /usr/bin/time -f "%M" -o "bench-$q.rss" \
    ./llama.cpp/build/bin/llama-bench -m "models/SmolLM2-135M-Instruct-$q.gguf" \
    -p 64 -n 32 -r 3 -o json > "bench-$q.json"
done

Each run takes a few seconds. The JSON output has one object per test. Summarise both files in one line each:

Bash
cd ~/llama-demo
for q in Q4_K_M Q8_0; do
  jq -r --arg q "$q" --arg rss "$(cat "bench-$q.rss")" '
    (map(select(.n_prompt > 0))[0].avg_ts) as $pp
    | (map(select(.n_gen > 0))[0]) as $tg
    | "\($q): weights \($tg.model_size / 1048576 | floor) MiB, peak RAM \($rss | tonumber / 1024 | floor) MiB, prompt \($pp | floor) tok/s, generate \($tg.avg_ts | floor) tok/s"
  ' "bench-$q.json"
done

Check it worked

You see two lines, one for Q4_K_M and one for Q8_0, each with the weight size, peak memory and two speeds. Your numbers depend on your CPU. Read them like this:

  • Weights and peak RAM track each other: the Q4_K_M run needs less memory, and the difference grows with model size. This is usually the deciding number, because a model that does not fit in RAM does not run well at all.
  • Generate tok/s is how fast answers appear. Generation reads every weight once per token, so smaller weights tend to be faster on CPU. On a model this small, the whole model fits in the CPU's caches and the two can come out close, or Q8_0 can even win, because 8-bit maths is simpler to unpack. Try the same comparison on a 1B to 8B model to see the usual gap.
  • Prompt tok/s is how fast the model reads your input, and is much higher than generation because the prompt is processed in batches.

On a low-end machine or a small cloud server, Q4_K_M of a model you can fit is the usual starting point. Move to Q5 or Q8 when you have memory to spare and notice quality problems.

Step 5 · Start llama-server

llama-server loads one model and serves it over HTTP. In your second terminal, start it on the Q4_K_M file:

Bash
cd ~/llama-demo
./llama.cpp/build/bin/llama-server -m models/SmolLM2-135M-Instruct-Q4_K_M.gguf \
  --alias smollm2-135m --host 127.0.0.1 --port 8080 -c 2048

What each option does:

  • -m is the model file.
  • --alias is the model name the API reports. Without it, the name is the file path.
  • --host 127.0.0.1 listens on this machine only. That is also the default, but writing it makes the choice visible. Do not change it to 0.0.0.0 until you have added the API key in a later step.
  • --port 8080 picks the port. llama-server's own default is 9931.
  • -c 2048 sets the context window to 2,048 tokens. Each slot of context reserves memory for its key-value cache, so a smaller context uses less RAM.

The server logs model details as it loads, then a line saying it is listening. Leave it running and use your first terminal for the next steps.

Check it worked

Bash
curl -s http://127.0.0.1:8080/health

The answer is {"status":"ok"}. While the model is still loading, the same request returns status 503 with a Loading model message; wait a moment and try again.

Step 6 · Call the OpenAI-compatible endpoint

llama-server answers on the same paths as the OpenAI API, so the request body is the one you would send to any OpenAI-compatible service. List the model first:

Bash
curl -s http://127.0.0.1:8080/v1/models | jq -r '.data[0].id'

It prints smollm2-135m, the alias you set.

Now send a chat request. temperature 0 and a fixed seed make the answer repeatable on your machine, and max_tokens caps its length:

Bash
cd ~/llama-demo
curl -s http://127.0.0.1:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "smollm2-135m",
    "messages": [
      {"role": "system", "content": "You answer in one short sentence."},
      {"role": "user", "content": "What is the capital of Kenya?"}
    ],
    "temperature": 0,
    "seed": 42,
    "max_tokens": 48
  }' > reply.json
jq -r '.choices[0].message.content' reply.json
jq '{finish: .choices[0].finish_reason, prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens, tokens_per_second: .timings.predicted_per_second}' reply.json

The response has the OpenAI shape (choices, message, usage) plus a llama.cpp extra, timings, with the generation speed for this one request.

Check it worked

The first jq prints a one-sentence answer, and the second prints a small object with finish set to stop (or length if it hit the 48-token cap), token counts above zero and a speed close to the generation figure from llama-bench.

Read the answer before you trust it. A 135M model often gets facts wrong, and even a large model can. Anything you build on a local model needs the same human or automated checks as one built on a hosted API.

Step 7 · Require an API key

By default anyone who can reach the port can use the server. Before you listen on anything but 127.0.0.1, give it a key. Create the key file and a curl header file with private permissions from the start, inside a subshell so the stricter umask does not stay in your shell:

Bash
cd ~/llama-demo
(
  umask 077
  openssl rand -hex 32 > api-key
  printf 'Authorization: Bearer %s\n' "$(cat api-key)" > auth.header
)
ls -l api-key auth.header

Both files show -rw-------: only your user can read them. The key never appears on a command line, so it stays out of your shell history and the process list.

Stop the first server with Ctrl+C in the second terminal, then start it again with the key file, on a new port so you can tell the two apart:

Bash
cd ~/llama-demo
./llama.cpp/build/bin/llama-server -m models/SmolLM2-135M-Instruct-Q4_K_M.gguf \
  --alias smollm2-135m --host 127.0.0.1 --port 8081 -c 2048 --api-key-file api-key

Send the same kind of request twice, once without the key and once with it. -H @auth.header makes curl read the header from the file:

Bash
cd ~/llama-demo
BODY='{"model": "smollm2-135m", "messages": [{"role": "user", "content": "Say hello."}], "max_tokens": 16}'
curl -s -o no-key.json -w "without key: %{http_code}\n" http://127.0.0.1:8081/v1/chat/completions \
  -H "Content-Type: application/json" -d "$BODY"
curl -s -o with-key.json -w "with key: %{http_code}\n" http://127.0.0.1:8081/v1/chat/completions \
  -H "Content-Type: application/json" -H @auth.header -d "$BODY"
jq -r '.error.message' no-key.json

/health stays open without a key, so monitoring can still reach it. An OpenAI client library sends the key the same way: pass the contents of api-key as its API key, read from a file or an environment variable, never written into your code.

Check it worked

The output is without key: 401, with key: 200 and Invalid API Key. A key alone does not encrypt traffic: to serve other machines, put the server behind a reverse proxy that terminates HTTPS, and keep llama-server itself on 127.0.0.1.

Step 8 · Clean up

Stop the server with Ctrl+C in the second terminal. Then remove the demo folder, which holds the source, the build, the models, the benchmark files and the key:

Bash
cd ~
rm -rf ~/llama-demo

If you installed the build tools only for this tutorial, you can remove them too. Skip any package you used before, since other software may need it:

Bash
sudo apt remove build-essential cmake libssl-dev jq time
sudo apt autoremove

Check it worked

Bash
test ! -e ~/llama-demo && echo "demo folder removed"

It prints demo folder removed, and curl -s http://127.0.0.1:8081/health now fails to connect.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.