Saving & Loading Models (weights_only)

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

torch.save and torch.load are built on Python’s pickle, and unpickling an untrusted file can execute arbitrary code. That fact shaped the biggest change to this area in recent years: since PyTorch 2.6 torch.load defaults to weights_only=True, which restricts what a file may contain. Tutorials and models written earlier often rely on the old permissive default and fail or, worse, are copied with weights_only=False without understanding why. This page explains what to save, how to load it, what the restricted unpickler allows, how to extend the allow-list, and the other options (device remapping, memory mapping, strict matching) that you meet in practice.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31, with safetensors 0.8 installed for the safetensors example.

What to save: state_dict, not the module

A module’s learnable parameters and registered buffers are exposed as an ordered dictionary of tensors by module.state_dict() (see nn.Module: Parameters, Buffers, state_dict, Hooks, Containers & Init). The official guidance is to save that dictionary instead of pickling the entire module object. The state_dict approach "will give you the most flexibility for restoring the model later", because it does not depend on the exact source layout of the class: a pickled module stores a reference to the class by module path, so renaming or moving the class file breaks loading. It is also what the restricted unpickler is designed to read.

import torch
from torch import nn

model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))

# Save
torch.save(model.state_dict(), "model.pt")

# Load: build the same architecture first, then load the weights
model2 = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
state = torch.load("model.pt", weights_only=True)
model2.load_state_dict(state)
model2.eval()                      # before inference

By convention checkpoint files use the extensions .pt or .pth. torch.save writes a ZIP64 archive that is uncompressed by default (this has been the default since PyTorch 1.6; _use_new_zipfile_serialization=False selects the older format).

Saving the whole module is possible (torch.save(model, path)) but it needs weights_only=False to load, which means executing pickle code, and it is therefore best reserved for files you produced yourself and trust. If you need a self-contained deployable graph, use the export paths instead: torch.export and Exporting to ONNX.

The weights_only default

Per the serialization notes, starting in version 2.6 torch.load uses weights_only=True when the pickle_module argument is not passed. In that mode the unpickler only runs the functions and builds the classes needed for state dicts of plain tensors plus some primitive types; the error messages name Tensor, Parameter and OrderedDict as permitted. It cannot dynamically import anything during unpickling. This removes the arbitrary-code-execution vector of a malicious pickle, but the notes are careful about the limits: it narrows the remote-code-execution surface, it does not protect against denial of service, and memory corruption may still be possible. Use weights_only=False only for files from sources you trust.

The practical consequence: plain state_dict files and checkpoint dictionaries containing tensors, numbers, strings, lists and dicts load without any extra step; objects of custom classes, whole modules, and some NumPy objects do not.

Three environment variables override call sites that do not pass the argument explicitly:

Variable Effect

TORCH_FORCE_WEIGHTS_ONLY_LOAD=1

Forces weights_only=True at all torch.load call sites.

TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1

Makes call sites use weights_only=False, but only where the argument was not passed. A migration escape hatch, not a recommendation.

In code that you control, prefer to state the choice explicitly (weights_only=True) so behaviour does not depend on the installed version. On PyTorch older than 2.6 the default was False, so passing True explicitly was the only way to get the safe behaviour; books and tutorials from that period omit it, and this is one of the main places where they are outdated.

Loading a checkpoint that fails: the allow-list

When a file contains something outside the allowed set, torch.load raises an UnpicklingError that names the offending global and explains the options. The right response, in order of preference:

  1. Re-save the data in a plain form (for example model.state_dict() rather than the module, or lists and tensors instead of a custom object).

  2. If the file is trusted and the extra type is harmless, allow-list that type.

  3. Only as a last resort, and only for files you trust, load with weights_only=False.

torch.serialization.add_safe_globals marks callables or classes as safe for weights_only loading for the rest of the process. Each entry can be the callable itself or a (callable, "full.path") tuple when the pickled path differs from the importable path. torch.serialization.safe_globals is the context-manager form that restores the previous list on exit. torch.serialization.get_unsafe_globals_in_checkpoint(f) inspects a file statically and returns the {module}.{name} strings that are not allow-listed, without loading it; because the analysis is static, types constructed dynamically during unpickling (the notes mention some NumPy dtypes) may not be reported.

import torch
from dataclasses import dataclass


@dataclass
class TrainConfig:
    lr: float = 1e-3
    epochs: int = 10


ckpt = {"model": torch.nn.Linear(2, 1).state_dict(), "config": TrainConfig()}
torch.save(ckpt, "ckpt_with_config.pt")

# Plain weights_only load fails on the custom class.
try:
    torch.load("ckpt_with_config.pt", weights_only=True)
except Exception as exc:
    print(type(exc).__name__)

# Inspect which globals the file needs, without loading it.
print(torch.serialization.get_unsafe_globals_in_checkpoint("ckpt_with_config.pt"))

# Allow just this class, for the duration of a block.
with torch.serialization.safe_globals([TrainConfig]):
    loaded = torch.load("ckpt_with_config.pt", weights_only=True)
print(loaded["config"])

A simpler and more portable design is to store the configuration as a plain dictionary (dataclasses.asdict(cfg)) so that no allow-listing is needed at all.

Moving weights between devices: map_location

torch.load restores each tensor on the device it was saved from. Loading a CUDA checkpoint on a machine without a GPU therefore fails unless you remap it with map_location. According to the tutorial, a GPU-trained model is loaded on the CPU with map_location=torch.device("cpu"), and a CPU-saved model is loaded onto a GPU by giving a CUDA device (for example "cuda:0") and then calling model.to(device) on the model. map_location also accepts a string, a dictionary of device remappings or a callable.

device = torch.accelerator.current_accelerator() or torch.device("cpu")

state = torch.load("model.pt", map_location="cpu", weights_only=True)  # safe on any machine
model2.load_state_dict(state)
model2.to(device)

Loading to the CPU first and moving the model afterwards is the most portable pattern and avoids a temporary doubling of GPU memory.

Large checkpoints: mmap

With mmap=True, torch.load maps the file into memory and loads tensor storages lazily instead of reading everything up front. This lowers peak host memory and start-up time for large checkpoints, especially with a model created on the meta device and filled with load_state_dict(..., assign=True). If mmap is not passed, the default comes from the torch.utils.serialization.config.load.mmap configuration value, which is False. Memory-mapping needs the file to be in the zip format and stay in place while tensors are in use.

state = torch.load("big_model.pt", mmap=True, map_location="cpu", weights_only=True)

with torch.device("meta"):
    model = build_model()               # parameters without storage
model.load_state_dict(state, assign=True)   # adopt the mapped tensors instead of copying

(build_model stands for your own constructor.) For sharded multi-process checkpoints see Distributed Checkpoint & Flight Recorder.

Views and shared storage

Tensors that share storage keep that relationship when saved together: the notes demonstrate that after saving a tensor and a view of it and loading both, changing one still changes the other. The flip side is a size trap: saving a small slice writes its entire underlying storage, so a 5-element view of a 999-element tensor produces a file holding all 999 values. Call .clone() on the slice before saving to store only what you need; the clone no longer shares memory with the original. This matters for checkpoints that contain slices of large embedding tables or KV caches.

x = torch.arange(1, 1000.0)
small = x[:5]

torch.save(small, "view.pt")             # stores all 999 elements
torch.save(small.clone(), "clone.pt")    # stores 5 elements

print(torch.load("view.pt", weights_only=True).untyped_storage().nbytes())
print(torch.load("clone.pt", weights_only=True).untyped_storage().nbytes())

Strict and partial loading

load_state_dict(state_dict, strict=True, assign=False) requires the keys and shapes to match exactly and raises on missing or unexpected keys. It returns a named tuple with missing_keys and unexpected_keys, which you should inspect when using strict=False. Passing strict=False ignores key mismatches, which is useful for warm-starting a model from a different one, adding a new classification head, or loading a backbone into a larger network; the tutorial adds that you can rename keys so that parameters from one layer load into another. Shape mismatches still raise even with strict=False.

pretrained = torch.load("backbone.pt", map_location="cpu", weights_only=True)
# Drop the old classifier so a new head can be trained from scratch.
pretrained = {k: v for k, v in pretrained.items() if not k.startswith("fc.")}

result = model.load_state_dict(pretrained, strict=False)
print("missing:", result.missing_keys)
print("unexpected:", result.unexpected_keys)

Two common key problems: a model trained under nn.DataParallel or DistributedDataParallel has every key prefixed with module., and a model compiled with torch.compile has an _orig_mod. prefix. Save and load the state dict of the underlying module (model.module.state_dict() or model._orig_mod.state_dict()), or strip the prefix when loading. Fine-tuning workflows that rely on partial loading are in Transfer Learning & Fine-Tuning.

Resumable checkpoints

To continue training exactly where it stopped, save everything the loop needs, not only the weights: epoch or step, model state, optimizer state, scheduler state, the gradient-scaler state when using mixed precision, and optionally random-number-generator states. Optimizers hold momentum and adaptive statistics that are expensive to rebuild, and learning-rate schedulers hold their position in the schedule.

The diagram shows which objects contribute to a resumable checkpoint and where each one goes back on resume.

flowchart LR subgraph Save["torch.save"] direction TB M1["model.state_dict()"] O1["optimizer.state_dict()"] S1["scheduler.state_dict()"] C1["scaler.state_dict() if used"] E1["epoch and best metric"] end Save --> F[("checkpoint file")] F --> L["torch.load with weights_only=True"] L --> M2["model.load_state_dict"] L --> O2["optimizer.load_state_dict"] L --> S2["scheduler.load_state_dict"] L --> C2["scaler.load_state_dict"] L --> E2["resume at epoch + 1"]
Figure 1. Contents of a resumable checkpoint
def save_checkpoint(path, model, optimizer, scheduler, scaler, epoch, best_metric):
    torch.save({
        "epoch": epoch,
        "model": model.state_dict(),
        "optimizer": optimizer.state_dict(),
        "scheduler": scheduler.state_dict(),
        "scaler": scaler.state_dict() if scaler is not None else None,
        "best_metric": best_metric,
        "rng": {"cpu": torch.get_rng_state(),
                "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None},
    }, path)


def load_checkpoint(path, model, optimizer, scheduler, scaler, device):
    ckpt = torch.load(path, map_location=device, weights_only=True)
    model.load_state_dict(ckpt["model"])
    optimizer.load_state_dict(ckpt["optimizer"])
    scheduler.load_state_dict(ckpt["scheduler"])
    if scaler is not None and ckpt["scaler"] is not None:
        scaler.load_state_dict(ckpt["scaler"])
    torch.set_rng_state(ckpt["rng"]["cpu"].cpu())
    return ckpt["epoch"] + 1, ckpt["best_metric"]

Write checkpoints atomically (save to a temporary name, then os.replace) so a crash during writing never destroys the previous good file. How these pieces fit in a loop is shown in The Training Loop & Evaluation; the data-loader position can be saved with the stateful loader from Workers, Pinned Memory & Samplers.

Other formats and legacy files

  • TorchScript archives (torch.jit.save) are produced by a deprecated API; new deployments should use torch.export, ONNX or ExecuTorch (see Legacy APIs & Migration).

  • Hugging Face’s safetensors format stores only tensors and cannot contain executable code, which makes it a common choice for sharing weights (see below and Ecosystem).

  • Very old checkpoints (before the zip format of 1.6) are still readable by torch.load, but they are the ones most likely to contain full pickled modules that require weights_only=False.

  • torch.serialization.skip_data and set_default_load_endianness exist in the serialization utilities; the notes describe the first as an early prototype subject to change.

safetensors files

Since PyTorch 2.13, torch.load recognises a .safetensors file by its format and returns its tensors as a plain dict, so the same call loads either kind of checkpoint. The parsing is still delegated to the safetensors package: without pip install safetensors, torch.load on such a file raises RuntimeError. Writing the format needs the library’s own save_file:

import torch
from torch import nn
from safetensors.torch import save_file, load_file

model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
save_file(model.state_dict(), "model.safetensors")          # tensors only, no pickle

state = torch.load("model.safetensors")                     # recognised by its format (2.13+)
print(sorted(state))                                        # ['0.bias', '0.weight', '2.bias', '2.weight']
model.load_state_dict(state)

same = load_file("model.safetensors", device="cpu")          # the library's own loader
print(torch.equal(same["0.weight"], state["0.weight"]))     # True

The cross-framework view of exchange formats is in ONNX & Model Interoperability.

Checklist

  • Save state_dict(), not the module, and keep the architecture code under version control with the weights.

  • Pass weights_only=True explicitly and map_location for portability.

  • Never load a .pt/.pth file from an untrusted source with weights_only=False.

  • Use get_unsafe_globals_in_checkpoint to see what an unknown file needs before deciding.

  • Clone slices before saving; mind module. and _orig_mod. key prefixes.

  • Save optimizer, scheduler and scaler state for resumable training, and write files atomically.