Skip to content
ml-recall

Topic notes

Training Deep Networks

How deep networks are trained in practice; minibatch SGD and the learning rate, momentum and Adam, initialization, batch normalization, and regularization (weight decay, dropout, early stopping).

5-min read AI-checked

Practise 129 questions Take a test

Key ideas

Formulas

w←w−η(∂L∂w+2λw)=(1−2ηλ) w−η ∂L∂wfor the penalty λ∥w∥2w \leftarrow w - \eta\left(\frac{\partial L}{\partial w} + 2\lambda w\right) = (1 - 2\eta\lambda)\,w - \eta\,\frac{\partial L}{\partial w}\qquad\text{for the penalty } \lambda\lVert\mathbf{w}\rVert^2

PyTorch's weight_decay=λ adds λw\lambda w to the gradient1: that is the penalty λ2∥w∥2\tfrac{\lambda}{2}\lVert\mathbf{w}\rVert^2, with factor 1−ηλ1 - \eta\lambda.

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,θ←θ−η mt/(1−β1t)vt/(1−β2t)+ϵm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t,\quad v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2,\quad \theta \leftarrow \theta - \eta\,\frac{m_t/(1 - \beta_1^t)}{\sqrt{v_t/(1 - \beta_2^t)} + \epsilon} μB=1m∑ixi,σB2=1m∑i(xi−μB)2,yi=γ xi−μBσB2+ϵ+β\mu_B = \frac{1}{m}\sum_i x_i,\quad \sigma_B^2 = \frac{1}{m}\sum_i (x_i - \mu_B)^2,\quad y_i = \gamma\,\frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}} + \beta

PyTorch's running estimates: μ^←0.9 μ^+0.1 μB\hat\mu \leftarrow 0.9\,\hat\mu + 0.1\,\mu_B and σ^2←0.9 σ^2+0.1 mm−1σB2\hat\sigma^2 \leftarrow 0.9\,\hat\sigma^2 + 0.1\,\frac{m}{m - 1}\sigma_B^26.

Inverted dropout on a value hh: E[h′]=(1−p)h1−p=h\mathbb{E}[h'] = (1 - p)\frac{h}{1 - p} = h and E[h′2]=h21−p\mathbb{E}[h'^2] = \frac{h^2}{1 - p}, so Var[h′]=h2p1−p\mathrm{Var}[h'] = h^2\frac{p}{1 - p}. Two dropout layers with rates pp and qq act like one with rate 1−(1−p)(1−q)1 - (1 - p)(1 - q).

Worked example

Minimize L(w)=(w−3)2L(w) = (w - 3)^2 from w0=0w_0 = 0 with η=0.1\eta = 0.1 and momentum β=0.5\beta = 0.5 in the PyTorch form:

The moving-average form vt=0.5 vt−1+0.5 gtv_t = 0.5\,v_{t-1} + 0.5\,g_t (with v0=0v_0 = 0) gives v1=−3v_1 = -3, w1=0.3w_1 = 0.3, then v2=−4.2v_2 = -4.2, w2=0.72w_2 = 0.72: the same direction with smaller steps, so a learning rate tuned for one convention does not carry over to the other.

In code

import torch
from torch import nn
bn = nn.BatchNorm1d(1)                     # gamma = 1, beta = 0, momentum = 0.1
x = torch.tensor([[2.0], [4.0], [4.0], [6.0]])
with torch.no_grad():
    print(bn(x).flatten())                 # tensor([-1.4142,  0.0000,  0.0000,  1.4142])  batch stats, var/n
    print(bn.running_mean, bn.running_var) # tensor([0.4000]) tensor([1.1667])  0.9*0 + 0.1*4, 0.9*1 + 0.1*8/3
    bn.eval()
    print(bn(x).flatten())                 # tensor([1.4813, 3.3329, 3.3329, 5.1846])  running stats
try: nn.BatchNorm1d(1)(torch.ones(1, 1))   # a single example in training mode
except ValueError as e: print(type(e).__name__)  # ValueError
torch.manual_seed(0)
drop = nn.Dropout(p=0.25)                  # training mode: kept values become 1/(1 - 0.25)
print(drop(torch.ones(6)))                 # tensor([0.0000, 1.3333, 1.3333, 0.0000, 1.3333, 0.0000])
print(drop.eval()(torch.ones(3)))          # tensor([1., 1., 1.])  dropout is off in eval mode

Common pitfalls

References

  1. PyTorch documentation: torch.optim.SGD — Algorithm box (weight decay λ, momentum μ, dampening τ, first step b_1 = g_1) and the note on Sutskever et al.
  2. Kingma & Ba (2015), Adam: A Method for Stochastic Optimization — Algorithm 1 and Sec. 2 Algorithm (2.1 Adam's Update Rule); Sec. 5 Related Work (RMSProp, AdaGrad)
  3. Loshchilov & Hutter (2019), Decoupled Weight Decay Regularization — Abstract; Sec. 1 Introduction
  4. Dive into Deep Learning — Sec. 5.4.1 Vanishing and Exploding Gradients (5.4.1.3 Breaking the Symmetry), 5.4.2.2 Xavier Initialization
  5. Dive into Deep Learning — Sec. 8.5.1 Training Deep Networks, 8.5.2.2 Convolutional Layers, 8.5.2.3 Layer Normalization, 8.5.2.4 Batch Normalization During Prediction
  6. PyTorch documentation: torch.nn.BatchNorm1d — Class description and note (biased variance in training, unbiased running variance, momentum 0.1, γ = 1 and β = 0 at start)
  7. Hinton et al. (2012), Improving neural networks by preventing co-adaptation of feature detectors — Main text, p. 2 (upper bound on each hidden unit's incoming weight norm; mean network with halved outgoing weights)
  8. Dive into Deep Learning — Sec. 5.6 Dropout (Eq. 5.6.1), 5.6.1 Dropout in Practice