ML serialization security default

PyTorch torch.load weights_only safe_globals documentation

The visible fix seems obvious, but the task requires preserving safe loading for user-supplied files.

verified-page-readyPyTorchMachine learningML serialization security defaultpytorch26

Agent Quick Fix

The allowlist must match the module path stored in the checkpoint. Importing a similarly named class from a different module path will not satisfy the safe loader.

Product: PyTorch
Affected: PyTorch 2.6 and newer, especially checkpoints serialized from notebooks or app modules with custom class paths.
Current-contract area: Blanket weights_only=False would violate untrusted-checkpoint requirement
Likely root cause: The visible fix seems obvious, but the task requires preserving safe loading for user-supplied files.
Patch:
from torch.serialization import add_safe_globals, get_unsafe_globals_in_checkpoint
from myapp.models import MyModel

print(get_unsafe_globals_in_checkpoint("model.pt"))
add_safe_globals([MyModel])
model = torch.load("model.pt", weights_only=True)

Validation Status

Codex searched organically in the validation run. No no-web counterfactual is attached to this page yet.

Symptom

The visible fix seems obvious, but the task requires preserving safe loading for user-supplied files.

Unsupported global
Please use torch.serialization.add_safe_globals

Why This Happens

The allowlist must match the module path stored in the checkpoint. Importing a similarly named class from a different module path will not satisfy the safe loader.

Before And After

Before

torch.serialization.add_safe_globals([MyModel])
torch.load("model.pt")

After

from torch.serialization import add_safe_globals, get_unsafe_globals_in_checkpoint
from myapp.models import MyModel

print(get_unsafe_globals_in_checkpoint("model.pt"))
add_safe_globals([MyModel])
model = torch.load("model.pt", weights_only=True)

Verification

python - <<'PY'
from torch.serialization import get_safe_globals
print(get_safe_globals())
PY

Common Wrong Fixes

  • Do not assume the class name alone is enough; the checkpoint records fully qualified globals.

Codex Search Keywords

These are the search terms observed in a neutral Codex validation run for this failure shape.

PyTorch torch.load weights_only safe_globals documentation
site:pytorch.org/docs/stable torch.load weights_only safe_globals
https://pytorch.org/docs/stable/generated/torch.load.html
https://docs.pytorch.org/docs/stable/generated/torch.load.html
'weights_only' in https://docs.pytorch.org/docs/2.12/generated/torch.load.html

Source Trail