Sub topic 4
Reading GGUF Files and Names like Q4_K_M
This chapter assumes you know what quantisation does to weights (the previous chapter) and can do byte and bit arithmetic. After it, you should be able to read a model file name, say what is inside the file, and predict its size.
What a GGUF file is
GGUF is the single-file model format used by llama.cpp and the tools built on it, such as Ollama and LM Studio. One file holds everything needed to run the model:
- Header. The magic bytes
GGUF, a format version, a tensor count, and a metadata entry count. - Metadata. Key-value pairs. They include the architecture (for example
llama), layer count, attention head counts, the trained context length, the tokenizer vocabulary, and often the chat template. - Tensor directory. For each tensor: its name, shape, quantisation type, and offset into the data section.
- Tensor data. The weights, aligned so the file can be memory-mapped (mapped into the address space and loaded on demand instead of copied).
Because the metadata describes the model's shape, a loader needs no separate config file. It also lets you do the memory arithmetic from the earlier chapters without running the model. The layer count, KV head count, and head size you need for KV cache estimates are all in the metadata.
You can read the header with a few lines of Python. This script prints the version, the number of tensors, and the number of metadata entries:
import struct
import sys
def read_gguf_header(path):
with open(path, "rb") as f:
if f.read(4) != b"GGUF":
raise ValueError("not a GGUF file")
(version,) = struct.unpack("<I", f.read(4))
n_tensors, n_kv = struct.unpack("<QQ", f.read(16))
return version, n_tensors, n_kv
if __name__ == "__main__":
version, n_tensors, n_kv = read_gguf_header(sys.argv[1])
print(f"GGUF v{version}: {n_tensors} tensors, {n_kv} metadata entries")This reads only the first 24 bytes. To see the full metadata and the type of every tensor, install the gguf package and dump the file:
pip install gguf
gguf-dump model-Q4_K_M.ggufThe same gguf package can also read tensors and write GGUF files from Python.
Decoding a quantisation name
Take Q4_K_M. It has three parts:
- Q4 is the nominal bit width of most weights. It is nominal because the real average is higher, as the next section explains.
- K marks the k-quant family. Weights are grouped into super-blocks of 256, split into smaller sub-blocks. Each sub-block has its own scale, and the scales are themselves stored in low precision.
- M is the mix. The suffixes S (small), M (medium) and L (large) say how many sensitive tensors get more bits. In the M mix, some of the attention value tensors and feed-forward down-projection tensors use a higher-precision type, such as Q6_K. S keeps more tensors at the base width and gives a smaller file. L gives more tensors the higher width and gives a larger file.
Legacy names, k-quants and i-quants
| Family | Examples | Notes |
|---|---|---|
| Unquantised | F32, F16, BF16 | Full or half precision. Used as the source for quantising. |
| Legacy | Q4_0, Q4_1, Q5_0, Q8_0 | Blocks of 32 weights with one scale each. Simple and fast. Q8_0 is still common as a near-lossless choice. |
| K-quants | Q2_K, Q3_K_M, Q4_K_M, Q5_K_M, Q6_K | The usual default. Better quality per bit than the legacy types. |
| I-quants | IQ2_XS, IQ3_XXS, IQ4_XS | Use lookup tables and usually an importance matrix. Best quality at very low bit widths, but often slower on CPUs. |
For general use, Q4KM is the usual starting point, with Q5KM and Q6_K as quality upgrades if memory allows.
From the name to a file size
Block scales cost bits too. A legacy Q40 block stores 32 four-bit weights plus one 16-bit scale: 32 × 4 + 16 = 144 bits for 32 weights, or 4.5 bits per weight. Q80 works out the same way to 8.5. K-quants carry extra per-sub-block data, and the M and L mixes add higher-precision tensors. That is why the effective figures sit above the number in the name.
These values are approximate averages for typical 7B to 70B models:
| Type | Bits per weight | File size for 8B parameters |
|---|---|---|
| Q2_K | about 2.6 | about 2.6 GB |
| Q3_K_M | about 3.9 | about 3.9 GB |
| Q4_K_M | about 4.85 | about 4.9 GB |
| Q5_K_M | about 5.7 | about 5.7 GB |
| Q6_K | about 6.6 | about 6.6 GB |
| Q8_0 | 8.5 | 8.5 GB |
| F16 | 16 | 16 GB |
Here GB means 10^9 bytes, which is how file sizes are usually shown. The memory formula from the weights chapter uses GiB, so convert before comparing.
You can also work backwards from a file you already have. This shows how far the real average is from the nominal width:
def effective_bits_per_weight(file_bytes, params):
return file_bytes * 8 / params
# A 4.9 GB file for a model with 8.0 billion parameters.
print(f"{effective_bits_per_weight(4.9e9, 8.0e9):.2f} bits per weight")The result is about 4.9, not 4.0. The file also holds the vocabulary and metadata, but these are small next to the weights.
Gotchas
- The file is not uniform. Different tensors use different types. The token embedding and output tensors are often kept at a higher width than the bulk of the layers. A dump of a Q4KM file will show several types, and that is normal.
- Names are not a guarantee of identical files. Two uploads both named Q4KM can differ in size and quality. They may be built from different source weights, and one may have used an importance matrix while the other did not. Compare file sizes and read the model card.
- The file size is not total memory. Weights are roughly the file size. You still have to add the KV cache and runtime overhead, as covered in the earlier chapters. The context length in the metadata is the maximum the model was trained for. It is not a recommendation, and allocating all of it can use far more memory than the weights.
- Split files. Large models are often shipped as
name-00001-of-00003.ggufand so on. Download every part into one directory and point the tool at the first part. - Old formats. Files with the
.ggmlextension, or an olderggjtformat, are not GGUF, and current llama.cpp will not load them. - Re-quantising loses quality. Quantise from an F16 or BF16 source. Quantising an already-quantised file stacks the errors, and
llama-quantizerefuses unless you pass--allow-requantize. - Lower is not always faster on every device. Fewer bits mean fewer bytes read per token, which usually helps generation speed. But some types, notably the i-quants, need more compute to decode, which can erase the gain on a CPU.
Making your own quantised file
If you have an F16 GGUF, llama-quantize converts it to another type in one step:
llama-quantize model-F16.gguf model-Q4_K_M.gguf Q4_K_MMost users download ready-made files. Quantising yourself helps when you need a type that nobody has published, or when you want an importance matrix computed from data close to your use case.
Exercise
A model has 13 billion parameters. You find a Q5KM file for it. Using about 5.7 effective bits per weight, estimate the file size in GB (10^9 bytes). Then name two reasons the memory needed at run time will be larger than that number.
Show answer
13 × 10^9 × 5.7 / 8 ≈ 9.3 × 10^9 bytes, so about 9.3 GB. Run-time memory is larger because the KV cache grows with the context length you choose, and because the runtime needs overhead for compute buffers. Mixed tensor types also mean the exact file size can differ a little from the estimate, so check the real size on disk.