Training with PyTorch
Introduction || Tensors || Autograd || Building Models || TensorBoard Support || ||
Introduction || Tensors || Autograd || Building Models || TensorBoard Support || ||
Follow along with the video below or on youtube.
In past videos, we’ve discussed and demonstrated:
Building models with the neural network layers and functions of the torch.nn module
The mechanics of automated gradient computation, which is central to gradient-based model training
Using TensorBoard to visualize training progress and other activities
In this video, we’ll be adding some new tools to your inventory:
We’ll get familiar with the dataset and dataloader abstractions, and how they ease the process of feeding data to your model during a training loop
We’ll discuss specific loss functions and when to use them
We’ll look at PyTorch optimizers, which implement algorithms to adjust model weights based on the outcome of a loss function
Finally, we’ll pull all of these together and see a full PyTorch training loop in action.
The Dataset and DataLoader classes encapsulate the process of
pulling your data from storage and exposing it to your training loop in
batches.
The Dataset is responsible for accessing and processing single
instances of data.
The DataLoader pulls instances of data from the Dataset (either
automatically or with a sampler that you define), collects them in
batches, and returns them for consumption by your training loop. The
DataLoader works with all kinds of datasets, regardless of the type
of data they contain.
For this tutorial, we’ll be using the Fashion-MNIST dataset provided by
TorchVision. We use torchvision.transforms.v2.Normalize() to
zero-center and normalize the distribution of the image tile content,
and download both training and validation data splits.
import torch
import torchvision
from torchvision.transforms import v2
# PyTorch TensorBoard support
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
transform =
0%| | 0.00/26.4M [00:00<?, ?B/s]
0%| | 65.5k/26.4M [00:00<01:14, 355kB/s]
1%| | 164k/26.4M [00:00<00:57, 457kB/s]
2%|▏ | 655k/26.4M [00:00<00:17, 1.46MB/s]
10%|█ | 2.65M/26.4M [00:00<00:04, 5.13MB/s]
34%|███▎ | 8.91M/26.4M [00:00<00:00, 17.7MB/s]
49%|████▉ | 13.1M/26.4M [00:01<00:00, 21.0MB/s]
65%|██████▌ | 17.2M/26.4M [00:01<00:00, 25.3MB/s]
90%|█████████ | 23.8M/26.4M [00:01<00:00, 35.3MB/s]
100%|██████████| 26.4M/26.4M [00:01<00:00, 20.1MB/s]
0%| | 0.00/29.5k [00:00<?, ?B/s]
100%|██████████| 29.5k/29.5k [00:00<00:00, 315kB/s]
0%| | 0.00/4.42M [00:00<?, ?B/s]
1%|▏ | 65.5k/4.42M [00:00<00:12, 340kB/s]
4%|▍ | 197k/4.42M [00:00<00:07, 539kB/s]
10%|█ | 459k/4.42M [00:00<00:04, 912kB/s]
36%|███▌ | 1.57M/4.42M [00:00<00:00, 3.17MB/s]
70%|███████ | 3.11M/4.42M [00:00<00:00, 5.51MB/s]
100%|██████████| 4.42M/4.42M [00:00<00:00, 5.07MB/s]
0%| | 0.00/5.15k [00:00<?, ?B/s]
100%|██████████| 5.15k/5.15k [00:00<00:00, 25.9MB/s]
Training set has 60000 instances
Validation set has 10000 instancesAs always, let’s visualize the data as a sanity check:
import matplotlib.pyplot as plt
import numpy as np
# Helper function for inline image display
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)

Trouser Trouser Coat SandalThe model we’ll use in this example is a variant of LeNet-5 - it should be familiar if you’ve watched the previous videos in this series.
import torch.nn as nn
import torch.nn.functional as F
# PyTorch models inherit from torch.nn.Module
class GarmentClassifier(nn.Module):
def __init__(self):
super
For this example, we’ll be using a cross-entropy loss. For demonstration purposes, we’ll create batches of dummy output and label values, run them through the loss function, and examine the result.
loss_fn = torch.nn.CrossEntropyLoss()
# NB: Loss functions expect data in batches, so we're creating batches of 4
# Represents the model's confidence in each of the 10 classes for a given input
dummy_outputs = torch.rand(
For this example, we’ll be using simple stochastic gradient descent with momentum.
It can be instructive to try some variations on this optimization scheme:
Learning rate determines the size of the steps the optimizer takes. What does a different learning rate do to the your training results, in terms of accuracy and convergence time?
Momentum nudges the optimizer in the direction of strongest gradient over multiple steps. What does changing this value do to your results?
Try some different optimization algorithms, such as averaged SGD, Adagrad, or Adam. How do your results differ?
# Optimizers specified in the torch.optim package
optimizer = torch.optim.SGD(
Below, we have a function that performs one training epoch. It enumerates data from the DataLoader, and on each pass of the loop does the following:
Gets a batch of training data from the DataLoader
Zeros the optimizer’s gradients
Performs an inference - that is, gets predictions from the model for an input batch
Calculates the loss for that set of predictions vs. the labels on the dataset
Calculates the backward gradients over the learning weights
Tells the optimizer to perform one learning step - that is, adjust the model’s learning weights based on the observed gradients for this batch, according to the optimization algorithm we chose
It reports on the loss for every 1000 batches.
Finally, it reports the average per-batch loss for the last 1000 batches, for comparison with a validation run
def train_one_epoch(epoch_index, tb_writer):
running_loss = 0.
last_loss =
Docs on the data utilities, including Dataset and DataLoader, at pytorch.org
A note on the use of pinned memory for GPU training
Documentation on the datasets available in TorchVision, TorchText, and TorchAudio
Documentation on the loss functions available in PyTorch
Documentation on the torch.optim package, which includes optimizers and related tools, such as learning rate scheduling
A detailed tutorial on saving and loading models
The Tutorials section of pytorch.org contains tutorials on a broad variety of training tasks, including classification in different domains, generative adversarial networks, reinforcement learning, and more
tensor([[0.5227, 0.7301, 0.3879, 0.4749, 0.0782, 0.9595, 0.2731, 0.9273, 0.6282,
0.5567],
[0.0553, 0.2698, 0.9677, 0.9083, 0.8512, 0.0733, 0.3278, 0.9623, 0.5227,
0.8953],
[0.7325, 0.7196, 0.0319, 0.9191, 0.2609, 0.6097, 0.6617, 0.4063, 0.1128,
0.5149],
[0.2570, 0.8825, 0.2047, 0.1464, 0.7476, 0.7900, 0.3416, 0.5665, 0.0610,
0.6016]])
tensor([1, 5, 3, 7])
Total loss for this batch: 2.2961769104003906There are a couple of things we’ll want to do once per epoch:
Perform validation by checking our relative loss on a set of data that was not used for training, and report this
Save a copy of the model
Here, we’ll do our reporting in TensorBoard. This will require going to the command line to start TensorBoard, and opening it in another browser tab.
# Initializing in a separate cell so we can easily add more epochs to the same run
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
writer = SummaryWriter(f'runs/fashion_trainer_{timestamp}')
epoch_number = 0
EPOCHS = 5
best_vloss = 1_000_000.
for epoch in range(EPOCHS):
print(f'EPOCH {epoch_number + 1}:')
# Make sure gradient tracking is on, and do a pass over the data
model.train(True)
avg_loss = train_one_epoch(epoch_number, writer)
running_vloss = 0.0
# Set the model to evaluation mode, disabling dropout and using population
# statistics for batch normalization.
model.eval()
# Disable gradient computation and reduce memory consumption.
with torch.no_grad():
for i, vdata in enumerate(validation_loader):
vinputs, vlabels = vdata
voutputs = model(vinputs)
vloss = loss_fn(voutputs, vlabels)
running_vloss += vloss
avg_vloss = running_vloss / (i + 1)
print(f'LOSS train {avg_loss} valid {avg_vloss}')
# Log the running loss averaged per batch
# for both training and validation
writer.add_scalars('Training vs. Validation Loss',
{ 'Training' : avg_loss, 'Validation' : avg_vloss },
epoch_number + 1)
writer.flush()
# Track best performance, and save the model's state
if avg_vloss < best_vloss:
best_vloss = avg_vloss
model_path = f'model_{timestamp}_{epoch_number}'
torch.save(model.state_dict(), model_path)
epoch_number += 1
EPOCH 1:
batch 1000 loss: 1.9652635745108127
batch 2000 loss: 0.9052902409695089
batch 3000 loss: 0.7397449058946222
batch 4000 loss: 0.645468397221528
batch 5000 loss: 0.6176268000644631
batch 6000 loss: 0.5655877286819742
batch 7000 loss: 0.5785269596131984
batch 8000 loss: 0.5210456388382009
batch 9000 loss: 0.5071101650317432
batch 10000 loss: 0.4893874109990429
batch 11000 loss: 0.4658944561849348
batch 12000 loss: 0.47671506229648364
batch 13000 loss: 0.4456375982982572
batch 14000 loss: 0.42922801233432256
batch 15000 loss: 0.42497535882936793
LOSS train 0.42497535882936793 valid 0.4328330457210541
EPOCH 2:
batch 1000 loss: 0.39239112416398714
batch 2000 loss: 0.3843224374121201
batch 3000 loss: 0.3961745523799327
batch 4000 loss: 0.3922887192061171
batch 5000 loss: 0.3877408395037928
batch 6000 loss: 0.3818856340610946
batch 7000 loss: 0.37698082695534685
batch 8000 loss: 0.40140343702136305
batch 9000 loss: 0.3950159136641887
batch 10000 loss: 0.3630793885382591
batch 11000 loss: 0.35454842985680446
batch 12000 loss: 0.36575457333672967
batch 13000 loss: 0.36060159780987305
batch 14000 loss: 0.33132429578946904
batch 15000 loss: 0.3456648207495164
LOSS train 0.3456648207495164 valid 0.3816662132740021
EPOCH 3:
batch 1000 loss: 0.3395612235102453
batch 2000 loss: 0.3111329080461583
batch 3000 loss: 0.3417170850656476
batch 4000 loss: 0.34823853657661674
batch 5000 loss: 0.3375430817813613
batch 6000 loss: 0.3260451234411739
batch 7000 loss: 0.3263871060455276
batch 8000 loss: 0.3258398874090999
batch 9000 loss: 0.3299242774377344
batch 10000 loss: 0.31727774918622165
batch 11000 loss: 0.3132680476934183
batch 12000 loss: 0.3213977004241874
batch 13000 loss: 0.3141196618589092
batch 14000 loss: 0.31595468455529774
batch 15000 loss: 0.3118095106043911
LOSS train 0.3118095106043911 valid 0.3512018322944641
EPOCH 4:
batch 1000 loss: 0.2951201605650167
batch 2000 loss: 0.2776860573143931
batch 3000 loss: 0.29999678020066406
batch 4000 loss: 0.2977859461875687
batch 5000 loss: 0.2932642808317505
batch 6000 loss: 0.31243592952477045
batch 7000 loss: 0.31030968287937866
batch 8000 loss: 0.2956587584875233
batch 9000 loss: 0.2896782423631957
batch 10000 loss: 0.2802430910715593
batch 11000 loss: 0.30512417771793116
batch 12000 loss: 0.3105422736661624
batch 13000 loss: 0.2972909490436141
batch 14000 loss: 0.3007740015379131
batch 15000 loss: 0.30024171043963
LOSS train 0.30024171043963 valid 0.33279046416282654
EPOCH 5:
batch 1000 loss: 0.2816707257943926
batch 2000 loss: 0.2714293124208034
batch 3000 loss: 0.28677609608457716
batch 4000 loss: 0.27748764843616663
batch 5000 loss: 0.2836894747605838
batch 6000 loss: 0.2642348917588679
batch 7000 loss: 0.29075609154358606
batch 8000 loss: 0.26379461509981045
batch 9000 loss: 0.2757050535863782
batch 10000 loss: 0.28349424521044786
batch 11000 loss: 0.2808729676506118
batch 12000 loss: 0.28424989291678504
batch 13000 loss: 0.2809979407788651
batch 14000 loss: 0.27653369863286115
batch 15000 loss: 0.2776913024963651
LOSS train 0.2776913024963651 valid 0.3163505494594574To load a saved version of the model:
saved_model = GarmentClassifier()
saved_model.load_state_dict(torch.load(PATH))
Once you’ve loaded the model, it’s ready for whatever you need it for - more training, inference, or analysis.
Note that if your model has constructor parameters that affect model structure, you’ll need to provide them and configure the model identically to the state in which it was saved.
Total running time of the script: (2 minutes 59.441 seconds)