Sub topic 15
Converting Existing Checkpoints to safetensors
This chapter assumes you know basic Python, PyTorch, model weights, and byte-based file formats. It also assumes that the checkpoint already exists and that you can identify the model architecture needed to use its weights.
A checkpoint is a saved training state. It may contain a model's parameters, optimizer state, training counters, configuration values, and other Python objects. A safetensors file stores named tensors and metadata in a format designed for safe, fast loading. It does not store arbitrary Python objects.
Why convert a checkpoint?
A legacy PyTorch file such as .pt or .pth often uses pickle internally. Pickle can represent almost any Python object, but loading it can execute code. Converting the file to safetensors removes that pickle dependency from future loads.
The conversion step still needs care. Reading an old checkpoint is itself a loading operation. Prefer weights_only=True when the checkpoint contains a plain tensor dictionary. If that fails, do not immediately enable unrestricted loading on a production machine. Use an isolated environment, inspect the source, and treat the file as executable input.
The conversion workflow
The usual workflow is:
- Obtain the checkpoint from a trusted source and record its hash.
- Load it on the CPU with restricted PyTorch loading.
- Locate the model's state dictionary, which is a mapping from parameter names to tensors.
- Move tensors to the CPU and make them contiguous.
- Write the tensors to a
.safetensorsfile. - Load the new file and compare its keys and tensor values with the source.
A practical conversion script
Install the required packages first:
python -m pip install torch safetensorsThis script accepts either a direct tensor dictionary or a checkpoint containing a state_dict entry. It rejects unexpected objects instead of silently discarding them.
import argparse
from pathlib import Path
import torch
from safetensors.torch import save_file
def extract_state_dict(checkpoint):
if not isinstance(checkpoint, dict):
raise TypeError("checkpoint must be a dictionary")
candidate = checkpoint.get("state_dict", checkpoint)
if not isinstance(candidate, dict):
raise TypeError("state_dict must be a dictionary")
invalid = [
key for key, value in candidate.items()
if not isinstance(key, str) or not isinstance(value, torch.Tensor)
]
if invalid:
raise TypeError(f"non-tensor or non-string entries found: {invalid[:5]}")
return {
key: value.detach().cpu().contiguous()
for key, value in candidate.items()
}
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
args = parser.parse_args()
checkpoint = torch.load(
args.source,
map_location="cpu",
weights_only=True,
)
state_dict = extract_state_dict(checkpoint)
save_file(
state_dict,
str(args.destination),
metadata={"converted_from": args.source.name},
)
print(f"wrote {len(state_dict)} tensors to {args.destination}")Run it like this:
python convert.py model.pth model.safetensorsOptimizer states are usually not included. That is intentional. Optimizer state is useful for resuming training, but it is not required for inference and may include structures that do not fit a tensor-only format. Keep the original checkpoint if you need to resume training.
Validate the result
You can inspect the new file without constructing the model:
from safetensors.torch import load_file
weights = load_file("model.safetensors")
print(len(weights), "tensors")
print(list(weights)[:5])For a stronger check, load both representations in a controlled environment and compare every key, shape, dtype, and value. Then load the safetensors dictionary into the correct model with model.load_state_dict(weights).
| Format | Main content | Typical conversion concern |
|---|---|---|
| PyTorch pickle checkpoint | Python objects and tensors | Loading may execute code |
| safetensors | Named tensors and metadata | Architecture must be supplied separately |
Exercise
Why does converting a checkpoint not make the original checkpoint safe to load?
Show answer
The conversion process must read the original file first. If that read uses unrestricted pickle loading, code could execute before the new safetensors file is created.