Batch normalization, gradients and convolutions
Just enough deep learning for the rest of the course — backpropagation, vanishing and exploding gradients, batch and instance normalization, convolutions and transposed convolutions.
Gradient descent and backpropagation
In the topic Fitting distributions with KL we fitted a Gaussian, and maximum likelihood had a closed form: match the mean and the covariance. The models in the rest of the course are neural networks, and no such formula exists for them. They are trained by gradient descent. This topic collects just enough deep-learning background for that: how the gradient is computed, why it can vanish or explode, the normalization layers that keep it in check, and the convolutions that image models are built from.
Gradient descent takes a loss , for us usually the negative log-likelihood averaged over a batch of training examples, and repeats one step:
where is the learning rate. All the work is in the gradient.
A network is a chain of layers. Take the simplest one, with one unit per layer and input . Layer computes a pre-activation and applies an activation function , such as ReLU:
The loss depends on only through , then , and so on up to the output. By the chain rule, each layer contributes one local factor:
Backpropagation organizes this computation. The forward pass computes all and and keeps them. The backward pass starts from at the output and moves towards the input, multiplying by one local factor per layer and reading off each weight's gradient along the way. Every derivative is computed once, so the backward pass costs about as much as the forward one. With many units per layer the local factors become Jacobian matrices, but the structure is the same. In PyTorch, loss.backward() does exactly this.
Vanishing and exploding gradients
Multiply the local factors from the output back to the input. The gradient that reaches the first layer is scaled by a product of numbers:
A product of many numbers is rarely moderate. Suppose every weight equals and every ReLU is active, so . After layers the factor is :
| 3 layers | 10 layers | 50 layers | |
|---|---|---|---|
| 2 | 8 | 1024 | |
| 1.1 | 1.33 | 2.59 | 117 |
| 0.9 | 0.73 | 0.35 | 0.0052 |
| 0.5 | 0.125 |
A weight only 10% away from 1 changes the gradient by two orders of magnitude over 50 layers. When the factor is tiny, the gradients are vanishing: the early layers barely move, whatever the learning rate. When it is huge, they are exploding: one step throws the parameters far away, and training diverges (Bengio, Simard and Frasconi, 1994; Pascanu, Mikolov and Bengio, 2013).
The activation matters too. ReLU has for positive inputs and otherwise. The sigmoid has , with the maximum at , and has , also with the maximum at . So a sigmoid layer with shrinks the gradient at least fourfold.
With many units per layer, each factor is a Jacobian , and the norm of the product is at most the product of norms, . The largest singular value of each plays the role of . Deep generators, discriminators and denoisers later in the course have dozens of layers, so this is not a corner case.
Keeping gradients in check
Every remedy aims at the same thing: keep the per-layer factor close to 1, or give the gradient a path around the product.
- Initialization. Draw the initial weights with a variance that keeps the signal's scale from layer to layer. For ReLU this is He initialization, , where is the number of inputs of a unit; the 2 compensates for ReLU zeroing half of its inputs (Glorot and Bengio, 2010; He et al., 2015).
- Non-saturating activations. ReLU does not shrink the gradient where it is active. LeakyReLU with slope 0.2, for and otherwise, also passes a little gradient where ReLU passes none. Most networks in this course use it.
- Normalization layers. They rescale activations inside the network; the next blocks treat them in detail.
- Residual connections. A block adds its input back, . Its Jacobian is , so the gradient always has an identity path that is not multiplied by small factors (He et al., 2016). The denoising networks of diffusion models are built from such blocks.
Two more tools act on the gradient itself. Gradient clipping caps its length: if the norm exceeds a threshold , the gradient is scaled down,
The direction is kept and the step is capped. Clipping only ever shrinks a gradient, so it guards against explosion, not against vanishing. Adaptive optimizers such as Adam divide each gradient coordinate by a running estimate of its typical size, which cancels a uniform scale.
Batch normalization
Batch normalization (Ioffe and Szegedy, 2015) standardizes each channel using the statistics of the current mini-batch. For the values of one channel, it computes the batch mean and the plain variance (divided by ), then
The small constant ( in PyTorch) guards against division by zero, and , are learned per channel, so the layer can still choose any scale and offset. For example, the batch has and , and becomes .
For a convolutional feature map with shape (batch, channels, height, width), BatchNorm2d pools each channel over the batch and all positions: values per channel.
Why it helps: whatever the earlier layers do to the scale of their outputs, the next layer sees inputs with mean and spread . The per-layer factors stay moderate, and larger learning rates become safe. Two side effects are worth knowing.
- Subtracting the mean cancels any constant added before it. So a convolution followed by batch norm is created with
bias=False. - Standardizing fixes the mean and variance, not the shape. A skewed batch stays skewed; the result is not a standard normal.
Training mode and evaluation mode
Batch norm computes a different function in training and in evaluation.
- Training mode,
model.train(): normalize with the batch statistics , and update the running averages, e.g. . - Evaluation mode,
model.eval(): normalize with the running averages , . Each example is then processed on its own.
The mode is a property of the model. torch.no_grad() is a different switch: it only stops PyTorch from recording the computation for gradients. The running averages are not gradients, so in training mode they keep updating even under no_grad().
For generative models, this has three consequences.
- Sample in evaluation mode. In training mode, each generated image is normalized with statistics computed from the whole batch of samples. Each output then depends on the others, and the running averages drift toward the statistics of generated images.
- Small batches. Statistics from a few examples are noisy, and at batch size one the training-mode statistics come from a single image while evaluation uses averages over many. The two modes then compute visibly different functions.
- Per-example gradients. Some losses need the gradient of a network's output with respect to each input separately. The WGAN critic with a gradient penalty, later in the course, is the main example. Batch norm mixes the examples of a batch, so such networks avoid it (Gulrajani et al., 2017).
Instance normalization
Instance normalization (Ulyanov, Vedaldi and Lempitsky, 2016) computes the statistics per image and per channel, over the positions only:
A map with values becomes , whatever the other images in the batch are. So training and evaluation compute the same function, batch size one is fine, and the gradient for each input involves that input alone. In PyTorch, InstanceNorm2d learns and only with affine=True.
The price: every map loses its own mean and spread. For a classifier this can throw away useful information. For image-to-image networks it is often what we want. In fast style transfer, the stylized result should not depend on the brightness and contrast of the content photo, and instance normalization removes exactly those.
Later in the course, CycleGAN trains its generators with instance normalization and batch size one, and WGAN critics with a gradient penalty use instance normalization (or none) instead of batch norm.
A convolution layer
A dense layer from a image to a map has million weights, and it ignores that neighbouring pixels belong together. A convolution uses a small learned kernel, say , and slides it over the image. The same few weights are applied at every position, so a pattern is detected wherever it appears.
A convolution layer maps input channels to output channels. Output channel has one kernel for every input channel , and sums their results:
where slides the kernel over the map and takes a weighted sum at each position (strictly a cross-correlation, but everyone calls it convolution). Each output is a feature map. The weights form a tensor of shape . For example, a layer from one channel to 16 channels with kernels has parameters.
The stride is how many pixels the kernel moves per step, and the padding adds rows and columns of zeros around the map. For an input side the output side is
and the width follows the same rule. With , , an even side is halved, so four such layers take . Each layer sees a larger patch of the original image than the one before. First-layer kernels learn edges, colour blobs and textures, and deeper layers combine them into parts (Zeiler and Fergus, 2014).
Transposed convolution
Encoders shrink images with strided convolutions. Decoders and generators must grow them back. In one dimension, a convolution is a linear map, a matrix of shape . A transposed convolution multiplies by instead, which goes from the small side to the large one. It reverses the shapes, not the values: it is not an inverse.
Concretely, each input value stamps a copy of the kernel, scaled by that value, onto the output. The stamps are placed pixels apart, and where they overlap they add up. The output side is
so , , doubles the side, and four such layers take . The name has a second meaning that connects to backpropagation: the backward pass of a strided convolution with respect to its input multiplies by , which is exactly a transposed convolution with the same kernel.
The overlap can be uneven. Take an all-ones input and an all-ones kernel in one dimension. With , every interior output is covered by exactly two stamps, so it equals 2. With , the interior alternates between 2 and 1. In two dimensions this becomes a checkerboard artifact, a grid pattern that the network must learn to cancel (Odena, Dumoulin and Olah, 2016). Choosing divisible by , or upsampling with a fixed rule (nearest-neighbour or bilinear) and then applying an ordinary convolution, avoids it.
Now all the bricks are on the table. A stack of strided convolutions with batch norm and LeakyReLU squeezes a image into a small block of numbers, and transposed convolutions grow it back. Train the pair to return its own input, and the small block in the middle becomes a learned code of the image. That network is the autoencoder, the next topic, Autoencoders.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.