- A GGUF file is one binary: a 24-byte header, typed metadata that carries the tokenizer, a tensor table, and weight data aligned to 32 bytes.
- Q8_0 packs 32 weights into 34 bytes (8.5 bits per weight) and Q4_K packs 256 into 144 (4.5). Q4_K_M stores some tensors as Q6_K and reaches 4.8944 bits per weight on Llama 3.1 8B.
- This article's size calculator matches llama.cpp's published bits per weight for six Llama 3.1 8B file types to four decimal places.
- In llama.cpp's April 2024 Llama 3 8B measurements, mean KL divergence from FP16 is 0.0055 for Q6_K, 0.031 for Q4_K_M, and 0.45 for Q2_K.
- Both scripts ran on Python 3.15.1. No model was downloaded and no llama.cpp command ran.
GGUF is the single-file model format that llama.cpp, Ollama, and LM Studio load, and the quantization name in a GGUF filename, such as Q4_K_M, sets both its size and how far its outputs drift from the original weights. Each name maps to a block layout in ggml's source and to rules about which tensors get extra bits. This article decodes both, computes file sizes that match published files, and sets measured quality beside each type. Types, block sizes, and rules were checked against llama.cpp at commit a946eb5 on November 16, 2026, after its v1.0.0 release.
#What is a GGUF file
A GGUF file is a binary container for one model: a header, typed key-value metadata, a tensor table, padding, and tensor data. The ggml spec defines version 3, and a runtime needs no other file, because the architecture, tokenizer, and chat template sit in the metadata.
- Header: the bytes
GGUF, auint32version, auint64tensor count, and auint64key count, 24 bytes in all. - Metadata: a length-prefixed key, a type code, and a value, in 13 types from 8-bit integers to strings and arrays.
- Tensor info: a name of at most 64 bytes, the dimensions, a
ggml_typecode, and an offset into the data section. - Zero padding to the alignment, set by
general.alignmentor 32 by default. - Tensor data, every tensor at an aligned offset, so a runtime can memory-map the file and use tensors in place.
GGUF replaced the GGML, GGMF, and GGJT formats and was merged into llama.cpp on August 21, 2023. Version 3 added big-endian files, but no field marks one, so readers assume little-endian.
#How to read a GGUF header in Python
Reading a GGUF header takes about 70 lines of standard-library Python, because every field is a fixed-width little-endian integer or a length-prefixed string. The first script writes a tiny GGUF file with zeroed weights, following the spec and the field order of llama.cpp's gguf_writer.py, and the second parses it. Both ran on Python 3.15.1; neither read a real model. Dimensions are listed innermost first, so 256 rows of 64 values is [64, 256].
"""Write a tiny GGUF v3 file with zeroed weights, following the ggml GGUF spec. Standard library only."""
import struct
import sys
ALIGN = 32 # the spec's default when general.alignment is absent
UINT32, STRING, ARRAY = 4, 8, 9 # gguf_metadata_value_type codes
F32, Q8_0, Q4_K = 0, 8, 12 # ggml_type codes
BLOCK = {F32: (1, 4), Q8_0: (32, 34), Q4_K: (256, 144)} # (weights, bytes) per block
def gstr(s: str) -> bytes:
raw = s.encode("utf-8")
return struct.pack("<Q", len(raw)) + raw # uint64 length, no terminator
def kv(key: str, vtype: int, payload: bytes) -> bytes:
return gstr(key) + struct.pack("<I", vtype) + payload
def nbytes(dims: list[int], ggml_type: int) -> int:
weights, size = BLOCK[ggml_type]
assert dims[0] % weights == 0, "blocks run along the first (innermost) dimension"
count = 1
for d in dims:
count *= d
return count // weights * size
def pad(n: int) -> int:
return (ALIGN - n % ALIGN) % ALIGN
metadata = [
kv("general.architecture", STRING, gstr("llama")),
kv("general.name", STRING, gstr("tiny-demo")),
kv("general.file_type", UINT32, struct.pack("<I", 15)), # 15 = MOSTLY_Q4_K_M
kv("general.quantization_version", UINT32, struct.pack("<I", 2)),
kv("llama.block_count", UINT32, struct.pack("<I", 1)),
kv("tokenizer.ggml.tokens", ARRAY, struct.pack("<IQ", STRING, 3) + gstr("<s>") + gstr("hello") + gstr("world")),
]
tensors = [ # name, dims with the innermost first, ggml_type
("token_embd.weight", [256, 3], Q4_K),
("blk.0.attn_norm.weight", [256], F32),
("blk.0.ffn_down.weight", [64, 256], Q8_0),
]
infos, offset = b"", 0
for name, dims, ggml_type in tensors:
infos += gstr(name) + struct.pack(f"<I{len(dims)}QIQ", len(dims), *dims, ggml_type, offset)
size = nbytes(dims, ggml_type)
offset += size + pad(size) # each tensor starts on an aligned offset
head = b"GGUF" + struct.pack("<IQQ", 3, len(tensors), len(metadata)) + b"".join(metadata) + infos
with open(sys.argv[1], "wb") as f:
f.write(head + bytes(pad(len(head))))
for name, dims, ggml_type in tensors:
size = nbytes(dims, ggml_type)
f.write(bytes(size + pad(size)))The parser stops at the end of the tensor table, so on a multi-gigabyte model it reads only the first few megabytes.
"""Print a GGUF file's header, metadata, and tensor table without reading tensor data."""
import os
import struct
import sys
SCALAR = {0: "<B", 1: "<b", 2: "<H", 3: "<h", 4: "<I", 5: "<i", 6: "<f", 7: "<?", 10: "<Q", 11: "<q", 12: "<d"}
TYPES = { # ggml_type code: (name, weights per block, bytes per block), from gguf-py/gguf/constants.py
0: ("F32", 1, 4), 1: ("F16", 1, 2), 30: ("BF16", 1, 2), 2: ("Q4_0", 32, 18), 8: ("Q8_0", 32, 34),
10: ("Q2_K", 256, 84), 11: ("Q3_K", 256, 110), 12: ("Q4_K", 256, 144), 13: ("Q5_K", 256, 176),
14: ("Q6_K", 256, 210), 23: ("IQ4_XS", 256, 136), 39: ("MXFP4", 32, 17),
}
class Reader:
def __init__(self, f):
self.f = f
def take(self, fmt: str):
return struct.unpack(fmt, self.f.read(struct.calcsize(fmt)))[0]
def string(self) -> str:
return self.f.read(self.take("<Q")).decode("utf-8")
def value(self, vtype: int):
if vtype == 8:
return self.string()
if vtype == 9: # array: element type, element count, then the elements
item_type, count = self.take("<I"), self.take("<Q")
return [self.value(item_type) for _ in range(count)]
return self.take(SCALAR[vtype])
def peek(path: str) -> None:
with open(path, "rb") as f:
if f.read(4) != b"GGUF":
raise SystemExit("not a GGUF file")
r = Reader(f)
version, n_tensors, n_kv = r.take("<I"), r.take("<Q"), r.take("<Q")
print(f"GGUF v{version}: {n_tensors} tensors, {n_kv} metadata keys")
meta = {}
for _ in range(n_kv):
key = r.string()
meta[key] = r.value(r.take("<I"))
shown = meta[key] if not isinstance(meta[key], list) else f"[{len(meta[key])} items] {meta[key][:3]}"
print(f" {key} = {shown}")
infos = []
for _ in range(n_tensors):
name = r.string()
dims = [r.take("<Q") for _ in range(r.take("<I"))]
infos.append((name, dims, r.take("<I"), r.take("<Q")))
end_of_info = f.tell()
align = meta.get("general.alignment", 32)
data_start = end_of_info + (align - end_of_info % align) % align
print(f"tensor info ends at byte {end_of_info}; data starts at byte {data_start} (alignment {align})")
data_end = data_start
for name, dims, code, offset in infos:
type_name, weights, size = TYPES.get(code, (f"type {code}", 0, 0))
count = 1
for d in dims:
count *= d
nbytes = count // weights * size if weights else 0
data_end = max(data_end, data_start + offset + nbytes)
aligned = "aligned" if offset % align == 0 else "NOT ALIGNED"
print(f" {name:24s} {type_name:5s} dims={dims} offset={offset} bytes={nbytes} {aligned}")
print(f"tensor data ends at byte {data_end}; file is {os.path.getsize(path)} bytes")
if __name__ == "__main__":
peek(sys.argv[1])python3 make_tiny_gguf.py tiny.gguf
python3 gguf_peek.py tiny.ggufGGUF v3: 3 tensors, 6 metadata keys
general.architecture = llama
general.name = tiny-demo
general.file_type = 15
general.quantization_version = 2
llama.block_count = 1
tokenizer.ggml.tokens = [3 items] ['<s>', 'hello', 'world']
tensor info ends at byte 474; data starts at byte 480 (alignment 32)
token_embd.weight Q4_K dims=[256, 3] offset=0 bytes=432 aligned
blk.0.attn_norm.weight F32 dims=[256] offset=448 bytes=1024 aligned
blk.0.ffn_down.weight Q8_0 dims=[64, 256] offset=1472 bytes=17408 aligned
tensor data ends at byte 19360; file is 19360 bytesThe 432-byte embedding needs 16 bytes of padding, so the next tensor starts at offset 448, counted from the start of the data section. For real files, use gguf-dump from llama.cpp's gguf Python package or the Hugging Face Hub file viewer.
#What GGUF quantization names mean
A GGUF quantization name is either a tensor type, such as Q4_K, or a file type, such as Q4_K_M, that mixes tensor types. The digit is roughly the bits per packed value. _0 and _1 mark the original block formats, K the 256-weight super-block formats, and IQ the codebook-based i-quants. On K-quants, S, M, and L say how many tensors get promoted to a larger type.
| Type | Weights per block | Bytes per block | Bits per weight | Stores |
|---|---|---|---|---|
| Q8_0 | 32 | 34 | 8.5 | 8-bit values, FP16 scale |
| Q6_K | 256 | 210 | 6.5625 | 6-bit values, 8-bit scales |
| Q4_K | 256 | 144 | 4.5 | 4-bit values, 6-bit scales and mins |
| Q2_K | 256 | 84 | 2.625 | 2-bit values, 4-bit scales and mins |
| Q4_0 | 32 | 18 | 4.5 | 4-bit values, FP16 scale |
| IQ4_NL | 32 | 18 | 4.5 | 16-value non-linear table |
| IQ4_XS | 256 | 136 | 4.25 | Same table, 6-bit scales |
| IQ3_XXS | 256 | 98 | 3.0625 | 4 weights per grid entry |
| IQ2_XXS | 256 | 66 | 2.0625 | 8 weights per grid entry |
| IQ1_S | 256 | 50 | 1.5625 | 8 weights per grid entry |
| MXFP4 | 32 | 17 | 4.25 | FP4 values, 8-bit shared scale |
| NVFP4 | 64 | 36 | 4.5 | FP4 values, E4M3 scale per 16 |
Block sizes are GGML_QUANT_SIZES in gguf-py's constants, and the grids are in ggml-common.h. Figure 2 adds Q5_K and Q3_K. Ternary TQ1_0, TQ2_0, and the newer Q1_0 and Q2_0 also exist. Hugging Face's quant table says IQ4_NL uses 256-weight super-blocks, but the struct and its pull request use blocks of 32.
The MXFP4_MOE file type stores expert tensors in MXFP4 and other matrices in Q8_0, which suits a mixture-of-experts model.
#How K-quants group weights
K-quants store 256 weights as one super-block, split into 8 blocks of 32 or 16 blocks of 16. Each small block gets a scale, type-1 formats add a minimum so a weight is d * q + m, and those scales are quantized against FP16 factors stored once per super-block. Q4_K spends 128 bytes on 4-bit values and 16 on everything else.
In the k-quants pull request of June 2023, type-0 formats (Q3_K, Q6_K) use w = d * q and type-1 formats (Q2_K, Q4_K, Q5_K) add the minimum.
Q4_0 and Q4_K both cost 4.5 bits per weight, yet the grouping changes the error. Q4_K_S (4.37 GiB) measured a KL divergence of 0.043 on Llama 3 8B against 0.072 for Q4_0 (4.34 GiB).
I-quants, which arrived in January 2024, replace evenly spaced integers with lookup grids. IQ2_XXS stores each group of 8 weights as an index into a 256-entry grid, with signs packed by a trick borrowed from QuIP#. IQ4_NL and IQ4_XS use a fixed 16-value table with more levels near zero.
#Why Q4_K_M is bigger than 4.5 bits
Q4_K_M is a recipe, not a block format. llama-quantize starts every weight matrix at Q4_K, then stores the output matrix and half of the attn_v and ffn_down tensors as Q6_K, which comes to 4.8944 bits per weight and 4.58 GiB on Llama 3.1 8B.
The rules in llama-quant.cpp, for a dense Llama-style model:
- The output matrix becomes Q6_K in K-quant and legacy file types, and Q5_K in the lowest IQ types.
- In Q4_K_M and Q5_K_M,
attn_vandffn_downbecome Q6_K whenuse_more_bits()is true: the first and last eighth of layers, and every third layer between. - Q4_K_S promotes the first four
attn_vtensors and the first eighth offfn_downto Q5_K. - Q3_K_L, the only
Ltype, putsattn_v,attn_output, andffn_downat Q5_K. - Norms stay F32, and in K-quant files the token embedding keeps the base type.
Other models get other mixes under the same name. A 70B Llama stores its remaining Q4_K attn_v tensors as Q5_K, and an 8-expert MoE puts attn_v and attn_k at Q8_0.
Names such as Q4_K_L on Hugging Face are custom mixes built with flags such as --output-tensor-type. In bartowski's Llama 3.1 8B files, the 389,898,240-byte gap between Q4_K_L and Q4_K_M is exactly what moving token_embd and output to Q8_0 adds.
#How to calculate GGUF file size and memory
GGUF file size is the sum over tensors of elements divided by block size times bytes per block, plus the metadata. For a quick estimate, multiply parameters by the file type's effective bits per weight and divide by 8. Runtime memory adds the KV cache and compute buffers.
This calculator applies the rules above to the shapes in Llama 3.1 8B's config.json. It ran on Python 3.15.1.
"""Estimate GGUF file size and memory for a dense Llama-style model. Standard library only."""
# (weights per block, bytes per block), copied from GGML_QUANT_SIZES in gguf-py/gguf/constants.py
BLOCKS = {
"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), "Q8_0": (32, 34), "Q6_K": (256, 210),
"Q5_K": (256, 176), "Q4_K": (256, 144), "Q3_K": (256, 110), "Q2_K": (256, 84),
"IQ4_XS": (256, 136), "IQ3_XXS": (256, 98), "IQ2_XXS": (256, 66), "IQ1_S": (256, 50),
}
BASE = {"Q8_0": "Q8_0", "Q6_K": "Q6_K", "Q5_K_M": "Q5_K", "Q5_K_S": "Q5_K", "Q4_K_M": "Q4_K", "Q4_K_S": "Q4_K"}
def bpw(ggml_type: str) -> float:
weights, nbytes = BLOCKS[ggml_type]
return nbytes * 8 / weights
def tensor_bytes(elements: int, ggml_type: str) -> int:
weights, nbytes = BLOCKS[ggml_type]
return elements // weights * nbytes
def more_bits(i: int, n: int) -> bool:
# use_more_bits() in llama.cpp src/llama-quant.cpp: first and last eighth, then every third layer
return i < n // 8 or i >= 7 * n // 8 or (i - n // 8) % 3 == 2
def pick_type(ftype: str, name: str, i: int, n: int) -> str:
"""Tensor type for a dense Llama-style model under 70B, mirroring llama-quant.cpp."""
if name.endswith("norm") or name == "rope_freqs":
return "F32" # 1D tensors stay in F32
if name == "output":
return "Q8_0" if ftype == "Q8_0" else "Q6_K"
if name == "attn_v" and ftype in ("Q4_K_M", "Q5_K_M") and more_bits(i, n):
return "Q6_K"
if name == "attn_v" and ftype == "Q4_K_S" and i < 4:
return "Q5_K"
if name == "ffn_down" and ftype in ("Q4_K_M", "Q5_K_M") and more_bits(i, n):
return "Q6_K"
if name == "ffn_down" and ftype == "Q4_K_S" and i < n // 8:
return "Q5_K"
return BASE[ftype]
def llama_tensors(hidden, ffn, layers, vocab, kv_dim, rope_freqs=0):
"""(name, layer, elements) for every tensor in the GGUF."""
out = [("token_embd", -1, vocab * hidden), ("output", -1, vocab * hidden), ("output_norm", -1, hidden)]
if rope_freqs:
out.append(("rope_freqs", -1, rope_freqs))
for i in range(layers):
for name, elements in [("attn_q", hidden * hidden), ("attn_k", hidden * kv_dim), ("attn_v", hidden * kv_dim),
("attn_output", hidden * hidden), ("ffn_gate", hidden * ffn), ("ffn_up", hidden * ffn),
("ffn_down", ffn * hidden), ("attn_norm", hidden), ("ffn_norm", hidden)]:
out.append((name, i, elements))
return out
def kv_cache_gib(layers, kv_dim, tokens, cache_type="F16"):
# keys and values, per layer, per token
return 2 * layers * tokens * tensor_bytes(kv_dim, cache_type) / 2**30
if __name__ == "__main__":
# Llama 3.1 8B: hidden 4096, FFN 14336, 32 layers, vocab 128256, 8 KV heads x 128, untied output
tensors = llama_tensors(4096, 14336, 32, 128256, 8 * 128, rope_freqs=64)
params = sum(e for _, _, e in tensors)
print(f"Llama 3.1 8B in GGUF: {params:,} parameters")
for ftype in ["Q8_0", "Q6_K", "Q5_K_M", "Q5_K_S", "Q4_K_M", "Q4_K_S"]:
nbytes = sum(tensor_bytes(e, pick_type(ftype, name, i, 32)) for name, i, e in tensors)
print(f" {ftype:7s} {nbytes:>14,d} bytes {nbytes / 2**30:5.2f} GiB {nbytes * 8 / params:.4f} bpw")
print("Raw type bpw:", ", ".join(f"{t} {bpw(t):g}" for t in ["Q8_0", "Q6_K", "Q4_K", "IQ4_XS", "Q2_K"]))
print(f"Quick estimate, Llama 3.1 70B at 4.8944 bpw: {70_553_706_496 * 4.8944 / 8 / 2**30:.1f} GiB")
for cache in ["F16", "Q8_0"]:
print(f"KV cache, Llama 3.1 8B, 32,768 tokens, {cache}: {kv_cache_gib(32, 1024, 32768, cache):.2f} GiB")Llama 3.1 8B in GGUF: 8,030,261,312 parameters
Q8_0 8,532,934,912 bytes 7.95 GiB 8.5008 bpw
Q6_K 6,588,170,496 bytes 6.14 GiB 6.5633 bpw
Q5_K_M 5,725,151,488 bytes 5.33 GiB 5.7036 bpw
Q5_K_S 5,591,458,048 bytes 5.21 GiB 5.5704 bpw
Q4_K_M 4,912,898,304 bytes 4.58 GiB 4.8944 bpw
Q4_K_S 4,684,833,024 bytes 4.36 GiB 4.6672 bpw
Raw type bpw: Q8_0 8.5, Q6_K 6.5625, Q4_K 4.5, IQ4_XS 4.25, Q2_K 2.625
Quick estimate, Llama 3.1 70B at 4.8944 bpw: 40.2 GiB
KV cache, Llama 3.1 8B, 32,768 tokens, F16: 4.00 GiB
KV cache, Llama 3.1 8B, 32,768 tokens, Q8_0: 2.12 GiBThe parameter count includes a 64-value rope_freqs tensor, so it is 64 higher than the Hugging Face count in the open-weight models dataset. The table checks the output against llama.cpp's quantize README and bartowski's published files, read November 16, 2026.
| File type | Computed bpw | README bpw | Computed tensor bytes | Published file bytes |
|---|---|---|---|---|
| Q8_0 | 8.5008 | 8.5008 | 8,532,934,912 | 8,540,775,840 |
| Q6_K | 6.5633 | 6.5633 | 6,588,170,496 | 6,596,011,424 |
| Q5_K_M | 5.7036 | 5.7036 | 5,725,151,488 | 5,732,992,416 |
| Q5_K_S | 5.5704 | 5.5704 | 5,591,458,048 | 5,599,298,976 |
| Q4_K_M | 4.8944 | 4.8944 | 4,912,898,304 | 4,920,739,232 |
| Q4_K_S | 4.6672 | 4.6672 | 4,684,833,024 | 4,692,673,952 |
Every published file is exactly 7,840,928 bytes larger than its tensor data: the header, metadata, and tensor table, including a 128,256-token vocabulary. The quick 70B estimate of 40.2 GiB matches the README's 43.1 GB (40.1 GiB), so use it for models the script's dense-Llama rules do not cover.
At a 32,768-token context, Llama 3.1 8B at Q4_K_M needs 4.58 GiB of weights plus 4.00 GiB of 16-bit KV cache, or 2.12 GiB with -ctk q8_0 -ctv q8_0. llama.cpp logs the file size, KV buffer, and compute buffer at load, so add all three before you buy hardware.
#How much quality each GGUF quant type loses
On llama.cpp's own Llama 3 8B measurements, Q8_0 and Q6_K are close to FP16, Q5_K_M and Q4_K_M lose a little, and quality falls fast below about 3.5 bits per weight. These LLM quantization numbers come from the LLaMA 3 8b scoreboard, measured by llama.cpp contributors at revision f364eb6f (April 30, 2024) on one RTX 4090 against Wikitext-2. Imatrix rows used 10 million Wikitext tokens.
| Quant | Size (GiB) | Mean KL divergence | Perplexity increase |
|---|---|---|---|
| Q8_0 | 7.96 | 0.0014 | 0.003 |
| Q6_K | 6.14 | 0.0055 | 0.022 |
| Q5_K_M | 5.33 | 0.0108 | 0.057 |
| Q4_K_M | 4.58 | 0.0313 | 0.175 |
| Q4_K_M with imatrix | 4.58 | 0.0282 | 0.151 |
| IQ4_XS with imatrix | 4.14 | 0.0363 | 0.228 |
| Q4_0 | 4.34 | 0.0719 | 0.469 |
| IQ3_XXS with imatrix | 3.05 | 0.1836 | 1.227 |
| Q2_K with imatrix | 2.96 | 0.3322 | 2.416 |
| IQ2_XXS with imatrix | 2.24 | 0.8120 | 7.860 |
| IQ1_S with imatrix | 1.88 | 2.2546 | 54.463 |
KL divergence measures how far the next-token distribution moves from FP16's; 0 means identical. Without an imatrix, the top token matched FP16 on 97.7% of tokens for Q8_0, 91.9% for Q4_K_M, and 71.1% for Q2_K.
These results transfer poorly between models. Llama 3 8B lost more than Llama 2 7B at every type the README compares, with Q4_K_M at 0.0313 against 0.0127. The scoreboard dates from April 2024, so treat it as a guide to the order of types, not a guarantee for current builds.
For an 8B-class model on one machine, Q4_K_M is the smallest K-quant worth shipping for general use, and Q5_K_M (0.75 GiB more) or Q6_K (1.56 GiB more) are worth it when memory allows. Go below 3.5 bits only with IQ types and an importance matrix, and only when a bigger model at 2 or 3 bits beats a smaller one at 4 bits on your task.
#What an importance matrix does
An importance matrix (imatrix) records how strongly each input channel of each weight matrix is activated on calibration text, and llama-quantize uses it to weight rounding error so weights that meet large activations stay more accurate. It is optional for most types and required for IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, and the Q2_K tensors in a Q2_K_S file.
The pull request that introduced it in January 2024 keeps only the mean squared activation per input column and uses those values as weights in the error minimization. In the scoreboard, it lowered KL divergence for Q4_K_M from 0.0313 to 0.0282, for Q3_K_M from 0.1019 to 0.0844, and for Q2_K from 0.4451 to 0.3322, with no consistent gain from more calibration tokens.
That test used Wikitext for both calibration and evaluation. If your model serves code or another language, calibrate on samples of that traffic and measure on it.
#How to convert and quantize a model with llama.cpp
Convert the Hugging Face checkpoint to a 16-bit GGUF with convert_hf_to_gguf.py, optionally compute an importance matrix with llama-imatrix, quantize with llama-quantize, and check the result with llama-perplexity. None of these commands ran for this article; they come from the llama.cpp READMEs at commit a946eb5.
# 1. Hugging Face safetensors to a 16-bit GGUF (run inside a virtual environment)
python convert_hf_to_gguf.py ./Llama-3.1-8B --outtype bf16 --outfile llama-3.1-8b-bf16.gguf
# 2. Optional: importance matrix from your own calibration text
./build/bin/llama-imatrix -m llama-3.1-8b-bf16.gguf -f calibration.txt -o imatrix.gguf -ngl 99
# 3. Quantize
./build/bin/llama-quantize --imatrix imatrix.gguf llama-3.1-8b-bf16.gguf llama-3.1-8b-Q4_K_M.gguf Q4_K_M
# 4. Record 16-bit logits once, then compare the quantized file against them
./build/bin/llama-perplexity -m llama-3.1-8b-bf16.gguf -f wiki.test.raw --kl-divergence-base llama-3.1-8b.kld
./build/bin/llama-perplexity -m llama-3.1-8b-Q4_K_M.gguf --kl-divergence-base llama-3.1-8b.kld --kl-divergence--outtype auto keeps supported FP8 weights and otherwise picks the best 16-bit type. Quantize from that file, not an existing quant; the README warns that --allow-requantize can severely reduce quality. Budget disk for step 4: the perplexity README puts the Llama 3 logits file for Wikitext-2 at 37 GiB.
Vision and audio models need a second file, written by convert_hf_to_gguf.py --mmproj and usually kept at BF16 or Q8_0.
#GGUF vs GPTQ, AWQ, EXL3, and MLX
GGUF is a file format with its own quantizers, built for llama.cpp's CPU, Apple, and consumer-GPU backends. GPTQ and AWQ are LLM quantization methods whose checkpoints load in GPU servers such as vLLM, EXL3 is ExLlamaV3's CUDA format, and MLX has its own format for Apple silicon.
| Format | Method | Calibration | Runtime | Status, November 16, 2026 |
|---|---|---|---|---|
| GGUF | K, IQ, and FP4 block types | Optional imatrix; required for the lowest types | llama.cpp, Ollama, LM Studio; vLLM through an experimental plugin | llama.cpp v1.0.0 |
| GPTQ | Layer-wise error correction from approximate second-order information | Yes | vLLM, Transformers | AutoGPTQ unmaintained; GPTQModel active |
| AWQ | Scales salient channels found from activations | Yes | vLLM, Transformers | AutoAWQ deprecated, adopted by LLM Compressor |
| EXL3 | Streamlined QTIP at a target bitrate | Built in | ExLlamaV3 and TabbyAPI, CUDA only | ExLlamaV3 v1.6.7; ExLlamaV2 archived |
| MLX | Affine, 4-bit, groups of 64 by default; mxfp4, nvfp4, mxfp8 modes | Optional DWQ, AWQ, GPTQ | MLX LM on Apple silicon | mlx-lm v0.32.2 |
Transformers can open a GGUF file too, but its quantization docs say most GGUF models are dequantized to full precision as they load, which gives up the memory saving.
Choose by where the model runs. For a laptop, a Mac, or one desktop GPU through llama.cpp or Ollama, use GGUF. For a GPU server batching many users, use GPTQ, AWQ, FP8, or NVFP4 checkpoints in vLLM, since vLLM's GGUF docs call its GGUF support highly experimental; the vLLM, SGLang, and llama.cpp comparison covers that split. On Apple silicon, test your model in both MLX and llama.cpp. More serving guides are on the inference topic page.
#Questions
What does GGUF stand for?
The GGUF spec does not expand the name, and secondary sources disagree on one. The spec describes GGUF as the successor to the GGML, GGMF, and GGJT formats that earlier llama.cpp versions used. In practice a GGUF file is a single binary with weights, tokenizer, and metadata. The format is at version 3 and was merged into llama.cpp in August 2023.
Is Q4_K_M or Q5_K_M better?
Q5_K_M stays closer to the original model and Q4_K_M is smaller. On llama.cpp's Llama 3 8B measurements, Q5_K_M had a mean KL divergence of 0.011 at 5.33 GiB, and Q4_K_M had 0.031 at 4.58 GiB. Use Q5_K_M if it fits next to your KV cache. Otherwise Q4_K_M with an importance matrix beats dropping to a 3-bit type.
What is the difference between GGUF and safetensors?
Safetensors stores tensors behind a small JSON header, and a Hugging Face checkpoint keeps its config, tokenizer, and chat template in separate files. GGUF puts tensors, tokenizer, hyperparameters, and chat template in one file and adds ggml's block-quantized types. Convert safetensors to GGUF with llama.cpp's convert_hf_to_gguf.py, then quantize the result with llama-quantize.
How much RAM do I need to run a GGUF model?
Plan for the file size, plus the KV cache for your context, plus compute buffers. Llama 3.1 8B at Q4_K_M is 4.58 GiB, and a 32,768-token context adds 4 GiB of 16-bit KV cache or 2.12 GiB with a Q8_0 cache. llama.cpp prints the file size, the KV buffer, and the compute buffer when it loads a model, so read those lines on your machine.
Can GGUF models run on a GPU?
Yes. llama.cpp runs GGUF files on CUDA, Metal, Vulkan, HIP, SYCL, and other backends, and its -ngl flag sets how many layers go to the GPU, so a model larger than VRAM can split between GPU and CPU. vLLM can also load GGUF, but its docs call that support highly experimental, and it needs the separate vllm-gguf-plugin package.
What are IQ quants in GGUF?
IQ types, or i-quants, store weights as indexes into fixed grids or a 16-value non-linear table instead of evenly spaced integers. They cover 1.56 to 4.5 bits per weight. IQ4_XS and IQ4_NL work without calibration, but llama-quantize refuses to write IQ1_S, IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, or IQ3_XXS tensors without an importance matrix.