GGUF is the single-file model format that llama.cpp loads, and it carries the weights, the tokenizer and the settings together. Since llama.cpp and ggml reached version 1.0.0 on November 13, 2026, the format is also the safest thing to build around, because reporting on the release says the GGUF format itself did not change and existing files do not need to be downloaded again.
That stability matters because most people meet GGUF as an unexplained filename suffix like Q4_K_M and pick a download by guesswork. This walkthrough replaces the guesswork with a measured process. You will convert a small model to GGUF, open the file and read its header, produce several quantized variants, score each one for quality and speed, then load the winner into Ollama. The whole lab takes about 70 minutes on a laptop, and it answers the question behind the “what is GGUF” searches: what is in this file, and which version of it should I run?
Ollama sits on top of the same engine. The company’s own post says its core product is a downloadable app for running open models locally with a simple API, and Ollama 0.30 added improved GGUF compatibility through llama.cpp. If you want the runtime trade-offs first, the comparison of llama.cpp and Ollama after the v1.0 release lays them out. Here the goal is narrower: understand the file, shrink it safely, and prove the result with numbers from your own machine.
Don't miss new tech stories on Google
Add Shattered once in the Google app and our stories show up in your news suggestions.
What Is GGUF? The Format Behind Local LLMs #
GGUF is a binary container designed by the ggml project for storing language models. A single .gguf file holds three things: a short header, a block of key-value metadata, and the tensor data itself. The ggml project documents the layout in its gguf.md specification on GitHub, and the design goal is plain. One file should be enough to load a model, with no sidecar configuration, no separate tokenizer download and no framework-specific checkpoint folder.
Compare that with the Hugging Face safetensors layout, which spreads a model across weight shards, a config.json, tokenizer files and a generation config. A GGUF folds all of that into one artifact. The metadata block stores the architecture name, the context length, the number of layers and attention heads, the tokenizer vocabulary and the chat template. Because the file describes itself, a can memory-map it and start generating without guessing anything.
The three parts of a GGUF file
- Header: a magic number that spells GGUF, a format version, the tensor count and the metadata count.
- Metadata: typed key-value pairs such as
general.architecture,general.name, the context length, the tokenizer tokens and the chat template. - Tensor info and data: a table listing each tensor’s name, shape and quantization type, followed by the aligned tensor bytes.
The tensor table is where quantization shows up. Each tensor carries its own type tag, so one file can mix precisions. Embedding and output layers often stay at higher precision while the bulky feed-forward layers drop to four bits. That per-tensor flexibility is why names like Q4_K_M describe a recipe rather than a single bit width. You will see it directly in Step 6 when the inspector script prints the type counts.
What changed with llama.cpp v1.0.0
The November 13, 2026 release moved both llama.cpp and ggml to 1.0.0 and adopted semantic versioning for the public C API. Coverage of the release says it removed 35 deprecated C-API functions, added FP8 key-value caches and introduced a mixture-of-experts weight cache. For this lab the practical takeaway is simple. The command-line tools used here sit above the C API, so the removals mainly hit people who link against libllama in their own code. Newer prerelease builds with names like b12649 keep appearing on the repository after v1.0.0, but those are prereleases. Pin the stable v1.0.0 tag so your results stay reproducible.
Adoption explains why the details matter. In the 2025 Stack Overflow Developer Survey, the survey’s AI section reports that among developers building AI agents, Ollama is the most-used framework, reported by 51% of respondents. Ollama says it now serves 8.9 million developers. Every one of those installs ends up reading GGUF files, whether the user knows it or not.
Prerequisites: Hardware, Software and Versions #
The lab runs on Linux, macOS or Windows with WSL2. A GPU speeds up the benchmark steps but nothing requires one, because the demo model is small enough for a CPU. Budget about 10 GB of free disk for the source checkout, the F16 conversion, four quantized files and the build tree.
| Component | Version to use | Why it matters |
|---|---|---|
| llama.cpp | Stable tag v1.0.0 (November 13, 2026) | Reproducible tools. Prerelease b##### builds are newer by date but not stable. |
| ggml | v1.0.0, built with llama.cpp | Ships in the same checkout, no separate install. |
| Ollama | Latest release (run ollama --version ) |
Ollama 0.30 added broader GGUF compatibility, and later releases keep that path. |
| Python | 3.10 or newer | Runs the inspector, the sweep runner and the report builder. |
| Python packages | Latest gguf ,requests ,huggingface_hub |
The gguf package reads headers andrequests calls the Ollama API. |
| Build tools | Git, CMake, a C++17 compiler | Needed to compile the quantize, perplexity and bench binaries. |
| Demo model | A small instruct model in safetensors form | Qwen3-0.6B is used below. Any small Hugging Face model works. |
A note on versions. This guide names the stable llama.cpp tag because the project’s release page marks it that way. For Ollama and the Python packages it says “latest” on purpose, since release numbers shift weekly and the commands below do not depend on a specific build. Run each tool’s version flag after installing and paste the output into your lab notes so you can reproduce the run later.
If you have never run a model locally, the walkthrough on running a Qwen3.8 model with llama.cpp covers the basics of and prompting. Everything in this lab builds on that foundation but focuses on the file rather than the chat.
Time and disk budget
Expect roughly 15 minutes for the build, 10 for the model download and conversion, 20 for the quantization sweep and perplexity runs, 10 for benchmarks and 15 for the Ollama steps and the report. A machine with a fast NVMe drive cuts the conversion time noticeably, because the F16 file is written once and then read by every quantize pass.
Steps 1 to 3: Build llama.cpp v1.0.0 and Set Up the Lab #
The first three steps give you a pinned toolchain and a tidy folder, which pays off later when you compare six files that all look alike. Do not skip the tag checkout. A repository head that moves daily can change tool flags between your first run and your last.
Step 1: Clone the repository and pin the stable tag
mkdir -p ~/gguf-lab && cd ~/gguf-lab
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
git checkout v1.0.0
git describe --tags
The last command should print v1.0.0. If it prints a build number such as b12649, you are on a prerelease and the checkout failed, so fetch tags with git fetch --tags and try again.
Step 2: Compile the tools
cmake -B build
cmake --build build --config Release -j 8
ls build/bin | grep -E "llama-(quantize|perplexity|bench|cli|imatrix)"
Expect five binaries in the listing: llama-quantize, llama-perplexity, llama-bench, llama-cli and llama-imatrix. The build takes 5 to 15 minutes depending on core count. Release binaries for several platforms also exist on the project’s release page, but building from the pinned tag guarantees the tools match the source you just checked out.
Step 3: Create the Python environment and folder layout
cd ~/gguf-lab
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install gguf requests huggingface_hub
ls llama.cpp/requirements
pip install -r llama.cpp/requirements/requirements-convert_hf_to_gguf.txt
mkdir -p models gguf results calib
The conversion requirements pull in a CPU build of PyTorch, which is a large download. If the requirements filename differs in your checkout, the ls line shows what is there. Your lab now has four folders: models for the original safetensors, gguf for every converted or quantized file, results for CSV output and calib for text used in quality tests.
Steps 4 and 5: Download a Model and Convert It to an F16 GGUF #
Quantization always starts from the highest-precision GGUF you can produce, and that is the F16 conversion of the original weights. Think of it as your lossless master. Every smaller file in the lab derives from it, and every quality score compares back to it.
Step 4: Download the source model
python - <<'EOF'
from huggingface_hub import snapshot_download
path = snapshot_download(
repo_id="Qwen/Qwen3-0.6B",
local_dir="models/qwen3-0.6b",
)
print("saved to", path)
EOF
ls -lh models/qwen3-0.6b
You should see config.json, tokenizer files and one or more .safetensors shards. A 0.6-billion-parameter model is deliberately tiny. It converts in under a minute, quantizes in seconds and still shows every effect this lab measures. Once the workflow is clear, swap in a larger model by changing the repo ID. The same steps apply to an 8B or 27B model, only slower. For gated models you need a Hugging Face token and an accepted license, and the download call will fail with a 401 until you provide both.
Step 5: Convert to an F16 GGUF
python llama.cpp/convert_hf_to_gguf.py models/qwen3-0.6b \
--outfile gguf/qwen3-0.6b-f16.gguf \
--outtype f16
ls -lh gguf/
The script reads the architecture from config.json, maps each tensor to its GGUF name, copies the tokenizer into the metadata block and writes one file. The log ends with a line reporting the written file size. Illustrative output looks like this, and your sizes will differ with the model you chose:
INFO:hf-to-gguf: model: qwen3-0.6b
INFO:hf-to-gguf:gguf: This GGUF file is for Little Endian only
INFO:hf-to-gguf:Exporting model...
INFO:hf-to-gguf:Model successfully exported to gguf/qwen3-0.6b-f16.gguf
The F16 file stores each weight in 16 bits, so a model with N billion parameters occupies roughly 2N gigabytes. That back-of-envelope rule explains why an 8B model needs about 16 GB at F16 before any context memory, and why quantization exists at all. If you later fine-tune with adapters, the guide to merging a LoRA adapter into a GGUF picks up exactly where this conversion step leaves off.
Two failure modes show up here more than any others. The first is a model architecture the converter does not know yet, which raises an error naming the unsupported class. The second is a missing tokenizer file, which stops the script before it writes anything. Both are covered in the troubleshooting section, so note the error text and move on if you hit either one.
Step 6: Inspect the GGUF Header, Metadata and Tensors in Python #
Reading the file yourself is the fastest way to stop treating GGUF as a black box. The gguf Python package parses the header, exposes the metadata fields and lists every tensor with its type and shape. The script below prints a compact report and flags the details that bite later: the chat template, the context length and the mix of tensor types.
import sys
from collections import Counter
from gguf import GGUFReader
SKIP_PREFIXES = ("tokenizer.ggml.tokens", "tokenizer.ggml.merges",
"tokenizer.ggml.token_type", "tokenizer.ggml.scores")
def field_value(field):
try:
return field.contents()
except Exception:
return "<unreadable>"
def main(path):
reader = GGUFReader(path)
print(f"file: {path}")
print(f"metadata keys: {len(reader.fields)} tensors: {len(reader.tensors)}")
print("-" * 60)
for key, field in reader.fields.items():
if key.startswith(SKIP_PREFIXES):
print(f"{key}: (large array, skipped)")
continue
value = field_value(field)
text = str(value)
if len(text) > 90:
text = text[:87] + "..."
print(f"{key}: {text}")
print("-" * 60)
types = Counter()
total = 0
for t in reader.tensors:
types[t.tensor_type.name] += 1
total += int(t.n_bytes)
for name, count in types.most_common():
print(f"{name:8s} {count:5d} tensors")
print(f"tensor data: {total / 1e6:.1f} MB")
if __name__ == "__main__":
main(sys.argv[1])
python inspect_gguf.py gguf/qwen3-0.6b-f16.gguf
Illustrative output, trimmed for space. Key names follow the GGUF specification, but the values will match your model rather than these:
file: gguf/qwen3-0.6b-f16.gguf
metadata keys: 30 tensors: 310
------------------------------------------------------------
general.architecture: qwen3
general.name: Qwen3 0.6B
qwen3.context_length: 40960
qwen3.block_count: 28
tokenizer.ggml.model: gpt2
tokenizer.chat_template: {%- if tools %}...
------------------------------------------------------------
F32 113 tensors
F16 197 tensors
tensor data: 1500.0 MB
Look at the type counts before anything else. Even an “F16” file contains a handful of F32 tensors, usually the normalization weights, because the converter keeps small sensitive tensors at full precision. The same logic applies after quantization, which is why a Q4_K_M file shows several tensor types at once. Check general.architecture too. If Ollama later refuses to load the file, a mismatch or an unsupported architecture value here is the first suspect.
Steps 7 and 8: Quantize and Compare the Variants #
Quantization stores each weight in fewer bits, grouped in small blocks that share a scale factor. The K-quant family adds a second level of scaling and spends more bits on the tensors that hurt quality most when squeezed. The suffixes encode that choice: S, M and L mean small, medium and large mixes within the same nominal bit width.
Step 7: Produce five quantized files
cd ~/gguf-lab
for q in Q8_0 Q5_K_M Q4_K_M Q3_K_M Q2_K; do
./llama.cpp/build/bin/llama-quantize \
gguf/qwen3-0.6b-f16.gguf \
gguf/qwen3-0.6b-$q.gguf \
$q
done
ls -lh gguf/
Each pass takes seconds for a small model and a few minutes for an 8B one. The tool prints per-tensor progress and finishes with a line giving the original and new sizes. Compare those two numbers in your own log. They are the first hard data point of the lab.
Step 8: Read the quant names correctly
| Type | Size versus F16 | Quality risk | Typical use |
|---|---|---|---|
| F16 | Baseline | None, the reference | Master file for conversion and scoring |
| Q8_0 | About half | Very low | Quality-first runs when memory allows |
| Q5_K_M | Smaller than Q8_0 | Low | Balanced choice for coding and reasoning |
| Q4_K_M | Smaller than Q5_K_M | Moderate | Common default for consumer GPUs and laptops |
| Q3_K_M | Smaller again | Noticeable on small models | Tight memory budgets |
| Q2_K | Smallest of the set | High | Emergency fit only, test before trusting |
The table orders files by size and risk without quoting bit counts, because the exact figure depends on the model and the mix of tensor types. Your inspector output from Step 6 is the authority. Run it on each quantized file and compare the type counts. You will see Q4_K_M files mixing Q4_K and Q6_K tensors, which is the K-quant recipe at work.
Step 9: Measure Quality With Perplexity #
File size tells you nothing about damage. Perplexity does. The llama-perplexity tool runs the model over a fixed text and reports how surprised it is on average. Lower is better, and the only meaningful comparison is between files scored on the same text with the same settings. The F16 score is your ceiling, and each quantized score shows how far the model slipped from it.
ls llama.cpp/scripts | grep -i wikitext
for f in gguf/*.gguf; do
echo "== $f"
./llama.cpp/build/bin/llama-perplexity \
-m "$f" -f calib/wiki.test.raw -c 512 --chunks 40 2>&1 \
| grep "Final estimate"
done
Each run ends with a line shaped like the one below. The numbers here are placeholders to show the format, so ignore the values:
== gguf/qwen3-0.6b-f16.gguf
Final estimate: PPL = 00.0000 +/- 0.00000
== gguf/qwen3-0.6b-Q4_K_M.gguf
Final estimate: PPL = 00.0000 +/- 0.00000
Read the plus-or-minus figure as an error bar. If two quantized files differ by less than their error bars, you cannot call one better. Raise --chunks to tighten the bars at the cost of runtime. Expect the score to climb as the bit width falls, with the steepest rise at Q3_K_M and Q2_K on a model this small. Small models degrade faster than large ones, so a result that looks painful at 0.6B often looks mild at 27B. Re-run Step 9 on a bigger model before you draw conclusions for production.
Step 10: Benchmark Speed With llama-bench #
Quality is one axis and speed is the other. The llama-bench tool measures two numbers per file. Prompt processing (pp) tells you how fast the model reads input, and token generation (tg) tells you how fast it writes output. Generation speed is the figure most people feel in a chat window, so it deserves the most attention.
for f in gguf/*.gguf; do
./llama.cpp/build/bin/llama-bench \
-m "$f" -p 512 -n 128 -r 3 -o csv >> results/llama-bench.csv
done
head -3 results/llama-bench.csv
The CSV carries one row per test. Look for rows labelled pp512 and tg128, and read the tokens-per-second column. Three repetitions with -r 3 smooth out thermal noise. For a rigorous machine-level baseline that goes beyond language models, the GPU benchmark test plan shows how to log temperatures and clocks alongside the same llama.cpp runs.
A pattern emerges once the numbers land. On memory-bound hardware, smaller files generate faster because each token requires reading fewer bytes from memory. Q8_0 therefore tends to trail Q4_K_M on generation speed even though both run the same arithmetic. The relationship is not perfectly linear, since dequantization has its own cost, and some GPU kernels favor particular formats. That is exactly why you measure rather than assume.
Step 11: Load a GGUF Into Ollama With a Modelfile #
Ollama imports a local GGUF through a short text file. Pick the Q4_K_M variant first because it is the usual default, then repeat for any other file you want to test through the API. The FROM line points at the file, and PARAMETER lines set defaults that the API can override per request.
FROM ./gguf/qwen3-0.6b-Q4_K_M.gguf
PARAMETER temperature 0.2
PARAMETER num_ctx 4096
ollama create qwen3-lab-q4 -f Modelfile.q4
ollama list
ollama show qwen3-lab-q4
ollama run qwen3-lab-q4 "Explain GGUF in two sentences."
The create command copies the weights into Ollama’s own store, so the original file in gguf/ can stay where it is. The show command prints the architecture, parameter count and quantization level that Ollama read from your file’s header. Compare that output with your Step 6 inspector report. They should agree, because both read the same metadata block.
Ollama’s runtime handling of GGUF depends on the engine underneath. Its 0.30 release added broader GGUF model compatibility through llama.cpp while keeping its MLX engine for Apple silicon. For a side-by-side view of how Ollama, LM Studio, llama.cpp and vLLM treat the same file, see the local LLM runtime comparison. Repeat the create step for Q8_0 and Q5_K_M with their own Modelfiles so you have three named models to benchmark.
Plans and prices, for context
Everything in this lab runs locally, so it costs nothing beyond electricity. Ollama also sells a cloud service for larger models. Its August 31, 2026 pricing change moved the paid plans to per-token billing, and the listed tiers include Pro at $20 a month with $60 of usage credits and Team at $500 a month with $1,000 of shared usage. Local runs avoid those charges entirely, which is the main economic argument for converting and quantizing your own files.
Step 12: Benchmark Through the Ollama API and Build the Report #
The final measurement step uses Ollama’s HTTP API on localhost:11434. A non-streaming /api/generate call returns timing fields in nanoseconds, including the number of generated tokens and the time spent generating them. Dividing one by the other gives tokens per second without any wall-clock guesswork. A second script then joins speed, size and perplexity into one table.
import csv
import statistics
import sys
import requests
URL = "http://localhost:11434/api/generate"
PROMPT = "Write a 150-word explanation of how a hash table handles collisions."
RUNS = 5
def run_once(model):
body = {
"model": model,
"prompt": PROMPT,
"stream": False,
"keep_alive": "10m",
"options": {"num_predict": 200, "temperature": 0.0, "seed": 7},
}
r = requests.post(URL, json=body, timeout=600)
r.raise_for_status()
d = r.json()
gen_tps = d["eval_count"] / (d["eval_duration"] / 1e9)
pp_tps = d["prompt_eval_count"] / max(d["prompt_eval_duration"] / 1e9, 1e-9)
return gen_tps, pp_tps
def main(models):
rows = []
for m in models:
run_once(m) # warm-up load, discarded
gens, pps = [], []
for _ in range(RUNS):
g, p = run_once(m)
gens.append(g)
pps.append(p)
rows.append({
"model": m,
"gen_tps_median": round(statistics.median(gens), 2),
"gen_tps_min": round(min(gens), 2),
"prompt_tps_median": round(statistics.median(pps), 2),
})
print(rows[-1])
with open("results/ollama-bench.csv", "w", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=rows[0].keys())
w.writeheader()
w.writerows(rows)
if __name__ == "__main__":
main(sys.argv[1:])
python bench_ollama.py qwen3-lab-q8 qwen3-lab-q5 qwen3-lab-q4
The warm-up call matters. The first request after a model loads includes disk reads and graph setup, which would drag the first sample far below steady state. The script discards it and reports the median of five timed runs plus the minimum, so one noisy run cannot hide a stutter. Fixing temperature at zero and pinning the seed keeps the generated text stable between files, which keeps the token counts comparable.
Illustrative output shape, with placeholder values:
{'model': 'qwen3-lab-q8', 'gen_tps_median': 0.0, 'gen_tps_min': 0.0, 'prompt_tps_median': 0.0}
{'model': 'qwen3-lab-q5', 'gen_tps_median': 0.0, 'gen_tps_min': 0.0, 'prompt_tps_median': 0.0}
{'model': 'qwen3-lab-q4', 'gen_tps_median': 0.0, 'gen_tps_min': 0.0, 'prompt_tps_median': 0.0}
If you later want a browser front end for the same files, the guide to serving GGUF models with llama.cpp and Open WebUI shows the server route. For the lab itself, the next section assembles the pieces into one repeatable project.
The Complete Working Project: One Script, One Report #
Running twelve steps by hand teaches the mechanics. Rerunning them for every new model needs automation. The project below has two files. run_lab.sh converts, quantizes, scores and benchmarks. report.py joins the outputs and recommends a file. Place both in ~/gguf-lab next to the folders from Step 3, with the Python environment active and the Ollama service running.
#!/usr/bin/env bash
set -euo pipefail
BASE="qwen3-0.6b"
SRC="models/${BASE}"
BIN="llama.cpp/build/bin"
EVAL="calib/wiki.test.raw"
QUANTS=(Q8_0 Q5_K_M Q4_K_M Q3_K_M Q2_K)
mkdir -p gguf results
: > results/perplexity.csv
: > results/llama-bench.csv
if [ ! -f "gguf/${BASE}-f16.gguf" ]; then
python llama.cpp/convert_hf_to_gguf.py "$SRC" \
--outfile "gguf/${BASE}-f16.gguf" --outtype f16
fi
for q in "${QUANTS[@]}"; do
out="gguf/${BASE}-${q}.gguf"
[ -f "$out" ] || "$BIN/llama-quantize" "gguf/${BASE}-f16.gguf" "$out" "$q"
done
for f in gguf/${BASE}-*.gguf; do
name=$(basename "$f" .gguf)
ppl=$("$BIN/llama-perplexity" -m "$f" -f "$EVAL" -c 512 --chunks 40 2>&1 \
| grep "Final estimate" | sed -E 's/.*PPL = ([0-9.]+).*/\1/')
echo "${name},${ppl}" >> results/perplexity.csv
"$BIN/llama-bench" -m "$f" -p 512 -n 128 -r 3 -o csv >> results/llama-bench.csv
done
for pair in "Q8_0:q8" "Q5_K_M:q5" "Q4_K_M:q4"; do
q="${pair%%:*}"; tag="${pair##*:}"
printf 'FROM ./gguf/%s-%s.gguf\nPARAMETER temperature 0.2\nPARAMETER num_ctx 4096\n' \
"$BASE" "$q" > "Modelfile.${tag}"
ollama create "qwen3-lab-${tag}" -f "Modelfile.${tag}"
done
python bench_ollama.py qwen3-lab-q8 qwen3-lab-q5 qwen3-lab-q4
python report.py
echo "done: see results/report.md"
python
import csv
import os
BASE = "qwen3-0.6b"
MAX_PPL_RISE = 0.05 # accept up to 5% worse perplexity than F16
OLLAMA = {"Q8_0": "qwen3-lab-q8", "Q5_K_M": "qwen3-lab-q5", "Q4_K_M": "qwen3-lab-q4"}
def read_ppl():
out = {}
with open("results/perplexity.csv") as fh:
for name, ppl in csv.reader(fh):
out[name.replace(f"{BASE}-", "")] = float(ppl)
return out
def read_speed():
out = {}
with open("results/ollama-bench.csv") as fh:
for row in csv.DictReader(fh):
out[row["model"]] = float(row["gen_tps_median"])
return out
def main():
ppl, speed = read_ppl(), read_speed()
base_ppl = ppl["f16"]
rows = []
for key, score in ppl.items():
quant = key.upper() if key != "f16" else "F16"
size = os.path.getsize(f"gguf/{BASE}-{key if key == 'f16' else quant}.gguf")
rows.append({
"quant": quant,
"size_mb": round(size / 1e6, 1),
"ppl": score,
"ppl_rise_pct": round((score / base_ppl - 1) * 100, 2),
"gen_tps": speed.get(OLLAMA.get(quant, ""), ""),
})
rows.sort(key=lambda r: r["size_mb"])
ok = [r for r in rows if r["ppl_rise_pct"] <= MAX_PPL_RISE * 100]
pick = ok[0] if ok else rows[-1]
lines = ["| Quant | Size (MB) | PPL | Rise vs F16 (%) | Gen tok/s |",
"|---|---|---|---|---|"]
for r in rows:
lines.append(f"| {r['quant']} | {r['size_mb']} | {r['ppl']} | "
f"{r['ppl_rise_pct']} | {r['gen_tps']} |")
lines.append("")
lines.append(f"Recommended: {pick['quant']} (smallest file within "
f"{MAX_PPL_RISE * 100:.0f}% of F16 perplexity)")
with open("results/report.md", "w") as fh:
fh.write("\n".join(lines))
print("\n".join(lines))
if __name__ == "__main__":
main()
The recommendation rule is deliberately simple. It picks the smallest file whose perplexity sits within five percent of the F16 master, and the threshold is a constant you can tighten for work where accuracy matters more than memory. The report prints a Markdown table, so you can paste it straight into a repository README or a ticket. Run the whole thing with bash run_lab.sh and expect about 20 minutes for the demo model.
Choosing a Quant: Memory Math and Decision Rules #
Your report picks a file for one model on one machine. To plan for others, use the arithmetic that sits under every GGUF download page. Weight memory in gigabytes is roughly the parameter count in billions multiplied by bits per weight, divided by eight. An 8-billion-parameter model at 16 bits needs about 16 GB. At 8 bits the weights shrink to about 8 GB, and at 4 bits they approach 4 GB plus per-block scale overhead. These are lower bounds for the weights alone.
Context memory comes on top. The key-value cache grows with context length, layer count and batch size, and it can rival the weights on long prompts. The November 2026 llama.cpp release added FP8 key-value caches, which cut that cost at some quality risk, so a long-context workload gives you a second dial besides the weight quantization. Test both together, because a harsh weight quant plus a low-precision cache compounds error.
| Situation | Start with | Move down when | Move up when |
|---|---|---|---|
| Coding assistant, ample VRAM | Q5_K_M or Q8_0 | The model does not fit with your context length | Generated code shows subtle logic slips |
| Laptop with shared memory | Q4_K_M | The system swaps or the fan never stops | Answers drift on long tasks |
| Phone or single-board computer | Q4_K_M or Q3_K_M | Load fails with out-of-memory | Output turns repetitive |
| Batch classification, strict accuracy | Q8_0 | Throughput matters more than a small score gap | Labels disagree with the F16 run |
| Tiny model under 2B parameters | Q5_K_M and up | Almost never | Any visible quality loss appears |
Treat the table as a starting point and let your own perplexity and task checks decide. A model that scores well on wikitext can still stumble on code or non-English text, because perplexity measures general next-token prediction on one corpus. Add five or ten prompts from your real workload and compare answers between the F16 and the candidate. Those spot checks catch regressions that a single score hides.
Common Pitfalls When Working With GGUF Files #
- Quantizing an already-quantized file. Feeding a Q8_0 file into
llama-quantizerequires an explicit requantize flag for a reason. Rounding errors stack, and the result is worse than quantizing from F16 directly. Always start from the master. - Comparing perplexity across different texts or settings. A score is only valid against another score from the same text, the same context size and the same chunk count. Change any one and the comparison breaks.
- Judging quality by file size. Two files of similar size can differ in quality because of the S, M and L tensor mixes. Score them, do not assume.
- Importing without checking the chat template. The template lives in the GGUF metadata, and a missing or wrong one makes an instruct model ramble or ignore roles. Confirm it in the Step 6 report and in
ollama show. - Mixing prerelease builds into a measurement run. A daily
b#####build can change kernels. Keep every number in a report on the same stable tag. - Skipping the warm-up call. The first request includes model . Counting it makes the file look slow and the comparison unfair.
- Grabbing the wrong file from a vision repository. Multimodal repos ship a separate projector file next to the language model. only one half gives an error or a text-only model.
The thread through all seven is the same. GGUF files look interchangeable because they share an extension, yet every one is a different experiment. Label each result with the exact file name, the tag of the tool that produced it and the settings used. A results folder with that discipline stays useful for months.
Troubleshooting: 12 Fixes for the Errors You Will Hit #
- Converter says the model architecture is not supported. The script names the unsupported class. Confirm you are on the v1.0.0 checkout, then look at the repository’s list of supported architectures. For a brand-new architecture, run that single conversion on a newer prerelease build, write the build number in your notes, and rerun the other steps with the stable tools.
- Converter cannot find the tokenizer. The download was incomplete. Delete the folder and rerun the Step 4 snapshot download so every tokenizer file arrives. Some models also need the
sentencepiecepackage in the environment. - Quantize prints a fallback warning for some tensors. A message that a tensor’s column count is not divisible by the block size means that tensor fell back to a different type. This is normal on small or unusual models. Run the inspector afterward and note which tensors changed.
- Perplexity returns nan or inf on the F16 file. A few models overflow in half precision. Reconvert with
--outtype bf16and use that file as the master for every later step. - Perplexity or bench runs out of memory. Lower the context with
-c, reduce--chunks, or offload fewer layers. On a GPU build, a smaller-nglkeeps some layers in system memory. ollama createreports invalid file magic. The file is not a GGUF. The usual cause is a failed download that saved an HTML error page, or a Git LFS pointer file. Check the size withls -lhand rerun Step 5 or Step 7.- Ollama refuses to load the architecture. Your Ollama build predates support for that model. Update to the latest release, then compare the architecture string in your Step 6 report with what
ollama showprints. - The imported model rambles or ignores roles. The chat template is missing or wrong. Confirm
tokenizer.chat_templateexists in the metadata, then add an explicitTEMPLATEblock to the Modelfile if needed. - The API returns a 404 for the model name. The name in the request must match
ollama listexactly, including the tag suffix. Recreate the model or fix the name in the script. - Connection refused on port 11434. The Ollama service is not running. Start the desktop app or run
ollama servein a second terminal, then retry the script. - Speed numbers swing between runs. Thermal throttling, a power-saver profile and background applications all distort results. Plug in the machine, close heavy apps, keep the warm-up call and compare medians, not single runs.
- A binary named in this guide is missing from
build/bin. Tool names can shift between releases. List the folder, run the closest match with--helpand adjust the commands. The release notes for v1.0.0 describe the changes that affect command-line users.
Advanced Tips for Better Quants and Faster Runs #
Use an importance matrix for low-bit files
The llama-imatrix tool runs a calibration text through the F16 model and records which weights matter most. Passing the resulting file to llama-quantize with the imatrix option lets low-bit types spend precision where the model needs it. The gain is largest at Q3 and Q2, where plain quantization hurts most. Calibrate on text that resembles your real workload. A code-heavy calibration set helps a coding model, while an English-only set can hurt multilingual output.
./llama.cpp/build/bin/llama-imatrix \
-m gguf/qwen3-0.6b-f16.gguf -f calib/workload.txt -o calib/imatrix.dat
./llama.cpp/build/bin/llama-quantize --imatrix calib/imatrix.dat \
gguf/qwen3-0.6b-f16.gguf gguf/qwen3-0.6b-Q3_K_M-im.gguf Q3_K_M
Score the new file with the same perplexity command and put it next to the plain Q3_K_M result. If the gap is large, you have evidence that calibration was worth the extra step.
Let Ollama quantize on import
Ollama can quantize while it imports a full-precision model, which saves a manual step when you only need one variant. Point the Modelfile at the F16 file and pass the quantize option to ollama create. Check ollama create --help for the exact flag spelling on your version. The trade-off is control. The manual route above gives you every variant, the scores and the importance matrix option.
Remember that mixture-of-experts files follow total parameters
A model with few active parameters still stores every expert. NVIDIA’s Nemotron 3.5 Lightning, which Ollama describes as a 30 billion parameter model with 3 billion active, is a good example. Speed follows the active count, but the file and the memory requirement follow the total. Size your quant choice against the total number, then expect generation speed closer to a 3B model.
Watch the runtime, not just the file
Runtime work can move your numbers without touching the file. Ollama reports that Gemma 4 runs up to 90% faster with coding agents on Apple silicon in its 0.31 release, using multi-token prediction through MLX, as measured on the Aider polyglot benchmark. The llama.cpp v1.0.0 notes also describe the speculative-decoding API moving into the public header. Re-run Steps 10 and 12 after every runtime upgrade and keep the old CSVs for comparison. For more reading on running and tuning models, the AI and machine learning section collects the related guides.
FAQ: GGUF, Quantization and Ollama #
What is GGUF in simple terms?
GGUF is a single-file format for language models used by llama.cpp and the tools built on it. The file holds the model weights, the tokenizer and the settings needed to run them, so one download is enough to start generating.
Do I need to redownload my GGUF files after llama.cpp v1.0.0?
No, according to reporting on the November 13, 2026 release, which says the GGUF format did not change. The release removed deprecated C-API functions, so code that links the library may need updates, but the files themselves keep working.
Is Q4_K_M good enough?
For most chat and coding use on consumer hardware, it is the common default and a reasonable start. Small models and accuracy-critical jobs deserve Q5_K_M or Q8_0. Measure on your own text rather than trusting a rule of thumb, which is exactly what Step 9 does.
What is the difference between GGUF and safetensors?
Safetensors stores weights only, and a model repository adds separate config and tokenizer files. GGUF bundles everything into one file and supports many quantization types. Safetensors is the usual source format for training and conversion, and GGUF is the usual format for local inference.
Can Ollama run any GGUF file?
It can import most files whose architecture its engine supports. A newer architecture may need a newer Ollama release. Check general.architecture in the file with the Step 6 script and compare it with what ollama show reports after import.
How much memory does a quantized model need?
Weights need roughly parameters in billions times bits per weight divided by eight, in gigabytes. Add memory for the key-value cache, which grows with context length. An 8B model at 4 bits needs a little over 4 GB for weights alone.
Can I convert a quantized GGUF back to full precision?
You can dequantize in memory when a tool loads it, but the lost information does not return. Keep the F16 or BF16 master file for any model you plan to requantize, and store the scores next to it so you can justify the final pick later.