05 / 34 · Foundations
Batch normalization, gradients and convolutions
The layer details the generative models of this course depend on: batch normalization's two modes and scale invariance, instance normalization, vanishing gradients through one unit, and the shapes of a convolution layer.
Neural networks · Backpropagation · Gradient descent · Normalization and initialization · Convolution
On this page 5
A VAE generates 64 faces with its batch-norm layers still in training mode. Each face is then normalized with the statistics of the other 63, so the same latent code decodes to a slightly different face in another batch. The critic of WGAN-GP, the gradient-penalty variant of the Wasserstein GAN, must contain no batch norm at all, and CycleGAN trains on one image at a time. The models of the previous note were too small to meet such details; every network from here on meets them.
The layers themselves are built in the Deep Learning course: Normalization and initialization, Optimizing deep networks and Convolution.
Batch normalization#
Batch normalization (Ioffe and Szegedy, 2015) standardizes each channel with the statistics of the current mini-batch. For the values of one channel in a batch,
where and are the batch mean and the plain variance (divided by ), in PyTorch, and and are learned per channel. BatchNorm2d pools each channel over the batch and all positions. The batch has and and becomes .
Batch normalization of one feature
In training the layer uses the batch statistics and updates running averages of them; in evaluation it uses the running averages, so an output no longer depends on the rest of the batch (both modes worked through). model.eval() switches the mode; torch.no_grad() does not, since it only stops autograd from recording the graph. A generator sampled in training mode therefore couples its samples to each other and drags the running averages toward the statistics of generated images.
Scale invariance and bias-free convolutions#
Subtracting cancels any constant bias, so a convolution followed by batch norm is created with bias=False. The layer also ignores the scale of what feeds it. Scaling the input or the weights of a bias-free convolution by scales every and by and by :
Up to the change of to the output is the same (Ioffe and Szegedy, 2015, section 3.3). A penalty on the size of whatever feeds such a block can be dodged by shrinking it, as the sparse autoencoder of the next note shows.
Instance normalization#
Instance normalization (Ulyanov, Vedaldi and Lempitsky, 2016) standardizes every image on its own. For image and channel of an feature map,
(InstanceNorm2d learns and only with affine=True.) If is the map of one channel of one image, it becomes whatever the other images contain. Training and evaluation compute the same function, and a batch of one image works (other axes).
The price is that each feature map loses its own mean and spread, which the shared and cannot restore. Fast style transfer wants that: the result should not depend on the contrast of the content image (Ulyanov et al., section 2).
Two later models depend on it. CycleGAN uses instance norm in its generators and discriminators and trains with batches of one image (Zhu et al., 2017, section 4). The gradient penalty of WGAN-GP constrains the critic’s gradient for each input separately, which needs each output to depend on its own input alone; Gulrajani et al. (2017), section 4, drop batch norm from the critic, and instance norm qualifies.
Vanishing and exploding gradients#
Backpropagation multiplies one factor per layer. With one unit per layer, and , the chain rule gives
With the same weight in every layer and ReLUs in their active region, the factor after layers is . A recurrent network applies the same weight at every time step, so it meets the same power along time (Bengio, Simard and Frasconi, 1994; recurrent networks).
| weight | 3 layers | 10 layers | 50 layers |
|---|---|---|---|
A weight only 10% away from 1 changes the gradient by two orders of magnitude over 50 layers: exploding gradients above 1, vanishing below. With many units per layer the factors are Jacobians . The norm of a product is at most the product of the norms, , and the norm of a matrix is its largest singular value, which therefore plays the role of : if every one stays below 1, the gradient must vanish, and an explosion needs at least one above 1 (Pascanu, Mikolov and Bengio, 2013, section 2.1); the Deep Learning course derives the factor per layer.
Repeated multiplication by w
A step of plain gradient descent, , is proportional to the gradient. An exploded gradient overshoots the minimum and the loss diverges; a vanished one leaves the early layers almost still.
What a huge or tiny gradient does to the training steps
Adam and AdamW behave differently. They divide a running mean of each coordinate’s gradient by the root of a running mean of its square (Adam). Multiplying every gradient by multiplies by and by , so and the step do not change: a consistently large or small gradient moves each weight by about . A single spike far larger than the gradients before it gives and late in training, a step of about whatever the size of . The failures above are therefore those of SGD. Adam absorbs a scale shared by all steps, though not a gradient below its , where the division stops rescaling.
Common remedies#
The rest of the course relies on the standard fixes:
- initialization that keeps the factor near 1, Glorot’s or He’s (Glorot and Bengio, 2010; He et al., 2015);
- normalization layers, as above;
- non-saturating activations. The sigmoid’s derivative is at most , its value at , so a sigmoid layer with shrinks the gradient at least fourfold. LeakyReLU, in most networks of this course (Maas, Hannun and Ng, 2013), has slope 1 for positive inputs and 0.2 for negative ones;
- gradient clipping, for a threshold (Pascanu, Mikolov and Bengio, 2013, section 3.2);
- residual connections , whose Jacobian always holds a path with factor 1 (He et al., 2016);
- gated recurrent cells (LSTM and GRU).
A convolution layer#
A convolution layer holds one kernel for every pair of input channel and output channel . With the cross-correlation,
The Deep Learning course derives the weight shape and the cost.
Shapes in a convolution layer: one output channel
With padding , stride and dilation , the output height is
and the same holds for the width (Dumoulin and Visin, 2016). It counts window positions: the kernel spans rows of the padded ones, and a window may start at every -th row up to the last start that fits (derivation). The encoder of the next note uses , , and , which halves an even side: . Decoders go back up with a transposed convolution or with upsampling followed by a convolution.
A convolution has . PyTorch’s default for Conv2d draws weights uniformly on , with variance (a uniform on has variance ), a sixth of He’s . A ReLU layer multiplies the signal variance by (the factor per layer), which He’s choice sets to 1, so a plain ReLU stack at this default loses a factor of 6 per layer; here batch norm after each convolution restores the scale.
Trained first-layer kernels become detectors of edges, colour blobs and textures, and deeper layers combine them into parts and objects (Zeiler and Fergus, 2014). That is why the evaluation metrics of the course compare images through pretrained convolutional features.
A training run in practice#
Runs follow the routine of training in practice: AdamW at PyTorch’s defaults, and weight decay (Loshchilov and Hutter, 2019), validation in eval() mode under torch.no_grad(), and a saved state_dict. Seeds are set for Python, NumPy and PyTorch. On GPUs cuDNN may pick the fastest of several convolution algorithms, which can differ between runs, and some are not deterministic; cudnn.benchmark = False and cudnn.deterministic = True turn both off at some cost in speed. Results then repeat only on the same hardware and software (PyTorch documentation, “Reproducibility”).
Notebook#
These pieces appear in the HSE-LAMBDA Deep Generative Models notebooks (quoted numbers come from the runs saved with the course; none are quoted here).
- The autoencoder notebook: encoder blocks of
Conv2d(bias=False),BatchNorm2dandLeakyReLU(0.2)with stride 2, and explicit switches betweentrain()andeval(). - The VAE notebook: samples under
torch.no_grad()withouteval(), the case of the opening paragraph; no saved outputs. - The WGAN notebook:
InstanceNorm2d(affine=True)in both critics, batch norm in the generators. - Homework 1: seeds and both cuDNN flags, an autoencoder trained with
AdamWat its defaults for 30 epochs; no saved outputs.
Next#
The next note stacks convolution, batch norm and LeakyReLU into an encoder and a decoder that reconstruct digits through a 512-number code, and asks what such a code captures and whether it can generate.
References#
- S. Ioffe, C. Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. ICML, 2015. Section 3.3: invariance to the scale of the weights.
- D. Ulyanov, A. Vedaldi, V. Lempitsky. Instance normalization: the missing ingredient for fast stylization. arXiv:1607.08022, 2016. Section 2 and Eq. (3): instance normalization and the contrast argument.
- J.-Y. Zhu, T. Park, P. Isola, A. A. Efros. Unpaired image-to-image translation using cycle-consistent adversarial networks. ICCV, 2017. Section 4 and appendix 7.2: instance normalization, batch size 1.
- I. Gulrajani, F. Ahmed, M. Arjovsky, V. Dumoulin, A. Courville. Improved training of Wasserstein GANs. NeurIPS, 2017. Section 4, “No critic batch normalization”.
- Y. Bengio, P. Simard, P. Frasconi. Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 1994.
- R. Pascanu, T. Mikolov, Y. Bengio. On the difficulty of training recurrent neural networks. ICML, 2013. Section 2.1 (the norm bound on a product of Jacobians) and section 3.2 (gradient-norm clipping).
- X. Glorot, Y. Bengio. Understanding the difficulty of training deep feedforward neural networks. AISTATS, 2010.
- K. He, X. Zhang, S. Ren, J. Sun. Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification. ICCV, 2015.
- K. He, X. Zhang, S. Ren, J. Sun. Deep residual learning for image recognition. CVPR, 2016.
- A. L. Maas, A. Y. Hannun, A. Y. Ng. Rectifier nonlinearities improve neural network acoustic models. ICML Workshop on Deep Learning for Audio, Speech and Language Processing, 2013.
- V. Dumoulin, F. Visin. A guide to convolution arithmetic for deep learning. arXiv:1603.07285, 2016.
- M. D. Zeiler, R. Fergus. Visualizing and understanding convolutional networks. ECCV, 2014.
- I. Loshchilov, F. Hutter. Decoupled weight decay regularization. ICLR, 2019.
- PyTorch documentation:
BatchNorm2d,InstanceNorm2d,Conv2dand Reproducibility.