Registry / serialization / safetensors

safetensors

JSON →
library0.8.0pypypi✓ verified 24d ago

Safetensors is a Python library and file format for securely and efficiently storing and distributing deep learning tensors. It provides a safer, zero-copy alternative to pickle-based serialization, emphasizing speed, security, and ease of use. The library is actively maintained by Hugging Face, with its latest version being 0.7.0, and has a frequent release cadence, often aligning with new tensor datatype support or framework integrations.

pip install safetensors
INSTALL
IMPORT
SIG · SAFETENSORS
S
safetensors
serializationpythonv0.8.0
Install
1.8s avg
Import
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.8.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 19.6MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.000s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

safe_open
from safetensors import safe_open
Main entry point for loading safetensors files generically.
save_file
from safetensors.torch import save_file
Framework-specific save function for PyTorch tensors. Similar imports exist for other frameworks (e.g., `.numpy`, `.tensorflow`).
load_file
from safetensors.torch import load_file
Framework-specific load function for PyTorch tensors. Similar imports exist for other frameworks.

This quickstart demonstrates how to save and load PyTorch tensors using the `safetensors.torch` API. It creates a dictionary of dummy tensors, saves them to a `.safetensors` file, then loads them back, and finally cleans up the file.

import torch from safetensors.torch import save_file, load_file import os # Define some dummy tensors tensors = { "weight1": torch.zeros((1024, 1024)), "bias": torch.ones((1024,)), "embedding": torch.randn((500, 768)) } file_path = "my_model.safetensors" # Save the tensors to a safetensors file save_file(tensors, file_path) print(f"Tensors saved to {file_path}") # Load the tensors from the safetensors file loaded_tensors = load_file(file_path) print("Tensors loaded:") for key, value in loaded_tensors.items(): print(f" {key}: shape={value.shape}, dtype={value.dtype}") # Clean up the created file os.remove(file_path) print(f"Cleaned up {file_path}")
Debug
Known issues
breakingWhen using new sub-byte dtypes like FP4/FP6, operations that lead to unused or unaligned bits within a byte will raise a `MisalignedByte` exception. This ensures data integrity but requires careful handling for these advanced types.
fix
Ensure tensors are properly aligned or handle `MisalignedByte` exceptions. Be aware of how FP4/FP6 types are represented and accessed.
affects: >=0.6.0
gotchaThe JSON header parsing, which delegates to `serde` (in Rust), explicitly rejects duplicate keys. Other JSON parsers (e.g., Python's built-in `json` module) might silently keep the first or last duplicate, leading to parser differentials if not using the `safetensors` library's own loading mechanism.
fix
Always use the `safetensors` library's provided `safe_open` or `load_file` functions to ensure consistent and secure JSON header parsing. Avoid external JSON parsers for `.safetensors` headers.
affects: All versions
gotchaFor PyTorch users, `torch`'s `float4_e2m1fn_x2` dtype actually represents two FP4 values. `safetensors` silently casts a tensor of shape `[..., z]` into `[..., z/2]` for this type, using the last dimension to 'swallow' the x2 contained within the types. This behavior might be unexpected and is subject to change.
fix
Be mindful of potential shape changes when working with PyTorch's `float4_e2m1fn_x2` and `safetensors`. Explicitly check tensor shapes after loading.
affects: >=0.6.0
deprecatedThe `safe_load_file` function (or equivalent `load_file` in framework-specific APIs) no longer defines a default framework. Users must explicitly set the `framework` parameter (e.g., `framework='torch'`).
fix
Update calls to `load_file` or `safe_open` to include the `framework` argument, e.g., `with safe_open('model.safetensors', framework='pt', device='cpu') as f:`.
affects: 0.2.0 and later
breakingThe `torch` module was not found, leading to a `ModuleNotFoundError`. This typically means PyTorch is not installed in the execution environment or is not accessible.
fix
Ensure that `torch` is installed in your environment. If running in a container, add `pip install torch` (or a specific version) to your Dockerfile or setup script. For specific PyTorch versions and CUDA support, refer to the official PyTorch installation instructions.
affects: All versions
breakingThe PyTorch library, a core dependency, is not installed or accessible in the execution environment. This typically leads to a `ModuleNotFoundError` when `import torch` is attempted.
fix
Ensure that PyTorch is correctly installed in the environment. For `pip`, use `pip install torch`. If running in a container, add `RUN pip install torch` to your Dockerfile or ensure the base image includes it. Verify the Python environment's paths.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'safetensors'
The 'safetensors' library is not installed in the current Python environment.
fix
pip install safetensors
safetensors_rust.SafetensorsError: Error while deserializing header: InvalidHeader
The file being loaded is either corrupted, not a valid .safetensors file, or has an incorrect header (e.g., a pickle file renamed to .safetensors).
fix
Verify the file's integrity and ensure it was genuinely created and saved in the safetensors format. Do not rename non-safetensors files to .safetensors.
TypeError: safetensors.save_file() missing 1 required positional argument: 'filename'
The `safetensors.save_file` function requires both the dictionary of tensors and the output filename as arguments, but the filename was omitted.
fix
safetensors.save_file(tensors_dict, 'path/to/your/file.safetensors')
ValueError: expected `tensor` to be dict-like, got type `<class 'str'>`
The `safetensors.save_file` function expects the first argument to be a dictionary mapping string keys to tensor-like objects, but received a non-dictionary type.
fix
Ensure the data passed to `save_file` is a dictionary, where keys are strings and values are actual tensors (e.g., NumPy arrays, PyTorch tensors, TensorFlow tensors).

import numpy as np
import safetensors

data_to_save = {"my_tensor": np.zeros((10, 10), dtype=np.float32)}
safetensors.save_file(data_to_save, "model.safetensors")
Upgrade
Version history
0.8.0latest on PyPI · released Jun 9, 2026
Audit
Dependencies
numpyoptionalCommonly used for tensor manipulation; minimal dependency for related libraries like safestructures.
torchoptionalFor PyTorch tensor serialization and deserialization.
tensorflowoptionalFor TensorFlow tensor serialization and deserialization.
jaxoptionalFor JAX tensor serialization and deserialization.
paddlepaddleoptionalFor PaddlePaddle tensor serialization and deserialization.
packagingoptionalRequired for the 'torch' extra to manage version compatibility.
Agent activity
25 hits · last 30 days
node
20
Amazon
1
OpenAI (training)
1
Resources