Batch Normalization

Batch normalization (BatchNorm) standardizes each activation across the examples of a batch , then shifts and rescales it with learned parameters. It first computes the batch mean and standard deviation,

where is the activation for example . It then standardizes and rescales every example:

Here prevents division by zero when every example has the same value, and the scale and offset are learned. After the operation the batch has mean and standard deviation . In a dense network each hidden unit has its own statistics and parameters, so layers of units add parameters. In a convolutional network the statistics of each channel are pooled over the batch and over all spatial positions, so layers of channels add offsets and scales. This version is sometimes called spatial batch normalization.

At test time there may be no batch. The network then uses fixed statistics from one of three sources:

  • Training-set averages, computed over the whole training set after training.
  • Running averages, updated during training. PyTorch uses these.
  • Held-out statistics, computed on separate data.

In a plain CNN, BatchNorm usually sits between a convolution and its ReLU. In a pre-activation residual block it sits at the start of the block. Ghost batch normalization computes the statistics on a subset of the batch.

BatchNorm has four benefits:

  • Stable forward pass: initializing and gives every normalized activation unit variance.
  • Higher learning rates: training tolerates larger steps.
  • Regularization: the batch statistics add noise to every example.
  • Smoother loss: the loss and its gradient vary less.

It also has three costs:

  • Batch dependence: each output depends on the other examples in the batch.
  • Train-test mismatch: training uses batch statistics, while testing uses fixed ones.
  • Redundant parameters: the mean subtraction cancels the bias of the preceding layer, and the scale of that layer’s weights no longer affects the output.

Two Ways to Write the Same Layer

The lecture and the textbook write with offset . Implementations such as PyTorch, and the homework, write and , with inside the square root and as the offset. The two agree when . The derivation below uses the implementation form.

Intuition

A layer’s input distribution changes every time the earlier layers update, and without control its scale can drift by a factor at each layer. BatchNorm measures where the batch currently sits and moves it back to mean zero and unit spread before the next layer sees it. The learned and then put the activations wherever the network finds useful, so no expressive power is lost. Each example is standardized against the other examples in the same batch. That coupling is what makes the layer both a regularizer and a source of trouble.

Properties

(Invariance to Weight Scale) The output of BatchNorm does not change when all the weights and the bias feeding an activation are multiplied by the same positive constant.

If the weights and bias that produce double, every doubles, doubles, doubles, and the standardized values stay the same. A whole family of weights therefore gives one function, and only the direction of each weight vector matters. Any bias before BatchNorm is also redundant, since subtracting removes it, and takes its role. Implementations therefore drop the bias of a convolution followed by BatchNorm. The scale invariance also decouples the size of the weights from the learning rate. Very aggressive learning-rate schedules, even exponentially growing ones, can still train.

(Why It Works) The evidence favors a smoother loss surface over the originally proposed reduction of internal covariate shift.

The original paper argued that BatchNorm reduces internal covariate shift, the change in each layer’s input distribution caused by updates to earlier layers. A later experiment injected random covariate shift after BatchNorm and found that the networks trained equally well. The same study measured that BatchNorm makes the loss and its gradient change more slowly along the gradient direction. A smoother surface keeps the gradient informative after each step, so a larger learning rate is safe, and larger learning rates also tend to improve generalization. BatchNorm also reduces shattered gradients in deep networks. The full mechanism is still not well understood.

(Batch Noise Regularizes) Each example is normalized with statistics that depend on the other examples in its batch, which adds random noise during training.

The same image is standardized slightly differently on every step, depending on which images share its batch. This noise works like other noise injected during training, such as dropout, and it improves generalization. The amount of noise falls as the batch grows, since larger batches give more accurate statistics. Ghost batch normalization computes the statistics on sub-batches to keep the noise when very large batches are used for speed. Alternatives to BatchNorm that only fix the initialization usually generalize worse, probably because they lack this noise.

(Train-Test Mismatch) BatchNorm computes a different function at test time than during training, and it fails when the batch is too small.

During training the statistics come from the current batch, and at test time they are frozen. If the frozen statistics do not match the test data, accuracy drops. Small batches give noisy statistics. In a dense layer with a batch of one, for every unit, so the output is the constant for any input, and no gradient reaches the earlier layers. A convolutional layer still pools over the positions of the single image. Sequence models are awkward, because statistics would be needed for every time step, and a test sequence can be longer than every training sequence. Training split across several machines needs the statistics of the whole batch. These cases are why layer normalization and group normalization exist.

Derivation

We want the gradient of the loss with respect to each input of a BatchNorm layer during training. For one channel and a batch of values (for a convolution, counts examples times positions), the forward pass is

where . Write . The parameter gradients follow directly from the last equation:

Each affects the loss through directly and through and , which every uses. The figure shows the computational graph for a batch of three. The paths that start at are red. The paths through and reach every , so the gradient for collects a sum over all .

\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=1cm,y=1cm,>={Stealth[length=2.2mm]},nd/.style={circle,draw,thick,minimum size=8mm,inner sep=0pt}]
\foreach \j/\y in {1/1.8,2/0,3/-1.8} {
\node[nd] (x\j) at (0,\y) {$x_{\j}$};
\node[nd] (xh\j) at (5.2,\y) {$\hat{x}_{\j}$};
\node[nd] (y\j) at (7.6,\y) {$y_{\j}$};
}
\node[nd,cold] (mu) at (2.6,0.9) {$\mu$};
\node[nd,cold] (var) at (2.6,-0.9) {$\sigma^2$};
\node[nd] (L) at (9.8,0) {$\mathcal{L}$};
\foreach \j in {2,3} {
\draw[->,mid,thick] (x\j) -- (mu);
\draw[->,mid,thick] (x\j) -- (var);
\draw[->,mid,thick] (x\j) -- (xh\j);
}
\draw[->,hot,very thick] (x1) -- (mu);
\draw[->,hot,very thick] (x1) -- (var);
\draw[->,hot,very thick] (x1) -- (xh1);
\draw[->,mid,thick] (mu) -- (var);
\foreach \j in {1,2,3} {
\draw[->,cold,thick] (mu) -- (xh\j);
\draw[->,cold,thick] (var) -- (xh\j);
\draw[->,thick] (xh\j) -- (y\j);
\draw[->,thick] (y\j) -- (L);
}
\node at (2.6,2.9) {\small statistics};
\node at (5.2,2.9) {\small standardize};
\node at (7.6,2.9) {\small $\gamma\hat{x}_j + \beta$};
\end{tikzpicture}
\end{document}

By the chain rule,

where the contribution of through vanishes because . Collecting the three paths,

Substituting and writing gives the closed form

Two consequences follow by summing. The input gradients add to zero, , and they are orthogonal to the standardized values, . Shifting or rescaling the whole batch does not change the output, so the gradient has no component in those two directions. With , as in a dense layer with a batch of one, the bracket is , which matches the batch-of-one failure above.

Examples

(Easy) Normalizing a Batch

One hidden unit takes the values on a batch of four examples. Its BatchNorm layer has and , and is negligible.

(Medium) A Weight Whose Size Does Not Matter

A unit computes from a scalar input and feeds BatchNorm. A batch has inputs .

(Hard) Backpropagating Through BatchNorm

A batch of three values passes through BatchNorm with , and negligible . The upstream gradient is , so the loss depends only on the first output.

See Also