Lab Session 4 - Deep Learning Tutorial⚓
Note
Before you begin, make sure you have downloaded the latest update of the course slides from here, and keep them close while doing the lab.
Warning
We will work with pytorch. If you don't have a GPU (which is very likely to be the case if you use a laptop), we recommend installing pytorch in "cpu only" mode as it will be much smaller to download. See pytorch installation instructions and select "cpu only" as compute platform.
If you run this notebook on Google Colab, you'll have access to a GPU.
Objectives of the lab⚓
At the end of this session, you will be able to : - Understand how PyTorch works. - Process data with PyTorch. - Train a Deep Learning model on your data. - Adapt this tutorial for the specificites of your modality.
0. What is this PyTorch?⚓
This session is a Deep Learning tutorial in Pytorch.
PyTorch is a Python-based scientific computing package serving two broad purposes:
- A replacement for NumPy to use the power of GPUs and other accelerators.
- An automatic differentiation library that is useful to implement Deep Learning architectures.
Note
PyTorch is one of the standard librairies to define neural networks. This tutorial is loosely based on the 60 min blitz Deep Learning with Pytorch but with many original parts.
The tutorial is structured as follows:
- Tensors in Pytorch
- Understanding the training loop and automatic differentiation
- Defining a Deep Learning Architecture
- Training a Classifier on CIFAR10, a standard image classification dataset
- Study specificities of Text, Audio and Image modalities
Note
Copy / modify / playaround with the code snippets that we provide. In part 4, you are expected to complete some empty cells to successfully train and test your net.
1. Tensors⚓
Tensors are a specialized data structure that are very similar to arrays and matrices. In PyTorch, we use tensors to encode the inputs and outputs of a model, as well as the model’s parameters.
Tensors are similar to NumPy’s ndarrays, except that tensors can run on GPUs or other specialized hardware to accelerate computing. If you’re familiar with ndarrays, you’ll be right at home with the Tensor API. If not, follow along in this quick API walkthrough.
1 2 | |
Tensor Initialization⚓
Tensors can be initialized in various ways. Take a look at the following examples:
Directly from data
Tensors can be created directly from data. The data type is automatically inferred.
1 2 | |
From a NumPy array
Tensors can be created from NumPy arrays (and vice versa).
1 2 | |
From another tensor:
The new tensor retains the properties (shape, datatype) of the argument tensor, unless explicitly overridden.
1 2 3 4 5 | |
With random or constant values:
shape is a tuple of tensor dimensions. In the functions below, it determines the dimensionality of the output tensor.
1 2 3 4 5 6 7 8 | |
Tensor Attributes⚓
Tensor attributes describe their shape, datatype, and the device on which they are stored.
1 2 3 4 5 | |
Tensor Operations⚓
Over 100 tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random sampling, and more are comprehensively described here.
Try out some of the operations from the list. If you're familiar with the NumPy API, you'll find the Tensor API a breeze to use.
Standard numpy-like indexing and slicing:
1 2 3 | |
Joining tensors You can use torch.cat to concatenate a sequence of tensors along a given dimension. See also torch.stack, another tensor joining operation that is subtly different from torch.cat.
1 2 | |
Multiplying tensors
1 2 3 4 | |
This computes the matrix multiplication between two tensors
1 2 3 | |
Bridge to NumPy
Tensor to NumPy array
1 2 3 4 | |
NumPy array to Tensor
1 2 | |
Changes in the NumPy array reflects in the tensor.
1 2 3 | |
2. Defining a Deep Learning Model⚓
A deep learning model takes the input, feeds it through several layers one after the other, and then finally gives the output.
A deep learning model can be constructed using the modules from the torch.nn package.
A typical training procedure for a deep learning model is as follows:
- Define the model that has some learnable parameters ("weights")
- Iterate over a dataset of inputs
- Process input through the model ("forward pass")
- Compute the loss (how far is the output from being correct)
- Propagate gradients back into the model’s parameters ("backpropagation")
- Update the weights of the model, typically using a simple update rule ("Gradient Descent"):
Define the model⚓
Let’s define a simple deep learning model :
- take as input a greyscale image (1 input channel),
- processes it with 2 layers of 2D convolutional filters (Conv2d), each followed by ReLu and 2D max pooling,
- followed by a 3 layer perceptron, which is composed of Linear units and ReLu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
The forward function of the model class is the one that implements the forward pass, which is the sequence of operations from input to output. It is possible to use all operators from nn.functional and modules defined in nn, as well as operations on tensors.
The backward function (where gradients are computed) is automatically defined for you in PyTorch. Under the hood, it uses a module called autograd, and details about autograd can be found here.
The learnable parameters of a model are returned by net.parameters()
1 2 3 | |
Let's try a random 32x32 input. (Note: expected input size of this net is 32x32.)
Warning
torch.nn only supports inputs in the form of batches, i.e. subsets of the datasets. In other words, the entire torch.nn package only supports inputs that are arrays of several samples ("batch"), and not a single sample.
For example, nn.Conv2d will take in a 4D Tensor of nSamples x nChannels x Height x Width.
If you have a single sample, just use input.unsqueeze(0) to add a fake batch dimension.
1 2 3 4 | |
In order to better understand the inner operations of the model, let's break down the forward pass layer by layer, and print the successive shapes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
Try changing the size (32x32) of the image input and see what happens !
1 | |
Before proceeding further, let's recap all the classes you’ve seen so far.
Recap:
torch.Tensor- A multi-dimensional array with support for autograd operations likebackward(). Also holds the gradient w.r.t. the tensor.nn.Module- Neural network module, basic blocks for defining a model. Convenient way of encapsulating parameters, with helpers for moving them to GPU, exporting, loading, etc.nn.Parameter- A kind of Tensor, that is automatically registered as a parameter of a model when assigned as an attribute to aModule.- These modules allowed us to define the constructor (init) and the forward pass for a model.
At this point, we covered:
- Defining a model
- Processing inputs (forward pass)
Still Left:
- Computing the loss
- Updating the weights of the network ("backpropgation")
Loss Function⚓
A loss function takes the (output, target) pair of inputs, and computes a value that estimates how far away the output is from the target.
There are several different loss functions inside the nn package. A simple loss is: nn.MSELoss which computes the mean-squared error between the input and the target. This loss is adapted for regression problems when the targets are continuous.
For example:
1 2 3 4 5 6 7 | |
Note
The nn package contains various modules and loss functions that form the building blocks of deep neural networks. A full list with documentation can be found here. Don't hesitate to use the most appropriate functions for your model!
Backpropagation⚓
To backpropagate, we first have to compute the gradients w.r.t. the error. This is done in PyTorch using loss.backward(). Under the hood, it uses autograd (see here for details about autograd).
Be careful though: you first need to clear the existing gradients! Otherwise, gradients will be accumulated to existing gradients (e.g., gradients computed at the previous iteration).
Let's call loss.backward() and have a look at conv1's bias gradients before and after the backward.
1 2 3 4 5 6 7 8 9 | |
In most applications, defining the loss and performing the backward propagation process using loss.backward() is sufficient. Hence, in practice, you will rarely need to have a look at the gradients when training a deep model, but it's good to know how to do it if you need it.
Now that the loss (error) is computed, we can update the weights of the model. The simplest update rule used in practice is the Stochastic Gradient Descent (SGD):
We could implement this using a (pseudo) Python code such as this one :
1 2 3 | |
However, there are various update rules (e.g. SGD, Nesterov-SGD, Adam, RMSProp, etc) with implementation details in order to accelerate the update or make the convergence more rbosut. Going into their details is way out of the scope of this course. Hence, computing the gradient descent by hand is largely inefficient.
Instead, PyTorch natively implements updates rules in the torch.optim module ("optimizers"), and using this module is really simple:
1 2 3 4 5 6 7 8 9 10 11 | |
We have seen how to define a deep learning model, compute loss and make updates to the weights of the network.
The last important step, is to preprocess the data!
Input Data⚓
Generally, when you have to deal with image, text, audio or video data, you can use standard python packages that load data into a numpy array. Then you can convert this array into a torch.Tensor.
- For images, packages such as Pillow (PIL), OpenCV are useful
- For audio, packages such as scipy and librosa or torchaudio
- For text, either raw Python or Cython based loading, or NLTK and SpaCy are useful
Specifically for vision, pytorch has created a package called torchvision, that has data loaders for common datasets such as Imagenet, CIFAR10, MNIST, etc. and data transformers for images, torchvision.datasets and torch.utils.data.DataLoader.
There is a similar package for audio, which is called torchaudio.
This provides a huge convenience and avoids writing boilerplate code.
For this tutorial, we will use the CIFAR10 dataset. It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size.
This is it. You are finally ready to:
3. Train a Classifier!⚓
We will do the following steps in order:
a. Load and normalizing the CIFAR10 training and test datasets using torchvision
b. Define a Convolutional Neural Network
c. Define a loss function
d. Train the network on the training data
e. Test the network on the test data
(bonus). Use a GPU
a. Loading and normalizing CIFAR10⚓
Using torchvision, it’s extremely easy to load CIFAR10.
1 2 3 | |
The output of torchvision datasets are PILImage images of range [0, 1].
We transform them to Tensors of normalized range [-1, 1].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Warning
If running on Windows you get a BrokenPipeError, try setting the num_worker of torch.utils.data.DataLoader() to 0.
Let us show some of the training images, for fun.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 | |
b. Define a Convolutional Neural Network⚓
Copy the neural network from the Neural Networks section before and modify it to take 3-channel (color) images, instead of 1-channel (black and white) images as it was defined.
Note
Pay attention to the in/out features dimensions, especially at the transition between a Convolution (Conv) and Fully connected (fc) linear layer!
In each convolutional layer, the feature size may be reduced by the conv operation (see below), and is then divided by the 2D max pooling layer!
You can compute the size of the output of a convolution operation based on the following formula: Denote as h_out the output size of a 2D Conv layer, h_out depends on h_in (size features input), k (convolutional kernel size), p (zero padding), and s (stride) (more details in Conv2D documentation).
1 | |
c. Define a Loss function and optimizer⚓
Let's use a Classification Cross-Entropy loss and SGD with momentum.
1 | |
d. Train the network⚓
This is when things start to get interesting! We simply have to loop over our data iterator, and feed the inputs to the network and optimize.
In this tutorial we will consider a small number of iterations over the dataset n_epochs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
e. Test the network on the test data⚓
We have trained the network for n_epochs passes over the training dataset.
But we need to check if the network has learnt anything at all.
We will check this by predicting the class label that the neural network outputs, and checking it against the ground-truth. If the prediction is correct, we add the sample to the list of correct predictions.
First things first, let us display an image from the test set to get familiar.
1 2 3 4 5 | |
Now, we turn to the neural network, and observe how it predicted the above examples.
The outputs are energies for the 10 classes. The higher the energy for a class, the more the network thinks that the image is of the particular class. So, let's get the index of the highest energy:
1 2 3 4 5 6 7 | |
Let us look at how the network performs on the whole dataset.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
That looks way better than chance, which is 10% accuracy (randomly picking a class out of 10 classes). Seems like the network learnt something.
Hmmm, what are the classes that performed well, and the classes that did not perform well:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
In order to have a better intuition about what a 2D-convolutional layer is, we will feed a batch of images into the first convolutional layer, and visualize the result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 | |
1 | |
You can see that the output of the first convolutional layer corresponds to filtered versions of the input. Convolutions can enhance or reduce some local contrast changes, or edges / contours. A convolutional neural network model will generate many different "feature maps" such as this one.
Let's now see the effect of relu and max pooling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 | |
1 | |
1 2 3 4 | |
By alternating 2D convolutional filter, which have the effect of amplifying / decreasing contrasts, edges, etc.. then ReLu which act as a threshold, and max pooling which reduces the resolution while keeping the largest values, many smaller "images" (also called "feature maps")are computed as the model gets deeper.
Saving/loading the model⚓
It may be useful to save your model after training (for instance to share it with your binome, to compare different models, or to share it with the community). This can be done in the following way:
1 2 3 4 5 6 7 | |
See [here] (https://pytorch.org/docs/stable/notes/serialization.html) for more details on saving PyTorch models.
(optional) Training on GPU⚓
Using GPU is preferred over CPU for deep learning models, because GPUs are way more powerful at computing matrix products. How do we run these neural networks on the GPU?
Just like how you transfer a Tensor onto the GPU, you transfer the neural net onto the GPU.
Note
PyTorch uses CUDA to easily transfer evertyhing to GPUs.
Let's first define our device as the first visible cuda device if we have CUDA available:
1 2 3 4 5 | |
The rest of this section assumes that device is a CUDA device. Otherwise, it means that you cannot run the code on a GPU (either you don't have a GPU, or the installation is broken).
The following method will recursively go over all modules and convert their parameters and buffers to CUDA tensors:
1 | |
Additionally, you will have to send the inputs and targets at every step to the GPU too:
1 | |
Why don't I notice MASSIVE speedup compared to CPU? Because your network is really small.
4. Specificities of modalities⚓
Let's turn to your modalities!
Here are links for specificities to deal with your modalities :
- Text : An introduction to Tokenization
- Audio : An introduction to dealing with audio data
- Image : Preprocessing for Computer Vision
You must follow the tutorial corresponding to your modality to end the Lab.
Tutorial ended!⚓
Goals achieved:
- Understanding PyTorch's Tensor library and neural networks at a high level.
- Train a small neural network to classify images
- Learned the basic components to apply a neural network to your modality



