30 Mins

6. Saving, Loading, & Inference

Persistence: Saving and Loading Model State

In PyTorch, the standard way to save a model is by saving its state_dict, which is a Python dictionary object that maps each layer to its parameter tensor. Using torch.save(model.state_dict(), PATH) is preferred over saving the entire model object because it is more robust, avoids pickling issues when directory structures change, and allows for greater flexibility during checkpointing.

To load a saved model, you must instantiate the original model class structure and then use the load_state_dict method. This ensures that the model architecture perfectly aligns with the parameters stored in the file, preventing runtime errors caused by structural mismatches.

Operator Note: Always save your model using the .pth or .pt extension for better compatibility with IDEs and cloud serving platforms.
Python 3
import torch
import torch.nn as nn

# Define a simple linear model
model = nn.Linear(10, 2)

# Save the state_dict
torch.save(model.state_dict(), 'model.pth')

# Load the state_dict into a new instance
new_model = nn.Linear(10, 2)
new_model.load_state_dict(torch.load('model.pth'))
print('Model loaded successfully.')

Mode Toggling: The Crucial Role of train() and eval()

PyTorch modules like Dropout and Batch Normalization behave differently during training and inference. The .train() method sets the module to training mode, where Dropout randomly zeroes out elements and Batch Norm updates its running mean and variance statistics based on the current batch.

Conversely, calling .eval() is non-negotiable for inference. In this state, Dropout layers become inactive (they pass inputs through unchanged), and Batch Normalization uses the accumulated running statistics rather than the current batch statistics to ensure deterministic and stable predictions.

Operator Note: Always wrap your inference code in 'with torch.no_grad():' to disable gradient calculation, which reduces memory consumption and speeds up computation.
Python 3
import torch.nn as nn

model = nn.Sequential(nn.Dropout(0.5), nn.BatchNorm1d(10))

# Set to inference mode
model.eval()
# Now Dropout is a no-op, and BatchNorm uses running stats
input_data = torch.randn(1, 10)
with torch.no_grad():
    output = model(input_data)

Production Deployment Paths

Moving beyond state_dict saving, production-grade deployment often requires TorchScript. TorchScript allows you to serialize your model into an intermediate representation that is decoupled from Python, enabling inference in environments like C++ or optimized high-performance runtimes.

By using either tracing (torch.jit.trace) or scripting (torch.jit.script), you can compile your model. This optimization phase can fuse layers and prune unused code paths, creating a highly efficient model graph suitable for high-throughput serving environments like NVIDIA Triton or AWS Sagemaker.

Operator Note: While state_dict is great for development checkpoints, always prefer TorchScript or ONNX exports for production deployments to minimize latency.
Python 3
import torch

model = torch.nn.Linear(10, 5).eval()
example_input = torch.rand(1, 10)

# Trace the model to create a script module
traced_model = torch.jit.trace(model, example_input)
traced_model.save('model_scripted.pt')

Knowledge Check

Ready to test your understanding of 6. Saving, Loading, & Inference?

Back