Course contents 04 / 14

04 / 14 · Training Neural Networks

Normalization and initialization

Why the scale of activations and gradients is multiplied at every layer, how Glorot and He initialization follow from keeping that factor at one, what batch, layer, group and RMS normalization compute and why they help, and how residual connections carry signals through depth.

On this page 8

The previous note trained a network of three layers and asked how to keep it from fitting its training set too well. A network of thirty layers has the opposite problem first: with the default initialization it does not fit its training set at all. The signal that reaches the top of the stack and the gradient that reaches the bottom are each multiplied by a factor at every layer, and over thirty layers any factor other than one grows or shrinks geometrically. This note derives the initializations that set that factor to one, shows what the normalization layers compute and what is still debated about why they work, and explains how a residual connection carries the signal and its gradient through depth. It ends with one experiment that puts the three tools side by side.

Notation. A layer computes the pre-activation zl=Wlhl−1z_l = W_l h_{l-1} and the activation hl=φ(zl)h_l = \varphi(z_l); biases are zero at initialization and left out. nl−1n_{l-1} and nln_l are the layer’s fan-in and fan-out, its input and output widths. The weights start as independent draws with mean 0 and variance vlv_l. The adjoint δl=∂L/∂zl\delta_l = \partial L / \partial z_l is the gradient of the loss with respect to the pre-activation. For a normalization layer, BB is the batch size, μ\mu and σ2\sigma^2 are a mean and a variance, x^\hat x the standardized value, and γ,β\gamma, \beta the learned scale and shift.

Baseline: a deep stack at its default initialization#

Take a plain stack of 50 bias-free ReLU layers of width 256 and feed it 512 standard normal inputs. The table gives the mean square of the pre-activations zlz_l at four depths, for weights with four variances: unscaled, 1/n1/n, the variance 1/(3n)1/(3n) that PyTorch’s nn.Linear uses by default, and 2/n2/n. The last column is the mean square of the adjoint at the first layer divided by that at the last, for a loss that is a fixed random projection of z50z_{50}.

weight variance vvlayer 1layer 10layer 25layer 50gradient, layer 1 / layer 50
112582582.4⋅10212.4 \cdot 10^{21}overflowoverflownot a number
1/n1/n1.011.012.0⋅10−32.0 \cdot 10^{-3}2.5⋅10−82.5 \cdot 10^{-8}2.2⋅10−152.2 \cdot 10^{-15}2.9⋅10−152.9 \cdot 10^{-15}
1/(3n)1/(3n), PyTorch default0.3360.3363.4⋅10−83.4 \cdot 10^{-8}2.9⋅10−202.9 \cdot 10^{-20}3.1⋅10−393.1 \cdot 10^{-39}1.2⋅10−381.2 \cdot 10^{-38}
2/n2/n2.022.022.042.040.8330.8332.462.461.661.66

With unscaled weights the signal overflows 32-bit arithmetic before layer 25. With the default it shrinks by about a factor of 6 per layer, and the gradient that reaches the first layer is 10−3810^{-38} of the one at the top: the first layers never move. Only the variance 2/n2/n keeps both the signal and the gradient at their scale. On real data the effect is the same: the thirty-layer network of the experiment, at its default initialization, stays at the loss ln⁡10=2.303\ln 10 = 2.303 of a uniform guess over 10 classes for all of training. The Machine Learning course draws the same picture for 30 layers (initialization that preserves the scale), and the Generative Models course traces the mechanism for one unit per layer (vanishing and exploding gradients). Here we derive the factor for both directions at once and then see what initialization cannot fix.

Why the scale is multiplied at every layer#

Forward. One pre-activation is zl,i=∑j=1nl−1Wl,ij hl−1,jz_{l,i} = \sum_{j=1}^{n_{l-1}} W_{l,ij}\, h_{l-1,j}. The weights have mean 0 and are independent of each other and of hl−1h_{l-1}, so the terms are uncorrelated and their variances add:

Var⁡(zl,i)=∑j=1nl−1E[Wl,ij2] E[hl−1,j2]=nl−1 vl E[φ(zl−1)2]=nl−1 vl κVar⁡(zl−1),κ=E[φ(z)2]Var⁡(z).\begin{aligned} \operatorname{Var}(z_{l,i}) &= \sum_{j=1}^{n_{l-1}} E\big[W_{l,ij}^2\big]\, E\big[h_{l-1,j}^2\big] \\ &= n_{l-1}\, v_l\, E\big[\varphi(z_{l-1})^2\big] \\ &= n_{l-1}\, v_l\, \kappa \operatorname{Var}(z_{l-1}), \qquad \kappa = \frac{E[\varphi(z)^2]}{\operatorname{Var}(z)} . \end{aligned}

The first line uses independence, the second that all inputs of a layer have the same distribution, the third only names the ratio κ\kappa: the fraction of the second moment that the activation lets through. For the identity κ=1\kappa = 1. For a ReLU and a zz symmetric around 0, half of the distribution is set to zero and the other half kept, so E[ReLU⁡(z)2]=12E[z2]E[\operatorname{ReLU}(z)^2] = \tfrac12 E[z^2] and κ=12\kappa = \tfrac12.

Backward. The chain rule gives δl−1=φ′(zl−1)⊙(Wl⊤δl)\delta_{l-1} = \varphi'(z_{l-1}) \odot \big(W_l^\top \delta_l\big). The jj-th entry is a sum over the nln_l outputs of the layer, and the same argument, with the usual assumption that WlW_l is independent of δl\delta_l at initialization, gives

Var⁡(δl−1)=nl vl κ′Var⁡(δl),κ′=E[φ′(z)2].\begin{aligned} \operatorname{Var}(\delta_{l-1}) &= n_l\, v_l\, \kappa' \operatorname{Var}(\delta_l), \\ \kappa' &= E\big[\varphi'(z)^2\big] . \end{aligned}

For the identity κ′=1\kappa' = 1; for a ReLU the slope is 1 or 0 with probability 12\tfrac12 each, so κ′=12\kappa' = \tfrac12.

Over LL layers the two recursions multiply:

Var⁡(zL)=Var⁡(z1)∏l=2Lnl−1vlκ,Var⁡(δ1)=Var⁡(δL)∏l=2Lnlvlκ′\boxed{ \begin{aligned} \operatorname{Var}(z_L) &= \operatorname{Var}(z_1) \prod_{l=2}^{L} n_{l-1} v_l \kappa, \\ \operatorname{Var}(\delta_1) &= \operatorname{Var}(\delta_L) \prod_{l=2}^{L} n_l v_l \kappa' \end{aligned} }

Any constant factor other than 1 per layer is raised to the power L−1L - 1. Worked example. For ReLU and square layers of width n=256n = 256: unscaled weights give the forward factor 256⋅1⋅12=128256 \cdot 1 \cdot \tfrac12 = 128, and 258⋅1289=2.4⋅1021258 \cdot 128^{9} = 2.4 \cdot 10^{21} at layer 10, as in the table; the largest 32-bit number, 3.4⋅10383.4 \cdot 10^{38}, is passed at about layer 19. v=1/nv = 1/n gives the factor 12\tfrac12 and 2−49=1.8⋅10−152^{-49} = 1.8 \cdot 10^{-15} at layer 50; PyTorch’s default gives 16\tfrac16 and 6−49=7.4⋅10−396^{-49} = 7.4 \cdot 10^{-39}. The table’s measured values follow these powers up to random fluctuation.

The gradient of a weight matrix is ∂L/∂Wl=δl hl−1⊤\partial L / \partial W_l = \delta_l\, h_{l-1}^\top, a product of a backward and a forward quantity. Its size at layer ll carries both products, so a network can learn evenly across its layers only when both factors stay near 1.

Initialization that keeps the factor at one#

Glorot (Xavier) initialization#

For a symmetric activation that is linear near zero, such as tanh at small inputs, κ=κ′=1\kappa = \kappa' = 1. Setting each factor to 1:

forward:nl−1vl=1  ⇒  vl=1nl−1,backward:nlvl=1  ⇒  vl=1nl,compromise:nl−1+nl2 vl=1  ⇒    vl=2nl−1+nl  \begin{aligned} \text{forward:}\quad n_{l-1} v_l = 1 &\;\Rightarrow\; v_l = \frac{1}{n_{l-1}}, \\ \text{backward:}\quad n_l v_l = 1 &\;\Rightarrow\; v_l = \frac{1}{n_l}, \\ \text{compromise:}\quad \frac{n_{l-1} + n_l}{2}\, v_l = 1 &\;\Rightarrow\; \boxed{\; v_l = \frac{2}{n_{l-1} + n_l} \;} \end{aligned}

The two conditions agree only for a square layer, so Glorot and Bengio (2010), eq. 12, require the average of fan-in and fan-out to give 1. Drawn from a uniform distribution on [−a,a][-a, a], whose variance is a2/3a^2/3, this means a=6/(nl−1+nl)a = \sqrt{6/(n_{l-1} + n_l)} (their eq. 16). In PyTorch: nn.init.xavier_uniform_ and xavier_normal_.

He (Kaiming) initialization#

For a ReLU, κ=κ′=12\kappa = \kappa' = \tfrac12:

forward:12 nl−1vl=1  ⇒    vl=2nl−1  (fan-in mode),backward:12 nlvl=1  ⇒  vl=2nl(fan-out mode).\begin{aligned} \text{forward:}\quad \tfrac12\, n_{l-1} v_l = 1 &\;\Rightarrow\; \boxed{\; v_l = \frac{2}{n_{l-1}} \;} \quad \text{(fan-in mode)}, \\ \text{backward:}\quad \tfrac12\, n_l v_l = 1 &\;\Rightarrow\; v_l = \frac{2}{n_l} \quad \text{(fan-out mode)} . \end{aligned}

Instead of a compromise, He et al. (2015), section 2.2, observe that one direction is enough. With the fan-in choice the backward factor of layer ll is 12nl⋅2/nl−1=nl/nl−1\tfrac12 n_l \cdot 2/n_{l-1} = n_l/n_{l-1}, and the product over the stack telescopes:

∏l=2Lnlnl−1=nLn1.\prod_{l=2}^{L} \frac{n_l}{n_{l-1}} = \frac{n_L}{n_1} .

The gradient is rescaled by the ratio of the last and the first width, a constant that does not grow with depth. In PyTorch: nn.init.kaiming_normal_(w, mode='fan_in', nonlinearity='relu').

Worked example. For a 256×256256 \times 256 layer, Glorot gives standard deviation 2/512=0.0625\sqrt{2/512} = 0.0625 and He 2/256=0.0884\sqrt{2/256} = 0.0884; drawn in the Code section they come out as 0.06240.0624 and 0.08870.0887. PyTorch writes both through a gain gg, with variance g2/ning^2/n_{\text{in}} for He’s form: g=2g = \sqrt2 for ReLU, g=2/(1+a2)g = \sqrt{2/(1 + a^2)} for a leaky ReLU with negative slope aa (so 1.3871.387 for a=0.2a = 0.2), and g=5/3g = 5/3 for tanh. The default of nn.Linear is a uniform draw with variance 1/(3nin)1/(3 n_{\text{in}}), which is He’s form with g2=1/3g^2 = 1/3, six times too small for a plain ReLU stack; it relies on normalization layers to restore the scale, as the convolution section of the Generative Models course explains.

What the formulas do not promise#

Optional depth: the gain of tanh, and fluctuations around the average. The rest of the note does not depend on it.

The derivation controls an average over random weights. Two things fall outside it.

Saturating activations have no exact answer. The factor κ\kappa of tanh depends on the variance itself: at small inputs κ≈1\kappa \approx 1, but E[tanh⁡(z)2]=0.394E[\tanh(z)^2] = 0.394 for a standard normal zz. Iterate ql=g2 E[tanh⁡(ql−1 ξ)2]q_l = g^2\, E[\tanh(\sqrt{q_{l-1}}\, \xi)^2] with ξ\xi standard normal. With g=1g = 1 the variance decays like 1/(2l)1/(2l): 0.01010.0101 after 50 layers. With PyTorch’s g=5/3g = 5/3 it settles at a fixed point q∗=1.178q^* = 1.178, but there the backward factor g2 E[tanh⁡′(q∗ ξ)2]g^2\, E[\tanh'(\sqrt{q^*}\, \xi)^2] is 1.2111.211, so gradients grow by about 21% per layer. This is the order-to-chaos picture of Schoenholz et al. (2017): a deep tanh stack either loses its forward signal slowly or amplifies its gradients, and no gain makes both factors exactly 1 away from zero.

Averages are not single networks. In the table above, the He stack has mean squares 2.022.02, 2.042.04, 0.8330.833 and 2.462.46 at layers 1, 10, 25 and 50: the logarithm of the scale performs a random walk around its average. Hanin and Rolnick (2018) show that for fully connected ReLU networks the variance of this walk grows with the sum of the reciprocals of the widths, ∑l1/nl\sum_l 1/n_l, so a deep and narrow network fluctuates more than a shallow and wide one, and that residual networks, correctly weighted, avoid the problem.

What initialization cannot fix#

He initialization keeps the scale. It does not keep the examples apart. For two inputs whose pre-activations have correlation cc, the correlation after a He-initialized ReLU layer is

f(c)=1−c2+(π−arccos⁡c) cπ,f(c) = \frac{\sqrt{1 - c^2} + (\pi - \arccos c)\, c}{\pi},

the normalized arc-cosine kernel of the ReLU. Its only fixed point is c=1c = 1, and from two orthogonal inputs the correlation climbs to f(0)=1/π=0.318f(0) = 1/\pi = 0.318 after one layer, 0.8720.872 after 10, 0.9720.972 after 30 and 0.9880.988 after 50. Every input is mapped close to the same direction, and the last layer sees nearly the same vector for every example. This is the rank collapse of deep unnormalized networks (Daneshmand et al., 2020). In the experiment at the end, the thirty-layer network with He initialization starts with an average cosine of 0.9930.993 between the outputs of 256 different digits, and after 12 epochs its validation accuracy ranges from 0.790.79 to 0.910.91 over three seeds.

Batch normalization in training and in evaluation#

Initialization fixes the scale once; during training the weights change, and so does the scale. Batch normalization (Ioffe and Szegedy, 2015) standardizes each feature over the batch at every step. The definition, the running averages, the scale invariance and the use with convolutions are written out in the Generative Models course. The figure shows the two modes of the layer on that course’s example batch.

Figure

Batch normalization in training mode and in evaluation mode

Batch normalization in training mode and in evaluation modeTop, training mode: the batch (1, 2, 3, 6) has mean 3 and variance 3.5; the standardized values are (−1.07, −0.53, 0, 1.60); after γ = 2 and β = 0.5 the output is (−1.64, −0.57, 0.50, 3.71). The running averages after one step are 0.3 and 1.367. Bottom, evaluation mode: the input 6 is standardized with the running averages, (6 − 0.3)/1.169 = 4.88, and the output is 10.25 instead of 3.71.training mode (model.train())1.002.003.006.00xμB = 3σ²_B = 3.51(x − μ)/σ−1.07−0.530.001.60x̂2γ = 2β = 0.5γx̂ + β−1.64−0.570.503.71y3μrun = 0.3σ²_{run} = 1.3670.9 · old + 0.1 · batch4evaluation mode (model.eval())6(x − 0.3)/1.1694.88γx̂ + β10.25training mode gave 3.715inputstateweights, gatesoutputBatch normalization in training mode and in evaluation modeTop, training mode: the batch (1, 2, 3, 6) has mean 3 and variance 3.5; the standardized values are (−1.07, −0.53, 0, 1.60); after γ = 2 and β = 0.5 the output is (−1.64, −0.57, 0.50, 3.71). The running averages after one step are 0.3 and 1.367. Bottom, evaluation mode: the input 6 is standardized with the running averages, (6 − 0.3)/1.169 = 4.88, and the output is 10.25 instead of 3.71.training mode (model.train())1.002.003.006.00xμB = 3σ²_B = 3.51(x − μ)/σ−1.07−0.530.001.60x̂2γ = 2β = 0.5γx̂ + β−1.64−0.570.503.71y3μrun = 0.3σ²_{run} = 1.3674evaluation mode (model.eval())6(x − 0.3)/1.1694.88γx̂ + β10.25training mode gave 3.715inputstateweights, gatesoutput
One feature, a batch of four values, ε = 10⁻⁵, learned γ = 2 and β = 0.5, PyTorch’s momentum 0.1, running averages starting at 0 and 1. In training (steps 1–3) every value is standardized with the statistics of its own batch, so one example’s output depends on the other examples in the batch. Along the way (step 4) the running averages are updated; their variance is the unbiased one, 4/3 · 3.5. In evaluation (step 5) they are used instead, and an output depends on its own input only. After one step the running averages are still far from the batch statistics, and the same input 6 gives 10.25 instead of 3.71: the two modes agree only once the averages have had time to settle.
  1. Training mode: compute the mean and variance of the feature over the batch, μB=3\mu_B = 3 and σB2=3.5\sigma_B^2 = 3.5.
  2. Standardize every value: x^i=(xi−μB)/σB2+ϵ\hat x_i = (x_i - \mu_B)/\sqrt{\sigma_B^2 + \epsilon}.
  3. Scale and shift by the learned γ=2\gamma = 2 and β=0.5\beta = 0.5.
  4. Update the running averages with momentum 0.10.1: μrun←0.9⋅0+0.1⋅3=0.3\mu_{\text{run}} \leftarrow 0.9 \cdot 0 + 0.1 \cdot 3 = 0.3, and the running variance from 1 to 0.9+0.1⋅43⋅3.5=1.3670.9 + 0.1 \cdot \tfrac43 \cdot 3.5 = 1.367, with the unbiased batch variance.
  5. Evaluation mode (model.eval()): standardize with the running averages instead. After one step they are far from the batch statistics, and the input 6 becomes 10.2510.25 instead of 3.713.71.

The gradient through the batch statistics#

Optional depth: the backward pass of the layer. The rest of the note uses only its two consequences.

In training mode μB\mu_B and σB\sigma_B depend on every example of the batch, so the gradient does too. Write s=σB2+ϵs = \sqrt{\sigma_B^2 + \epsilon} and gi=∂L/∂x^ig_i = \partial L / \partial \hat x_i (the upstream gradient times γ\gamma). From ∂μB/∂xj=1/B\partial \mu_B / \partial x_j = 1/B and ∂σB2/∂xj=2(xj−μB)/B\partial \sigma_B^2 / \partial x_j = 2(x_j - \mu_B)/B we get ∂s/∂xj=x^j/B\partial s / \partial x_j = \hat x_j / B, and then

∂x^i∂xj=δij−1/Bs−xi−μBs2⋅x^jB=1s(δij−1B−x^ix^jB),∂L∂xj=∑i=1Bgi∂x^i∂xj=1s(gj−gˉ−x^j gx^‾),\begin{aligned} \frac{\partial \hat x_i}{\partial x_j} &= \frac{\delta_{ij} - 1/B}{s} - \frac{x_i - \mu_B}{s^2} \cdot \frac{\hat x_j}{B} = \frac1s\Big(\delta_{ij} - \frac1B - \frac{\hat x_i \hat x_j}{B}\Big), \\ \frac{\partial L}{\partial x_j} &= \sum_{i=1}^{B} g_i \frac{\partial \hat x_i}{\partial x_j} = \frac1s\Big(g_j - \bar g - \hat x_j\, \overline{g \hat x}\Big), \end{aligned}

where δij\delta_{ij} is 1 for i=ji = j and 0 otherwise, and the bars are averages over the batch. The first line is the quotient rule; the second sums it against gg. The result is the upstream gradient with its mean removed and its component along x^\hat x removed, divided by ss. Two consequences: the gradients of a batch always sum to 0 and are orthogonal to x^\hat x, and each example’s gradient depends on all the others. Worked example. For the batch (1,2,3,6)(1, 2, 3, 6) and g=(1,0,0,0)g = (1, 0, 0, 0): s=1.871s = 1.871, gˉ=0.25\bar g = 0.25, gx^‾=−0.267\overline{g \hat x} = -0.267, and the gradient is (0.248,−0.210,−0.134,0.095)(0.248, -0.210, -0.134, 0.095). Only the first output was pushed, yet all four inputs receive a gradient, and they sum to 0. Autograd in the Code section gives the same numbers.

Small batches and the gap between training and evaluation#

The batch statistics are estimates from BB values, and two failures follow from that.

Very small batches. With B=2B = 2 the standardized values are always ±1\pm 1: for any two different numbers a<ba < b, the mean is their midpoint and the standard deviation half their distance. The layer outputs β∓γ\beta \mp \gamma whatever the inputs were; in the Code section the batch (4,10)(4, 10) becomes (−1.5,2.5)(-1.5, 2.5) for γ=2\gamma = 2, β=0.5\beta = 0.5. With B=1B = 1 the variance is 0 and PyTorch refuses to normalize in training mode. Statistics from a handful of examples are noisy, and the noise grows as the batch shrinks; on ImageNet, a ResNet-50 with 2 images per GPU had a top-1 error 10.6 points higher with batch normalization than with group normalization, introduced below (Wu and He, 2018).

Running averages lag behind. With momentum 0.10.1, the running average weights the batch from kk steps ago by 0.1⋅0.9k0.1 \cdot 0.9^{k}, an average over roughly the last 10 to 20 batches. They estimate the statistics of weights that have changed since, and a model evaluated early, or right after a large step, sees a mismatch between the two modes, as in step 5 of the figure. Forgetting model.eval() causes the opposite error: predictions that depend on the other examples of the evaluation batch.

Why does it help? The debated explanations#

Batch normalization allows larger learning rates and makes deep convolutional networks train much faster; why is still argued.

  • Internal covariate shift. The original motivation: each layer’s input distribution keeps changing as the layers below learn, and standardizing it stabilizes learning (Ioffe and Szegedy, 2015, section 2). Santurkar et al. (2018) injected random noise with changing mean and variance after the normalization layers, which recreates the shift, and the networks still trained about as well as with plain batch normalization (section 2.1). They argue instead that it makes the loss and its gradients smoother along the training path (section 3).
  • Scale invariance. A weight vector ww followed by batch normalization can be multiplied by any c>0c > 0 without changing the output. Differentiating L(cw)=L(w)L(cw) = L(w) in cc at c=1c = 1 gives w⊤∇L(w)=0w^\top \nabla L(w) = 0, and differentiating in ww gives ∇L(cw)=∇L(w)/c\nabla L(cw) = \nabla L(w)/c. A gradient step therefore turns the direction of ww by about η∥∇L(w)∥/∥w∥\eta \lVert\nabla L(w)\rVert / \lVert w \rVert, an effective learning rate η/∥w∥2\eta/\lVert w \rVert^2 for the direction, and since the step is orthogonal to ww it can only grow ∥w∥\lVert w\rVert and shrink that rate. Arora, Li and Lyu (2019) show that this tunes the effective rate automatically. In the Code section, multiplying the weights before a batch-norm layer by 10 leaves the output unchanged and divides the gradient by 10. How weight decay interacts with this is in Optimizing deep networks.
  • Residual blocks close to the identity. In a residual network, batch normalization on the branch scales it down relative to the skip path by a factor of about the square root of the depth, so that at initialization each block is close to the identity (De and Smith, 2020). This is the mechanism of the residual section below.
  • Noise as regularization. Each example is normalized with statistics of a random batch, a form of noise; the original paper found that it reduced the need for dropout (section 4.2.1).

Not every effect is good. Batch normalization keeps the examples apart, since subtracting the batch mean removes the direction they share: in the experiment below, the average cosine between outputs is 0.3350.335 with it against 0.9930.993 without. But in a deep stack without residual connections it makes the gradients explode at initialization, by a factor that grows exponentially with depth whatever the weight variance (Yang et al., 2019): in the experiment, the first layer’s weight gradient is 168 times the last one’s.

Normalizing over other axes#

Every normalization layer computes the same thing, y=γ⊙(x−μS)/σS2+ϵ+βy = \gamma \odot (x - \mu_S)/\sqrt{\sigma_S^2 + \epsilon} + \beta, with the mean and variance taken over a set SS of values. They differ only in SS. For a batch of feature maps with NN examples, CC channels and H×WH \times W positions:

Figure

Which values share one mean and one variance

Which values share one mean and one varianceFour grids of 4 examples (rows) by 6 channels (columns). Batch norm highlights one column, all examples. Layer norm highlights one row, all channels. Instance norm highlights one cell. Group norm with two groups highlights half a row, three channels of one example.batch normC →NN · H · W valuesdepends on the batchlayer normC →NC · H · W valuesone exampleinstance normC →NH · W valuesone examplegroup norm (G = 2)C →NC/G · H · W valuesone exampleEach cell is the H × W positions of one channel of one example.RMSNorm uses the set of layer norm and does not subtract the mean.Which values share one mean and one varianceFour grids of 4 examples (rows) by 6 channels (columns). Batch norm highlights one column, all examples. Layer norm highlights one row, all channels. Instance norm highlights one cell. Group norm with two groups highlights half a row, three channels of one example.batch normC →NN · H · W valuesdepends on the batchlayer normC →NC · H · W valuesone exampleinstance normC →NH · W valuesone examplegroup norm (G = 2)C →NC/G · H · W valuesone exampleEach cell is the H × W positionsof one channel of one example.RMSNorm uses the set of layer normand does not subtract the mean.
A batch of N = 4 examples with C = 6 channels; a cell stands for all H × W positions of one channel of one example. Highlighted: the values over which one mean and one variance are computed. The layer always computes γ(x − μ)/√(σ² + ε) + β; only the set changes. Only batch norm’s set runs across examples, which is why it depends on the batch size and behaves differently in training and evaluation. Group norm with G = 1 is layer norm, with G = C instance norm. In a Transformer a row is a token and the columns are its d features, so layer norm normalizes each token separately.
  • Batch norm: one channel, all examples and positions. Depends on the batch.
  • Layer norm (Ba, Kiros and Hinton, 2016): one example, all channels and positions. In a Transformer, one token’s dd features.
  • Instance norm (Ulyanov, Vedaldi and Lempitsky, 2016): one example and one channel, its H×WH \times W positions; used for style transfer and in CycleGAN.
  • Group norm (Wu and He, 2018): one example and a group of C/GC/G channels. With G=1G = 1 it is layer norm, with G=CG = C instance norm; the paper’s default is G=32G = 32. It does not depend on the batch, which is why detection and segmentation networks, trained with one or two images per GPU, use it.

Worked example. For N=32N = 32 images, C=256C = 256 channels of 14×1414 \times 14: batch norm averages over 32⋅196=627232 \cdot 196 = 6272 values per statistic, layer norm over 256⋅196=50,176256 \cdot 196 = 50{,}176, instance norm over 196, and group norm with 32 groups over 8⋅196=15688 \cdot 196 = 1568. Only batch norm’s count depends on NN; at N=2N = 2 it falls to 392.

RMSNorm (Zhang and Sennrich, 2019) uses layer norm’s set but divides by the root mean square without subtracting the mean; the formula and an example are in the Transformer note. What it gives up is an invariance: layer norm returns the same output when a constant is added to every feature, RMSNorm only when all features are multiplied by a positive constant (both checked in the Code section). The authors’ hypothesis is that the invariance to re-scaling does the work, and they report running times 7% to 64% lower than with layer norm on different models. Where the normalization sits in a Transformer block, before or after the residual sum, is a separate choice discussed in pre-norm versus post-norm.

What normalizing one example cannot do. Layer norm and RMSNorm restore the scale of each example, but they never compare examples, so they cannot undo the rank collapse of the previous section. In the experiment below a plain thirty-layer stack with layer norm after every linear layer starts with an average cosine of 0.9950.995 between examples and never leaves the loss 2.3032.303, exactly like the stack without normalization. In Transformers layer norm works because the residual stream carries the input past every block.

Residual connections: an identity path, and the variance it adds#

A residual block computes xl+1=xl+Fl(xl)x_{l+1} = x_l + F_l(x_l). Its Jacobian is I+∂Fl/∂xlI + \partial F_l/\partial x_l, so the gradient reaches every block through a term that passes through no weight matrix; the Machine Learning course derives this and the Transformer note expands the product of such Jacobians. What the identity path does to the forward scale is the other half of the story.

At initialization, the last weight matrix of the branch has mean 0 and is independent of everything else, so E[xlFl(xl)]=0E[x_l F_l(x_l)] = 0 and the variances add:

E[xl+12]=E[xl2]+E[Fl(xl)2].E\big[x_{l+1}^2\big] = E\big[x_l^2\big] + E\big[F_l(x_l)^2\big] .

Take a branch F(u)=W2ReLU⁡(W1u)F(u) = W_2 \operatorname{ReLU}(W_1 u) with He variance 2/n2/n for W1W_1 and 1/n1/n for W2W_2, which returns the mean square of its input. Three choices give three growth laws over L=50L = 50 blocks, starting from mean square 1:

  • No normalization, F(xl)F(x_l): each block doubles the mean square, 2l2^{l}, so 250=1.1⋅10152^{50} = 1.1 \cdot 10^{15} at the top. Measured: 867867, 2.9⋅1072.9 \cdot 10^7 and 4.1⋅10144.1 \cdot 10^{14} after 10, 25 and 50 blocks.
  • Pre-norm, F(LN⁡(xl))F(\operatorname{LN}(x_l)): the branch sees an input of mean square 1 and adds 1 per block, 1+l1 + l, so 51 at the top. Measured: 11.311.3, 2626 and 52.752.7.
  • Scaled branch, F(xl)/LF(x_l)/\sqrt L: each block multiplies the mean square by 1+1/L1 + 1/L, and (1+1/50)50=2.69(1 + 1/50)^{50} = 2.69, below ee for any depth. Measured: 1.21.2, 1.661.66 and 2.732.73.

The backward pass has the same structure, δl=(I+∂Fl/∂xl)⊤δl+1\delta_l = (I + \partial F_l/\partial x_l)^\top \delta_{l+1}, and the same additive accounting. This is why every deep residual network does one of these things. Pre-norm Transformers normalize the branch input. ResNets with batch normalization get the down-scaling from the normalization on the branch (De and Smith, 2020) and often go further by setting the scale γ\gamma of the last batch-norm layer of each block to 0, so that every block starts as the exact identity (Goyal et al., 2017, section 5.1). Fixup trains residual networks without any normalization by zeroing the last layer of each branch and scaling the others down with depth (Zhang, Dauphin and Ma, 2019).

The identity path also keeps examples apart. Since xl+1x_{l+1} contains xlx_l unchanged, the differences between two inputs are carried up the stack, and the correlation grows much more slowly than in a plain stack: for the pre-norm network the theory gives 0.440.44 after 10 blocks and 0.590.59 after 50, against 0.870.87 and 0.990.99 for the plain He stack.

Figure

Scale and the difference between examples across depth

Scale and the difference between examples across depthLeft: the mean square of the signal over 50 layers, on a log scale. A residual stack without normalization grows like 2 to the power l, to 1.1·10^15; pre-norm grows linearly, to 51; with the branch divided by the square root of L it reaches 2.7; a plain stack with He initialization stays at 1. Right: the cosine between the representations of two initially orthogonal inputs. In the plain stack it climbs to 1 (0.99 at layer 50), without normalization to 0.96, with pre-norm to 0.59, with the scaled branch to 0.25.110⁵10¹⁰10¹⁵0.00.51.00255002550layer or block llayer or block lmean square of xₗ (log scale)cosine between two inputs1.1·10¹⁵512.70.990.960.590.25plain stack, Heresidual, no normalizationresidual, pre-normresidual, branch / √LScale and the difference between examples across depthLeft: the mean square of the signal over 50 layers, on a log scale. A residual stack without normalization grows like 2 to the power l, to 1.1·10^15; pre-norm grows linearly, to 51; with the branch divided by the square root of L it reaches 2.7; a plain stack with He initialization stays at 1. Right: the cosine between the representations of two initially orthogonal inputs. In the plain stack it climbs to 1 (0.99 at layer 50), without normalization to 0.96, with pre-norm to 0.59, with the scaled branch to 0.25.110⁵10¹⁰10¹⁵0.00.51.00255002550layer or block llayer or block lmean square of xₗ (log scale)cosine between two inputs1.1·10¹⁵512.70.990.960.590.25plain stack, Heresidual, no normalizationresidual, pre-normresidual, branch / √L
Theory for infinite width at initialization, 50 layers or blocks, inputs with mean square 1 and correlation 0. The residual branch F(u) = W₂ ReLU(W₁ u), with weight variances 2/n and 1/n, returns the mean square of its input. Left: variances add, so without normalization every block doubles the signal, pre-norm adds 1 per block, and a branch divided by √L multiplies it by 1 + 1/L, with (1.02)⁵⁰ = 2.69; the plain He stack stays at 1. Right: a plain ReLU stack maps any two inputs to almost the same direction (0.87 after 10 layers, 0.99 after 50), while the identity path of a residual stack carries their difference upwards. The Code section measures the same quantities at width 256 and gets close numbers.

An experiment: thirty layers on digits#

The setting: the 1797 bundled digit images, 70% for training and 30% for validation, a linear input layer to width 64, thirty hidden layers of width 64 and a linear output layer, trained with Adam at learning rate 10−310^{-3}, batches of 32, for 12 epochs. Plain layers compute ReLU⁡(Norm⁡(Wh))\operatorname{ReLU}(\operatorname{Norm}(W h)); residual blocks compute h+WReLU⁡(Norm⁡(h))h + W \operatorname{ReLU}(\operatorname{Norm}(h)), the pre-norm form. The first two columns are measured at initialization on 256 training images: the average cosine between the network’s final hidden vectors for different images, and the norm of the first hidden layer’s weight gradient divided by the last one’s. The last two are means over three seeds.

configurationcosine at initgradient, first / lasttraining lossvalidation accuracy
plain, default init1.0002.0⋅10−112.0 \cdot 10^{-11}2.3030.102
plain, He init0.9931.140.4250.834
plain, batch norm0.3351681.2740.556
plain, layer norm0.9950.2462.3030.100
residual, default init0.8500.8130.0210.966
residual, pre-norm with layer norm0.7585.060.0360.961

Each row matches one mechanism of the note. The default stack loses both the scale and the differences between examples, and learns nothing. He initialization restores the gradient but not the differences, and trains unevenly. Batch norm keeps the examples apart but its gradients explode, and in 12 epochs it gets only part of the way. Layer norm restores the scale of each example but cannot separate them. Both residual networks train to a training loss near 0 and above 96% validation accuracy; with PyTorch’s default initialization the plain residual branch is small enough that the stack works without normalization at this depth. These are three seeds of one small setting; with more epochs the plain configurations improve, but the order between failing and training does not change.

What changed#

Plain deep stackWith the tools of this note
Scale of activationsmultiplied by nvκn v \kappa per layerfactor 1 at init (Glorot, He); held during training by normalization
Scale of gradientsmultiplied by nvκ′n v \kappa' per layerfactor 1 at init; identity path in residual blocks
Differences between examplescollapse towards one directionkept by batch norm and by residual connections
Dependence on the batchnonebatch norm only: noisy for small batches, two modes
Residual stack scale2l2^l without control1+l1 + l with pre-norm, below ee with scaled branches
Thirty layers on digitsstuck at loss 2.3030.96–0.97 validation accuracy

Limitations#

  • Initialization is a statement about averages at step 0. Once training starts, weights and inputs are no longer independent, and the derivations no longer hold; single networks fluctuate around the average, more so when they are narrow.
  • Batch norm couples examples. It needs batches large enough for stable statistics, behaves differently in training and evaluation, and its running averages must be recomputed whenever the weights change without training steps, for example after averaging weights.
  • The explanations are partial. Why batch norm helps is still debated, and the arguments above (smoothness, scale invariance, identity bias, noise) are each supported in some settings and not a complete account.
  • Normalizing one example does not separate examples. Layer norm, group norm and RMSNorm work in practice inside residual architectures; in a plain deep stack they do not prevent rank collapse.
  • Saturating activations have no exact fix. For tanh no gain keeps both the forward and the backward factor at 1 away from zero.

What you should remember#

  • Per layer, the forward variance is multiplied by ninvκn_{\text{in}} v \kappa and the backward variance by noutvκ′n_{\text{out}} v \kappa', with κ=κ′=12\kappa = \kappa' = \tfrac12 for ReLU and 1 for a linear activation; over LL layers the factors are raised to the power L−1L - 1.
  • Glorot: v=2/(nin+nout)v = 2/(n_{\text{in}} + n_{\text{out}}). He: v=2/ninv = 2/n_{\text{in}}, with the backward product telescoping to nL/n1n_L/n_1. PyTorch’s default 1/(3nin)1/(3 n_{\text{in}}) shrinks a plain ReLU stack by 6 per layer.
  • Deep unnormalized ReLU stacks map every input towards one direction; initialization cannot prevent it.
  • Batch norm standardizes each feature over the batch; its gradient removes the batch mean and the component along x^\hat x; it uses batch statistics in training and running averages in evaluation, and fails for very small batches.
  • Batch, layer, instance and group norm differ only in the set of values that share a mean and a variance; RMSNorm drops the mean and the invariance to shifts.
  • A residual block adds variances: 2l2^l without normalization, 1+l1 + l with pre-norm, below ee with branches scaled by 1/L1/\sqrt L or zero-initialized; it keeps both the gradient path and the differences between examples.

Code#

The scale of 50 layers under four initializations, Glorot and He, the gain of tanh, the backward pass of batch norm checked against autograd, its two modes and its scale invariance, the axes of the normalization layers, residual stacks with three growth laws, and the experiment of the last section. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about 40 seconds on a laptop CPU, almost all of it in the experiment.

Data. Optical Recognition of Handwritten Digits, E. Alpaydin and C. Kaynak (1998), UCI Machine Learning Repository, CC BY 4.0. Loaded through scikit-learn; the transformations used in this example are specified in the code.

import math, numpy as np, torch
from torch import nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

# 1. the scale of z_l in a stack of 50 bias-free ReLU layers of width 256, for four weight variances v
n, L = 256, 50
torch.manual_seed(0)
x0 = torch.randn(512, n, requires_grad=True)
r = torch.randn(512, n)                       # a fixed random direction for the loss at the top
for name, v in [('N(0,1)', 1.0), ('1/n', 1 / n), ('default', 1 / (3 * n)), ('He', 2 / n)]:
    torch.manual_seed(1)
    h, zs = x0, []
    for l in range(L):
        z = h @ (torch.randn(n, n) * math.sqrt(v)).T
        z.retain_grad(); zs.append(z); h = torch.relu(z)
    (zs[-1] * r).sum().backward()
    ms = ['%.3g' % zs[i].pow(2).mean().item() for i in (0, 9, 24, 49)]
    print(name, ms, 'gradient ratio z_1 / z_50: %.3g' % (zs[0].grad.pow(2).mean() / zs[-1].grad.pow(2).mean()).item())
# N(0,1) ['258', '2.41e+21', 'inf', 'nan'] gradient ratio z_1 / z_50: nan
# 1/n ['1.01', '0.00199', '2.48e-08', '2.19e-15'] gradient ratio z_1 / z_50: 2.94e-15
# default ['0.336', '3.37e-08', '2.93e-20', '3.05e-39'] gradient ratio z_1 / z_50: 1.23e-38
# He ['2.02', '2.04', '0.833', '2.46'] gradient ratio z_1 / z_50: 1.66

# 2. Glorot and He for a 256 x 256 layer, and the gain of tanh: the variance a deep tanh stack settles at
torch.manual_seed(0); W = torch.empty(256, 256)
print(round(nn.init.xavier_normal_(W).std().item(), 4), round(nn.init.kaiming_normal_(W, nonlinearity='relu').std().item(), 4))
# 0.0624 0.0887   (theory 0.0625 and 0.0884)
xi = np.random.default_rng(0).standard_normal(2_000_000)
for g in (1.0, 5 / 3):
    q, qs = 1.0, []
    for l in range(200):
        q = g * g * np.mean(np.tanh(math.sqrt(q) * xi) ** 2); qs.append(q)
    chi = g * g * np.mean((1 - np.tanh(math.sqrt(q) * xi) ** 2) ** 2)   # backward factor per layer at that variance
    print('gain %.3f' % g, [round(float(qs[i]), 4) for i in (9, 49, 199)], 'backward factor %.3f' % chi)
# gain 1.000 [0.0521, 0.0101, 0.0024] backward factor 0.995
# gain 1.667 [1.1776, 1.1776, 1.1776] backward factor 1.211

# 3. batch norm: the gradient through the batch statistics, checked against autograd
x = torch.tensor([1.0, 2.0, 3.0, 6.0], requires_grad=True)
g = torch.tensor([1.0, 0.0, 0.0, 0.0])          # upstream gradient dL/dxhat
mu, var = x.mean(), x.var(unbiased=False)
xhat = (x - mu) / torch.sqrt(var + 1e-5)
(xhat * g).sum().backward()
by_hand = (g - g.mean() - xhat * (g * xhat).mean()) / torch.sqrt(var + 1e-5)
print([round(v, 4) for v in x.grad.tolist()], [round(v, 4) for v in by_hand.tolist()], round(x.grad.sum().item(), 6))
# [0.2482, -0.21, -0.1336, 0.0954] [0.2482, -0.21, -0.1336, 0.0954] 0.0

# 4. train and eval statistics: one training step of BatchNorm1d, then the same inputs in eval mode
bn = nn.BatchNorm1d(1)
with torch.no_grad(): bn.weight.fill_(2.0); bn.bias.fill_(0.5)
xb = torch.tensor([[1.0], [2.0], [3.0], [6.0]])
print([round(v, 3) for v in bn(xb).flatten().tolist()], round(bn.running_mean.item(), 3), round(bn.running_var.item(), 3))
bn.eval()
print([round(v, 3) for v in bn(xb).flatten().tolist()])
bn.train()
print([round(v, 3) for v in bn(torch.tensor([[4.0], [10.0]])).flatten().tolist()])   # a batch of two: always beta -/+ gamma
# [-1.638, -0.569, 0.5, 3.707] 0.3 1.367
# [1.698, 3.408, 5.119, 10.252]
# [-1.5, 2.5]

# 5. scale invariance: multiplying the weights before batch norm by 10 leaves the output and divides the gradient by 10
torch.manual_seed(0)
Wa = torch.randn(8, 4, requires_grad=True); Wb = (10 * Wa.detach()).requires_grad_()
xs, bn2 = torch.randn(16, 4), nn.BatchNorm1d(8, eps=1e-12)
ya, yb = bn2(xs @ Wa.T), bn2(xs @ Wb.T)
ya.pow(3).sum().backward(); yb.pow(3).sum().backward()
print(round((ya - yb).abs().max().item(), 6), round((Wa.grad.norm() / Wb.grad.norm()).item(), 3), abs(round((Wa.detach() * Wa.grad).sum().item(), 4)))
# 0.0 10.0 0.0   (the last number: the gradient is orthogonal to the weights)

# 6. which values share a statistic, for a batch of 32 feature maps with 256 channels of 14 x 14
N, C, HW, G = 32, 256, 14 * 14, 32
print({'batch': N * HW, 'layer': C * HW, 'instance': HW, 'group': C // G * HW})
# {'batch': 6272, 'layer': 50176, 'instance': 196, 'group': 1568}
t = torch.randn(2, 4, 3, 3)
print(torch.allclose(nn.GroupNorm(1, 4, affine=False)(t), F.layer_norm(t, t.shape[1:]), atol=1e-5),
      torch.allclose(nn.GroupNorm(4, 4, affine=False)(t), F.instance_norm(t), atol=1e-5))
# True True: one group is layer norm, one channel per group is instance norm
v = torch.tensor([1.0, 2.0, 3.0, 6.0]); rms = nn.RMSNorm(4, elementwise_affine=False)
print(torch.allclose(F.layer_norm(v + 5, (4,)), F.layer_norm(v, (4,)), atol=1e-5), torch.allclose(rms(v + 5), rms(v), atol=1e-5))
# True False: layer norm ignores a shift of all features, RMSNorm does not

# 7. stacks of 50 blocks: plain He layers, and residual blocks x + F(x) with F = W2 relu(W1 u), Var W1 = 2/n, Var W2 = 1/n
def stack(mode, x, L=50):
    torch.manual_seed(1)
    out = []
    for l in range(L):
        W1, W2 = torch.randn(n, n) * math.sqrt(2 / n), torch.randn(n, n) * math.sqrt(1 / n)
        if mode == 'plain':
            x = torch.relu(x @ (torch.randn(n, n) * math.sqrt(2 / n)).T)
        else:
            u = F.layer_norm(x, (n,)) if mode == 'pre-norm' else x
            branch = torch.relu(u @ W1.T) @ W2.T
            x = x + (branch / math.sqrt(L) if mode == 'scaled' else branch)
        out.append(x)
    return out
a, b = torch.randn(n), torch.randn(n)
xx = torch.stack([a, b - (a @ b) / (a @ a) * a])              # two orthogonal inputs
xx = xx / xx.pow(2).mean(1, keepdim=True).sqrt()              # each with mean square 1
for mode in ('plain', 'none', 'pre-norm', 'scaled'):
    hs = stack(mode, xx)
    ms = ['%.3g' % hs[i].pow(2).mean().item() for i in (9, 24, 49)]
    cos = [round(F.cosine_similarity(hs[i][0], hs[i][1], dim=0).item(), 3) for i in (9, 29, 49)]
    print(mode, ms, cos)
# plain ['0.765', '1.85', '2.93'] [0.887, 0.984, 0.996]      theory: cosine 0.872, 0.972, 0.988
# none ['867', '2.9e+07', '4.14e+14'] [0.71, 0.92, 0.94]    theory: 2^l; cosine 0.708, 0.915, 0.960
# pre-norm ['11.3', '26', '52.7'] [0.499, 0.553, 0.546]     theory: 1 + l; cosine 0.441, 0.553, 0.595
# scaled ['1.2', '1.66', '2.73'] [0.067, 0.125, 0.22]       theory: 1.02^l; cosine 0.060, 0.164, 0.251

# 8. thirty layers of width 64 on digits: initialization, normalization and residual connections
X, y = load_digits(return_X_y=True)
Xtr, Xva, ytr, yva = train_test_split(X / 16.0, y, test_size=0.3, random_state=0, stratify=y)
Xtr, Xva = torch.tensor(Xtr, dtype=torch.float32), torch.tensor(Xva, dtype=torch.float32)
ytr, yva = torch.tensor(ytr), torch.tensor(yva)

class Net(nn.Module):
    def __init__(self, norm, he, res, width=64, depth=30):
        super().__init__()
        self.inp, self.out, self.res = nn.Linear(64, width), nn.Linear(width, 10), res
        self.lins = nn.ModuleList([nn.Linear(width, width) for _ in range(depth)])
        make = {'none': nn.Identity, 'batch': lambda: nn.BatchNorm1d(width), 'layer': lambda: nn.LayerNorm(width)}[norm]
        self.norms = nn.ModuleList([make() for _ in range(depth)])
        if he:
            for lin in self.lins: nn.init.kaiming_normal_(lin.weight, nonlinearity='relu'); nn.init.zeros_(lin.bias)
    def forward(self, x):
        h = self.inp(x)
        for lin, norm in zip(self.lins, self.norms):
            h = h + lin(F.relu(norm(h))) if self.res else F.relu(norm(lin(h)))   # residual blocks are pre-norm
        return self.out(h)

configs = [('plain, default init', 'none', False, False), ('plain, He', 'none', True, False),
           ('plain, batch norm', 'batch', False, False), ('plain, layer norm', 'layer', False, False),
           ('residual', 'none', False, True), ('residual, layer norm', 'layer', False, True)]
print('                       cos at init  grad first/last   train loss  val acc')
for name, norm, he, res in configs:
    torch.manual_seed(0)
    model = Net(norm, he, res)
    h = model.inp(Xtr[:256])                                   # diagnostics at initialization, 256 training images
    for lin, nm in zip(model.lins, model.norms):
        h = h + lin(F.relu(nm(h))) if res else F.relu(nm(lin(h)))
    z = F.normalize(h, dim=1); cos = ((z @ z.T).sum() - 256) / (256 * 255)
    F.cross_entropy(model.out(h), ytr[:256]).backward()
    ratio = model.lins[0].weight.grad.norm() / model.lins[-1].weight.grad.norm()
    runs = []
    for seed in range(3):
        torch.manual_seed(seed)
        model = Net(norm, he, res)
        opt = torch.optim.Adam(model.parameters(), lr=1e-3)
        loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(Xtr, ytr), batch_size=32, shuffle=True, drop_last=True)
        for epoch in range(12):
            model.train()
            for xb, yb in loader:
                opt.zero_grad(); F.cross_entropy(model(xb), yb).backward(); opt.step()
        model.eval()
        with torch.no_grad():
            runs.append([F.cross_entropy(model(Xtr), ytr).item(), (model(Xva).argmax(1) == yva).float().mean().item()])
    m = np.mean(runs, axis=0)
    print(f'{name:22} {cos.item():10.3f} {ratio.item():14.3g} {m[0]:12.3f} {m[1]:8.3f}')
#                        cos at init  grad first/last   train loss  val acc
# plain, default init         1.000       1.97e-11        2.303    0.102
# plain, He                   0.993           1.14        0.425    0.834
# plain, batch norm           0.335            168        1.274    0.556
# plain, layer norm           0.995          0.246        2.303    0.100
# residual                    0.850          0.813        0.021    0.966
# residual, layer norm        0.758           5.06        0.036    0.961

Next#

With the scale under control, a deep network can be trained; how fast and how well depends on the optimizer. Its loss surface is not convex, its best learning rate changes during training, its weight decay interacts with the normalization layers of this note, and its numbers may be stored in 16 bits. The next note takes up the learning-rate schedule and warm-up, AdamW, gradient clipping, the link between batch size and learning rate, flat minima, and mixed precision.

References#