Skip to content

SafeTensors

Qubitium edited this page Dec 5, 2026 · 16 revisions

SafeTensors checkpoints

Full signatures and usage: SafeTensors archives · Indexed PyTorch checkpoints.

DataShoal can inspect, read and write a local SafeTensors file using Python and its bundled codecs. The format stores named, dense, row-major tensors as little-endian bytes with a JSON index. It carries no executable checkpoint code. PyTorch is optional. Upstream file format

Write and read raw weights

from struct import pack, unpack
from datashoal import SafeTensors as st

weights = st.wire.TensorData(dtype="F32", shape=(2,), data=pack("<2f", 1.25, 2.5))
st.save("model.safetensors", {"scale": weights}, metadata={"source": "example"})

with st.load("model.safetensors") as archive:
    print(archive.wire.metadata["source"])
    print(archive.wire.tensors["scale"].shape)
    print(unpack("<2f", archive.read("scale")))

st.wire.TensorData(dtype, shape, data) takes a wire dtype, a shape, and a contiguous buffer already encoded in little-endian order. The shape () denotes a scalar. A dimension of zero produces an empty payload. Metadata keys and values are strings. Writes atomically replace the destination once complete. Synchronize writes to mutable input buffers or tensors during serialization.

Serialize in memory

Use payload = st.dumps(tensors, metadata={"format": "pt"}) to produce immutable checkpoint bytes. Use with st.loads(payload) as archive: to read those bytes with the same index validation and tensor operations as a file. Both accept limits=. The complete output of dumps must also fit the whole-tensor materialization budget.

Read only the bytes you need

st.load(path) validates the complete index before exposing metadata or payloads. The index contains a read-only mapping of tensor names to immutable descriptors. For example, archive.wire.tensors["scale"].shape counts the values declared in the header. Payloads stay on disk until requested. Pass a local shard path directly. For a cached model repository, use with st.load("org/model", file="model.safetensors") as archive:. Pass download=True to permit fetching that shard.

import hashlib
from datashoal import SafeTensors as st

with st.load("model.safetensors") as archive:
    digest = hashlib.sha256()
    for chunk in archive.chunks("scale", size=1024 * 1024):
        digest.update(chunk)
    target = bytearray(archive.wire.tensors["scale"].nbytes)
    archive.readinto("scale", target)

read(name) returns owned bytes, like a file read. Low-level byte access keeps file-style names: read, readinto and chunks. chunks(name, size=None) yields independently owned bytes on demand. By default each chunk is at most 8 MiB. Lowering st.TensorLimits.max_chunk_bytes below 8 MiB also lowers the default chunk size. An explicit size must be between 1 and that configured limit, inclusive. An empty tensor yields no chunks. readinto(name, buffer) writes into an exactly sized, writable contiguous buffer. Results survive archive closure. Complete pending iteration inside the context.

Large owned reads on POSIX use a just-in-time compiled CPython routine that fills the final buffer in positional reads of up to 64 MiB and releases the GIL during I/O. Short reads to bytes use CPython's positional read directly. On systems with preadv, readinto fills caller-owned buffers at explicit file offsets. The portable fallback fills a buffer through the file object. No operation maps the whole checkpoint. Independent reads can share one archive. Closing prevents new operations, while in-flight reads retain their original file descriptor.

Use PyTorch when installed

import torch
from datashoal import SafeTensors as st

st.save("model.safetensors", {"scale": torch.tensor([1.25, 2.5])})
with st.load("model.safetensors") as archive:
    scale = archive.torch("scale")  # Writable CPU tensor with its own storage.

Pass device="cuda" or another available device to transfer the result. The archive exposes its torch method when PyTorch is installed. The adapter accepts dense PyTorch tensors, including noncontiguous inputs, on little-endian machines. It uses PyTorch's public byte-buffer operations and imports the framework only when its adapter is used. Availability of particular tensor dtypes and accelerator devices depends on the installed PyTorch build.

Wire dtypes and validation

Raw reads and writes support BOOL, signed and unsigned 8/16/32/64-bit integers, F16, BF16, F32, F64, C64, F4, F6_E2M3, F6_E3M2, F8_E4M3, F8_E5M2, F8_E4M3FNUZ, F8_E5M2FNUZ and F8_E8M0. Packed tensors must occupy a whole number of bytes. F4 can also use a PyTorch runtime with packed float4 support. Use raw buffers for 6-bit formats. Published dtype list

The reader checks UTF-8 JSON, duplicate keys, nesting, dimensions, exact tensor sizes, and a payload index with complete, nonoverlapping coverage. A structural scan bounds collection sizes before the JSON decoder allocates the header objects. Reading or writing one shard has no network effects. Applications select individual shards for sharded checkpoints.

Resource budgets

Both st.load(path, limits=...) and st.save(path, tensors, limits=...) accept an immutable st.TensorLimits. The defaults apply per archive.

Limit Default Applies to
max_header_bytes 16 MiB Encoded JSON including padding. The format ceiling is 100,000,000 bytes.
max_tensors 65,536 Named tensors
max_rank 32 Dimensions per tensor
max_metadata_entries 4,096 String pairs in file metadata
max_materialized_bytes 1 GiB Owned whole-tensor reads, PyTorch loads and full contiguous copies for PyTorch writes
max_chunk_bytes 64 MiB Chunk output and bounded data transfers. Owned reads and vectored writes use up to 64 MiB. Default stream chunks use up to 8 MiB.
max_file_bytes 1 TiB Aggregate header, prefix and tensor bytes

On systems with writev, saves from raw tensor buffers gather small pieces into bounded vectors and write large pieces directly from their existing buffers. The writer checks partial writes before atomically publishing the file.

Stream a multi-gigabyte weight with archive.chunks(name) or fill an existing allocation with archive.readinto(name, buffer). For a trusted weight that must be materialized, choose a budget that fits available memory.

from datashoal import SafeTensors as st

with st.load("model.safetensors", limits=st.TensorLimits(max_materialized_bytes=2 << 30)) as archive:
    weights = archive.read("scale")

Select rows and repartition shards

Inspect a local shard and stream a range of leading rows into a new archive. This path works with Python alone and preserves the stored dtype.

from datashoal import SafeTensors as st

layout = st.wire.layout("model-00001.safetensors")
st.save("subset.safetensors", {"embedding": layout.select("embedding", rows=(16, 32))})

Pass durable=True to flush and sync the output file before atomic replacement. For applications that stream payloads from several formats, st.wire.encode_header(specs, metadata=...) builds a validated header from ordered (name, dtype, shape, byte_count) entries.

Indexed PyTorch reads

from datashoal import SafeTensors as st

weights = st.index(["model-00001.safetensors", "model-00002.safetensors"])
ref = weights["embedding"]
rows = ref.load(rows=(16, 32))
assert rows.dtype == ref.dtype
print(ref.shape, ref.wire.shape, ref.wire.dtype)
for ref, value in weights.load(["layer.weight"], device="cpu", zero_copy=True):
    print(ref.name, value.shape)

The index reads shard headers and detects duplicate names. weights.load(names) yields (ref, tensor) pairs for the named tensors, or for every tensor when names is omitted. ref.load() uses the limits the index was built with unless you pass limits=. Compatible CPU tensors can share a private mapping of adjacent selected weights. Changes to those tensors stay private, and the mapping lives as long as its last view. Keep source files immutable while tensors reference them. Oversized weights are copied in segments. window_bytes bounds each mapping (256 MiB by default), and TensorLimits.max_materialized_bytes bounds individual copies. Pass device or dtype callbacks to choose placement and casting per tensor.

Wire shape, PyTorch shape, and byte size

Use ref.wire.shape to answer “how many values does the checkpoint declare along each axis?” It is the shape field in the SafeTensors JSON header. “Wire” refers to the file format. Its unit is values. Use ref.shape to answer “what dimensions will I get from a full ref.load()?” Its unit is PyTorch elements. Use ref.wire.nbytes for the payload length in bytes. All three are available before reading the payload.

Header dtype (wire.dtype) Header shape (wire.shape) Shape returned by PyTorch (shape) Payload bytes per row Total (wire.nbytes)
F16 (4, 8) (4, 8) 16 64
F4 (4, 8) (4, 4) 4 16

Consider one row with eight F4 values. Each pair fits in one byte, so the encoded row occupies four bytes. PyTorch’s float4_e2m1fn_x2 dtype exposes each pair as one tensor element. Four rows therefore give PyTorch shape (4, 4). The file and tensor describe the same payload. For F16, each PyTorch element holds one value and occupies two bytes, so the two shapes agree.

Finding a tensor in the file

ref.wire.begin is the absolute byte offset of the first payload byte; ref.wire.end is the exclusive end. Their difference is ref.wire.nbytes. The JSON header expresses its data_offsets relative to layout.wire.data_start, the first payload byte after the header. For example, a tensor at header offsets [0, 16] occupies 16 bytes starting at layout.wire.data_start.

layout = st.wire.layout(path)
entry = layout.wire.header()[name]
ref = st.index(path)[name]
start, stop = entry["data_offsets"]
assert ref.wire.begin == layout.wire.data_start + start
assert ref.wire.end == layout.wire.data_start + stop
assert ref.wire.nbytes == stop - start

Reading a slice

ref.load(rows=(start, stop)) uses the first axis of ref.shape, with an exclusive stop. In the matrix above, rows=(0, 1) reads one complete row of eight F4 values. For a one-dimensional F4 tensor with wire.shape == (8,), PyTorch shape is (4,). The same slice then reads one packed element containing two F4 values.

This example requires PyTorch with the packed F4 dtype.

from pathlib import Path
from tempfile import TemporaryDirectory
from datashoal import SafeTensors as st

with TemporaryDirectory() as directory:
    path = Path(directory) / "example.safetensors"
    st.save(path, {"weights": st.wire.TensorData("F4", (4, 8), bytes(16))})
    ref = st.index(path)["weights"]
    assert ref.wire.shape == (4, 8)
    assert ref.shape == ref.load().shape == (4, 4)
    assert ref.wire.nbytes == 16
    assert ref.load(rows=(0, 1)).shape == (1, 4)

Citation

DataShoal’s checkpoint reader and writer implement the file format published by the SafeTensors contributors. Upstream specification

@misc{safetensors_format,
  author = {{SafeTensors contributors}},
  title  = {{SafeTensors}},
  url    = {https://github.com/safetensors/safetensors}
}

Loading reference · Runtime and performance

Clone this wiki locally