Sub topic 11
GGUF for local inference and quantized models
GGUF is a single-file binary format for running models locally, mainly with llama.cpp and tools built on it. It stores tensors and metadata as plain data. Loading a GGUF file does not unpickle anything, so the __reduce__ attack from earlier chapters has no equivalent in the format. This chapter assumes you know what a tensor and a dtype are, and that you have read the pickle chapters.
Why GGUF exists
llama.cpp runs large language models on CPUs, laptops, and small GPUs. These machines have limited memory, so the format must do three things:
- Keep everything in one file: weights, tokenizer, and hyperparameters. Users download one artifact instead of a checkpoint plus config and tokenizer files.
- Support quantized tensor types natively. Quantization stores weights with fewer bits than 16-bit floats.
- Be memory-mappable. The runtime can
mmapthe file and use tensor bytes in place, without copying or deserializing them.
GGUF replaced the earlier GGML, GGMF, and GGJT formats. Those formats had no extensible metadata, so adding a new hyperparameter could break old files. GGUF stores metadata as key-value pairs, so new keys can be added without breaking old readers.
File layout
A GGUF file has four consecutive regions.
- Header. The four magic bytes
GGUF, auint32version (currently 3), auint64tensor count, and auint64metadata count. - Metadata. Each entry is a string key, a
uint32value type, and a value. Value types include integers, floats, booleans, strings, and arrays. Typical keys aregeneral.architecture,llama.context_length, andtokenizer.ggml.tokens. - Tensor info table. Each entry holds the tensor name, its number of dimensions, the dimensions, a quantization type code, and an offset into the data block.
- Tensor data. The raw tensor bytes, aligned to
general.alignment(32 bytes by default).
Version 3 integers are little-endian by default, and the version also allows big-endian files. Strings are a uint64 length followed by UTF-8 bytes, with no terminator.
Compare this with safetensors. Both put a self-describing index in front of raw tensor bytes. GGUF also carries the tokenizer and architecture details that a runtime needs to execute the model, and safetensors does not.
Reading a GGUF file without a library
The layout is simple enough to parse with struct. This script reads the header, the metadata, and the first few tensor entries. It never executes anything from the file. It also rejects absurdly long strings, because an untrusted file can claim any length.
import struct
import sys
SCALARS = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i",
6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
STRING, ARRAY = 8, 9
MAX_STRING = 1 << 24 # 16 MiB sanity limit
TYPE_NAMES = {0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 8: "Q8_0",
12: "Q4_K", 13: "Q5_K", 14: "Q6_K"}
def read_exact(f, n):
data = f.read(n)
if len(data) != n:
raise ValueError("truncated file")
return data
def read_u32(f):
return struct.unpack("<I", read_exact(f, 4))[0]
def read_u64(f):
return struct.unpack("<Q", read_exact(f, 8))[0]
def read_string(f):
n = read_u64(f)
if n > MAX_STRING:
raise ValueError(f"string length {n} exceeds limit")
return read_exact(f, n).decode("utf-8")
def read_value(f, vtype):
if vtype in SCALARS:
fmt = SCALARS[vtype]
return struct.unpack(fmt, read_exact(f, struct.calcsize(fmt)))[0]
if vtype == STRING:
return read_string(f)
if vtype == ARRAY:
etype = read_u32(f)
count = read_u64(f)
return [read_value(f, etype) for _ in range(count)]
raise ValueError(f"unknown metadata type {vtype}")
def inspect(path):
with open(path, "rb") as f:
if read_exact(f, 4) != b"GGUF":
raise ValueError("not a GGUF file")
version = read_u32(f)
tensor_count = read_u64(f)
kv_count = read_u64(f)
print(f"version={version} tensors={tensor_count} metadata={kv_count}")
for _ in range(kv_count):
key = read_string(f)
value = read_value(f, read_u32(f))
if isinstance(value, list):
value = f"<array of {len(value)}>"
elif isinstance(value, str) and len(value) > 60:
value = value[:60] + "..."
print(f" {key} = {value!r}")
for _ in range(min(tensor_count, 5)):
name = read_string(f)
n_dims = read_u32(f)
dims = [read_u64(f) for _ in range(n_dims)]
ttype = read_u32(f)
offset = read_u64(f)
label = TYPE_NAMES.get(ttype, f"type {ttype}")
print(f" tensor {name} {dims} {label} @ {offset}")
if __name__ == "__main__":
inspect(sys.argv[1])Run it as python inspect_gguf.py model.gguf. The first thing to check is general.architecture, because the runtime picks its compute graph from that value.
Quantization
Quantization replaces 16-bit or 32-bit floats with low-bit integers plus a scale. The simplest GGUF scheme is block quantization. Q8_0 splits a tensor into blocks of 32 weights. Each block stores one float16 scale and 32 signed 8-bit integers. A weight is reconstructed as scale * q. That is 34 bytes for 32 weights, or 8.5 bits per weight.
The "K-quants" (names like Q4_K_M) use larger super-blocks with scales for sub-blocks. They keep more accuracy at about the same size. The suffix S, M, or L indicates how many sensitive tensors keep a higher precision.
| Type | Approx. bits per weight | Approx. size for a 7B model | Typical use |
|---|---|---|---|
| F16 | 16 | 14 GB | Reference copy for conversion |
| Q8_0 | 8.5 | 7.4 GB | Near-lossless |
| Q5_K_M | about 5.7 | 5 GB | Quality-focused |
| Q4_K_M | about 4.8 | 4.1 GB | Common default |
| Q4_0 | 4.5 | 3.9 GB | Older, smaller, lower quality |
The sizes are approximate and vary by model. Lower precision saves memory and often speeds up CPU inference, which is limited by memory bandwidth. The cost is accuracy: the model gives slightly different outputs from the original, and the loss is larger below about 4 bits.
Two points about quantization:
- It is lossy and not reversible. You cannot recover the original weights from a Q4 file. Keep the original checkpoint if you may need other quantizations.
- A quantized file is a new artifact. Its accuracy has to be evaluated on your task, and the original publisher's benchmarks do not cover it.
Security properties
GGUF is safer than pickle-based checkpoints because the format has no mechanism for naming a callable. The loader reads typed fields and byte ranges. There is no opcode stream and no find_class.
"No code in the format" does not mean "no risk". The remaining risks are different:
- Parser bugs. The reader trusts counts, lengths, and offsets from the file. A crafted file can claim a huge array or an offset past the end of the data. Memory-safety bugs in C and C++ GGUF parsers have been reported and fixed, so keep llama.cpp and its bindings up to date.
- Metadata that downstream code interprets. The key
tokenizer.chat_templateholds a Jinja template that frontends render to format conversations. If a frontend renders it in an unsandboxed Jinja environment, a malicious template can execute code. This was the basis of a reported vulnerability in a Python binding for llama.cpp. - Resource exhaustion. Oversized tensors or counts can exhaust memory even when no bug is triggered.
- Model-level risk. A poisoned or backdoored model is equally dangerous in any format. The format cannot tell you whether the weights behave honestly.
Practical handling
- Download from the publisher's official repository and compare the SHA-256 hash with the one the publisher lists.
- Inspect the header and metadata with a script like the one above before loading the model. Check the architecture, the tensor count, and the template.
- Run inference in a container or under a low-privilege account with no network access, as the defense-in-depth chapter describes.
- Prefer converting from a safetensors source to GGUF yourself when you can trust the source, instead of downloading arbitrary quantizations.
Exercise
A GGUF file's header says it has 291 tensors and 25 metadata entries. Your parser reads a metadata string whose length field is 9,000,000,000. What should the parser do, and why does this check matter even though GGUF contains no executable code?
Show answer
It should reject the file, because the length is far larger than any plausible string and larger than the file itself. A parser that allocates or reads the claimed length can exhaust memory or read past a buffer. GGUF has no code-execution mechanism like pickle's __reduce__, but a loader that trusts lengths, counts, and offsets from an untrusted file can still crash or be exploited. So bounds checks on every field are the main defense.