Sub topic 15
Converting existing checkpoints to safetensors
This chapter assumes you can read a PyTorch state_dict, know that torch.load unpickles files, and have read the earlier chapters on weights_only=True and the safetensors layout. Here you will turn a .pt or .pth checkpoint into a .safetensors file, check that the result is faithful, and handle the cases where conversion fails.
Why convert at all
A pickle-based checkpoint stays a risk every time someone loads it. Even with weights_only=True, you depend on the allowlist inside the unpickler being correct and on every consumer remembering to pass the flag. A safetensors file removes that dependency. It contains a JSON header and raw tensor bytes, so no consumer can run code by opening it.
Conversion is a one-time cost. The file you produce is safe for every later load, and it also loads faster because tensors can be memory-mapped instead of rebuilt by an opcode interpreter.
The conversion is the risky step
Converting means loading the old pickle once. You are using the dangerous operation to get rid of it, so treat that load with care.
- Checkpoint you trained or produced yourself: load it with
weights_only=Trueon your own machine. - Checkpoint from a third party: load it with
weights_only=Trueinside a disposable environment, such as a container with no network, no credentials, and no mounted home directory. Remove the environment afterwards. - Checkpoint that fails with
weights_only=True: do not retry withweights_only=Falseon your workstation. A failure means the file contains a global that is not on the allowlist. Inspect the opcodes withpickletools.disfirst and decide whether the global is legitimate.
The conversion pipeline
A complete conversion script
The script below handles the three most common shapes of checkpoint: a bare state dict, a dict with a state_dict or model key, and a training checkpoint that also holds optimizer state and counters. It writes only the tensors, then reloads the output and compares it with the input.
import sys
import torch
from safetensors.torch import save_file, load_file
CANDIDATE_KEYS = ("state_dict", "model_state_dict", "model")
def extract_state_dict(obj):
"""Return the dict of name -> tensor from a loaded checkpoint."""
if not isinstance(obj, dict):
raise TypeError(
f"Expected a dict checkpoint, got {type(obj).__name__}. "
"Whole-model pickles must be rebuilt from trusted code first."
)
for key in CANDIDATE_KEYS:
if key in obj and isinstance(obj[key], dict):
return obj[key]
return obj
def convert(src: str, dst: str) -> None:
ckpt = torch.load(src, map_location="cpu", weights_only=True)
state = extract_state_dict(ckpt)
tensors = {}
for name, value in state.items():
if not isinstance(value, torch.Tensor):
print(f"skipping non-tensor entry: {name} ({type(value).__name__})")
continue
# clone() gives each tensor its own storage, which removes sharing;
# contiguous() guarantees a plain row-major layout.
tensors[name] = value.detach().clone().contiguous()
if not tensors:
raise ValueError("No tensors found; refusing to write an empty file.")
save_file(tensors, dst, metadata={"format": "pt"})
# Verify by reading the new file back and comparing with the source.
loaded = load_file(dst)
if set(loaded) != set(tensors):
raise RuntimeError("Key mismatch after round trip.")
for name, original in tensors.items():
restored = loaded[name]
if restored.dtype != original.dtype or not torch.equal(restored, original):
raise RuntimeError(f"Tensor differs after round trip: {name}")
print(f"Converted {len(tensors)} tensors to {dst}")
if __name__ == "__main__":
convert(sys.argv[1], sys.argv[2])Run it as python convert.py model.pth model.safetensors.
What each step protects against
extract_state_dictremoves optimizer state, learning-rate schedulers, and epoch counters. safetensors stores tensors only, so that data cannot go into the file.detach()drops autograd history. A parameter that still requires gradients carries graph information that has no place in a data file.clone()gives every tensor its own memory. This avoids the shared-storage error described below.contiguous()matters becausesave_filewrites raw bytes in row-major order and rejects tensors with other layouts, such as the result of a transpose.metadata={"format": "pt"}records that the tensors came from PyTorch. Libraries such as Hugging Facetransformerscheck for this key when loading. The metadata map must contain only string keys and string values.- The reload comparison catches silent problems such as a dtype change or a truncated write. It compares dtype and values exactly, so it passes only for a bit-for-bit match. Use
torch.equal, nottorch.allclose, because the conversion should not change a single value.
Common failures and fixes
| Symptom | Cause | Fix |
|---|---|---|
| `UnpicklingError` mentioning a global such as `__main__.MyModel` | The checkpoint is a whole-model pickle (`torch.save(model)`) | Rebuild the model from trusted code and obtain its `state_dict` another way, or ask the publisher for a state dict |
| `RuntimeError` about tensors sharing memory | Tied weights, such as an input embedding and an output head, point at one storage | Clone each tensor as in the script, or use `safetensors.torch.save_model` |
| `ValueError` about non-contiguous tensors | A parameter is a transposed or sliced view | Call `.contiguous()` before saving |
| File is far larger than expected | A small slice of a large tensor was saved, and its whole storage went with it | `clone()` copies only the slice |
| Loader complains about missing metadata | The file was saved without `format: pt` | Pass `metadata={"format": "pt"}` |
| A key was dropped | The entry was not a tensor, for example an integer step counter | Store such values in a separate JSON file or in string metadata |
Tied weights and `save_model`
Tied weights deserve a closer look because they are the most frequent surprise. When two names refer to the same tensor, save_file raises an error instead of guessing which names to keep. Cloning, as in the script, resolves the error but stores the data twice. If file size matters and you hold a live module, use the model-level helper:
import torch
from safetensors.torch import save_model, load_model
class Tied(torch.nn.Module):
def __init__(self):
super().__init__()
self.embed = torch.nn.Embedding(10, 4)
self.head = torch.nn.Linear(4, 10, bias=False)
self.head.weight = self.embed.weight # shared storage
model = Tied()
save_model(model, "tied.safetensors") # stores the shared tensor once
restored = Tied()
load_model(restored, "tied.safetensors") # re-ties the duplicate name
print(torch.equal(model.embed.weight, restored.embed.weight))save_model finds the groups of names that share storage and writes one of them. load_model fills the other names from that copy and reports any other missing or unexpected keys.
Sharding and large checkpoints
Large models are usually split into several files plus an index. The Hugging Face convention is a JSON index named model.safetensors.index.json. Its weight_map field maps each tensor name to the shard that holds it. If you convert a sharded checkpoint, convert each shard with the script above and write a matching index. Check that the union of keys across all shards equals the key set of the original checkpoint.
With transformers, the simplest route is to load the model once in a sandbox and call model.save_pretrained(path). Recent versions write safetensors by default and handle tied weights and sharding for you. You still need the original pickle load to happen safely first.
After the conversion
- Compute a SHA-256 hash of the new file and publish or record it next to the file.
- Store the safetensors file and delete the pickle from any location that serves downloads.
- Configure consumers to refuse pickle: in
transformers, passuse_safetensors=Truetofrom_pretrained, so the call fails instead of falling back to a.binfile. - Keep the original checkpoint in cold storage if you must prove provenance, but do not load it again.
Exercise
A converted file fails to save with an error saying two tensors share memory. Your model ties the input embedding to the output head. Give two ways to fix it, and state the cost of each.
Show answer
Option 1: clone each tensor (or call .clone().contiguous()) before savefile. This gives every name its own storage and works for any dict of tensors, but the shared data is written twice, so the file is larger. Option 2: use safetensors.torch.savemodel on the live module. It writes the shared tensor once and load_model restores the tie, so the file stays small, but it needs an instantiated model class from trusted code rather than just a dict of tensors.
Exercise
Your round-trip check uses torch.allclose and passes, but a colleague says it should use torch.equal plus a dtype comparison. Who is right, and why?
Show answer
The colleague is right. Conversion only copies bytes and should not alter any value, so any difference signals a bug. allclose accepts small differences and can pass after a silent precision change, for example float32 values stored as float16 and then compared after casting. Comparing dtype and using torch.equal requires an exact match.