Input and output
Nx_io loads and saves arrays in image, NumPy, SafeTensors, and delimited text
formats, and loads GGUF. Files of named arrays are read and written as
archives, and values made of arrays are saved and loaded through their
structure. A load returns host arrays; a save takes an array on any device
set.
Images
An image is a uint8 array of shape [| height; width; channels |], first row
at the top, with 1 channel for grey, 2 for grey and alpha, 3 for RGB and 4 for
RGBA. load_image recognizes PNG and JPEG streams from their contents and
returns the image with the channels its file holds:
let img = Nx_io.load_image "photo.png" (* Nx.shape img = [| height; width; channels |] *)
A program that wants one layout converts the image with Nx. Grey luma from an RGB image is a weighted sum over the channel axis:
let gray = let weights = Nx.create Nx.float32 [| 3 |] [| 0.299; 0.587; 0.114 |] in Nx.(Infix.(sum ~axes:[ 2 ] ~keepdims:true (cast float32 img * weights))) |> Nx.round |> Nx.cast Nx.uint8 (* Nx.shape gray = [| height; width; 1 |] *)
Each save writes the format it is named after, whatever the path's extension.
save_png stores 1 to 4 channels, so every image load_image reads from a
PNG file saves back as itself; save_jpeg stores 1 or 3. A grey
[| height; width |] array gains its channel axis first:
Nx_io.save_png "copy.png" img; Nx_io.save_jpeg "thumbnail.jpg" thumbnail; Nx_io.save_png "mask.png" (Nx.unsqueeze ~axes:[ 2 ] mask)
NumPy arrays
NPY files
An NPY file carries a dtype that is known only at runtime, so load_npy returns
a packed array, an Nx.packed.
let packed = Nx_io.load_npy "data.npy" let data = Nx.unpack Nx.float32 packed (* [Nx.unpack] raises [Invalid_argument] if the file contains another dtype. *) let () = Nx_io.save_npy "copy.npy" data
Pattern matching is useful when code can operate without fixing the dtype:
let describe path = let (Nx.P x) = Nx_io.load_npy path in (Nx.Dtype.name (Nx.dtype x), Nx.shape x)
NPY versions 1.0, 2.0, and 3.0 are accepted. Nx reads and writes boolean,
16/32/64-bit floating-point, 8/16/32/64-bit signed and unsigned integer, and
64/128-bit complex arrays. Both C and Fortran input order and either byte order
are accepted. Dtypes without a standard NPY representation, such as bfloat16,
float8, and 4-bit integers, cannot be saved. A bit mask is saved as
Nx.cast Nx.bool m, one byte per value, or as its packed bytes,
Nx.bitcast Nx.uint8 of the mask padded to a multiple of 8.
Named arrays
A model, an optimizer state or a dataset is a set of arrays, each with a name.
Files that hold such sets (NPZ, SafeTensors, GGUF) are read and written as an
Nx_io.Archive.t: an immutable collection of arrays keyed by distinct,
non-empty names. NPZ and SafeTensors have a load and a save named after the
format; GGUF has a load only.
let a = Nx_io.Archive.of_list [ ("weights", Nx.P weights); ("labels", Nx.P labels) ] let () = Nx_io.save_safetensors "data.safetensors" a let () = Nx_io.save_npz "data.npz" a let names = Nx_io.Archive.names (Nx_io.load_npz "data.npz") (* ["labels"; "weights"] *)
An entry's dtype is known only at runtime. Archive.tensor asks for one at the
dtype and shape the program expects, and fails naming the entry when the file
holds anything else:
let a = Nx_io.load_safetensors "data.safetensors" let weights = Nx_io.Archive.tensor ~shape:[| 784; 10 |] Nx.float32 "weights" a
Where the system can map a file, a load returns each array whose bytes lie in
the file in the host's byte order and in C order, suitably aligned, as a
mapped array over the file's pages: load_safetensors reads the file's
header, and the elements of only the arrays it cannot map, such as a
misaligned one, which it reads at load into memory of their own. Placing a mapped array on a device
shares the pages with a device that addresses host memory, and copies them to
any other. The file must not change in place while a mapped array from it is
reachable. A save writes a new file and renames it over the old one, which
leaves the arrays loaded from the old file their elements.
load_npz reads every entry's bytes, since each entry's checksum covers all
of them. NPZ names are logical names without the .npy suffix, and a saved
name must be valid UTF-8 and a safe relative path. save_npz compresses each
entry with DEFLATE where that shrinks its first 64 KiB, and stores it
otherwise.
load_gguf reads a GGUF file's metadata, its arrays as an archive, and a
description of each array:
let g = Nx_io.load_gguf "model.gguf" let info = Nx_io.Gguf.info "blk.0.ffn_up.weight" g let a = Nx_io.Gguf.tensors g
An array stored in a block format, such as Q8_0, loads as its bytes at uint8,
as do the SafeTensors dtypes Nx lacks. Bytes are never reinterpreted: their
meaning comes from code that knows the format.
Saving and loading values
A value made of arrays, such as a model's parameters, has a structure, an
Nx.Ptree.t (see Structures), which names each of its
arrays by its path: blocks.0.w is the field w of the first element of the
field blocks. Archive.of_value turns a value into the archive of its arrays
under those names, and Archive.to_value turns an archive back into a value:
let () = Nx_io.save_safetensors "params.safetensors" (Nx_io.Archive.of_value mlp params) let params = Nx_io.Archive.to_value mlp ~like:params (Nx_io.load_safetensors "params.safetensors")
Reading back needs a value of the same shape, ~like: it supplies the record,
the list lengths, the options that are present, and each array's dtype, shape
and placement. A program resuming its training has such a value, the one it
would start from. The arrays read back are the file's entries as stored,
mapped where the system can map them, and nothing is converted: a value whose
dtypes differ from the file's fails, and never narrows what was saved.
~prefix puts a value's names under a prefix and a dot, so one file holds
several sections, and Archive.union puts their archives together. Here
optim describes the optimizer's state, opt:
let () = Nx_io.save_safetensors path (Nx_io.Archive.union [ Nx_io.Archive.of_value ~prefix:"model" mlp params; Nx_io.Archive.of_value ~prefix:"optim" optim opt ]) let a = Nx_io.load_safetensors path let params = Nx_io.Archive.to_value ~prefix:"model" mlp ~like:params a let opt = Nx_io.Archive.to_value ~prefix:"optim" optim ~like:opt a
Under a prefix p, a value owns p and every name that starts with p and a
dot; without a prefix, it owns every name. Reading back is strict within those
names and fails, naming the entry, before any array is placed:
- when an array of the value has no entry;
- when an entry has another dtype or shape, as in
Nx_io.Archive.to_value: model.blocks.1.w: shape [3] in the archive, [2; 3] in the value; - when an entry is named by no array of the value. A model of 12 blocks
refuses a file of 24, since
model.blocks.12.wnames nothing.
Entries outside the value's names are ignored, so reading model above
leaves the optim section alone.
Files written elsewhere
A file another program wrote has its own names and layouts. Reading it into a
value is a function that asks for each entry by name, shape and dtype, and
rearranges it with Nx. Archive.float reads an entry stored as float16,
bfloat16, float32 or float64 at the float dtype the program computes in,
converting when the two differ:
let linear a ~inputs ~outputs name = (* The file stores the weight as [outputs; inputs]. *) let w = Nx_io.Archive.float ~shape:[| outputs; inputs |] Nx.float32 (name ^ ".weight") a in Nx.matrix_transpose w
A wrong configuration fails at the first entry it gets wrong, naming it. The importer needs no value to start from, and at the file's own dtype every array it returns is the file's entry, unread.
Compressed files
Nx_io reads no gzip stream. A .gz file is decompressed first, for instance
with Lz.Gzip.decode from Raven's lz package, and the result written to a
file that Nx_io then loads.
Errors and replacement
A load or a save raises Failure when its file cannot be read or written or
breaks its format, and a load also when its path names no regular file. The
message starts with the path, as in w.npy: the file ends inside its header.
A mismatch between an archive and what is asked of it also raises Failure,
naming the entry. A function raises Invalid_argument naming itself for an
array, a name or an argument its format cannot store, as in
Nx_io.save_npy: npy has no bfloat16, and for a name that cannot name an
entry, empty or given twice.
A save writes a new file and renames it over its path, so after a crash the path holds the old file or the whole new one, and a save that fails before the rename leaves the path as it was.
Implementation and performance
Nx owns the ISC image and ZIP implementations used by nx.io, and takes
DEFLATE, zlib and gzip from Raven's lz library; it does not require system
zlib, libpng, libjpeg, or pkg-config. A mapped array costs no read at load.
Any other array, such as a deflated NPZ entry, a misaligned one or an image, is
read at load into memory of its own: image decoding writes into the final
buffer, and a deflated NPZ entry is decompressed once, into memory the array
then uses directly when its data is aligned.
this page is tested with mdxedit this page ↗