Sub topic 10
safetensors: a Data-Only Tensor Format
This chapter assumes basic Python, familiarity with model weights, and basic PyTorch use. The goal is to load tensor data without asking Python to reconstruct arbitrary objects.
Why safetensors exists
A model checkpoint usually contains named tensors such as weights and biases. Python’s pickle format can store these tensors, but it can also store instructions that execute during loading. A file extension such as .pt or .bin does not prove that a file is safe.
safetensors is a format designed for tensor data. Its loader reads tensor descriptions and byte ranges. It does not use Python’s general-purpose object deserialization process.
| Format | Main contents | Code execution during normal loading | Typical use |
|---|---|---|---|
| pickle-based checkpoint | Python objects and tensor data | Possible | Framework-specific checkpoints |
| safetensors | Named tensors and metadata | Not from stored pickle instructions | Portable model weights |
| ONNX | Computation graph and tensor initializers | Not from pickle instructions | Cross-framework inference |
A data-only format reduces one important risk. It does not make the entire model pipeline automatically safe. The model architecture, custom code, and inference inputs still require review.
File layout
A safetensors file has a simple binary layout:
- An 8-byte little-endian integer gives the length of the JSON header.
- The JSON header describes each tensor’s data type, shape, and byte offsets.
- The remaining bytes contain the raw tensor data.
The offsets let a loader read only the tensors it needs. They also make memory mapping and lazy access practical in some libraries.
The header can also contain non-executable metadata. Metadata is useful for information such as a license or model name, but it should not be treated as a security policy.
Saving and loading tensors
The PyTorch integration accepts a dictionary whose values are tensors. It does not save a complete Python model object.
import torch
from safetensors.torch import load_file, save_file
model = torch.nn.Linear(4, 2)
# Save only named tensor values.
save_file(model.state_dict(), "linear.safetensors")
# Load tensor values onto the CPU.
state_dict = load_file("linear.safetensors", device="cpu")
new_model = torch.nn.Linear(4, 2)
new_model.load_state_dict(state_dict)
print(new_model.weight.shape)The architecture must already exist when loading. This separation is deliberate: the file supplies parameters, while your trusted program defines how those parameters are used.
A safetensors loader can still fail because of a corrupted file, an unexpected shape, insufficient memory, or an incompatible data type. Validate the expected keys and shapes before using the weights in a production service.
Inspecting the header
Because the header is JSON after the initial length field, it can be inspected without constructing a model. A parser should still enforce sensible limits on the header length and file size when processing files from untrusted sources.
import json
import struct
def read_safetensors_header(path):
with open(path, "rb") as file:
raw_length = file.read(8)
if len(raw_length) != 8:
raise ValueError("file is too short")
(header_length,) = struct.unpack("<Q", raw_length)
header = file.read(header_length)
if len(header) != header_length:
raise ValueError("truncated header")
return json.loads(header)
print(read_safetensors_header("linear.safetensors"))Exercise
Why does loading a safetensors file still require a trusted model definition?
Show answer
Safetensors stores tensor values, not the model's Python architecture. The application supplies the architecture and decides how to execute it.