# bend-safetensors-reader Reads `.safetensors` files into Bend 2 arrays: it parses and checks the header, finds tensors by name, and loads a tensor's bytes, or its values widened to F32, into an `Array`. Files past 4 GiB work: offsets are 64-bit. ```python import bend-safetensors-reader@/st.bend as ST import bend-safetensors-reader@/header.bend as H ``` ```python # load one tensor as F32 into a new array, and print its element count @unsafe def load(+s: ST.St, m: Maybe<&2, H.Ent>) -> IO(Unit): match m: case None{}: IO.print("no such tensor") case Some{+e}: do IO: a : Array <- ST.St.read_f32(s, e, 0, Array.new(U32, ST.depth(ST.Ent.count(e)), 0)) IO.print(H.Ent.name(e) ++ ": " ++ U32.show(ST.Ent.count(e)) ++ " values") @unsafe def opened(r: Result<&2, &2, String, ST.St>) -> IO(Unit): match r: case Done{+s}: load(s, ST.St.find(s, "decoder.norm_out.weight")) case Fail{why}: IO.print(why) @unsafe def main() -> IO(Unit): do IO: r : Result<&2, &2, String, ST.St> <- ST.St.open("vae.safetensors") opened(r) ``` ## API (`st.bend`) | Definition | What it does | | - | - | | `St.open(path) -> IO(Result)` | reads and checks the header; a refusal says what is wrong | | `St.tensors(s)`, `St.meta(s)` | the tensors (`H.Ent{name, dtype, shape, begin, end}`, sorted by offset) and the `__metadata__` entries (`H.KV{key, value}`) | | `St.find(s, name) -> Maybe` | the tensor with that name | | `Ent.count(e)`, `Ent.cells(e)`, `Ent.bytes(e)` | element count; cells `read` fills (bytes / 4, rounded up); byte count (`W64`) | | `St.read(s, e, dst, a) -> IO(Array)` | the tensor's bytes into `a` from cell `dst` on, 4 a cell, little-endian; the last cell's unused high bytes are 0 | | `St.can_f32(e)`, `St.read_f32(s, e, dst, a)` | the values as F32 bits, one a cell: F32 as is, BF16 and F16 widened exactly; other dtypes stop the program | | `depth(n)` | the smallest `d` with `2^d >= n`, for `Array.new(U32, d, 0)` | `header.bend` is the pure core: `parse(bytes) -> Result`, the `DType` names and sizes, and `nbytes`. `widen.bend` has the bit conversions (`bf16`, `f16`); `w64.bend` the 64-bit arithmetic (`W64{hi, lo}`) the offsets use. ## What is checked A header is refused unless: - it is one JSON object of tensors, each with exactly `dtype` (one of BOOL, U8, I8, F8_E5M2, F8_E4M3, I16, U16, F16, BF16, I32, U32, F32, F64, I64, U64), `shape` and `data_offsets` (two numbers), plus at most one `__metadata__` object of strings; - sorted by offset, the tensors tile the data section from byte 0, each starting where the one before ends and spanning exactly its element count times its dtype size, with no arithmetic past 2^64 - 1; - no two tensors share a name; - the header is at most 100,000,000 bytes, and the file's size is the header's end plus the data section (checked when Base's `File.size` can tell, which is below 4 GiB; above it, a read past the end stops the program). These follow the reference Rust implementation, with one difference: an unknown field inside a tensor is refused, not ignored. ## Laws `bend PROOF.bend` checks `LAWS.bend` (in about a second). Three laws hold for every input: | Law | What it says | | - | - | | `tile_agrees` | the check that runs (`tile`, with error messages) reaches the same end as the plain spec `Ends`, and refuses exactly when it does | | `parse_sound` | whenever `parse` accepts bytes, the tensors it returns tile the data section from 0 to the size it returns, and no two share a name | | `dtype_names` | every dtype's name reads back as that dtype | | `dtype_sizes` | the byte size of each of the 15 dtypes | | `parse_example` | one header (out of order, an escaped name, an empty tensor, metadata) parses to exactly the expected tensors | | `w64_edges` | 64-bit add, multiply, decimal digits, rounding to cells, equality and order at the carry and overflow boundaries | | `nbytes_edges` | byte counts of real and extreme shapes, including counts past 2^64 - 1 being refused | The last four are checks at literal values: Base has no theory of U32 arithmetic to prove them for every input. Each of 21 one-line bugs planted in the core (a dropped carry, a skipped check, a wrong dtype size, a reversed shape, duplicates allowed, ...) makes the gate fail but one, a wrongly joined surrogate pair, which the tests below catch. Not covered by laws: that the lexer and parser read every JSON header as JSON does (the tests), the widening (tested on all 65,536 F16 values), and the IO in `st.bend`. ## Tests `test/run.sh [FILE.safetensors ...]` builds `test/list.bend`, `test/read.bend` and `test/f16_all.bend` and compares them with Python and NumPy (the `.py` checkers beside them, which are not part of the hub package): 40 edge-case files (13 to accept and read, 27 to refuse), every F16 bit pattern, and for each file given, every tensor's name, dtype, shape and offsets plus a sample of tensor reads. Checked on three real checkpoints of 1.2, 21 and 27 GB (2,996 tensors; F32, BF16, F16, I8 and U8). ## Requirements and speed - Reading tensor data uses `bend-raw-cells` (foreign C), so programs that read data must be native builds (`bend main.bend -o main`); the header parser is plain Bend and runs anywhere. - Opening a 27 GB checkpoint (a 181 KB header, 1,602 tensors) takes about 0.03 s. `read_f32` of a 154-million-value BF16 tensor took 1.6 s (one value at a time, on the CPU). - To widen on the GPU instead, load the raw 16-bit values with `St.read` (two a cell, low half first) and convert them in your own data-parallel kernel with `widen.bend`'s `bf16` and `f16`, which are plain pure functions of one value's bits (for example as the item function of a `bang` from bend-gpu-kernels).