Bookmarks

Safetensors format

A simple file format for storing tensors, such as model weights, safely: loading only reads the data and never executes code, unlike pickle.

Also: .safetensors files, safe weights format

checked 18 Nov

All terms

Safetensors stores tensors — the multidimensional arrays of numbers that make up a neural network’s weights — in a simple file with a header and a data buffer. The format is open, and its specification and Rust implementation are in the project’s repository; it is used by Hugging Face, EleutherAI and StabilityAI, and its files have the .safetensors extension.

Why not pickle

Older PyTorch weight files (.bin, .pt) are based on pickle, which can run arbitrary code when read: a file from someone else can execute commands on your computer. Safetensors works differently: the file contains only data, and the loader merely maps it onto tensors.

How the file is laid out

Part of the fileWhat it holds
First 8 bytesa number N — the size of the header (unsigned 64-bit integer, little-endian)
Header, N bytesJSON in UTF-8: for each tensor, its type (dtype), shape (shape) and the start and end offsets (data_offsets)
The resta contiguous buffer with the tensor data, with no gaps

Thanks to this layout, you can read just the header (over a network, two small requests with Range are enough), find out the list and sizes of the tensors and load only the ones you need. This matters when weights are split across several GPUs: each card needs only its own part. To stop a file being used for a denial-of-service attack, the header size is limited to 100 MB, and data regions cannot overlap.

What the format does not do

  • it does not check the values themselves: a tensor may contain NaN and infinities;
  • it does not store the model’s code or architecture: those need separate files such as config.json;
  • it does not guarantee that a model is good or honestly trained: safety concerns loading the file, not the contents of the weights.

Sources

the term is written from these pages

Verified 18 Nov

Not to be confused with

what it is mixed up with and how it differs

  • GGUFGGUF format

    GGUF is the format for llama.cpp: a single file holds the weights, often already quantised, the tokeniser and the model’s metadata.

  • model checkpoint

    A checkpoint is a saved training state; safetensors is just one of the formats it can be written in.

In depth in the references

where the topic is covered in detail