CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
pytorch

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: pytorch/tutorials
Path: blob/main/beginner_source/basics/saveloadrun_tutorial.py
Views: 494
1
"""
2
`Learn the Basics <intro.html>`_ ||
3
`Quickstart <quickstart_tutorial.html>`_ ||
4
`Tensors <tensorqs_tutorial.html>`_ ||
5
`Datasets & DataLoaders <data_tutorial.html>`_ ||
6
`Transforms <transforms_tutorial.html>`_ ||
7
`Build Model <buildmodel_tutorial.html>`_ ||
8
`Autograd <autogradqs_tutorial.html>`_ ||
9
`Optimization <optimization_tutorial.html>`_ ||
10
**Save & Load Model**
11
12
Save and Load the Model
13
============================
14
15
In this section we will look at how to persist model state with saving, loading and running model predictions.
16
"""
17
18
import torch
19
import torchvision.models as models
20
21
22
#######################################################################
23
# Saving and Loading Model Weights
24
# --------------------------------
25
# PyTorch models store the learned parameters in an internal
26
# state dictionary, called ``state_dict``. These can be persisted via the ``torch.save``
27
# method:
28
29
model = models.vgg16(weights='IMAGENET1K_V1')
30
torch.save(model.state_dict(), 'model_weights.pth')
31
32
##########################
33
# To load model weights, you need to create an instance of the same model first, and then load the parameters
34
# using ``load_state_dict()`` method.
35
#
36
# In the code below, we set ``weights_only=True`` to limit the
37
# functions executed during unpickling to only those necessary for
38
# loading weights. Using ``weights_only=True`` is considered
39
# a best practice when loading weights.
40
41
model = models.vgg16() # we do not specify ``weights``, i.e. create untrained model
42
model.load_state_dict(torch.load('model_weights.pth', weights_only=True))
43
model.eval()
44
45
###########################
46
# .. note:: be sure to call ``model.eval()`` method before inferencing to set the dropout and batch normalization layers to evaluation mode. Failing to do this will yield inconsistent inference results.
47
48
#######################################################################
49
# Saving and Loading Models with Shapes
50
# -------------------------------------
51
# When loading model weights, we needed to instantiate the model class first, because the class
52
# defines the structure of a network. We might want to save the structure of this class together with
53
# the model, in which case we can pass ``model`` (and not ``model.state_dict()``) to the saving function:
54
55
torch.save(model, 'model.pth')
56
57
########################
58
# We can then load the model as demonstrated below.
59
#
60
# As described in `Saving and loading torch.nn.Modules <pytorch.org/docs/main/notes/serialization.html#saving-and-loading-torch-nn-modules>`__,
61
# saving ``state_dict``s is considered the best practice. However,
62
# below we use ``weights_only=False`` because this involves loading the
63
# model, which is a legacy use case for ``torch.save``.
64
65
model = torch.load('model.pth', weights_only=False),
66
67
########################
68
# .. note:: This approach uses Python `pickle <https://docs.python.org/3/library/pickle.html>`_ module when serializing the model, thus it relies on the actual class definition to be available when loading the model.
69
70
#######################
71
# Related Tutorials
72
# -----------------
73
# - `Saving and Loading a General Checkpoint in PyTorch <https://pytorch.org/tutorials/recipes/recipes/saving_and_loading_a_general_checkpoint.html>`_
74
# - `Tips for loading an nn.Module from a checkpoint <https://pytorch.org/tutorials/recipes/recipes/module_load_state_dict_tips.html?highlight=loading%20nn%20module%20from%20checkpoint>`_
75
76