Course contents 05 / 34

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.

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 nn values x1,…,xnx_1, \dots, x_n of one channel in a batch,

x^i=xi−μBσB2+ε,yi=γ x^i+β,\begin{aligned} \hat x_i &= \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \varepsilon}}, \\ y_i &= \gamma\, \hat x_i + \beta , \end{aligned}

where μB\mu_B and σB2\sigma_B^2 are the batch mean and the plain variance (divided by nn), ε=10−5\varepsilon = 10^{-5} in PyTorch, and γ\gamma and β\beta are learned per channel. BatchNorm2d pools each channel over the batch and all positions. The batch (1,2,3,6)(1, 2, 3, 6) has μB=3\mu_B = 3 and σB2=3.5\sigma_B^2 = 3.5 and becomes (−1.069,−0.535,0,1.604)(-1.069, -0.535, 0, 1.604).

Figure

Batch normalization of one feature

Histogram of a batch before and after normalizationThree histograms on a shared horizontal axis. The top one is a right-skewed batch centred near 6.32. An arrow labelled subtract mu B moves it to the middle row, now centred at zero with the same width. Two arrows labelled divide by the square root of sigma B squared plus epsilon squeeze the plus and minus one standard deviation marks to plus and minus one, giving the bottom histogram: narrower, taller, still skewed, with mean 0 and variance 1. A dashed standard normal curve is drawn on the bottom row for comparison.batch xᵢμB = 6.32subtract μBxᵢ − μB−σBσBdivide by √(σB2 + ε)x̂imean 0.00, variance 1.00𝒩(0, 1)051015−11Histogram of a batch before and after normalizationThree histograms on a shared horizontal axis. The top one is a right-skewed batch centred near 6.32. An arrow labelled subtract mu B moves it to the middle row, now centred at zero with the same width. Two arrows labelled divide by the square root of sigma B squared plus epsilon squeeze the plus and minus one standard deviation marks to plus and minus one, giving the bottom histogram: narrower, taller, still skewed, with mean 0 and variance 1. A dashed standard normal curve is drawn on the bottom row for comparison.batch xᵢμB = 6.32subtract μBxᵢ − μB−σBσBdivide by √(σB2 + ε)x̂imean 0.00, variance 1.00𝒩(0, 1)051015−11
A skewed batch of n = 256 activations, x = 2 + 4·exp(0.45 z) with z ~ 𝒩(0, 1); batch mean 6.32, standard deviation 2.06, ε = 10⁻⁵. Subtracting the mean moves the histogram to zero and dividing by √(σ_B² + ε) gives it unit variance. Look at the shape: it stays skewed and does not become the dashed standard normal.

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 μB\mu_B 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 r>0r > 0 scales every xix_i and μB\mu_B by rr and σB2\sigma_B^2 by r2r^2:

rxi−rμBr2σB2+ε=xi−μBσB2+ε/r2.\frac{r x_i - r\mu_B}{\sqrt{r^2\sigma_B^2 + \varepsilon}} = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \varepsilon/r^2}} .

Up to the change of ε\varepsilon to ε/r2\varepsilon/r^2 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 nn and channel cc of an H×WH \times W feature map,

μnc=1HW∑h,wxnchw,σnc2=1HW∑h,w(xnchw−μnc)2,ynchw=γc xnchw−μncσnc2+ε+βc.\begin{aligned} \mu_{nc} &= \frac{1}{HW}\sum_{h,w} x_{nchw}, \\ \sigma_{nc}^2 &= \frac{1}{HW}\sum_{h,w} \left(x_{nchw} - \mu_{nc}\right)^2, \\ y_{nchw} &= \gamma_c\, \frac{x_{nchw} - \mu_{nc}}{\sqrt{\sigma_{nc}^2 + \varepsilon}} + \beta_c . \end{aligned}

(InstanceNorm2d learns γc\gamma_c and βc\beta_c only with affine=True.) If (1,2,3,6)(1, 2, 3, 6) is the 2×22 \times 2 map of one channel of one image, it becomes (−1.069,−0.535,0,1.604)(-1.069, -0.535, 0, 1.604) 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 γc\gamma_c and βc\beta_c 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, hi=φ(ai)h_i = \varphi(a_i) and ai=wihi−1+bia_i = w_i h_{i-1} + b_i, the chain rule gives

∂hi∂hi−1=wi φ′(ai),∂hL∂h0=∏i=1Lwi φ′(ai).\begin{aligned} \frac{\partial h_i}{\partial h_{i-1}} &= w_i\, \varphi'(a_i), \\ \frac{\partial h_L}{\partial h_0} &= \prod_{i=1}^{L} w_i\, \varphi'(a_i) . \end{aligned}

With the same weight ww in every layer and ReLUs in their active region, the factor after τ\tau layers is wτw^\tau. 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).

weight3 layers10 layers50 layers
w=2w = 288102410241.1⋅10151.1\cdot 10^{15}
w=1.1w = 1.11.331.332.592.59117117
w=0.9w = 0.90.730.730.350.350.00520.0052
w=0.5w = 0.50.1250.1259.8⋅10−49.8\cdot 10^{-4}8.9⋅10−168.9\cdot 10^{-16}

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 JiJ_i. The norm of a product is at most the product of the norms, ∥JL⋯J1∥≤∏i∥Ji∥\lVert J_L \cdots J_1\rVert \le \prod_i \lVert J_i\rVert, and the norm of a matrix is its largest singular value, which therefore plays the role of ww: 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.

Figure

Repeated multiplication by w

Gradient factor w to the power τ on a log scaleThree straight lines on a logarithmic vertical axis from 1/1024 to 1024, against time steps 0 to 10. The line for w equals 2 rises to 1024 through the shaded exploding region; the line for w equals 1 stays at 1; the line for w equals 0.5 falls to 1/1024 through the shaded vanishing region. Points at τ equal 1, 2 and 3 on the rising line are labelled 2, 4 and 8.10243211/321/10240246810steps τfactor wτ (log scale)exploding: wτ → ∞vanishing: wτ → 0w = 2w = 1w = 0.5248Gradient factor w to the power τ on a log scaleThree straight lines on a logarithmic vertical axis from 1/1024 to 1024, against time steps 0 to 10. The line for w equals 2 rises to 1024 through the shaded exploding region; the line for w equals 1 stays at 1; the line for w equals 0.5 falls to 1/1024 through the shaded vanishing region. Points at τ equal 1, 2 and 3 on the rising line are labelled 2, 4 and 8.10243211/321/10240246810steps τfactor wτ (log scale)exploding: wτ → ∞vanishing: wτ → 0w = 2w = 1w = 0.5248
The factor w^τ after τ layers or time steps, on a logarithmic axis. With w = 2 it reaches 1024 after ten steps (exploding); with w = 0.5 it falls to 1/1024 (vanishing); only w = 1 keeps the scale. The red points 2, 4 and 8 are the first three steps.

A step of plain gradient descent, −η g-\eta\, g, is proportional to the gradient. An exploded gradient overshoots the minimum and the loss diverges; a vanished one leaves the early layers almost still.

Figure

What a huge or tiny gradient does to the training steps

Overshooting steps versus steps that are too smallTwo copies of a parabola-shaped loss. In the first, labelled exploding, gradient-descent iterates start near the minimum and jump to alternating sides, each farther out, with red arcs between them. In the second, labelled vanishing, eleven blue points creep slowly down the right branch and stop at max steps, far from the minimum at zero.w ≫ 1: steps too largeminimumstartovershoots,divergesw → 0: steps too smallminimumstartstopped atmax_steps = 10Overshooting steps versus steps that are too smallTwo copies of a parabola-shaped loss. In the first, labelled exploding, gradient-descent iterates start near the minimum and jump to alternating sides, each farther out, with red arcs between them. In the second, labelled vanishing, eleven blue points creep slowly down the right branch and stop at max steps, far from the minimum at zero.w ≫ 1: steps too largeminimumstartovershoots,divergesw → 0: steps too smallminimumstartstopped atmax_steps = 10
Gradient descent on the toy loss L(θ) = θ²/2 with the gradient multiplied by a factor g: θ ← (1 − η g) θ. Red: η g = 2.3 from θ₀ = 1, so each step multiplies θ by −1.3 and the iterates bounce outwards. Blue: η g = 0.03 from θ₀ = 2.5, so ten steps reach only 1.84, far from the minimum.

Adam and AdamW behave differently. They divide a running mean mm of each coordinate’s gradient by the root of a running mean vv of its square (Adam). Multiplying every gradient by cc multiplies mm by cc and vv by c2c^2, so m/vm/\sqrt v and the step do not change: a consistently large or small gradient moves each weight by about η\eta. A single spike gg far larger than the gradients before it gives m≈(1−β1) g=0.1 gm \approx (1 - \beta_1)\,g = 0.1\,g and v≈(1−β2) g2=0.001 g2v \approx (1 - \beta_2)\,g^2 = 0.001\,g^2 late in training, a step of about 0.1/0.001≈3.16 η0.1/\sqrt{0.001} \approx 3.16\,\eta whatever the size of gg. The failures above are therefore those of SGD. Adam absorbs a scale shared by all steps, though not a gradient below its ε=10−8\varepsilon = 10^{-8}, 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 σ(1−σ)\sigma(1 - \sigma) is at most 14\tfrac14, its value at σ=12\sigma = \tfrac12, so a sigmoid layer with ∣wi∣≤1|w_i| \le 1 shrinks the gradient at least fourfold. LeakyReLU, max⁡(0.2x,x)\max(0.2x, x) 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, g←g⋅min⁡(1,c/∥g∥)g \leftarrow g \cdot \min(1, c/\lVert g\rVert) for a threshold cc (Pascanu, Mikolov and Bengio, 2013, section 3.2);
  • residual connections xl+1=xl+F(xl)x_{l+1} = x_l + F(x_l), whose Jacobian I+∂F/∂xlI + \partial F/\partial x_l 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 kH×kWk_H \times k_W kernel Wj,cW_{j,c} for every pair of input channel cc and output channel jj. With ⋆\star the cross-correlation,

out[j]=∑c=1incWj,c⋆in[c]+bj.\text{out}[j] = \sum_{c=1}^{\text{in}_c} W_{j,c} \star \text{in}[c] + b_j .

The Deep Learning course derives the weight shape and the cost.

Figure

Shapes in a convolution layer: one output channel

Computing one output channel of a convolutionRows for input channels 1, 2 up to in_c. In each row a 6 by 6 input plane in[c] of size H_in by W_in is cross-correlated with a 3 by 3 kernel slice W j c, giving a 4 by 4 partial map. The three kernel slices are boxed together as filter W j of shape in_c by k by k. Arrows bring all partial maps into a summation node, a bias b j is added from above, and the result is output plane out[j] of size H_out by W_out, drawn in front of a stack of out_c planes, one per filter.in[c]Hin × WinWj,ck × kWj,cin[c]c = 1c = 2c = inc⋮⋮filter Wjinc × k × kΣover cbj+ biasout[j]Hout × Woutoutc planesrepeat with each of the outc filters W1, …, Woutc → outc planesComputing one output channel of a convolutionRows for input channels 1, 2 up to in_c. In each row a 6 by 6 input plane in[c] of size H_in by W_in is cross-correlated with a 3 by 3 kernel slice W j c, giving a 4 by 4 partial map. The three kernel slices are boxed together as filter W j of shape in_c by k by k. Arrows bring all partial maps into a summation node, a bias b j is added from above, and the result is output plane out[j] of size H_out by W_out, drawn in front of a stack of out_c planes, one per filter.in[c]Hin × WinWj,ck × kWj,cin[c]c = 1c = 2c = inc⋮⋮filter Wjinc × k × kΣbj+ biasout[j]Hout × Woutrepeat with each of the outc filters W1, …, Woutc→ outc output planes
Output channel j slides one k × k kernel slice over each input channel, sums the in_c results and adds its bias; the amber window and cell show the inputs of one output value. All out_c filters give a weight tensor of shape out_c × in_c × k × k. Drawn with a 6 × 6 input, k = 3, stride 1 and no padding, so the outputs are 4 × 4.

With padding pp, stride ss and dilation dd, the output height is

Hout=⌊Hin+2p−d (kH−1)−1s⌋+1,H_{\text{out}} = \left\lfloor \frac{H_{\text{in}} + 2p - d\,(k_H - 1) - 1}{s} \right\rfloor + 1 ,

and the same holds for the width (Dumoulin and Visin, 2016). It counts window positions: the kernel spans d(kH−1)+1d(k_H - 1) + 1 rows of the Hin+2pH_{\text{in}} + 2p padded ones, and a window may start at every ss-th row up to the last start that fits (derivation). The encoder of the next note uses k=3k = 3, p=1p = 1, s=2s = 2 and d=1d = 1, which halves an even side: 64→32→16→8→464 \to 32 \to 16 \to 8 \to 4. Decoders go back up with a transposed convolution or with upsampling followed by a convolution.

A convolution has fanin=inc kHkW\text{fan}_{\text{in}} = \text{in}_c\, k_H k_W. PyTorch’s default for Conv2d draws weights uniformly on ±1/fanin\pm 1/\sqrt{\text{fan}_{\text{in}}}, with variance 1/(3 fanin)1/(3\,\text{fan}_{\text{in}}) (a uniform on ±b\pm b has variance b2/3b^2/3), a sixth of He’s 2/fanin2/\text{fan}_{\text{in}}. A ReLU layer multiplies the signal variance by faninVar⁡(w)/2\text{fan}_{\text{in}}\operatorname{Var}(w)/2 (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, η=10−3\eta = 10^{-3} and weight decay 10−210^{-2} (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), BatchNorm2d and LeakyReLU(0.2) with stride 2, and explicit switches between train() and eval().
  • The VAE notebook: samples under torch.no_grad() without eval(), 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 AdamW at 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#