safetensors replaces pickle with a JSON header in front of a flat byte buffer
Simple, safe way to store and distribute tensors
At a glance
- What is it?
- safetensors is a file format for tensors, written in Rust and consumed from Python. A file is eight bytes of header length, a JSON header that names every tensor, then one byte buffer with no holes in it. Nothing in that layout is executed at load time.
- Who is it for?
- safetensors fits one job: reading and writing tensor files without giving the file the power to run code in your process, which is the property pickle cannot offer. Take it if you are storing model weights in Python and want lazy access to individual tensors, or if you are writing a distributed loader that needs to reach one tensor without pulling in the rest of the file.
- Can I use it commercially?
- Yes. Apache-2.0 is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 1 day ago.
- What is it written in?
- Mainly Rust, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 22, 2026, and from our analysis. They are not legal advice.
Star history
- safetensors/safetensors3,984 ★ · +84
| Repository | 2026-09-24 | 2026-11-22 |
|---|---|---|
| safetensors/safetensors | 3.9k | 4k |
84 Stars in the last 59 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
Eight bytes of header length, then JSON, then the buffer
A safetensors file has exactly three parts, and the first part is a number. The first 8 bytes are N, an unsigned little-endian 64-bit integer giving the size of the header. The next N bytes are the header itself, a JSON UTF-8 string, and everything after that is one byte buffer. The header data must begin with a `{` character (0x7B) and may be trailing padded with whitespace (0x20), which is what lets the total header length stay a multiple of eight while the JSON stays compact. Endianness is little-endian throughout, and the element order is C, that is row-major, which is the order PyTorch and numpy use. There is no separate magic number and no version field: a reader takes the first eight bytes, seeks to the header, parses it, and starts reading tensor data immediately after it.
data_offsets count from the buffer, and END is one past
Each entry in the header maps a tensor name to three values, and the shape of that mapping is the whole addressing scheme:
{"TENSOR_NAME": {"dtype": "F16", "shape": [1, 16, 256], "data_offsets": [BEGIN, END]}, "NEXT_TENSOR_NAME": {...}, ...}The two offsets are relative to the beginning of the byte buffer, not to absolute positions in the file, and END is a one-past offset, so the byte size of a tensor is END minus BEGIN. That single convention is what makes a file readable in pieces. Because every tensor carries its own span, a reader that wants one tensor computes its position from the header and reads only that range, and it can list every tensor name in the file without reading a single byte of data. The distribution case is the one the format is designed around: load shard 3 of 12 without touching the other shards.
The buffer must be fully indexed, which blocks polyglot files
One rule does more work than it looks like it does: the byte buffer needs to be entirely indexed and cannot contain holes. Every byte between the start of the buffer and its end belongs to some tensor. The stated reason is that this prevents the creation of polyglot files, that is, a file that is one thing to a loader and something else to whatever else opens it. A format that lets you append unreferenced bytes after the last tensor leaves room for a second payload that a tensor parser never sees. Under this rule that space does not exist, so if you want slack in a file you have to declare it as a tensor, including the degenerate kind: tensors with one dimension of 0 are allowed, they store no data in the buffer, and they still occupy a slot with a size in the header.
The parser checks structure and never checks values
What the loader guarantees is layout. What it does not guarantee is arithmetic. Tensor values are not checked against anything, so NaN and plus or minus infinity can be present in a file and will be handed to you as ordinary values. The header accepts several shapes that a stricter format might reject: empty tensors with one dimension of 0, which carry no data but keep their size, and zero-rank tensors with shape `[]`, which are scalars. One more wrinkle sits in the notes: some smaller than 1 byte dtypes have appeared, which makes alignment tricky, and non-traditional APIs may be required to read them. The practical reading is that the format is happy to describe a tensor it cannot represent densely, and that a value range check, if you need one, has to live in your code rather than in the file.
__metadata__ takes strings only, and duplicate keys are out
The header is a JSON object whose values are tensor entries, with one exception. A special key `__metadata__` is allowed to hold a free form map of strings to strings, and the constraint is stated tightly: arbitrary JSON is not allowed and all values must be strings. So a training run identifier, a library version or a base model name can ride along in the file, but a nested object cannot. Duplicate keys are disallowed, with the caveat that not all parsers may respect this. There is also an explicit statement about how strict the JSON is: the subset is implicitly decided by serde_json for this library, and anything obscure might be modified later, for instance the ways integers, newlines and escapes are represented in UTF-8 strings, with the note that such a change would be made only for safety concerns. If you generate safetensors files from another language, keep the header boring.
The comparison table gives up flexibility and nothing else
The format argues its case with a table that scores pickle, H5, SavedModel, MsgPack, Protobuf, Cap'n Proto, Arrow, numpy and pdparams against safetensors on seven axes. Reading the safetensors row tells you the trade: it takes safe, zero-copy, lazy loading, no file size limit, layout control and bfloat16 or fp8, and gives up only flexibility, which is defined as whether you can save custom code in the format and run it later with zero extra code. Layout control gets its own definition because it is the one people misread: if the information about tensors is spread out across your file, then even when that information is lazily accessible you may still have to touch most of the file to read the tensors you want, incurring many disk to RAM copies. Keeping a single tensor cheap to reach is the point of the offsets, not an extra.
The formats it argues against, and on what grounds
Each rejection in that table comes with a stated reason rather than a score. Pickle is unsafe because it runs arbitrary code. H5 is described as apparently now discouraged for TF and Keras, with some classic use after free issues behind it, and the size comparison is the one that sticks: 210k lines of code against roughly 400 lines for this library currently. SavedModel is Tensorflow specific because it contains TF graph information. MsgPack has no layout control, so lazy loading of a single part does not work in a distributed setting. Protobuf runs into a hard maximum file size limit. Cap'n Proto is missing float16 support, which would force a manual wrapper over a byte buffer, and its buffers carry limitations that make layout control possible but not trivial. numpy npz has no bfloat16 support. The pattern is consistent: each alternative loses on a specific, checkable property.
Two ways in: pip, or the Python binding from source
The packaged route is one line:
pip install safetensorsBuilding it yourself needs Rust first, and the source route in the documentation stays inside the Python binding directory, not the crate root:
# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Make sure it's up to date and using stable channel
rustup update
git clone https://github.com/huggingface/safetensors
cd safetensors/bindings/python
pip install setuptools_rust
pip install -e .The repository layout explains why that path is the documented one. The Rust crate sits in its own directory, the language bindings live under `bindings/`, and there is a `docs/` tree, an `attacks/` directory, a `Dockerfile.s390x.test`, a `flake.nix` and `flake.lock`, a `Makefile` whose only target regenerates both READMEs with `cargo readme`, plus `RELEASE.md`, `SECURITY.md`, `GOVERNANCE.md`, `MAINTAINERS.md` and a pre-commit config. Python docs live on Hugging Face, the crate on crates.io, and there is a docs.rs entry as well.
Writing with save_file and reading back with safe_open
The round trip in Python is symmetric, and the read side is where the header pays off. Save a dict of tensors under a filename, then open the file with a context manager that names the framework and the device, list the keys, and pull the tensors you want:
import torch
from safetensors import safe_open
from safetensors.torch import save_file
tensors = {
"weight1": torch.zeros((1024, 1024)),
"weight2": torch.zeros((1024, 1024))
}
save_file(tensors, "model.safetensors")
tensors = {}
with safe_open("model.safetensors", framework="pt", device="cpu") as f:
for key in f.keys():
tensors[key] = f.get_tensor(key)Two arguments carry the weight of that call. The framework argument picks the tensor library, `pt` for PyTorch here, and the device argument says where the data lands, `cpu` in the example. The loop is deliberately lazy in shape even though it reads everything: because keys and get_tensor are driven by the header, replacing the body of that loop with a single key is a matter of editing one line, with no scan of the rest of the buffer.
Editorial conclusion
safetensors fits one job: reading and writing tensor files without giving the file the power to run code in your process, which is the property pickle cannot offer. Take it if you are storing model weights in Python and want lazy access to individual tensors, or if you are writing a distributed loader that needs to reach one tensor without pulling in the rest of the file. Look elsewhere if you need custom code inside the container, because the format has no room for it and the comparison in its own documentation gives that up as the single axis it loses. Before you commit, check two things. The published line is still moving: the last two releases are 0.9.0 release candidates from September 2026, after 0.8.0 in June, so pin a version rather than tracking whatever is newest. And note what the parser does not do, which is validate values. A file can hold NaN and infinities, empty tensors and zero-rank scalars, all of which are legal in the header and none of which are rejected on the way in.
Frequently asked questions
What are safetensors for?
Storing tensors in a file that is safe to load and still fast, described as zero-copy, as an alternative to pickle. A file is 8 bytes holding the header size, then a JSON header, then one byte buffer.
Why are they called safetensors?
Because the format is presented as the safe alternative to pickle, which PyTorch uses by default and which runs arbitrary code when loaded. The comparison table scores pickle as not safe and safetensors as safe.
How do I open a safetensors file?
In Python, open it with safe_open, passing the path plus a framework and a device, then call keys() for the tensor names and get_tensor for each one. The header is JSON and the first 8 bytes give its size, so names can be listed without reading tensor data.
Are safetensors files safe to use?
Loading one does not run code the way pickle does, and the byte buffer must be entirely indexed with no holes, which the format gives as the reason polyglot files are prevented. Values are not checked, so NaN and plus or minus infinity can be in the file.
how to install safetensors
Run pip install safetensors. From source you need Rust, then clone the repository, cd into safetensors/bindings/python, and run pip install setuptools_rust followed by pip install -e .
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/safetensors-safetensors)Star history chart for your README
[](https://hysenlabs.com/projects/safetensors-safetensors)Was this useful?