Saving and Loading Models
beginner/saving_loading_models
=
nn
.
MaxPool2d
(
2
,
2
)
self
.
conv2
=
nn
.
Conv2d
(
6
,
16
,
5
)
self
.
fc1
=
nn
.
Linear
(
16
*
5
*
5
,
120
)
self
.
fc2
=
nn
.
Linear
(
120
,
84
)
self
.
fc3
=
nn
.
Linear
(
84
,
10
)
def
forward
(
self
,
x
):
x
=
self
.
pool
(
F
.
relu
(
self
.
conv1
(
x
)))
x
=
self
.
pool
(
F
.
relu
(
self
.
conv2
(
x
)))
x
=
x
.
view
(
-
1
,
16
*
5
*
5
)
x
=
F
.
relu
(
self
.
fc1
(
x
))
x
=
F
.
relu
(
self
.
fc2
(
x
))
x
=
self
.
fc3
(
x
)
return
x
model
=
TheModelClass
()
optimizer
=
optim
.
SGD
(
model
.
parameters
(),
lr
=
0.001
,
momentum
=
0.9
)
print
(
"Model's state_dict:"
)
for
param_tensor
in
model
.
state_dict
():
print
(
param_tensor
,
"
\t
"
,
model
.
state_dict
()[
param_tensor
]
.
size
())
print
(
"Optimizer's state_dict:"
)
for
var_name
in
optimizer
.
state_dict
():
print
(
var_name
,
"
\t
"
,
optimizer
.
state_dict
()[
var_name
])
'params'
[
4675713712
4675713784
4675714000
4675714072
4675714216
4675714288
4675714432
4675714504
4675714648
4675714720
]}]
eval
()
This save/load process uses the most intuitive syntax and involves the
least amount of code. Saving a model in this way will save the entire
module using Python’s
pickle module. The
disadvantage of this approach is that the serialized data is bound to
the specific classes and the exact directory structure used when the
model is saved. The reason for this is because pickle does not save the
model class itself. Rather, it saves a path to the file containing the
class, which is used during load time. Because of this, your code can
break in various ways when used in other projects or after refactors.
A common PyTorch convention is to save models using either a .pt or
.pth file extension.
Remember that you must call model.eval() to set dropout and batch
normalization layers to evaluation mode before running inference.
Failing to do this will yield inconsistent inference results.
.
load_state_dict
(
checkpoint
[
'model_state_dict'
])
optimizer
.
load_state_dict
(
checkpoint
[
'optimizer_state_dict'
])
epoch
=
checkpoint
[
'epoch'
]
loss
=
checkpoint
[
'loss'
]
model
.
eval
()
model
.
train
()
When saving a general checkpoint, to be used for either inference or
resuming training, you must save more than just the model’s
state_dict. It is important to also save the optimizer’s state_dict,
as this contains buffers and parameters that are updated as the model
trains. Other items that you may want to save are the epoch you left off
on, the latest recorded training loss, external torch.nn.Embedding
layers, etc. As a result, such a checkpoint is often 2~3 times larger
than the model alone.
To save multiple components, organize them in a dictionary and use
torch.save() to serialize the dictionary. A common PyTorch
convention is to save these checkpoints using the .tar file
extension.
To load the items, first initialize the model and optimizer, then load
the dictionary locally using torch.load(). From here, you can easily
access the saved items by simply querying the dictionary as you would
expect.
Remember that you must call model.eval() to set dropout and batch
normalization layers to evaluation mode before running inference.
Failing to do this will yield inconsistent inference results. If you
wish to resuming training, call model.train() to ensure these layers
are in training mode.
(
*
args
,
**
kwargs
)
checkpoint
=
torch
.
load
(
PATH
,
weights_only
=
True
)
modelA
.
load_state_dict
(
checkpoint
[
'modelA_state_dict'
])
modelB
.
load_state_dict
(
checkpoint
[
'modelB_state_dict'
])
optimizerA
.
load_state_dict
(
checkpoint
[
'optimizerA_state_dict'
])
optimizerB
.
load_state_dict
(
checkpoint
[
'optimizerB_state_dict'
])
modelA
.
eval
()
modelB
.
eval
()
modelA
.
train
()
modelB
.
train
()
When saving a model comprised of multiple torch.nn.Modules, such as
a GAN, a sequence-to-sequence model, or an ensemble of models, you
follow the same approach as when you are saving a general checkpoint. In
other words, save a dictionary of each model’s state_dict and
corresponding optimizer. As mentioned before, you can save any other
items that may aid you in resuming training by simply appending them to
the dictionary.
A common PyTorch convention is to save these checkpoints using the
.tar file extension.
To load the models, first initialize the models and optimizers, then
load the dictionary locally using torch.load(). From here, you can
easily access the saved items by simply querying the dictionary as you
would expect.
Remember that you must call model.eval() to set dropout and batch
normalization layers to evaluation mode before running inference.
Failing to do this will yield inconsistent inference results. If you
wish to resuming training, call model.train() to set these layers to
training mode.
args
,
**
kwargs
)
model
.
load_state_dict
(
torch
.
load
(
PATH
,
weights_only
=
True
))
model
.
to
(
device
)
When loading a model on a GPU that was trained and saved on GPU, simply
convert the initialized model to a CUDA optimized model using
model.to(torch.device('cuda')). Also, be sure to use the
.to(torch.device('cuda')) function on all model inputs to prepare
the data for the model. Note that calling my_tensor.to(device)
returns a new copy of my_tensor on GPU. It does NOT overwrite
my_tensor. Therefore, remember to manually overwrite tensors:
my_tensor = my_tensor.to(torch.device('cuda')).
args
,
**
kwargs
)
model
.
load_state_dict
(
torch
.
load
(
PATH
,
weights_only
=
True
,
map_location
=
"cuda:0"
))
model
.
to
(
device
)
When loading a model on a GPU that was trained and saved on CPU, set the
map_location argument in the torch.load() function to
cuda:device_id. This loads the model to a given GPU device. Next, be
sure to call model.to(torch.device('cuda')) to convert the model’s
parameter tensors to CUDA tensors. Finally, be sure to use the
.to(torch.device('cuda')) function on all model inputs to prepare
the data for the CUDA optimized model. Note that calling
my_tensor.to(device) returns a new copy of my_tensor on GPU. It
does NOT overwrite my_tensor. Therefore, remember to manually
overwrite tensors: my_tensor = my_tensor.to(torch.device('cuda')).
DataParallel
model.module.state_dict()