Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Model Saving and Loading

PyTorch Model Saving and Loading

In deep learning projects, model saving and loading are crucial steps, mainly for the following reasons:

  1. Resume from Training Interruption: when training is unexpectedly interrupted, you can resume from a saved checkpoint
  2. Model Deployment: deploy a trained model to a production environment
  3. Model Sharing: facilitate sharing model results among team members
  4. Transfer learning: save pre-trained models for other tasks
  5. Performance Evaluation: save models from different training stages for comparison

Basic Saving and Loading Methods

Save the Entire Model

This is the simplest method, saving both the model architecture and parameters:

Example

import

torch

import

torchvision.

models

as

models

Create and train a model

model

=

models.

resnet18

(

pretrained

=

True

)

... training code ...

Save the Entire Model

torch.

save

(

model

,

'model.pth'

)

Load the Entire Model

loaded_model

=

torch.

load

(

'model.pth'

)

Advantages:

Disadvantages:

Save Only Model Parameters (Recommended)

A more recommended approach is to save only the model's state dictionary (state_dict):

Example

Save model parameters

torch.

save

(

model.

state_dict

(

)

,

'model_weights.pth'

)

Load Model Parameters

model

=

models.

resnet18

(

)

 

You must first create a model with the same architecture

model.

load_state_dict

(

torch.

load

(

'model_weights.pth'

)

)

model.

eval

(

)

 

Set to evaluation mode

Advantages:


Saving and Loading Training State

In real projects, we usually also need to save the optimizer state, epoch, and other information:

Example

Save a Checkpoint

checkpoint

=

{

   

'epoch'

: epoch

,

   

'model_state_dict'

: model.

state_dict

(

)

,

   

'optimizer_state_dict'

: optimizer.

state_dict

(

)

,

   

'loss'

: loss

,

   

You can add other information that needs to be saved

}

torch.

save

(

checkpoint

,

'checkpoint.pth'

)

Load a Checkpoint

checkpoint

=

torch.

load

(

'checkpoint.pth'

)

model.

load_state_dict

(

checkpoint

[

'model_state_dict'

]

)

optimizer.

load_state_dict

(

checkpoint

[

'optimizer_state_dict'

]

)

epoch

=

checkpoint

[

'epoch'

]

loss

=

checkpoint

[

'loss'

]

model.

eval

(

)

 

or model.train() depending on your needs


Cross-Device Model Loading

CPU/GPU Compatibility Handling

Example

Specify map_location when saving

torch.

save

(

model.

state_dict

(

)

,

'model_weights.pth'

)

Load onto CPU (when the model was trained on GPU)

device

=

torch.

device

(

'cpu'

)

model.

load_state_dict

(

torch.

load

(

'model_weights.pth'

,

map_location

=

device

)

)

Load onto GPU

device

=

torch.

device

(

'cuda'

)

model.

load_state_dict

(

torch.

load

(

'model_weights.pth'

,

map_location

=

device

)

)

model.

to

(

device

)

Loading Multi-GPU Trained Models

Example

Save a Multi-GPU Model

torch.

save

(

model.

module

.

state_dict

(

)

,

'multigpu_model.pth'

)

Load onto a Single GPU

model

=

ModelClass

(

)

model.

load_state_dict

(

torch.

load

(

'multigpu_model.pth'

)

)


Model Conversion and Compatibility

PyTorch Version Compatibility

Example

Specify _use_new_zipfile_serialization=True when saving for better compatibility

torch.

save

(

model.

state_dict

(

)

,

'model.pth'

,

_use_new_zipfile_serialization

=

True

)

Convert to TorchScript

Example

Convert a model to TorchScript format

scripted_model

=

torch.

jit

.

script

(

model

)

torch.

jit

.

save

(

scripted_model

,

'model_scripted.pt'

)

Load a TorchScript Model

loaded_script

=

torch.

jit

.

load

(

'model_scripted.pt'

)


Best Practices and Common Issues

Best Practices

  1. Naming Convention: use meaningful file names, such asresnet18_epoch50.pth
  2. Save Regularly: save a checkpoint every few epochs
  3. Verify Loading: test loading immediately after saving
  4. Documentation: record the model architecture and training parameters
  5. Versioning: put model files under version control

Common Problem Solutions

Problem 1:Missing key(s) in state_dict
Solution: ensure the model architecture matches exactly, or usestrict=FalseParameters:



model.load_state_dict(torch.load('model.pth'), strict=False)

Problem 2:CUDA out of memory
Solution: first load onto CPU:

Example

model.

load_state_dict

(

torch.

load

(

'model.pth'

,

map_location

=

'cpu'

)

)

Problem 3: cannot load a model from an older version
Solution: try loading in different PyTorch versions, or convert the model format


Practical Application Examples

Image Classification Model Saving and Loading Flow

Complete Code Example

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

Define a Simple Model

class

SimpleModel

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

SimpleModel

,

self

)

.

init

(

)

       

self

.

fc

=

nn.

Linear

(

10

,

2

)

   

   

def

forward

(

self

,

x

)

:

       

return

self

.

fc

(

x

)

Initialization

model

=

SimpleModel

(

)

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.01

)

criterion

=

nn.

CrossEntropyLoss

(

)

Simulate the Training Process

for

epoch

in

range

(

5

)

:

   

Simulate a training step

    inputs

=

torch.

randn

(

32

,

10

)

    labels

=

torch.

randint

(

0

,

2

,

(

32

,

)

)

   

    optimizer.

zero_grad

(

)

    outputs

=

model

(

inputs

)

    loss

=

criterion

(

outputs

,

labels

)

    loss.

backward

(

)

    optimizer.

step

(

)

   

   

Save a checkpoint every 2 epochs

   

if

epoch %

2

==

0

:

        checkpoint

=

{

           

'epoch'

: epoch

,

           

'model_state_dict'

: model.

state_dict

(

)

,

           

'optimizer_state_dict'

: optimizer.

state_dict

(

)

,

           

'loss'

: loss.

item

(

)

,

       

}

        torch.

save

(

checkpoint

,

f

'checkpoint_epoch{epoch}.pth'

)

       

print

(

f

'Checkpoint saved at epoch {epoch}'

)

Final Save

torch.

save

(

model.

state_dict

(

)

,

'final_model.pth'

)

Loading Example

loaded_model

=

SimpleModel

(

)

loaded_model.

load_state_dict

(

torch.

load

(

'final_model.pth'

)

)

loaded_model.

eval

(

)

Test the Loaded Model

test_input

=

torch.

randn

(

1

,

10

)

with

torch.

no_grad

(

)

:

    output

=

loaded_model

(

test_input

)

print

(

f

'Test output: {output}'

)