Safetensors

0.7.0 · active · verified Sat Mar 28

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.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →