Saving, Loading, and Checkpointing Models
6 min read
Course: PyTorch
πΎ Saving, Loading, and Checkpointing Models
Hello there! So you've spent hours, maybe even days, training your magnificent neural network. It's learning, it's improving, and then... the power goes out. Or your cloud instance times out. Or you simply want to close your laptop and use your amazing trained model in an application tomorrow.
This is where saving and loading your model's progress comes in. It's like saving your progress in a video game. You wouldn't want to start from level 1 every single time, right? In this guide, we'll cover the essential, industry-standard ways to save your work, so you never have to say, "Oops, I trained it again... from scratch."
1. Understanding the state_dict π§
The Problem: How do we save the "knowledge" of a model without saving a ton of unnecessary information?
The Solution: The state_dict!
A state_dict is a simple Python dictionary object that maps each layer of your model to its learned parameters (weights and biases). Think of it as the model's brain. It doesn't include the model's architecture (the "body"), just the learned knowledge.
- What's inside? Only the layers with learnable parameters (like convolutional layers, linear layers, etc.) and registered buffers (like the running mean in batch normalization) have entries in the model's
state_dict. - What about optimizers? Optimizer objects (
torch.optim) also have astate_dict. This dictionary contains information about the optimizer's state and the hyperparameters it's using (like the learning rate). This is crucial for resuming training, as we'll see later.
Because state_dict objects are just Python dictionaries, they are incredibly flexible and easy to save, load, and even modify.
Let's look at a quick example. First, let's define a simple model.
import torch
import torch.nn as nn
import torch.optim as optim
# Define a simple model
class MyAwesomeNet(nn.Module):
def __init__(self):
super(MyAwesomeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
self.relu = nn.ReLU()
self.fc1 = nn.Linear(16 * 24 * 24, 10) # Assuming 24x24 input image
def forward(self, x):
x = self.relu(self.conv1(x))
x = x.view(x.size(0), -1) # Flatten
x = self.fc1(x)
return x
model = MyAwesomeNet()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Let's print the model's state_dict keys
print("Model's state_dict keys:")
for param_tensor in model.state_dict():
print(param_tensor, "\t", model.state_dict()[param_tensor].size())
print("\nOptimizer's state_dict keys:")
# Note: The optimizer's state_dict is empty before the first .step() call
# Let's fake a training step to populate it
dummy_input = torch.randn(1, 3, 24, 24)
optimizer.zero_grad()
output = model(dummy_input)
loss = output.sum()
loss.backward()
optimizer.step()
for state in optimizer.state_dict():
print(state)Industry Practice: The most common and recommended way to save a model is by saving its
state_dict. Saving the entire model object can seem easier, but it tightly binds the saved file to your specific code structure. If you refactor your code or use the model in another project, loading can easily break. Saving thestate_dictgives you much more flexibility.
2. Saving and Loading Model Weights for Inference π
The Problem: You have a trained model, and now you want to use it in an application to make predictions (this is called "inference"). You need a lightweight and reliable way to load its knowledge.
The Solution: Save the model's state_dict and then load it into a new instance of the model architecture.
This is the most common scenario. Here's the two-step process:
Step 1: Save the state_dict
We use torch.save() to save the state_dict dictionary to a file. A common convention is to use .pt or .pth as the file extension.
# Assume 'model' is our trained model instance
PATH = "my_awesome_model.pth"
torch.save(model.state_dict(), PATH)That's it! You now have a file my_awesome_model.pth containing all the learned weights and biases.
Step 2: Load the state_dict
To load the model for inference, you must first create an instance of the model structure and then load the dictionary of weights into it.
# Create a new instance of the model
loaded_model = MyAwesomeNet()
# Load the saved state_dict
# Note: You must deserialize the saved object before passing it to load_state_dict
loaded_model.load_state_dict(torch.load(PATH))
# β IMPORTANT: Set the model to evaluation mode
# This is crucial for layers like Dropout and BatchNorm, which behave differently
# during training and inference.
loaded_model.eval()β οΈ Don't Forget model.eval()!
Calling model.eval() is a critical step. It tells PyTorch to turn off behaviors like dropout and use the learned running statistics for batch normalization. Forgetting this will lead to inconsistent and likely worse prediction results.
3. Checkpointing: Saving Optimizer State and Epoch Iterations π
The Problem: Training can take a long, long time. What if your program crashes 10 hours into a 12-hour training run? Starting from scratch would be a disaster. You need a way to save not just the model's weights, but the entire training state, so you can resume exactly where you left off.
The Solution: Create a "checkpoint" file. A checkpoint is a dictionary that saves everything needed to resume training seamlessly:
- The model's
state_dict - The optimizer's
state_dict - The epoch you left off on
- The latest training loss
- Anything else you might need!
Saving the optimizer's state is especially important for adaptive optimizers like Adam, which maintain internal states (momentum and variance estimates) that evolve during training. Losing this information would be like giving your model amnesia about its learning trajectory.
Here's how to save a comprehensive checkpoint. A common convention is to use .tar for these checkpoint files.
EPOCH = 50
LOSS = 0.042
CHECKPOINT_PATH = f"model_checkpoint_epoch_{EPOCH}.tar"
# We save everything in a dictionary
torch.save({
'epoch': EPOCH,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': LOSS,
}, CHECKPOINT_PATH)Now you have a snapshot of your training process frozen in time!
4. Resuming Training from Saved Checkpoints πββοΈ
The Problem: Your training was interrupted, but luckily you were saving checkpoints. How do you load one and get the training loop back up and running as if nothing happened?
The Solution: Load the checkpoint dictionary and restore the state of your model and optimizer.
This process is the reverse of saving. You first initialize your model and optimizer, then load the saved states into them.
# First, initialize a new model and optimizer
resume_model = MyAwesomeNet()
resume_optimizer = optim.Adam(resume_model.parameters(), lr=0.001)
# Load the checkpoint
checkpoint = torch.load(CHECKPOINT_PATH)
# Restore the state
resume_model.load_state_dict(checkpoint['model_state_dict'])
resume_optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
start_epoch = checkpoint['epoch']
last_loss = checkpoint['loss']
# β IMPORTANT: Set the model to training mode
resume_model.train()
print(f"Resuming training from epoch {start_epoch + 1}")
# Now you can continue your training loop
# for epoch in range(start_epoch + 1, NUM_EPOCHS):
# #... your training code⨠model.train() vs model.eval()
Just as model.eval() is crucial for inference, model.train() is necessary when you resume training. It tells your model to re-enable layers like dropout and to update batch normalization statistics.
By mastering these saving, loading, and checkpointing techniques, you ensure your progress is safe, your models are reusable, and your training process is robust against interruptions. Happy training!
π Further Reading & References
- Official PyTorch Tutorial: Saving and Loading Models
- PyTorch Recipes: Saving and Loading a General Checkpoint for Inference and/or Resuming Training
torch.saveDocumentation: torch.save()torch.loadDocumentation: torch.load()Module.load_state_dictDocumentation: load_state_dict()
Challenge
You are in the middle of a long training run for a critical deep learning model. To prevent losing progress due to unexpected interruptions, you must implement a robust checkpointing system.
Your task is to write the PyTorch code for two distinct operations:
Saving a Checkpoint: Inside a hypothetical training loop, you need to capture the current state. Create a dictionary that includes the model's
state_dict, the optimizer'sstate_dict, the currentepochnumber, and the latest trainingloss. Save this entire dictionary to the file specified byCHECKPOINT_PATH.Resuming from a Checkpoint: After a simulated crash and restart, you need to load the saved checkpoint. Initialize a new model and optimizer, load the saved states into them, retrieve the saved
epochandlossvalues, and critically, ensure the model is set to the correct mode to continue training.
Expected result
Your final code should correctly implement both the saving and loading logic in the designated sections.
For Part 1, the solution must use torch.save() to save a dictionary object. This dictionary must contain the following keys: 'model_state_dict' mapped to model.state_dict(), 'optimizer_state_dict' mapped to optimizer.state_dict(), and keys for the epoch and loss variables.
For Part 2, the solution must first use torch.load() to load the checkpoint file into a variable. It must then correctly call resumed_model.load_state_dict() and resumed_optimizer.load_state_dict() with the corresponding states from the loaded dictionary. The final and essential step is to call resumed_model.train() to put the model in training mode.