Single-file, mmap-friendly container used by ggml / llama.cpp / whisper.cpp and derivatives. Fixed header, typed key/value metadata section, tensor-info table, zero-padding to an alignment boundary, then a tensor data blob. Tensors may use plain element types (F32/F16/BF16/I8..I64/F64) or ggml block-quantized types (Q4_0, Q8_0, K-quants, IQ-quants, TQ, MXFP4, NVFP4, Q1_0, Q2_0). Dimension order is ggml order: ne[0] is the innermost (fastest-varying, contiguous) dimension, i.e. the REVERSE of numpy/PyTorch shape order.
What it is
many tensors
Byte order
undeclared default little
Dimension order
innermost first (ggml ne[])
Compression
none
Metadata
typed kv
Loading
does not execute code
How to read it
header (incl. all metadata KV) | tensor_info[tensor_count] | zero padding to ALIGNMENT (relative to the GGUF magic) | tensor_data. Every field is packed (no implicit alignment) except the padding before tensor_data and between tensors. ALIGNMENT is only known after parsing metadata (general.alignment).
header
gguf_header
tensor_infos
gguf_tensor_info[header.tensor_count]
padding
u8[align_up(pos, ALIGNMENT) - pos]
ggml only seeks to the aligned offset when tensor_count > 0
tensor_data
bytes
each tensor at data_start + info.offset; gap between tensors zero-padded to ALIGNMENT
0 4 8 16 24
+--------+--------+----------------+----------------+-----------------------------+
| "GGUF" | ver u32| tensor_cnt u64 | kv_count u64 | kv[0] kv[1] ... (packed) |
+--------+--------+----------------+----------------+-----------------------------+
| tensor_info[0] ... tensor_info[n-1] (packed) |
+----------------------------------------------------------------------------------+
| 0x00 padding up to multiple of ALIGNMENT (relative to the GGUF magic) |
+----------------------------------------------------------------------------------+ <- data_start
| tensor 0 data | pad | tensor 1 data | pad | ... |
+----------------------------------------------------------------------------------+
row-major (C) in canonical shape terms; no strides
alignment
ALIGNMENT = metadata general.alignment (u32) if present, else 32. start of tensor_data section (relative to the start of the GGUF data, i.e. the magic; equal to the file offset for a standalone .gguf file) and every tensor's offset within tensor_data. general.alignment; spec says multiple of 8; ggml requires power of two (>0)
gguf_string
len
u64
byte length (u32 in v1)
data
utf8
UTF-8, not NUL-terminated. size len
gguf_array
elem_type
gguf_metadata_value_type
len
u64
number of ELEMENTS, not bytes (u32 in v1)
elems
gguf_value(elem_type)[len]
packed, no alignment, no per-element type tags
gguf_value
Spec allows nested arrays (ARRAY of ARRAY). The ggml C reader (gguf.cpp) REJECTS nested arrays ("invalid GGUF type 9"); gguf-py reads and writes them (verified-empirical). Writers targeting llama.cpp must not nest.
UINT8
u8
INT8
i8
UINT16
u16
INT16
i16
UINT32
u32
INT32
i32
FLOAT32
f32
BOOL
bool8
STRING
gguf_string
ARRAY
gguf_array
UINT64
u64
INT64
i64
FLOAT64
f64
gguf_metadata_kv
key
gguf_string
value_type
gguf_metadata_value_type
value
gguf_value(value_type)
gguf_header
magic
u8[4]
constant GGUF
version
u32
tensor_count
u64
u32 in v1
metadata_kv_count
u64
u32 in v1
metadata_kv
gguf_metadata_kv[metadata_kv_count]
gguf_tensor_info
name
gguf_string
< 64 bytes for ggml (GGML_MAX_NAME=64 incl. NUL)
n_dimensions
u32
<= 4 in ggml
dimensions
u64[n_dimensions]
ggml ne[]; ne[0] innermost (u32 in v1)
type
ggml_type
offset
u64
byte offset relative to start of tensor_data; multiple of ALIGNMENT
Reader
The procedure that finds each tensor's bytes.
read
pseudo-python
def read_gguf(f):
gguf_start = f.tell() # file position of the magic
if f.read(4) != b"GGUF": raise Invalid("magic")
E = "<" # byte order
version = unpack(E + "I", f.read(4))
if version & 0xFFFF == 0: # looks byte-swapped -> big-endian file (gguf-py; ggml refuses, GGUF-002i)
E = ">"; version = byteswap32(version)
if version == 1: raise Unsupported("GGUF v1 (u32 counts); not loaded")
if version not in (2, 3): raise Unsupported(version)
W = "Q" # v2/v3 counts, lengths, and dims are u64
def rd(fmt): return unpack(E + fmt, f.read(calcsize(fmt)))
def rd_str(): n = rd(W); return f.read(n).decode("utf-8")
SCALAR = {0:"B",1:"b",2:"H",3:"h",4:"I",5:"i",6:"f",7:"?",10:"Q",11:"q",12:"d"}
def rd_val(t):
if t in SCALAR: return rd(SCALAR[t]) # BOOL: validate byte in {0,1}
if t == 8: return rd_str()
if t == 9:
et = rd("I"); n = rd(W)
if et in SCALAR: return read_packed_array(f, E + SCALAR[et], n) # bulk read
return [rd_val(et) for _ in range(n)] # strings (or nested arrays)
raise Invalid("value type %d" % t)
n_tensors = rd(W); n_kv = rd(W)
meta = {}
for _ in range(n_kv):
k = rd_str(); t = rd("I")
if k in meta: raise Invalid("duplicate key")
meta[k] = TypedValue(t, rd_val(t))
A = meta["general.alignment"].value if "general.alignment" in meta else 32
infos = []
for _ in range(n_tensors):
name = rd_str(); nd = rd("I")
ne = [rd(W) for _ in range(nd)]
gt = rd("I"); off = rd("Q")
infos.append((name, ne, gt, off))
data_start = gguf_start + align_up(f.tell() - gguf_start, A)
tensors = []
for name, ne, gt, off in infos:
be, bb = BLOCK[gt] # (block_elements, block_bytes) from dtypes[]
assert ne[0] % be == 0 and off % A == 0
nbytes = prod(ne) // be * bb
tensors.append(Tensor(name=name, dtype=CANON[gt], shape=list(reversed(ne)),
offset=data_start + off, nbytes=nbytes, byte_order=E))
for t in tensors: # GGUF-023 convention, optional
o = meta.pop(t.name + ".orig_shape", None)
if o is not None and prod(o.value) == prod(t.shape): t.shape = list(o.value)
return meta, tensors # data = mmap(file)[offset:offset+nbytes]
split_shards
gguf-split.cpp at llama.cpp 23deec025587. A tensor is never cut across files. Padding used for the size budget and for the bytes written after each tensor is GGUF_DEFAULT_ALIGNMENT (32 in ggml include/gguf.h at 3612c0af93f2), not general.alignment. M and G are decimal (1000 and 1000**3). The default mode is --split-max-tensors 128.
pseudo-python
def split_gguf(tensors, meta, mode, limit, no_tensor_first_split=False):
# mode "tensors" (default, limit 128) or "size" (limit in bytes; "128M"/"4G" are decimal)
shards = [{"tensors": [], "meta": dict(meta)}] # KV only on shard 0
if no_tensor_first_split:
shards.append({"tensors": [], "meta": {}}) # tensors start on shard 1
cur = shards[-1]
plan_bytes = 0
for i, t in enumerate(tensors):
padded = align_up(nbytes(t), 32) # GGUF_DEFAULT_ALIGNMENT, not general.alignment
need = (mode == "size" and plan_bytes + padded > limit) or (mode == "tensors" and i > 0 and i % limit == 0)
if need:
if not cur["tensors"]:
raise Invalid("a split would contain 0 tensors") # one tensor larger than --split-max-size
cur = {"tensors": [], "meta": {}}
shards.append(cur)
plan_bytes = 0
cur["tensors"].append(t) # whole tensor; never sliced
plan_bytes += padded
n = len(shards)
total = len(tensors)
for i, s in enumerate(shards):
s["meta"]["split.no"] = i # u16
s["meta"]["split.count"] = n # u16, filled once n is known
s["meta"]["split.tensors.count"] = total # i32, every shard
s["filename"] = "%s-%05d-of-%05d.gguf" % (prefix, i + 1, n)
return shards
Number formats
The name in the file, and the canonical dtype it maps to.
In the file
Code
Canonical
Bits
F32
0
float32
32
F16
1
float16
16
BF16
30
bfloat16
16
F64
28
float64
64
I8
24
int8
8
I16
25
int16
16
I32
26
int32
32
I64
27
int64
64
Q4_2removed
4
none
—
type_size 0 in ggml; reject
Q4_3removed
5
none
—
type_size 0 in ggml; reject
Q4_0_4_4removed
31
none
—
interleaved Q4_0 for ARM; removed from files
Q4_0_4_8removed
32
none
—
Q4_0_8_8removed
33
none
—
IQ4_NL_4_4removed
36
none
—
IQ4_NL_4_8removed
37
none
—
IQ4_NL_8_8removed
38
none
—
Quantized block types
The name in the file, the canonical block type, and the bytes one block occupies.
def dequant(b):
d = f16(b, 0); m = f16(b, 2); qs = b[4:20]; y = [0.0] * 32
for j in range(16):
y[j] = (qs[j] & 0x0F) * d + m
y[j + 16] = (qs[j] >> 4) * d + m
return y
Activation-side format for dot products; ggml has no dequantize_row_q8_1 and gguf-py raises NotImplementedError. Not expected in files. Dequant below (x = qs*d) is inferred. HISTORY: older ggml used f32 d and s (40-byte block); gguf-py <= 0.19.0 still lists (32, 40). Current ggml struct is 36 bytes.
pseudo-python
def dequant(b):
d = f16(b, 0)
return [i8(b, 4 + j) * d for j in range(32)]
16 sub-blocks of 16. scales[i]: low nibble = scale, high nibble = min. x = d*sc*q - dmin*m. NOTE d/dmin are at the END.
pseudo-python
def dequant(b):
sc = b[0:16]; qs = b[16:80]; d = f16(b, 80); dmin = f16(b, 82)
y = []; i = 0; q = 0
for n in range(2): # two halves of 128
shift = 0
for j in range(4):
s = sc[i]; i += 1
dl = d * (s & 0xF); ml = dmin * (s >> 4)
for l in range(16): y.append(dl * ((qs[q + l] >> shift) & 3) - ml)
s = sc[i]; i += 1
dl = d * (s & 0xF); ml = dmin * (s >> 4)
for l in range(16): y.append(dl * ((qs[q + l + 16] >> shift) & 3) - ml)
shift += 2
q += 32
return y
16 sub-blocks of 16, 6-bit scales (biased by 32) packed in 12 bytes. q = low 2 bits from qs, minus 4 if the matching hmask bit is CLEAR. x = d * (scale - 32) * q.
pseudo-python
def dequant(b):
hm = b[0:32]; qs = b[32:96]; d = f16(b, 108)
a = [u32(b, 96), u32(b, 100), u32(b, 104), 0]
km1 = 0x03030303; km2 = 0x0F0F0F0F; tmp = a[2]
a[2] = ((a[0] >> 4) & km2) | (((tmp >> 4) & km1) << 4)
a[3] = ((a[1] >> 4) & km2) | (((tmp >> 6) & km1) << 4)
a[0] = (a[0] & km2) | (((tmp >> 0) & km1) << 4)
a[1] = (a[1] & km2) | (((tmp >> 2) & km1) << 4)
scales = [s - 256 if s > 127 else s for s in b"".join(v.to_bytes(4, "little") for v in a)]
y = []; i = 0; q = 0; m = 1
for n in range(2):
shift = 0
for j in range(4):
dl = d * (scales[i] - 32); i += 1
for l in range(16): y.append(dl * (((qs[q + l] >> shift) & 3) - (0 if hm[l] & m else 4)))
dl = d * (scales[i] - 32); i += 1
for l in range(16): y.append(dl * (((qs[q + l + 16] >> shift) & 3) - (0 if hm[l + 16] & m else 4)))
shift += 2; m <<= 1
q += 32
return y
8 sub-blocks of 32; 6-bit scale + 6-bit min per sub-block packed in 12 bytes (get_scale_min_k4). Each 32-byte qs chunk holds two sub-blocks: low nibbles = first, high nibbles = second. x = d*sc*q - dmin*m.
pseudo-python
def scale_min_k4(j, q): # q = 12 scale bytes
if j < 4:
return q[j] & 63, q[j + 4] & 63
return (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4), (q[j + 4] >> 4) | ((q[j] >> 6) << 4)
def dequant(b):
d = f16(b, 0); dmin = f16(b, 2); sc = b[4:16]; qs = b[16:144]
y = []; q = 0
for j in range(4):
s1, m1 = scale_min_k4(2 * j, sc); s2, m2 = scale_min_k4(2 * j + 1, sc)
d1 = d * s1; mm1 = dmin * m1; d2 = d * s2; mm2 = dmin * m2
for l in range(32): y.append(d1 * (qs[q + l] & 0xF) - mm1)
for l in range(32): y.append(d2 * (qs[q + l] >> 4) - mm2)
q += 32
return y
Per 32 elements: 8 bytes = u32 a0 (4 x 8-bit indices into iq2xxs_grid, 8 values each) + u32 a1 (4 x 7-bit indices into ksigns_iq2xs, top 4 bits = sub-block scale).
pseudo-python
def dequant(b):
d = f16(b, 0); y = []
for ib in range(8):
a0 = u32(b, 2 + 8 * ib); a1 = u32(b, 6 + 8 * ib)
db = d * (0.5 + (a1 >> 28)) * 0.25
for l in range(4):
g = grid("iq2xxs_grid", (a0 >> (8 * l)) & 0xFF)
s = T["ksigns_iq2xs"][(a1 >> (7 * l)) & 127]
for j in range(8):
y.append(db * g[j] * (-1.0 if s & T["kmask_iq2xs"][j] else 1.0))
return y
qs[k]: low 9 bits = iq2xs_grid index, high 7 bits = ksigns index. scales: two 4-bit scales per 32 elements.
pseudo-python
def dequant(b):
d = f16(b, 0); sc = b[66:74]; y = []
for ib in range(8):
db = (d * (0.5 + (sc[ib] & 0xF)) * 0.25, d * (0.5 + (sc[ib] >> 4)) * 0.25)
for l in range(4):
v = u16(b, 2 + 2 * (4 * ib + l))
g = grid("iq2xs_grid", v & 511); s = T["ksigns_iq2xs"][v >> 9]
for j in range(8):
y.append(db[l // 2] * g[j] * (-1.0 if s & T["kmask_iq2xs"][j] else 1.0))
return y
def dequant(b):
d = f16(b, 0); qs = b[2:66]; y = []
for ib in range(8):
a = u32(b, 66 + 4 * ib)
db = d * (0.5 + (a >> 28)) * 0.5
for l in range(4):
s = T["ksigns_iq2xs"][(a >> (7 * l)) & 127]
g1 = grid("iq3xxs_grid", qs[8 * ib + 2 * l]); g2 = grid("iq3xxs_grid", qs[8 * ib + 2 * l + 1])
for j in range(4):
y.append(db * g1[j] * (-1.0 if s & T["kmask_iq2xs"][j] else 1.0))
for j in range(4):
y.append(db * g2[j] * (-1.0 if s & T["kmask_iq2xs"][j + 4] else 1.0))
return y
Ternary {-1,0,1}*d, base-3 packed 5 trits/byte (qs) and 4 trits/byte (qh). Note the u8 wrap-around in q*pow3.
pseudo-python
def dequant(b):
qs = b[0:48]; qh = b[48:52]; d = f16(b, 52); p3 = [1, 3, 9, 27, 81, 243]; y = []
def trit(byte, n):
q = (byte * p3[n]) & 0xFF
return ((q * 3) >> 8) - 1
for n in range(5):
for m in range(32): y.append(trit(qs[m], n) * d)
for n in range(5):
for m in range(16): y.append(trit(qs[32 + m], n) * d)
for n in range(4):
for j in range(4): y.append(trit(qh[j], n) * d)
return y
def dequant(b):
qs = b[0:64]; d = f16(b, 64); y = []
for j in (0, 32):
for l in range(4):
for m in range(32):
y.append((((qs[j + m] >> (2 * l)) & 3) - 1) * d)
return y
OCP MX FP4: E2M1 codes with a shared E8M0 exponent. ggml stores kvalues_fp4 as DOUBLED E2M1 values [0,1,2,3,4,6,8,12,0,-1,-2,-3,-4,-6,-8,-12] and compensates with e8m0_half(e) = 2^(e-128). Element order: low nibbles = elements 0..15, high nibbles = 16..31 (ggml order). Packed-MXFP4 elsewhere (e.g. OCP/PyTorch float4_e2m1fn_x2, safetensors F4) pairs CONSECUTIVE elements in a byte; scales usually live in a separate tensor -> both data reorder and scale merge are needed when converting.
pseudo-python
def dequant(b):
d = e8m0_half(b[0]); kv = T["kvalues_fp4"]; y = [0.0] * 32
for j in range(16):
y[j] = kv[b[1 + j] & 0xF] * d; y[j + 16] = kv[b[1 + j] >> 4] * d
return y
NVFP4
40
ggml_nvfp4
4.5
64 × 36 B
struct block_nvfp4 { u8 d[4]; u8 qs[32]; } // d@0 (4 x UE4M3, one per 16 elements) qs@4
Recent addition (ggml_type 40). Four 16-element sub-blocks; within sub-block s, qs[8s+j] low nibble = element 16s+j, high nibble = element 16s+j+8. NVIDIA's per-tensor FP32 second-level scale is not part of the block. The converter writes it as a separate F32 tensor <tensor>.scale, plus <tensor>.input_scale, and skips both when the value is 1.0. A per-expert vector uses the same names and is skipped when every entry is 1.0.
pseudo-python
def dequant(b):
kv = T["kvalues_fp4"]; y = [0.0] * 64
for s in range(4):
dd = ue4m3_half(b[s])
for j in range(8):
q = b[4 + 8 * s + j]
y[16 * s + j] = kv[q & 0xF] * dd; y[16 * s + j + 8] = kv[q >> 4] * dd
return y
2-bit codes LSB-first, 4 per byte: 00=-1, 01=0, 10=+1, 11=+2 (x = (q-1)*d). Not in gguf-py 0.19.0; matches ggml's dequantize_row_q2_0 in ggml-quants.c.
pseudo-python
def dequant(b):
d = f16(b, 0)
return [(((b[2 + j // 4] >> ((j % 4) * 2)) & 3) - 1) * d for j in range(64)]
dequantize_tensor
Convert any GGUF tensor to float32 in canonical (row-major) shape using each block type's dequant above
pseudo-python
def dequantize_tensor(raw, gt, ne):
be, bb = BLOCK[gt]
if be == 1: return frombuffer(raw, ELEMENT_DTYPE[gt]).astype(float32).reshape(ne[::-1])
out = []
for i in range(0, len(raw), bb):
out.extend(DEQUANT[gt](raw[i:i + bb])) # blocks run along ne[0]
return array(out, float32).reshape(ne[::-1])
helpers
text
f16(b, o) IEEE binary16 little-endian at byte offset o -> float
f32(b, o) IEEE binary32 LE -> float
u16(b, o), u32(b, o) unsigned LE ints; i8(b, o) signed byte
T[name] tables/ggml-lookup-tables.json -> tables[name].values
grid(name, idx) tables[name].bytes_le[idx] (list of 8 or 4 ints; int8 for iq1s_grid, uint8 otherwise)
e8m0_half(x) bits = (0x00200000 << x) if x < 2 else ((x - 1) << 23); float32_from_bits(bits) # = 2^(x-128)
ue4m3_half(x) 0 if x in (0, 0x7F) else (man*2^-9 if exp == 0 else (1 + man/8)*2^(exp-7)) * 0.5, exp=(x>>3)&15, man=x&7
pack_f16(v) 2 bytes LE (round-to-nearest-even)
int_trunc_i8(v) C (int8_t) cast: truncate toward zero
round_half_away C roundf
NB: ggml computes in float32; Python floats are float64 -> results may differ by ~1 ulp of float32.
Reject the file when
Listed in the spec's order. Only rules marked MUST that reject the file are shown. The other IDs are warnings or implementation limits.
Rule
Must hold
Error
GGUF-001
magic bytes == 'GGUF'
GGUF-002
After the endian heuristic, version 2 and 3 are readable. Version 1 is detected and rejected (historical; u32 widths, no reader). Version > 3 is unsupported.
if version & 0xFFFF == 0: retry as big-endian; reject version == 1 and version not in (2, 3)
GGUF-003
every count/length bounded by remaining file size before allocating (ggml: n <= SIZE_MAX/sizeof(elem))
GGUF-004
metadata value_type and array elem_type in 0..12
GGUF-006
no duplicate metadata keys; no duplicate tensor names
GGUF-007
BOOL values are 0 or 1
GGUF-008
general.alignment, if present, is UINT32 and a non-zero power of two. Another integer type (UINT64, INT32, ...) is rejected, not widened: general.alignment is not one of the type-flexible keys of GGUF-Q3. An invalid value (0, not a power of two) is rejected; there is no fallback to 32. gguf.cpp at 3612c0af93f2 logs an error and returns no context in both cases.
GGUF-018
Do not write n_dimensions 0 for a scalar. Store n_dimensions 1 and dimensions [1], and record that the canonical shape was []. The reader returns [1].
GGUF-011
type < GGML_TYPE_COUNT and block size/type size non-zero (not a removed type)
GGUF-012
Reader and writer. ne[0] % block_elements(type) == 0. gguf.cpp checks it on read.
GGUF-013
Reader and writer. offset % ALIGNMENT == 0. gguf.cpp enforces it on read through the exact offset check of GGUF-014, which only produces aligned offsets.
GGUF-015
Reader and writer. data_start + offset + nbytes <= file_size, checked before mapping or reading the span. A reader may otherwise trust the offsets (GGUF-014 is IMPL) and report each tensor's span; a tensor need not fill the gap to the next offset beyond the padding.
GGUF-021
Reader. A file with tensor_count 0 is valid, and may end right after the last KV with no padding: gguf.cpp seeks to the aligned data section only when n_tensors > 0. A writer may emit zero-tensor files (metadata-only or vocabulary-only). ggml's own writer still pads to ALIGNMENT after the KV section. Test file: edge/gguf-v3-no-tensors.gguf.
Example
Example file. Shapes are outermost first: the file stores that list reversed, fastest dimension first. w_q8_0 is the Q8_0 blocks for w_f32. e_bf16 is in this file. s_f32 is not: a scalar is stored as one dimension of length 1, and that stored shape must not replace the canonical shape [].