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.
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.
moon add moonbitstack/moongguf
import {
"moonbitstack/moongguf",
}
Bytes and BytesView.
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.
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")
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.
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.
let read = @moongguf.File::parse(bytes[:])
println("version \{read.version().code()}")
println("tensors \{read.tensor_count()}, pairs \{read.meta().count()}")
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.
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())
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.
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.
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]}")
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.
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.
let piece = read.shard(
"token_embd.weight",
Bytes::make(64, b'\x00')[:],
at=2304L,
)
println("\{piece.length()} bytes from 2304")
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.
let index = file.encode_index()
println("index \{index.length()} bytes, data at \{file.data_start()}")
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.
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.
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")
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.
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.
let why = try {
let _ = @moongguf.File::parse(Bytes::from_array([0x47, 0x47, 0x55, 0x00])[:])
"it read"
} catch {
error => error.to_string()
}
println(why)
Refused and matches the variant: Magic,
Version, Truncated, Duplicate,
Mismatch, Blocks, Offset,
Missing and the rest. The reference lists
them all with their fields.
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.
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)