Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Safetensors is a file format and library for storing machine-learning tensors, especially model weights. Unlike pickle-based checkpoints, it is designed to read tensor data and structured metadata without reconstructing arbitrary Python objects—reducing the risk that loading a weight file will execute malicious code.

That protection has a clear boundary: Safetensors does not encrypt weights, authenticate their publisher, or make an entire model repository trustworthy. Use it to reduce serialization risk, then secure the artifact’s source, distribution, and runtime separately.

Why use Safetensors instead of a pickle-based checkpoint?

Traditional PyTorch checkpoints often use Python pickle or a pickle-derived format. Pickle can represent arbitrary Python objects, and deserializing a file can invoke code supplied by that file. As a result, a checkpoint that looks like a collection of weights can pose a code-execution risk when loaded.

Safetensors takes a narrower approach: its file stores tensor metadata and raw tensor bytes. A loader reconstructs tensors using declared data types, shapes, and byte ranges rather than rebuilding arbitrary Python objects. This substantially reduces the arbitrary-code-execution risk associated with pickle-based weight loading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
  • Use scikit-learn to track an example ML project end to end
  • Explore several models, including support vector machines, decision trees, random forests, and ensemble methods
  • Exploit unsupervised learning techniques such as dimensionality reduction, clustering, and anomaly detection
  • Dive into neural net architectures, including convolutional nets, recurrent nets, generative adversarial networks, autoencoders, diffusion models, and transformers
  • Use TensorFlow and Keras to build and train neural nets for computer vision, natural language processing, generative models, and deep reinforcement learning

The distinction is important: Safetensors protects the weight-file deserialization step. It does not secure Python files, shell scripts, custom model code, tokenizers, configuration, extensions, or inference behavior supplied alongside the weights.

What is inside a .safetensors file?

A Safetensors file has three parts: an 8-byte unsigned little-endian integer stating the header length, a JSON header, and the raw tensor data. A tensor entry describes its name, data type, shape, and start and end offsets in the data buffer. The end offset is exclusive.

{
  "weight": {
    "dtype": "F16",
    "shape": [1024, 4096],
    "data_offsets": [0, 8388608]
  }
}

The reserved __metadata__ field can hold string-to-string metadata, such as a format label or source revision. It is descriptive, not proof: publishers can put inaccurate claims in it.

Because the header identifies each tensor’s byte range, a loader can seek to a particular tensor instead of deserializing a general-purpose object. The JSON header is also small relative to most model weights, and can be inspected separately. The format documentation describes retrieving metadata with small HTTP range requests, which can help inspect remote files without downloading the full tensor payload: Safetensors metadata parsing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What Safetensors protects—and what it does not

What it helps protect against

  • Arbitrary code execution through pickle deserialization: The format is designed for tensor data and structured metadata, not arbitrary Python object reconstruction.
  • Unnecessary full-file reads in supported workflows: Offset-based access, memory mapping, and lazy access can let compatible applications retrieve selected tensors.
  • Some pathological headers: The PyTorch Safetensors project page describes a 100 MB header-size limit intended to reduce denial-of-service risk.

The library has also been assessed in an external security audit commissioned by Hugging Face, EleutherAI, and Stability AI. An audit is useful assurance about the library; it does not certify every file or repository that uses the format. See the Safetensors security audit announcement.

What it does not provide

  • Encryption or confidentiality: Anyone who can access the file can generally read its weights. Protect sensitive files with encryption supplied by your storage or transfer system.
  • Publisher identity or integrity verification: The format does not prove who created a file or whether it was changed. Verify hashes or signatures independently.
  • Access control, audit logs, or copy prevention: Those controls belong to the hosting platform, identity system, and operational policy.
  • Protection from bad model behavior: A syntactically valid file can contain poisoned, low-quality, or deceptive weights.
  • Safety of surrounding code and configuration: A repository can include unsafe custom code even when its weights use Safetensors.
  • Freedom from all parser or resource risks: Malformed files, vulnerabilities in software, oversized tensors, and resource exhaustion remain concerns.

For Hugging Face-compatible workflows, the project security guidance recommends preferring Safetensors and forcing it where supported, for example with use_safetensors=True. Review repository code separately and do not enable arbitrary remote code unless you have audited and trust it. See the Safetensors security guidance.

Install, save, and load tensors in Python

Install the Python package with:

pip install safetensors

For production, pin and test a package version instead of relying on an unpinned install.

Save and load a PyTorch tensor file

import torch
from safetensors.torch import save_file, load_file

tensors = {
    "weight1": torch.zeros((1024, 1024)),
    "weight2": torch.zeros((1024, 1024)),
}

save_file(tensors, "model.safetensors")
loaded = load_file("model.safetensors")
print(loaded["weight1"].shape)

Inspect keys and retrieve a tensor

Use safe_open to inspect keys and access a tensor through the relevant framework binding:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from safetensors import safe_open

with safe_open("model.safetensors", framework="pt", device="cpu") as f:
    print(list(f.keys()))
    weight = f.get_tensor("weight1")

Memory mapping, lazy access, and partial loading behavior depend on the binding, framework, filesystem, and access pattern; they are not identical across every integration.

Attach descriptive metadata

import torch
from safetensors.torch import save_file

save_file(
    {"weight": torch.zeros((2, 2))},
    "model.safetensors",
    metadata={
        "format": "pt",
        "license": "Apache-2.0",
        "source_commit": "abc123",
    },
)

Only string values are supported in the reserved metadata map. Treat those values as publisher-supplied labels, not verified license, provenance, or security claims. See the official Safetensors repository and Safetensors documentation for APIs and framework-specific details.

Use Safetensors safely with model repositories

A model repository is more than its weight files. It may also contain configuration, tokenizer assets, custom Python code, and scripts. Pin an immutable model revision or commit so a deployment does not silently change when a branch moves. Where the loader supports it, explicitly request Safetensors and configure failure rather than silently falling back to a pickle-based file.

Do not treat use_safetensors=True as an audit of the repository. Inspect code and configuration, and avoid enabling options such as trust_remote_code=True unless you have reviewed and trust the code being executed. Keep inference in a least-privilege environment even when weights are in Safetensors format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Large repositories may distribute weights as multiple Safetensors shards accompanied by index metadata. Validate the complete set of shards and index against the intended model revision; opening one shard successfully does not establish that the complete model is present or compatible.

Convert an existing checkpoint without trusting it blindly

Safetensors can replace the tensor-weight portion of a checkpoint, but it is not a universal container for everything in a training run. Optimizer and scheduler state, custom Python objects, architecture code, tokenizer files, quantization configuration, and training-step metadata may need separate files or formats.

  1. Isolate conversion. Run it in a disposable or sandboxed environment with no unnecessary credentials or privileged access.
  2. Treat the source as untrusted. Loading a pickle checkpoint can itself be dangerous. Do not load an unknown file in a privileged production environment.
  3. Use a trusted converter. Inspect and pin the conversion tooling and its dependencies. Follow the Hugging Face conversion guidance.
  4. Compare contents. Check tensor names, counts, shapes, and dtypes; compare selected values or hashes where appropriate.
  5. Test the resulting model. In a controlled environment, compare expected inference behavior rather than stopping when the converted file opens.
  6. Record provenance. Retain the source hash, source revision, converter and version, destination hash, and validation results; sign or attest to the resulting artifact before distribution.

Performance: what the format can improve

Safetensors is designed to support direct seeking, memory mapping, and lazy or partial access in compatible workflows. Avoiding general-purpose object deserialization and unnecessary intermediate copies can reduce startup memory pressure and make it easier to load only required tensors. These mechanisms can also help parallel or distributed loading.

The project repository reports one BLOOM example loading across eight GPUs in approximately 45 seconds with Safetensors, compared with approximately 10 minutes for regular PyTorch weights. This is a project-reported example, not a guaranteed speedup: results depend on hardware, storage, filesystem, model layout, framework, and loading strategy. See the project repository for the example and implementation details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Safetensors compared with other model formats

Format Best fit Key trade-off
Safetensors Portable tensor weights, especially for distributing and loading pretrained models Does not store arbitrary Python objects or provide encryption, provenance, or a complete model pipeline
PyTorch .pt or .pth Native training checkpoints that may include optimizer state and other Python structures Flexible, but pickle-based loading of untrusted files carries deserialization risk
GGUF Quantized LLM distribution and local inference, particularly in llama.cpp-oriented ecosystems Runtime- and architecture-specific; not a drop-in general-purpose framework checkpoint
ONNX Exchanging computation graphs and deploying with standardized inference runtimes Operator-set, runtime, and conversion compatibility can be constraints
TensorFlow SavedModel TensorFlow-native model and serving workflows Fits a TensorFlow-specific deployment ecosystem and carries more serving structure than a tensor-only file
HDF5 or NumPy formats Scientific arrays and framework-specific storage Do not automatically provide Safetensors’ intended model-weight loading properties or security posture

Choose by what the artifact must represent and which runtime must consume it. Safetensors is a strong option for weight distribution; it does not replace every complete training checkpoint, quantized inference package, or computation-graph format.

Build a secure distribution workflow

Use Safetensors as one layer in a broader supply-chain and deployment process:

  • Integrity: Publish a SHA-256 or stronger hash and verify it after download. A hash detects mismatch only when the expected hash itself comes from a trusted channel.
  • Authenticity: Sign releases or publish verifiable attestations that bind the artifact to its publisher and build or conversion process.
  • Confidentiality: Use encryption in transit and at rest when weights are sensitive; Safetensors does not provide it.
  • Authorization: Restrict private artifacts with repository permissions, cloud IAM, or short-lived credentials.
  • Auditability: Retain hosting-platform access logs and record who approved or promoted a model.
  • Scanning: Scan the full repository and archives, including scripts and custom code, not only the weight file.
  • Reproducibility: Use immutable revisions and document conversion inputs, tools, and validation.
  • Runtime isolation: Serve models with least privilege and resource limits, and sandbox code that must be executed.
  • Availability: For large artifacts, plan for sharding, resumable downloads, mirrors, and retention.

Use the release page to check the package version current for your deployment rather than relying on a version number that may become stale: Safetensors releases. Safetensors was announced as a contributed project to the PyTorch Foundation in March 2026; see the PyTorch Foundation announcement for the governance update.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.