Containers · .safetensors

safetensors

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.

Nu64leheader length in bytes
headerutf8[N]JSON Header object, optionally followed by 0x20 padding
bufferbytes[*]tensor bytes back to back, in data_offsets order, without gaps
0        8                    8+N                                    EOF
+--------+--------------------+--------------------------------------+
| N u64  | {"__metadata__":..,| t0 bytes | t1 bytes | ... | tk bytes |
|   LE   |  "t0":{...},...}   |                                      |
|        |  + ' ' padding     |  offsets are relative to byte 8+N    |
+--------+--------------------+--------------------------------------+

One tensor

nameheader key
dtypeTensorInfo.dtype -> dtypes[].canonical
shapeTensorInfo.shape (already row-major, outermost first)
data_offset8 + N + data_offsets[0] (absolute in file)
nbytesdata_offsets[1] - data_offsets[0]
orderalways C
stridesimplicit C-contiguous
alignment8. 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>TensorInfocount 0..n

TensorInfo

The spec does not define extra TensorInfo fields; the reference reader ignores them, so writers should not rely on them.

dtypestring (dtypes[].name)
shapearray<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.

metadataobject{"total_size": <int, sum of tensor bytes>} (+ optional extra keys such as total_parameters)
weight_mapmap<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 fileCanonicalBits
BOOLbool8
F4float4_e2m1fn4
F6_E2M3float6_e2m3fn6
F6_E3M2float6_e3m2fn6
U8uint88
I8int88
F8_E5M2float8_e5m28
F8_E4M3float8_e4m3fn8
F8_E8M0float8_e8m0fnu8
F8_E4M3FNUZfloat8_e4m3fnuz8
F8_E5M2FNUZfloat8_e5m2fnuz8
I16int1616
U16uint1616
F16float1616
BF16bfloat1616
I32int3232
U32uint3232
F32float3232
C64complex6464
F64float6464
I64int6464
U64uint6464

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.

RuleMust holdError
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.

small.safetensors1,408 bytes

NameDtypeShapeBytes
s_f32F32float32[]4
w_f32F32float324 × 641,024
i_i32I32int323 × 224
e_bf16BF16bfloat162 × 312
b_f16F16float16816

Header

{
  "s_f32": {
    "dtype": "F32",
    "shape": [],
    "data_offsets": [
      0,
      4
    ]
  },
  "w_f32": {
    "dtype": "F32",
    "shape": [
      4,
      64
    ],
    "data_offsets": [
      4,
      1028
    ]
  },
  "i_i32": {
    "dtype": "I32",
    "shape": [
      3,
      2
    ],
    "data_offsets": [
      1028,
      1052
    ]
  },
  "e_bf16": {
    "dtype": "BF16",
    "shape": [
      2,
      3
    ],
    "data_offsets": [
      1052,
      1064
    ]
  },
  "b_f16": {
    "dtype": "F16",
    "shape": [
      8
    ],
    "data_offsets": [
      1064,
      1080
    ]
  }
}

Sources

Tensref rev 3.1