Sub topic 9
Loading PyTorch Files with `weights_only=True`
Assume you know basic Python classes, PyTorch tensors, and the difference between a model and its learned weights. This chapter focuses on loading a PyTorch checkpoint safely. It does not make an untrusted file automatically safe.
Why `torch.load` needs a restriction
A PyTorch checkpoint often uses Python's pickle serialization internally. Pickle can reconstruct tensors and dictionaries, but it can also request that Python import and call functions while loading.
That means this code can be dangerous:
checkpoint = torch.load("downloaded-model.pth")The file might contain a complete model object, optimizer state, or custom Python classes. Reconstructing those objects can execute code before torch.load returns.
A weights-only load uses a restricted unpickler. It is intended to read tensor data, primitive values, dictionaries, and a limited set of safe types. It rejects many arbitrary classes and callable objects.
Loading a state dictionary
A state dictionary is a mapping from parameter names to tensors. It contains the learned numbers, rather than the Python code that defines the model.
import torch
model = torch.nn.Linear(4, 2)
# Save only named tensors.
torch.save(model.state_dict(), "linear-model.pth")
# Load the checkpoint without allowing arbitrary pickle objects.
state_dict = torch.load(
"linear-model.pth",
map_location="cpu",
weights_only=True,
)
model.load_state_dict(state_dict)
model.eval()
print(model.weight.shape)map_location="cpu" prevents a checkpoint from placing tensors directly on a GPU during loading. This makes loading more predictable and avoids requiring a GPU just to inspect the file.
The restriction applies to the loading operation. It does not replace the model class. You still define the architecture in trusted source code, then copy the loaded tensors into that architecture with load_state_dict.
What the option allows and blocks
| Data or operation | Typical result with `weights_only=True` |
|---|---|
| Tensors and tensor dictionaries | Allowed |
| Strings, numbers, lists, and ordinary dictionaries | Usually allowed |
| Arbitrary custom model classes | Blocked unless explicitly approved |
| A pickle instruction that calls a function | Blocked |
| Unknown globals imported from a module | Blocked |
The exact allowlist depends on the PyTorch version and checkpoint contents. A legitimate checkpoint can fail if it contains a class or special type that the restricted unpickler does not recognize.
Handling an unsupported type
PyTorch may report an unsupported global and suggest adding it to a safe-global allowlist. Do this only after inspecting the source and understanding the type. Adding a class to the allowlist means trusting its reconstruction behavior.
Do not solve the problem by immediately switching back to unrestricted loading. Instead, obtain a state-dictionary-only export from the publisher, convert the file in an isolated environment, or review the checkpoint's contents first.
Exercise
Why should a trusted model architecture be defined separately from a downloaded state dictionary?
Show answer
The architecture comes from reviewed source code, while the state dictionary supplies tensor values. Separating them avoids reconstructing arbitrary Python objects from the checkpoint.