moongguf

Guide · ten steps

The library, end to end.

A file built, read, questioned, streamed and refused. Every block below compiles against this repository, and the line under each one is what it prints.

01

Install

One package, no dependencies of its own. moon add writes it into moon.mod; the import below goes in moon.pkg for the package that uses it.

shell
moon add moonbitstack/moongguf
moon.pkg
import {
  "moonbitstack/moongguf",
}
The library never opens a file. Whatever read the bytes — a disk, a range request, a mapped buffer — hands them over, and everything below works on Bytes and BytesView.
02

Build a file

Start from an empty version 3 file, put metadata in by key and value, and hand each tensor its bytes. encode lays the whole thing out: header, table, index, then the data on the alignment the file records.

moonbitmain.mbt
let file = @moongguf.File::new()
file.set("general.architecture", @moongguf.Value::String("llama"))
file.set("llama.block_count", @moongguf.Value::UInt32(32))
file.set(
  "tokenizer.ggml.tokens",
  @moongguf.Value::Array(@moongguf.ValueType::String, [
    @moongguf.Value::String("a"),
    @moongguf.Value::String("b"),
  ]),
)
file.add(
  @moongguf.Tensor::new(
    name="token_embd.weight",
    kind=@moongguf.Q4_0,
    dims=[4096UL, 2UL],
  ),
  Bytes::make(4608, b'\x00')[:],
)
let bytes = file.encode()
println("\{bytes.length()} bytes")
4832 bytes
The two dimensions are ggml's: a row of 4096 values, two rows of them. q4_0 packs 32 values into 18 bytes, so a row is 128 whole blocks and the tensor is 2304 × 2 bytes.
03

Read it back

parse reads the header, the metadata table and the tensor index, and checks that the index's offsets meet the way the data section expects. The weights are not touched.

moonbitmain.mbt
let read = @moongguf.File::parse(bytes[:])
println("version \{read.version().code()}")
println("tensors \{read.tensor_count()}, pairs \{read.meta().count()}")
version 3 tensors 1, pairs 3
04

The metadata table

A value comes back as the kind the file says it is. The getters that name a type — text, uint, int, float, flag, items — return None for a key that is absent or holds another kind, so one call answers both questions.

moonbitmain.mbt
println(read.meta().text("general.architecture").unwrap_or("?"))
println(read.meta().uint("llama.block_count").unwrap_or(0UL))
println(read.meta().items("tokenizer.ggml.tokens").unwrap().length())
llama 32 2
entries gives the table in file order, each with the position it was read from — which is how a dump can say where in the file a pair lives.
05

A tensor’s bytes

extent says where a tensor's bytes sit in the data section and how far they run; data hands them over as a view into the bytes that were parsed. Nothing is copied, so a four-gigabyte buffer costs nothing to look at.

moonbitmain.mbt
let tensor = read.tensor("token_embd.weight").unwrap()
println(
  "\{tensor.kind().name()} · \{tensor.n_elements()} values · \{tensor.byte_length()} bytes",
)
let extent = read.extent("token_embd.weight")
println("data at \{extent.at}, \{extent.length} bytes")
let data = read.data("token_embd.weight").unwrap()
println("first byte \{data[0]}")
Q4_0 · 8192 values · 4608 bytes data at 0, 4608 bytes first byte 0
The offset is not a file offset. extent.at counts from the start of the data section; add file.data_start() for the position in the file. A reader that mixes the two lands on the wrong bytes without any error at all.
06

A shard of it

For a file too large to hold, take a tensor a piece at a time. shard is given the piece that was read and where it starts inside the tensor, and returns the part of it that belongs there — a piece that runs past the end is cut, not refused.

moonbitmain.mbt
let piece = read.shard(
  "token_embd.weight",
  Bytes::make(64, b'\x00')[:],
  at=2304L,
)
println("\{piece.length()} bytes from 2304")
64 bytes from 2304
A shard that starts past the end of the tensor is a caller's mistake, not a file's, and is refused with the length the tensor has.
07

Write the index first

A writer that streams weights does not want to hold them. encode_index writes everything up to the data section and nothing after it, and data_start says where the first byte of the section lands — so the weights can follow one at a time.

moonbitmain.mbt
let index = file.encode_index()
println("index \{index.length()} bytes, data at \{file.data_start()}")
index 224 bytes, data at 224
add_index puts a tensor into the index without its bytes, for exactly this: the offsets are computed from the encodings and the alignment, so the weights can arrive later.
08

Where the next one lands

Each tensor begins where the one before it ended, rounded up to the file's alignment. That is why a second tensor may not begin right after the first: 4608 bytes is already a multiple of 32, and the next one starts at 4608 — but add it and the index grows, so the data section moves and the whole file grows by more than the tensor.

moonbitmain.mbt
file.add(
  @moongguf.Tensor::new(
    name="output_norm.weight",
    kind=@moongguf.F32,
    dims=[8UL],
  ),
  Bytes::make(32, b'\x00')[:],
)
let second = file.extent("output_norm.weight")
println("second tensor at \{second.at}, \{second.length} bytes")
println("\{file.encode().length()} bytes in all")
second tensor at 4608, 32 bytes 4928 bytes in all
File::new(alignment=64U) sets the alignment before anything is added. It must be a power of two, it is written into the file as general.alignment, and it moves the data section — so set it first, not last.
09

When bytes are not a file

Every read that cannot go on ends in a Refused, and every Refused carries the position it happened at. Four bytes that are not the magic are the simplest case.

moonbitmain.mbt
let why = try {
  let _ = @moongguf.File::parse(Bytes::from_array([0x47, 0x47, 0x55, 0x00])[:])
  "it read"
} catch {
  error => error.to_string()
}
println(why)
not a GGUF file
A caller that wants the reason in a form it can match on catches Refused and matches the variant: Magic, Version, Truncated, Duplicate, Mismatch, Blocks, Offset, Missing and the rest. The reference lists them all with their fields.
10

The ceilings

A count in a corrupt file is a claim, and a reader that believes it allocates whatever the claim asks for. Limits bounds the number of pairs, tensors, text and array entries, and the depth of nesting; pass a record to narrow them for an input you do not trust.

moonbitmain.mbt
let tight = { ..@moongguf.limits, tensors: 0 }
let refusal = try {
  let _ = @moongguf.File::parse(bytes[:], limits=tight)
  "it read"
} catch {
  error => error.to_string()
}
println(refusal)
1 tensors past 0
The message names the ceiling and the number that passed it. The variant carries both as fields, so a caller can report them without parsing text.
Where next

The file itself, drawn.