Sub topic 9
Loading PyTorch files with weights_only=True
This chapter assumes you know how torch.save and torch.load are used, what a state_dict is, and why unpickling untrusted data can run code (the __reduce__ mechanism from earlier chapters). Here you will see what weights_only=True allows, what it rejects, how it fails, and where it stops protecting you.
The problem the option solves
A PyTorch .pt or .pth file is a zip archive. Inside it is a pickle stream plus raw tensor storage. By default, torch.load runs that pickle stream through a full unpickler. A hostile file can use __reduce__ to make the unpickler call any importable function, such as os.system, while the file loads.
weights_only=True replaces the full unpickler with a restricted one. It follows the same idea as the find_class allowlist from the previous chapter, but the allowlist is built into PyTorch and tuned for model data.
Basic usage
The following script is complete. It saves a small model's state_dict and loads it back with the restricted unpickler.
import io
import torch
from torch import nn
model = nn.Linear(4, 2)
buffer = io.BytesIO()
torch.save(model.state_dict(), buffer) # a dict of tensors
buffer.seek(0)
state_dict = torch.load(buffer, map_location="cpu", weights_only=True)
fresh = nn.Linear(4, 2)
fresh.load_state_dict(state_dict)
print(sorted(state_dict.keys())) # ['bias', 'weight']Two details matter here:
map_location="cpu"loads tensors onto the CPU even if they were saved from a GPU. This avoids failures on machines without that GPU.load_state_dictcopies the values into a model you constructed yourself. Your code defines the architecture. The file supplies only numbers.
What the restricted unpickler allows
The weights-only unpickler accepts a short list of types. These are the ones you will meet in practice:
- Tensors and the helper functions PyTorch needs to rebuild them, such as storages and
torch._utils._rebuild_tensor_v2. - Python primitives:
int,float,str,bool,bytes,None. - Containers:
dict,list,tuple,set, andcollections.OrderedDict. torch.Sizeandtorch.dtype.
Anything else triggers an error as soon as the unpickler meets a global (a module and name pair) that is not on the list. The error is raised before the object is created, so the callable never runs.
Watching it block a payload
This script reuses the __reduce__ trick from earlier. The load fails instead of executing.
import io
import pickle
import torch
class Payload:
def __reduce__(self):
return (print, ("this must not run",))
buffer = io.BytesIO()
torch.save({"weights": torch.zeros(2), "extra": Payload()}, buffer)
buffer.seek(0)
try:
torch.load(buffer, weights_only=True)
except pickle.UnpicklingError as exc:
print("blocked:", str(exc).splitlines()[0])The message names the unsupported global, here builtins.print. The print call never happens. Without weights_only=True, the same file would print the message during loading.
Common errors and what they mean
Most failures fall into a few patterns. The table maps each to its cause and the correct response.
| Symptom | Likely cause | Response |
|---|---|---|
| `Unsupported global: GLOBAL __main__.MyModel` | The file was saved with `torch.save(model)`, which pickles the whole module object | Re-save with `model.state_dict()`, or convert the file in an isolated environment |
| `Unsupported global: GLOBAL numpy...` | The checkpoint contains NumPy arrays or scalars, often optimizer or logging state | Convert those values to tensors or Python numbers at save time |
| `Unsupported global` for a class you wrote | A custom config or dataclass was stored in the checkpoint | Store plain dicts, or allowlist the class explicitly (see below) |
| `Weights only load failed` with a long hint | PyTorch is telling you to choose between trusting the file and loading it differently | Read the named global before deciding anything |
The tempting fix for every one of these is weights_only=False. Do that only for files you created or whose origin you can verify. An unsupported global in a file from a stranger is the exact signal the option exists to give you.
Allowlisting your own types
Sometimes a checkpoint you trust contains a type that is not on the default list. PyTorch lets you extend the allowlist in two ways:
torch.serialization.add_safe_globals([...])adds globals for the rest of the process.- The
torch.serialization.safe_globals([...])context manager adds them only inside awithblock.
Prefer the context manager, because it keeps the widened trust narrow. Never allowlist a function such as os.system, eval, or subprocess.Popen. Allowlisting a global means the unpickler may call it with attacker-chosen arguments. Add only classes whose construction is harmless, and read the failing global name from the error before you add it.
Default changed in PyTorch 2.6
Before PyTorch 2.6, torch.load defaulted to weights_only=False. Starting with 2.6, the default is True. Two consequences follow:
- Old scripts that loaded full-model pickles may start failing after an upgrade. That failure is the new default working as intended.
- Code that must run on older versions should pass
weights_only=Trueexplicitly. Explicit is also clearer to reviewers than relying on a version-dependent default.
Check which version you run with print(torch.__version__).
What the option does not protect against
Even on a patched version, a restricted unpickler leaves some risks open:
- Resource exhaustion. A file can declare very large tensors or deeply nested containers. Loading it may use all available memory or time without running any foreign code.
- Poisoned weights. The file may contain valid tensors that make the model behave badly, for example backdoored outputs. No loader can detect that. Only evaluation and provenance checks help.
- Parser bugs. The unpickler is still a parser of untrusted input. Bugs in it are possible, as the CVE above showed.
- Other code in the repository. Many model repositories ship Python files, for example custom modeling code that a library imports when you pass
trust_remote_code=True. That is separate from the weights file and unaffected by this option.
For these reasons, a data-only format such as safetensors, covered in the next chapter, is a stronger choice when the publisher offers it. weights_only=True is the right precaution when you must load a .pt or .pth file.
A safe loading helper
A small wrapper makes the safe path the easy one. It refuses anything unsafe and gives a clear message.
import pickle
import torch
def load_checkpoint(path: str) -> dict:
"""Load a checkpoint as plain tensors and containers only."""
try:
obj = torch.load(path, map_location="cpu", weights_only=True)
except pickle.UnpicklingError as exc:
raise RuntimeError(
f"{path} needs more than weights to load. "
"Do not retry with weights_only=False unless you trust its source."
) from exc
if not isinstance(obj, dict):
raise RuntimeError(f"{path} did not contain a state dict")
return objThe wrapper never offers a flag to turn the protection off. Changing that requires editing the code, which makes the decision visible in review.
Summary of the working model
torch.load(..., weights_only=True)swaps in an unpickler that accepts only tensors, primitives, and basic containers.- Any other global raises
UnpicklingErrorbefore it is called. - The usual cause of a failure is a file that stores a whole module or custom objects. The fix is to save a
state_dict. - The option reduces risk but does not remove it. Keep PyTorch current, and prefer data-only formats.
Exercise
A colleague gives you a downloaded model.pt and says "just add weights_only=False, the error is a false alarm." The error reads Unsupported global: GLOBAL posix.system. What do you do, and why?
Show answer
Do not load it with weights_only=False. posix.system is the function behind os.system, so the file asks the unpickler to run a shell command, which is not a false alarm. Treat the file as malicious. Do not load it, report it to the source or hosting platform, and, if you need to look inside, disassemble it with pickletools.dis in an isolated environment without executing it. Ask the publisher for a safetensors version, or obtain the weights from a verified source.
Exercise
You upgrade from PyTorch 2.4 to 2.6 and a script that called torch.load("run.pt") now fails with an unsupported global for a class named TrainConfig. Give two ways to fix it and say which you prefer for a file you created.
Show answer
Option one: re-save the checkpoint so it contains only tensors and plain values, for example torch.save({"model": model.state_dict(), "lr": 0.001}, "run.pt"), and load it with weights_only=True. Option two: allowlist the class for the load, using with torch.serialization.safe_globals([TrainConfig]): torch.load("run.pt", weights_only=True). For a file you created, prefer option one. It keeps the file loadable without extending trust, and it works with the default setting. Use option two only as a bridge for existing files.