Sub topic 10
safetensors: a data-only tensor format
This chapter assumes you know basic Python, what a model's weights are, and how to save and load a state dict in PyTorch. It also assumes you have read the earlier chapters on pickle and __reduce__, so you know why loading a pickle can run code. Here we look at the format that removes that risk by design.
Why a data-only format
A pickle file is a program for a small virtual machine. Loading it means running that program, and the program can import and call any function it names. A safetensors file contains no program. It holds named tensors and a small amount of metadata. The loader reads bytes, checks them, and builds tensors. No step in that process imports a module or calls a function named by the file.
This is the property that matters for untrusted models. The format has no instruction that could trigger code execution, so a malicious file has nothing to exploit at the format level.
The file layout
A safetensors file has three parts, in this order:
- An 8-byte unsigned integer in little-endian byte order. It gives the size of the JSON header in bytes.
- A JSON header. It maps each tensor name to its
dtype, itsshape, anddata_offsets, a pair[begin, end]of byte positions inside the data section. An optional__metadata__key holds string-to-string pairs. - The data section. It holds the raw tensor bytes, back to back.
Because the header is plain JSON, you can read it without any special library. This code parses it with the standard library only:
import json
import struct
def read_safetensors_header(path):
with open(path, "rb") as f:
(header_len,) = struct.unpack("<Q", f.read(8)) # 8-byte little-endian length
return json.loads(f.read(header_len))
print(read_safetensors_header("model.safetensors"))For a file with a 2x2 weight and a length-2 bias in float32, the header looks roughly like this (key order can vary):
{
"bias": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]},
"weight": {"dtype": "F32", "shape": [2, 2], "data_offsets": [8, 24]}
}The offsets are relative to the start of the data section, not the start of the file. The bias tensor takes 2 values times 4 bytes, which is 8 bytes. The weight tensor takes 4 values times 4 bytes, which is 16 bytes. The tensors are contiguous and non-overlapping.
Saving and loading
The Python API stores a flat dictionary of names to tensors.
import torch
from safetensors.torch import save_file, load_file
tensors = {"weight": torch.zeros(2, 2), "bias": torch.zeros(2)}
save_file(tensors, "model.safetensors")
loaded = load_file("model.safetensors")
print(loaded["weight"].shape)Loading returns a plain dictionary of tensors. You then pass it to model.load_state_dict(loaded) as you would with any state dict.
The format stores tensors only. It cannot hold an optimizer object, a Python class instance, a learning-rate scheduler, or a whole nn.Module. If you need those, you save them separately in a format suited to them, such as JSON for configuration. This limit is the cost of the safety guarantee.
What the loader checks
A data-only format is safe from code execution, but a parser still has to handle hostile input carefully. A malformed header could claim huge sizes or overlapping regions. The reference implementation, written in Rust, validates the following before it hands you any tensor:
- The header size is within a fixed upper limit (100 MB in the reference implementation), so the loader cannot be made to allocate an enormous header.
- The header is valid UTF-8 JSON, and the offsets are valid.
- Each tensor's byte range matches its
dtypeandshape. For example, a[2, 2]tensor ofF32must span exactly 16 bytes. - Tensor ranges do not overlap, and they cover the data section with no gaps or trailing bytes.
- Offsets fall inside the file.
If any check fails, loading raises an error instead of returning partial data.
Lazy loading and memory mapping
The header tells you where every tensor lives, so you can read one tensor without reading the rest. The safe_open function uses this:
from safetensors import safe_open
with safe_open("model.safetensors", framework="pt", device="cpu") as f:
print(list(f.keys())) # tensor names, read from the header
print(f.metadata()) # the __metadata__ dict, or None
bias = f.get_tensor("bias") # reads only this tensor's bytes
part = f.get_slice("weight")[0:1] # reads only the first rowThe file is memory-mapped, so the operating system pages in only the bytes you touch. This helps in three common cases:
- Large models split across several files, where each process needs only some of the tensors.
- Tensor-parallel inference, where each GPU needs a slice of a weight matrix.
- Quick inspection, such as listing names and shapes without loading gigabytes.
Pickle-based loading cannot do this. A pickle stream must be executed from the beginning, so you cannot jump to one tensor.
Sharded checkpoints
Large models are often stored as several files, such as model-00001-of-00003.safetensors. A small JSON index file, usually model.safetensors.index.json, maps each tensor name to the shard that holds it. Libraries such as Hugging Face Transformers read the index and open only the shards they need. The index is also plain JSON, so reading it carries no code-execution risk. Still, check that the shard names it lists stay inside the model directory before you open them in your own tooling.
Gotchas
Shared tensors. Some models tie weights, for example an input embedding and an output projection that share one tensor. In PyTorch they are two names for the same storage. save_file refuses to write such a dictionary because the format has no notion of aliasing, and it raises an error. Fix this by saving with save_model(model, "model.safetensors"), which removes the duplicates, and loading with load_model. Alternatively, clone one tensor before saving.
Metadata is strings only. The __metadata__ values must be strings. Store numbers as text and parse them yourself. Treat metadata as untrusted input, like any other field from a file you did not create.
Contiguous storage. Tensors are saved in a contiguous layout. Non-contiguous views, such as a transposed tensor, must be made contiguous first. Call .contiguous() before saving if the library reports a layout error.
Endianness. The format specifies little-endian data. Big-endian machines must convert, and the library handles this for you.
Not a model description. The file records tensors but not the architecture. You still need the model code or a config file to know how to use the weights.
Comparison with the pickle path
| Property | Pickle-based `.pt` / `.pth` | safetensors |
|---|---|---|
| Code runs on load | Possible, unless restricted | No |
| Contents | Any Python object | Named tensors and string metadata |
| Read one tensor alone | No | Yes |
| Header readable without the library | No | Yes, JSON |
| Stores optimizer or module objects | Yes | No |
The weights_only=True option from the previous chapter narrows what a pickle may do, but it is a filter on a format that can express code. safetensors cannot express code at all.
Exercise
You open a safetensors file and the parsed header contains "embed": {"dtype": "F16", "shape": [1000, 64], "data_offsets": [0, 128000]}. Is this header consistent? Then explain why a model with tied embedding and output weights causes save_file to fail.
Show answer
Yes. A float16 value takes 2 bytes, and 1000 x 64 = 64,000 values, so the tensor needs 64,000 x 2 = 128,000 bytes, which matches the range 0 to 128000. A loader that found a different size would reject the file. Tied weights fail because two dictionary names point to the same memory, and safetensors has no way to record that two names share storage. Use save_model (which drops the duplicates) or clone one tensor before calling save_file.
Exercise
Why does the data-only design let safe_open read a single tensor, while pickle.load cannot?
Show answer
The safetensors header lists each tensor's byte offsets, so the loader can seek straight to the needed range, and the file is memory-mapped. A pickle is an instruction stream that must be run from the start to rebuild objects, so there is no table that says where one tensor begins.