Hugging Face's safe, mmap-friendly tensor container. An 8-byte little-endian header length N, an N-byte UTF-8 JSON header mapping tensor names to {dtype, shape, data_offsets}, plus an optional "__metadata__" string->string map, then one contiguous byte buffer. Tensors are dense, little-endian, C-order, with no strides. Loading cannot execute code. It is the default format for HF Transformers / Diffusers checkpoints; large models are sharded with a JSON index file.
What it is
many tensors
Byte order
little
Dimension order
row major
Compression
none
Metadata
string map
Loading
does not execute code
How to read it
[N: u64 LE][header: N bytes UTF-8 JSON, space padded][byte buffer]. File size = 8 + N + buffer length.
N
u64le
header length in bytes
header
utf8[N]
JSON Header object, optionally followed by 0x20 padding
buffer
bytes[*]
tensor bytes back to back, in data_offsets order, without gaps
8. header length N. Writers since v0.3.1 pad N to a multiple of 8 so the buffer starts 8-aligned. v0.2.x does not pad. v0.3.0 pads by (len % 8) spaces, which does not align. Tensor data offsets are NOT padded. Readers accept any N.
Header
Top-level JSON object. Every key except "__metadata__" is a tensor name whose value is a TensorInfo. Key order carries no meaning; the reference writer emits "__metadata__" first, then tensors in data order.
__metadata__
map<string,string>
optional; values MUST be JSON strings
<tensor name>
TensorInfo
count 0..n
TensorInfo
The spec does not define extra TensorInfo fields; the reference reader ignores them, so writers should not rely on them.
dtype
string (dtypes[].name)
shape
array<uint>
[] = scalar; zeros allowed
data_offsets
[uint, uint]
[begin, end) relative to the start of the byte buffer
ShardIndex
Sidecar file "<prefix>.safetensors.index.json" (e.g. model.safetensors.index.json) for sharded checkpoints, with shards named "<prefix>-00001-of-00005.safetensors". It is a convention of transformers/huggingface_hub, not part of the format.
metadata
object
{"total_size": <int, sum of tensor bytes>} (+ optional extra keys such as total_parameters)
weight_map
map<string,string>
tensor name -> shard file name
Reader
The procedure that finds each tensor's bytes.
read
pseudo-python
def read_safetensors(f, strict=True):
size = file_size(f)
if size < 8: raise Invalid("HeaderTooSmall")
N = unpack("<Q", f.read(8))
if N > 100_000_000: raise Invalid("HeaderTooLarge")
if 8 + N > size: raise Invalid("InvalidHeaderLength")
raw = f.read(N)
if strict and raw[:1] != b"{": raise Invalid("header must start with '{'")
hdr = json_loads(raw.decode("utf-8"), reject_duplicate_keys=strict)
meta = hdr.pop("__metadata__", None) or {} # null and absent both mean no metadata (ST-009i)
if not all(isinstance(v, str) for v in meta.values()): raise Invalid("metadata values must be strings")
buf_start = 8 + N; buf_len = size - buf_start
infos = sorted(hdr.items(), key=lambda kv: tuple(kv[1]["data_offsets"]))
pos = 0; tensors = []
for name, ti in infos:
d = DTYPE[ti["dtype"]] # KeyError -> Unsupported
b, e = ti["data_offsets"]
if b != pos or e < b: raise Invalid("InvalidOffset " + name)
nbits = prod(ti["shape"]) * d.bits
if nbits % 8: raise Invalid("MisalignedSlice")
if e - b != nbits // 8: raise Invalid("TensorInvalidInfo")
pos = e
tensors.append(Tensor(name, d.canonical, list(ti["shape"]), offset=buf_start + b, nbytes=e - b))
if pos != buf_len: raise Invalid("MetadataIncompleteBuffer")
return {k: TypedValue("string", v) for k, v in meta.items()}, tensors
read_shard_index
pseudo-python
def read_sharded(index_path):
idx = json_load(index_path)
shards = sorted(set(idx["weight_map"].values()))
out = []
for s in shards:
meta, ts = read_safetensors(open(join(dirname(index_path), s), "rb"))
out += ts # weight_map[t.name] SHOULD equal s
return idx.get("metadata", {}), out
Number formats
The name in the file, and the canonical dtype it maps to.
In the file
Canonical
Bits
BOOL
bool
8
F4
float4_e2m1fn
4
F6_E2M3
float6_e2m3fn
6
F6_E3M2
float6_e3m2fn
6
U8
uint8
8
I8
int8
8
F8_E5M2
float8_e5m2
8
F8_E4M3
float8_e4m3fn
8
F8_E8M0
float8_e8m0fnu
8
F8_E4M3FNUZ
float8_e4m3fnuz
8
F8_E5M2FNUZ
float8_e5m2fnuz
8
I16
int16
16
U16
uint16
16
F16
float16
16
BF16
bfloat16
16
I32
int32
32
U32
uint32
32
F32
float32
32
C64
complex64
64
F64
float64
64
I64
int64
64
U64
uint64
64
Reject the file when
Listed in the spec's order. Only rules marked MUST that reject the file are shown. The other IDs are warnings or implementation limits.
Rule
Must hold
Error
ST-001
file length >= 8
HeaderTooSmall
ST-002
N <= 100,000,000
HeaderTooLarge
ST-003
8 + N <= file length
InvalidHeaderLength
ST-004
header bytes are valid UTF-8 and valid JSON for the Header type
InvalidHeader / InvalidHeaderDeserialization
ST-005
header begins with '{' (0x7B)
header[0] == 0x7B
ST-007
no duplicate keys in any JSON object of the header: the top-level object, __metadata__, and each TensorInfo. The README sentence ('Duplicate keys are disallowed') does not limit itself to tensor keys.
ST-008
dtype is one of dtypes[].name
ST-009
__metadata__ values are strings
ST-010
for each tensor 0 <= begin <= end
InvalidOffset
ST-011
sorted by begin, the ranges tile [0, buffer_len) exactly: first begin == 0, each begin == previous end (no holes, no overlaps)
InvalidOffset
ST-012
prod(shape)*bits is a multiple of 8
MisalignedSlice
ST-013
end - begin == prod(shape)*bits/8
TensorInvalidInfo
ST-014
8 + N + last end == file length (no trailing bytes)
MetadataIncompleteBuffer
ST-015
shape products and byte sizes do not overflow u64/usize
ValidationOverflow
Example
Example file. The header is one JSON object. The header below is spaced for reading; the file pads that JSON with spaces out to a multiple of 8.