All guides

Save and restore PyTorch model weights: state_dict, weights_only=True and eval()

Save a state_dict, rebuild the same model, load with weights_only=True, then call eval(). Checked locally on a tiny model; the official vgg16 example was not run.

AINav editorsWritten / Updated Sources checked
On this page

At a glance

PyTorch's documentation has two pages on saving and restoring models: "Save and Load the Model" in the basics tutorial, and "Saving and Loading Models". Both recommend the same path: save the learned parameters with torch.save(model.state_dict(), ...), then, to restore, build an instance of the same model, read the dictionary with torch.load(..., weights_only=True), pass it to load_state_dict(), and call model.eval() before inference. This article follows that path through one task: take a trained nn.Module, produce model_weights.pth, restore the weights into a freshly built untrained model, end up with a model ready for inference, and check that the restore really worked. The official basics example downloads about 528MB of vgg16 pretrained weights, and this article did not run it. This site ran the same API flow locally on a model of a few layers; its code and output are labeled as this site's own and say nothing about how the official example runs. Anything the pages do not state is written as "not stated on the official pages".

From saving to a model ready for inference

  1. Save only the state_dict

    The basics page saves with torch.save(model.state_dict(), 'model_weights.pth'). It says PyTorch models store their learned parameters in an internal state dictionary called state_dict. The other page adds that a state_dict is a plain Python dictionary mapping each layer to its parameter tensor, and that only layers with learnable parameters (convolutional, linear and so on) and registered buffers (such as batchnorm's running_mean) have entries. The file therefore holds parameters and registered buffers and no class definition, which is why the next step has to build an instance first.

  2. Build an instance of the same model

    The basics page is direct about this: before loading weights, create an instance of the same model, because the class defines the network's structure. Its example calls models.vgg16() without weights, which gives an untrained model. The other page defines an example class TheModelClass and restores with TheModelClass(*args, **kwargs), which is a template form; swap in your own class and constructor arguments. What error you get when the structure does not match is not stated on either page; the errors shown below come from this site's small model.

  3. Read a dictionary, then restore: weights_only=True

    The page restores with model.load_state_dict(torch.load('model_weights.pth', weights_only=True)). torch.load reads the file into a dictionary and load_state_dict() copies it into the model. The page explains that weights_only=True limits the functions executed during unpickling to those needed for loading weights, and calls it a best practice for loading weights. The other page warns that load_state_dict() takes a dictionary, not a path, so model.load_state_dict(PATH) does not work.

  4. Call eval() before inference

    The basics page says to call model.eval() before inferencing, to put dropout and batch normalization layers in evaluation mode, and that skipping it gives inconsistent inference results. The other page repeats the reminder in both its state_dict and whole-model sections. Neither page says what other inference settings are needed beyond eval(), such as turning gradients off, and this article does not add any.

  5. Deliver and check

    The deliverables are model_weights.pth and a freshly built model that has the weights restored and eval() called. Three checks apply: load_state_dict reports no key mismatch, model.eval() has been called, and you can explain why pickling the whole model is not the first choice. The pages do not define what counts as a successful restore, so this article treats the load_state_dict return value, model.training and an output comparison on a fixed input as this site's checks, and marks them as observed on a small local model.

State_dict, weights_only and eval() explained from the two official pages; the official example was not run, and the small model is this site's local illustration.

Task and deliverable

You have a trained torch.nn.Module. You want its weights in a file, and later, in another process, a model of the same structure with those weights restored and switched to evaluation mode. There are two deliverables: model_weights.pth, and a newly built model that has the weights restored and eval() called. Done means three things: load_state_dict reports no key mismatch, model.eval() has been called, and you can say why the official pages call whole-model pickling (weights_only=False) a legacy use and what coupling to the class definition it brings.

The official basics example uses the torchvision vgg16 pretrained weights, and the page's download log shows 528M. This article did not run it. So that you can follow the whole flow without downloading weights, it uses a small model, TinyNet, which this site wrote and ran locally. The two pages also cover checkpoint resume, several models in one file, loading across devices and warmstarting with strict=False. Those are separate tasks and appear here only at the boundaries.

Prepare the input and environment

  • A trained nn.Module and its class definition. Restoring needs the same class and the same constructor arguments to build a new instance. The pages do not say how to record constructor arguments, so keep them yourself.
  • Python and PyTorch. The official basics example also uses torchvision.models; the small model here needs only torch. The page body does not state which PyTorch version the examples target and gives no install command. This site's checks ran in a temporary virtual environment with Python 3.12.10 and the CPU build of torch 2.15.0.
  • Network and disk. The official vgg16 example downloads weights from download.pytorch.org, and the page log shows 528M. The small model downloads nothing.
  • Where the weights file came from. The pages describe no procedure for judging a file's source; this site's suggestion is to load only files you saved yourself or have confirmed as trusted.

Mechanism: what the two pages say

What the three functions do. The second page lists them separately. torch.save serializes objects with Python's pickle, and models, tensors and dictionaries can all be saved. torch.load uses pickle's unpickling to read a file back into memory and also decides which device the data is loaded onto. torch.nn.Module.load_state_dict restores a model's parameters from a deserialized state_dict. Saving and restoring each have two parts: pull out the dictionary and write the file, then read the file into a dictionary and put it into the model.

Why store only parameters. The second page says that for inference only the trained parameters need saving, and that saving the state_dict gives the most flexibility when restoring later, which is why it is the recommended method. A state_dict is just a dictionary, so it can be saved, updated, altered and restored. The page also notes that the usual file extension convention is .pt or .pth, and that since PyTorch 1.6 torch.save uses a zip-based format while torch.load can still read the old one.

What weights_only=True limits. The basics page says that setting weights_only=True limits the functions executed during unpickling to those necessary for loading weights, and states: "Using weights_only=True is considered a best practice when loading weights." That is all the page offers. It does not list the restricted functions and does not state the default value of weights_only, so this article makes no claim about the default and passes weights_only=True explicitly.

Saving the whole model is a separate route. The basics page also shows torch.save(model, 'model.pth') and torch.load('model.pth', weights_only=False), and says it uses weights_only=False because loading a whole model is a legacy use case for torch.save. The page warns that this approach uses pickle and relies on the actual class definition being available at load time. The second page goes further: pickle does not save the model class itself but a path to the file containing the class, which is used at load time, so code can break in various ways in other projects or after refactors.

The two ways to save, side by side

state_dict versus whole-model pickle, all entries taken from the two official pages
AspectSave the state_dictSave the whole model
Save calltorch.save(model.state_dict(), PATH)torch.save(model, PATH)
Restore callBuild an instance of the same structure, then model.load_state_dict(torch.load(PATH, weights_only=True))torch.load(PATH, weights_only=False), with the class definition already available
Official stanceThe second page heads this section Recommended; the basics page calls saving the state_dict the best practice and weights_only=True a best practice for loading weightsThe basics page calls it a legacy use case for torch.save; the second page says the syntax is the most intuitive and takes the least code, but lists a disadvantage
What the file holdsA dictionary of parameters and buffers, no classThe whole module, pickled; it records the path of the file containing the class, not the class itself
Coupling to codeYou supply a class of the same structure to build the instanceBound to the classes and directory structure used at save time; may break in other projects or after refactors
Before inferenceCall model.eval()Call model.eval()

Steps to finish the task

Step 1, confirm the input. You need a trained nn.Module, and its class definition and constructor arguments stored somewhere you will certainly find them later. The official basics page uses models.vgg16(weights='IMAGENET1K_V1'); this article uses TinyNet.

Step 2, save. Run torch.save(model.state_dict(), 'model_weights.pth'). Check that the file exists and that list(model.state_dict().keys()) matches the layer names you expect. For TinyNet the result is fc1.weight, fc1.bias, fc2.weight and fc2.bias, which come from the two nn.Linear layers; nn.Dropout has no parameters, so it does not appear.

Step 3, build a new instance of the same structure without loading anything. The official form is models.vgg16(), and the page's comment says this creates an untrained model. Check that its parameters differ from the original's; the local output is before load, fc1.weight equal: False. Without this check, a later "equal" would not show that the restore did the work.

Step 4, read and restore with model.load_state_dict(torch.load('model_weights.pth', weights_only=True)). Check the return value; locally it is <All keys matched successfully>. How that return value looks was observed on this site's machine and is not described on the official pages.

Step 5, call model.eval(). Check that model.training is False, and, if the model has Dropout, that two consecutive forward passes give the same output in evaluation mode. In training mode the outputs may differ; they did differ in this example, but that is a random effect, not guaranteed every time, and not a check that must come out a certain way. The official reason is that dropout and batch normalization layers behave differently in evaluation mode. The model.training check is this site's addition.

Step 6, compare on a fixed input (this site's suggestion). Run the same fixed input through the restored model and the original and require torch.equal to be True. In real projects the original model is often gone by then; in that case record its output on a fixed input before saving and compare after restoring. It is only a supporting check and does not prove every parameter was restored. The pages do not describe this practice, and this batch did not run it separately.

Step 7, deliver. Hand over model_weights.pth, the class definition file, the constructor arguments, the restore script and the PyTorch version you used. The pages do not state how far loading is compatible across PyTorch versions, so write the version down.

Running example: saving and restoring TinyNet

All code below is this site's illustrative code, not the official example and not vgg16. TinyNet has two nn.Linear layers and one nn.Dropout; the Dropout is there so the effect of eval() can be seen. The scripts were actually run on this site's machine in a temporary virtual environment (Python 3.12.10, CPU build of torch 2.15.0; the versions come from python -c 'import torch, sys; print(torch.__version__, sys.version.split()[0])', which printed 2.15.0 3.12.10), and the outputs are recorded as printed. The environment variable PYTHONWARNINGS=ignore was set before running, to hide an initialization warning, unrelated to this flow, that appears because NumPy is not installed in that environment. TinyNet is not trained: what gets saved is randomly initialized weights, so these scripts only check the save and restore flow and say nothing about restoring trained weights. First, the official basics page's version, which was not run in this batch.

Save and restore code from the official basics page, merged in page order; official example, not run by this site, needs a download of about 528MB of pretrained weights
python
import torch
import torchvision.models as models

model = models.vgg16(weights='IMAGENET1K_V1')
torch.save(model.state_dict(), 'model_weights.pth')

model = models.vgg16() # we do not specify ``weights``, i.e. create untrained model
model.load_state_dict(torch.load('model_weights.pth', weights_only=True))
model.eval()

Now the small model. The model definition goes in tiny.py, followed by the save script.

This site's illustrative code: tiny.py, the small model definition; run locally
python
import torch
import torch.nn as nn


class TinyNet(nn.Module):
    def __init__(self, hidden=8):
        super().__init__()
        self.fc1 = nn.Linear(4, hidden)
        self.drop = nn.Dropout(p=0.5)
        self.fc2 = nn.Linear(hidden, 3)

    def forward(self, x):
        return self.fc2(self.drop(torch.relu(self.fc1(x))))
This site's illustrative code: save_weights.py, saves the state_dict; run locally
python
import torch
from tiny import TinyNet

torch.manual_seed(0)
model = TinyNet()
torch.save(model.state_dict(), "model_weights.pth")
print(list(model.state_dict().keys()))
Output of running save_weights.py locally, as printed
Plain text
$ python save_weights.py
['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']

The four keys are the weights and biases of the two linear layers, and the working directory now contains model_weights.pth. Next comes the restore script. It follows the official order of building an instance, calling load_state_dict and calling eval(), and adds the checks described above.

This site's illustrative code: restore_weights.py, restores and checks; run locally
python
import torch
from tiny import TinyNet

x = torch.ones(1, 4)

torch.manual_seed(0)
reference = TinyNet()   # same seed as save_weights.py, so same weights as the saved model
reference.eval()

torch.manual_seed(1)
model = TinyNet()       # new untrained instance with different random weights
print("before load, fc1.weight equal:", torch.equal(model.fc1.weight, reference.fc1.weight))

result = model.load_state_dict(torch.load("model_weights.pth", weights_only=True))
print("load_state_dict ->", result)

model.eval()
print("model.training after eval():", model.training)
print("after load, outputs equal:", torch.equal(model(x), reference(x)))
print("eval mode, two passes equal:", torch.equal(model(x), model(x)))

model.train()
print("train mode, two passes equal:", torch.equal(model(x), model(x)))

model.eval()   # switch back to evaluation mode before using the model for inference
print("model.training after switching back to eval():", model.training)
Output of running restore_weights.py locally, as printed
Plain text
$ python restore_weights.py
before load, fc1.weight equal: False
load_state_dict -> <All keys matched successfully>
model.training after eval(): False
after load, outputs equal: True
eval mode, two passes equal: True
train mode, two passes equal: False
model.training after switching back to eval(): False

Reading the output line by line: before the load, the new instance's fc1.weight differs from the reference model's. load_state_dict returns <All keys matched successfully>. After eval(), model.training is False and the outputs match the reference. Two forward passes are equal in evaluation mode. The script switches to train() for a demonstration, and in this run the two passes were unequal because Dropout drops units at random; that is not guaranteed every time, but it fits the official warning that forgetting eval() gives inconsistent results. The last line switches the model back to eval(), so model.training is False again, and only then is the model in a state fit to hand over for inference. The reference model was rebuilt from the same random seed and never read the file, so the matching outputs come from the restore. That trick works only because the model was never trained; a trained model's reference weights cannot be rebuilt by resetting a seed, so record the output on a fixed input yourself before saving. A fixed-input output comparison is only a supporting check and does not prove every parameter was restored.

Next, a few failures, to see what they look like. check_keys.py tries a mismatched structure, a missing key, strict=False, and passing a path straight to load_state_dict.

This site's illustrative code: check_keys.py, how a few failures look; run locally
python
import torch
from tiny import TinyNet

state = torch.load("model_weights.pth", weights_only=True)

try:
    TinyNet(hidden=16).load_state_dict(state)
except RuntimeError as err:
    print(err)

partial = {k: v for k, v in state.items() if k != "fc2.bias"}
try:
    TinyNet().load_state_dict(partial)
except RuntimeError as err:
    print(err)

print(TinyNet().load_state_dict(partial, strict=False))

try:
    TinyNet().load_state_dict("model_weights.pth")
except TypeError as err:
    print("TypeError:", err)
Output of running check_keys.py locally, as printed
Plain text
$ python check_keys.py
Error(s) in loading state_dict for TinyNet:
	size mismatch for fc1.weight: copying a param with shape torch.Size([8, 4]) from checkpoint, the shape in current model is torch.Size([16, 4]).
	size mismatch for fc1.bias: copying a param with shape torch.Size([8]) from checkpoint, the shape in current model is torch.Size([16]).
	size mismatch for fc2.weight: copying a param with shape torch.Size([3, 8]) from checkpoint, the shape in current model is torch.Size([3, 16]).
Error(s) in loading state_dict for TinyNet:
	Missing key(s) in state_dict: "fc2.bias".
_IncompatibleKeys(missing_keys=['fc2.bias'], unexpected_keys=[])
TypeError: Expected state_dict to be dict-like, got <class 'str'>.

With a mismatched structure, the default is a RuntimeError that lists each size mismatch. With a missing key it is also a RuntimeError that names the Missing key(s). With strict=False nothing is raised, and missing_keys in the return value records the missing key. The pages say only that strict=False ignores non-matching keys; they do not describe the default behavior or the error text, so these are this site's observations on torch 2.15.0. The TypeError for a path matches the official warning.

Finally, the whole-model route. whole_model.py saves the entire model with torch.save(TinyNet(), 'model.pth'). load_whole.py loads it with weights_only=True and with False, and then tiny.py is renamed to simulate a refactor that moves the class, and renamed back.

This site's illustrative code: whole_model.py, saves the entire model; run locally
python
import torch
from tiny import TinyNet

torch.manual_seed(0)
torch.save(TinyNet(), "model.pth")
print("saved model.pth")
This site's illustrative code: load_whole.py, loads the whole-model file with both weights_only values; run locally
python
import torch

for flag in (True, False):
    try:
        torch.load("model.pth", weights_only=flag)
        print(f"weights_only={flag}: loaded")
    except Exception as err:
        print(f"weights_only={flag}: {type(err).__name__}: {str(err)[:60]}")
Recorded as printed locally: loading the whole-model file, then the result after tiny.py is renamed and renamed back; the last line shows the state_dict file is unaffected
Plain text
$ python whole_model.py
saved model.pth
$ python load_whole.py
weights_only=True: UnpicklingError: Weights only load failed. This file can still be loaded, to
weights_only=False: loaded
$ mv tiny.py tiny_moved.py
$ python load_whole.py
weights_only=True: UnpicklingError: Weights only load failed. This file can still be loaded, to
weights_only=False: ModuleNotFoundError: No module named 'tiny'
$ mv tiny_moved.py tiny.py
$ python load_whole.py
weights_only=True: UnpicklingError: Weights only load failed. This file can still be loaded, to
weights_only=False: loaded
$ python -c "import torch; sd = torch.load('model_weights.pth', weights_only=True); print(type(sd).__name__, list(sd))"
OrderedDict ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']

The whole-model file fails to load with weights_only=True and loads only with False. Once the class module is moved away, even False fails because the module cannot be found, which agrees with the second page's statement that pickle records the path of the file containing the class. After tiny.py gets its name back, the whole-model file loads with False again. By contrast, model_weights.pth still reads into a dictionary when tiny.py is absent, although building the instance afterwards still needs a class of the same structure.

Check the result and the failure paths

  • Success (this site's check): load_state_dict returns <All keys matched successfully>, model.training is False, and the output on a fixed input is torch.equal to the original model's. The pages give the call order only and define no such criteria.
  • If missing_keys or unexpected_keys in a strict=False return value is not empty, do not treat it as success. The second page presents strict=False for warmstarting, where only some parameters are loaded; the task here requires every key to match.
  • When key names do not line up, the second page says that to load parameters from one layer into another whose keys differ, you change the parameter keys in the state_dict so they match the target model. That is the warmstart practice and is not covered here.
  • Stopping rule (this site's suggestion): on a key or shape mismatch, first check that the class definition and constructor arguments match what was used at save time, then check that the file comes from the same save. Do not silence the error with strict=False and carry on to inference.
  • If you pick the best state inside a training loop: the second page warns that best_model_state = model.state_dict() returns a reference to the state, not a copy, so you must serialize it or use deepcopy(model.state_dict()); otherwise it keeps being updated by later training iterations. This article's example has no training loop, so it does not touch that case.
  • Files of unknown origin: do not make the error go away by switching weights_only to False. The basics page says weights_only=True limits the functions executed during unpickling; it does not spell out the risk of False, so this item is this site's suggestion.
What happens, what the official pages say, and what this site observed
SituationWhat the official pages sayObserved on this site's machine (torch 2.15.0, small model)
Passing a path to load_state_dictDoes not work: it takes a dictionary, not a path, so model.load_state_dict(PATH) cannot be usedTypeError: Expected state_dict to be dict-like, got <class 'str'>.
New instance does not match the file (hidden=16)The error is not described on the official pagesA default RuntimeError listing the size mismatch for fc1.weight, fc1.bias and fc2.weight
File missing one key (fc2.bias removed)Setting strict to False ignores non-matching keys; the default behavior is not described on the official pagesA default RuntimeError: Missing key(s) in state_dict: "fc2.bias".; with strict=False nothing is raised and the return value is _IncompatibleKeys(missing_keys=['fc2.bias'], unexpected_keys=[])
eval() forgotten after restoringInference results will be inconsistentIn this run two forward passes differed in training mode (Dropout drops units at random; not guaranteed every time)
Whole-model file loaded with weights_only=TrueNot described on the official pagesUnpicklingError: Weights only load failed.
Whole-model file loaded with weights_only=False after the class module movedRelies on the class definition at load time; pickle records the path of the file containing the classModuleNotFoundError: No module named 'tiny'

Scope and limits

  • The output shown in the official basics example (the download log and the printed VGG structure) is the page's own output, not a result from this site. This batch did not download the vgg16 weights or run the official example.
  • Not stated on the official pages: the default value of weights_only, the error text for a structure or key mismatch, how far loading is compatible across PyTorch versions, and whether gradients should be turned off for inference.
  • TheModelClass on the second page is an example class there, and TheModelClass(*args, **kwargs) is a template form, not code you can run as is; swap in your own class and constructor arguments.
  • This site's small-model check covers one untrained Linear-plus-Dropout network on CPU and the two routes, state_dict and whole model; its conclusions concern the save and restore flow only, not trained weights. It did not cover GPU, map_location, batch normalization layers, DataParallel, checkpoint resume or saving with torch.export; apart from batch normalization layers, the second page has a section for each, so read it when you need them.
  • The whole-model route is not the first choice, yet the basics page still shows how to do it. If you use it, the class definition and directory structure must stay the same as at save time.

This batch checked the two official pages against the documentation and verified the same API flow locally on the small model above. The official vgg16 example, GPU and other device paths, and batch normalization layers were not run. The small model (untrained, randomly initialized) shows only how state_dict, weights_only=True and eval() behave on this simple structure; it does not predict what vgg16 or your own model will do in your environment.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. PyTorch · Official sources
    View details
  2. PyTorch · Official sources
    View details