Training is not the finish line. A model must be saved, loaded, versioned, and served consistently. Inference code should use the same preprocessing as training, put the model in eval mode, disable gradients, and return stable outputs.
PyTorch commonly saves state dictionaries rather than entire model objects. This is safer because code defines architecture and checkpoint files store learned weights.
A training checkpoint should contain enough information to resume training and audit the experiment. An inference artifact may contain only the model state and class labels.
Inference should be deterministic and memory efficient. Use eval mode, no_grad or inference_mode, correct device handling, and input validation.
This pattern supports both resuming training and loading the best validation model.
import torch
def save_checkpoint(path, model, optimizer, epoch, metrics, class_names):
torch.save({
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"metrics": metrics,
"class_names": class_names,
}, path)
def load_for_training(path, model, optimizer, device):
checkpoint = torch.load(path, map_location=device)
model.load_state_dict(checkpoint["model_state_dict"])
optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
return checkpoint["epoch"], checkpoint["metrics"]
This function is the shape of a safe inference boundary.
@torch.inference_mode()
def predict(model, batch, device, class_names):
model.eval()
batch = batch.to(device)
logits = model(batch)
probabilities = torch.softmax(logits, dim=1)
confidence, class_id = probabilities.max(dim=1)
return [
{
"class": class_names[idx.item()],
"confidence": conf.item(),
}
for conf, idx in zip(confidence, class_id)
]
Use TorchScript when staying in PyTorch-serving environments. Use ONNX when you need broader runtime interoperability. Test exported outputs against PyTorch outputs.
state_dict stores weights separately from code, making artifacts less brittle and easier to load across controlled code versions.
Save model and optimizer states, scheduler and scaler states, epoch position, and relevant random-generator states.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.