Model Saving

During training in PyTorch, torch.save() is typically used to save checkpoint files. Model files are saved in two formats depending on their subsequent use, as described below.

.pth or .pt File

Files with .pth or .pt extensions are used for online inference. Only model parameters are saved, without the model structure, in order to reduce file size. They can be opened with visualization tools such as Netron, as shown in Figure 1.

Figure 1 .pth file

Save and load the model via state_dict.

The following is a simple model. For an end-to-end example, see train_1p.py.

# Create the save path
save_pt_path = "state_dict_model.pt"
# Save the model
torch.save(model.state_dict(), save_pt_path) # model is the variable defined during previous training

Load the model for online inference. An example is as follows:

# Model file save path
save_pt_path = "state_dict_model.pt"

model = TheModelClass(*args, **kwargs)        # Fill in the function and parameters based on the actual model definition
# Take model = ToyModel() as an example
  
# Load the model
model.load_state_dict(torch.load(save_pt_path))
model.eval()

Note

When saving as a .pth or .pt file, you must provide the model definition file; otherwise, the model cannot be deployed later.

.pth.tar File

Files with the .pth.tar extension are typically used to save training checkpoints, which can be reloaded to resume training. The file content is generally saved in dictionary format, which may include the model's state_dict, the optimizer's state_dict, the stopping epoch, and the most recent training loss. For inference-only deployment, it is usually enough to save just the model's state_dict and load it together with the model definition for restoration.

The following is a simple model. For an end-to-end example, see train_1p.py.

checkpoint_path = "checkpoint.pth.tar"
torch.save({
    'epoch': epoch,
    'loss': loss,
    'state_dict': model.state_dict(),
    'optimizer': optimizer.state_dict(),
    ...
}, checkpoint_path)

An example of loading a model for inference or resumable training is shown below:

model = TheModelClass(*args, **kwargs)            # Fill in the function and parameters according to the actual model definition
optimizer = TheOptimizerClass(*args, **kwargs)    # Fill in the function and parameters based on the actual optimizer
  
checkpoint = torch.load(checkpoint_path)
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']
  
model.eval()
# - or -
model.train()

[!NOTICE]

Typically, the same operator, for example, operators such as BatchNorm and Dropout, may behave differently in training mode and inference mode. Therefore, before running inference, you must call model.eval() to set the model to inference mode.