state_dict over full model — every time
Two ways to save a model:
- state_dict (recommended) — saves only the parameters and buffers. To restore, you instantiate the model class and call
load_state_dict. Robust to code changes, framework version differences, and class renames. - torch.save(model) — pickles the whole Python object. Fragile: it requires the exact class definition on load, and any rename / refactor breaks it.
Always use state_dict.
What goes in a "training" checkpoint
For inference, just save the model state_dict. For resuming training, you need:
- Model state_dict
- Optimizer state_dict (Adam's running moments are not trivial to recreate)
- Scheduler state_dict (the current step / last_lr / etc.)
- Current epoch / step number
- Best validation metric so far (for early stopping)
- RNG state if you care about exact reproducibility
weights_only=True
When loading, pass weights_only=True. PyTorch 2.x will eventually default to it, but explicit is good. It refuses to deserialize arbitrary Python — only tensor data. Defends against the (real) class of attacks where a malicious .pt file executes code on load.
Early stopping
Save a "best so far" checkpoint whenever val loss improves; track patience and stop when N epochs pass without improvement. Five lines of class state, prevents wasted compute.