Sitemap
TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

The real reason why BatchNorm works

11 min readMar 16, 2020

--

Normalization techniques are some of the great tools we have while analyzing any form of data, a simple operation of adjusting the mean and variance of a distribution results in the catastrophic success of various normalizing techniques in deep neural networks, one of them being the famous batch normalization Ioffe et al.¹.

Everyone’s heard of it:

Press enter or click to view image in full size
Algorithm-1 from Ioffe et al.¹

Currently, the most widely accepted explanation of BatchNorm’s success, as well as its original motivation, relates to the so-called internal covariate shift (ICS). Informally, ICS refers to the change in the distribution of layer inputs caused by updates to the preceding layers. It is conjectured that such continual change negatively impacts training. The goal of BatchNorm was to reduce ICS and thus remedy this effect.

In Ilyas et al.², the authors present a view that there does not seem to be any link between the performance gain of BatchNorm and the reduction of internal covariate shift. Or that this link is tenuous, at best. In fact, they found that in a certain sense BatchNorm might not even be reducing internal covariate shift, and prove that, under natural conditions, the Lipschitzness of both the loss and the gradients (basically smoothness of the loss surface and its gradients) are improved in models with BatchNorm, hence demonstrating that BatchNorm impacts network training in a fundamental way: it makes the landscape of the corresponding optimization problem significantly more smooth.

Here, we’ll analyze the second-order properties of the error surface for models where the error space is quadratic in weights, then re-parametrizing the surface in order to get an analysis in terms of eigenspectrum of the covariance matrix of the input, and thence using the results to infer why batch norm might be improving the rate of convergence and why does it make the network invariant to initialization.

For various learning algorithms that search the space of weights {W} for optimal values W* for which the error function E(W) is minimal, based on gradient descent, their properties are controlled by second-order properties of E(W) surface.

For this analysis, I’ll focus on a single layer of a neural network with X(Nx1) as an input vector to this layer and W(1xN) be the weights of this layer and Y(1x1) be the output of this layer, for convenience considering mean squared error:

p is the size of the dataset

Now clearly error surface is quadratic in weights, therefore rewriting it:

where R is defined as:

Press enter or click to view image in full size

where Xui is ith component of uth input vector(Nx1), therefore R is clearly the NxN input covariance matrix.

Q is an N-dim vector, defined as:

c is just a constant:

Now, the gradient of E(W) w.r.t. W is J(E) = RW-Q while the Hessian matrix of second derivatives is clearly H = R

The solution space W* which minimizes E(W) obviously contains entries for which gradient is zero, therefore this solution space is the subspace of solutions of linear equation:

(from J(E)=0)

Now, this RW=Q is a common type of problem in linear algebra(Ax=b), many problems in engineering applications can be solved by formulating in this format and then analyzing the eigenspectrum of A.

As the solution space W* was a subspace of solutions of RW=Q, now if all columns of R are independent, therefore R has full rank, clearly, this subspace collapses to a single point(unique solution).

Now all this is good, but why should we do this?

The eigenvectors of R define the principal axes of E(W) when loss surface is quadratic in weights (this can be studied from “Active Control of Noise and Vibration (Colin Hansen, Scott Snyder)” section-6.5.2)⁵
and we can compute the second derivative of a surface in the direction of any unit vector u by:

Choosing u to be an eigenvector of H(=R), we can get the second derivative in the direction of principal axes of E(W), which, as known from diagonalization of a matrix, will be the eigenvalues of H(=R).

We already have our gradient expressed in terms of R and our Hessian = R, and as we can define principal axes of E(W) in terms of R, we will do 2 transformations on the space containing our error surface:

  • Centering to the solution point, by basic translation
  • Rotation, we have to rotate this V` onto the principal axes of E(W), so that we can analyze the Hessian in the directions of principal axes. Now, if we multiply a matrix to a vector, it results in a spatial transformation(ranging from rotation, translation to squishing the space into a single point). To achieve rotation, we will multiply V` with eigenvector matrix of R, containing mutually orthogonal normalized eigenvectors of R, naming this matrix U(general convention), clearly this matrix will be orthonormal and columns will be of the same dimension as W, so:

The complete transformation will be:

Based on this, our equation of E(W) gets reparametrized as :

where D is just the diagonal matrix containing eigenvalues of R on the diagonal (also called diagonalization of a matrix) and E_o is just E(W*).

Remember V is still a vector, but each component of V represents the corresponding principal axis of the error surface.

Then,

λ_j is jth diagonal element of D, also the eigenvalue of jth eigenvector of R(=H)

and

𝛿(j,k)=1 for j=k and 0 everywhere else

Clearly the eigenvalues of the input covariance matrix give the second derivative of error surface w.r.t. its principal axes.

Putting these two results in a matrix gives the Hessian as the diagonal eigenmatrix D, (H = D), hence

As the basic weight update rule for gradient descent is:
V(k+1) = V(k) — η*J(E(V))
V(k+1) = v(k) — η*D*V(k)

V(k) is the value of V at kth timestep.

V being Nx1 vector, this results in N decoupled equations (as each component in V is orthonormal), and as V=U(W-W*), for the optimal solution V decays to zero, therefore each component evolves along a principal direction as

Vj(0) is the jth component of V at initialization

Get Harshveer Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Now for this Vj to converge to zero over multiple timesteps(k>0), a term with positive power must be less than 1 in magnitude, so

|1-η*λ_j| < 1
0 < η < 2/λ_j

As this is just a formulation of exponential decay, Vj decays to zero in the characteristic time:

  • For η in range (1/λ_j, 2/λ_j)
    1-η*λ_j is negative, hence it converges with oscillatory behavior and step size is large
  • For η in range (0, 1/λ_j),
    step size is small, convergence requires a high value of k(timesteps)
  • Well, if η = 1/λ_j, if such a choice is possible, convergence is reached in a single iteration.

Now, if all eigenvalues are equal,λ_j = λ, for all 1<=j<=N, as H=D, convergence is reached in a single step with:

η = 1/λ

But this highly symmetric case rarely occurs. Geometrically, this occurs if the cross-sections of error surface E(W) are hyper-spheres in N-dim space {W}(hyper-sphere formed by encircling principle components, with these eigenvalues being equal, they get stretched or squished equally, thence a hyper-sphere), but this is very rare. The cross-section of E(W) is elliptical with different eigenvalues along different principle directions.

Based on the above equations, η must be chosen between (0,1/λ_mx) and λ_mx being the largest eigenvalue of the input covariance matrix, the slowest time constant is

The smallest step size η=1/λ_max gives:

to decay along the principle direction of smallest non-zero curvature (basically eigenvector with smallest non-zero eigenvalue, i.e. λ_mn).

This clearly shows, that for error surface quadratic in weights, learning dynamics are controlled by the eigenvalue distribution of Hessian.

Now that we know this, why stop here, let’s examine the eigenspectrum here.

It is assumed, that the input components, i.e., {Xi} are independent for all 1<=i<=N and each component is drawn from mean m and variance v( for convenience, considering all components of an input having numerically same mean and variance). We have p as the data size and N as vector dimension, say α = p/N (ratio quantifying the training set), the eigenspectrum is yielded as (the complete derivation of the eigenspectrum can be found in the combined works of I. Kanter, Yann Lecun and A. Solla 1991)

Press enter or click to view image in full size
Equation-13 from LeCun et al.³

where

For λ ∈ (λ-,λ+), the spectrum is continuous, then in the limit of p and α tending to infinity, λ- =λ+ = v

  • As should be clear by now, if p<N, the number of independent columns of R will be equal to p. R won’t be full rank, so a total of (N-p) eigenvalues will be zero out of N, results in a delta function contribution of weight 1-α for all the zero eigenvalues (basically spectral density for eigenvalue being zero will be 1-α ).
  • A large isolated eigenvalue of order N, call it λ_N is present in the case when inputs are biased i.e., m≠0. This can be clearly understood, consider
    the structure of R for p → ∞ limit,
    1. All off-diagonal elements are equal to m²(product of means of both)
    2. All diagonal elements are equal to v+m²

So, the eigenvector U_N = (1….1) thus corresponds to the eigenvalue

∵ R*U_N = (Nm²+v)*U_N

and all other N-1 eigenvalues are equal to v,(how? satisfying the fact that trace(R) = sum of eigenvalues = N(m² + v) ), moreover the continuous part of spectrum collapses onto a delta function at λ- = λ+= v as p->inf and only one value(=λ_N) is greater than λ+.

The largest part of λ_N is eliminated if m=0, that is, centered inputs with no bias, reduces λ_N significantly, and as λ_N was the largest(λ_max), reducing its value affects t_mx significantly based on previous equations, clearly showing that using centered inputs improves learning time.

So it’s clear that biased inputs produce large eigenvalues and are responsible for slow convergence, to remove this, either the inputs can be centered,
or, another way to deal with this based on our previous equations, is to use individual learning rates inversely proportional to N(number of inputs to the neuron under observation).

All this proves the following clearly:

  • For the loss surface, gradient depends on i/p covariance matrix and weights, but Hessian is constant in the direction of a given principal axis(here ith column of U ), and only depends on i/p covariance matrix
  • Biased inputs slow down convergence
  • Large eigenvalues ( large compared to other eigenvalues, not absolutely large) of the input covariance matrix also slow down convergence
  • The eigenvalue spectrum of Hessian of error surface is heavily controlled by the variance of input component distribution
  • Large learning rates can be used by having good control over eigenvalues of the covariance matrix

In terms of BatchNorm:

  • We know “relatively” large eigenvalues (basically, outlying eigenvalues) hurt the convergence, and batch-norm suppresses these outliers (based on the plots of eigenspectrum in Ghorbani et al.⁴), pointing to one of the reasons why BN works
Press enter or click to view image in full size
Figure 6 from Ghorbani et al.⁴, the y-axis shows λ_mx/λ_mn where λ_mx and λ_mn are the largest and smallest eigenvalues of Hessian respectively.
Press enter or click to view image in full size
Figure 7 from Ghorbani et al.⁴ showing the eigenspectrum of Hessian of loss surface for both batch norm and without batch norm resnet
  • In the first part of this blog, we have an analytical reason for why “relatively” large eigenvalues hurt, Ghorbani et al.⁴ shows this in terms of gradient energy. Through analysis(graphs and Appendix E), they show that without batch norm, the direction of the computed “stochastic” gradient at timestep t is not aligned with the direction towards the optimum, instead, it mostly lies in the subspace of the dominant eigenvectors and is mostly orthogonal to the direction towards the optimum. But after batch norm the gradient direction is almost
    orthogonal to the dominant eigenvector and is better aligned towards the direction of the optimum point. Because, when the gradient is aligned in the direction of dominant eigenvectors, only those components get trained and others(with low eigenvalues), take time to train(because the gradient is mostly towards the other directions, the direction of dominant eigenvectors), and the projection of gradient in the direction of those with low eigenvalues is small, hence slow convergence. Even above here, as we calculated t=(1/η*λ), for a given η, low λ takes more time, now this λ is basically the second derivative in the direction of a given eigenvector, small means flatter region. And, these directions with small λ contribute to almost 50% of L1 energy of Hessian eigenvalues

Basically these small eigenvalues matter a lot to the loss, the path to optimum consists of these directions.

Press enter or click to view image in full size
Figure 11 from Ghorbani et al.⁴, the y-axis is the ratio of the norm of projection of loss gradient in the direction of most dominant eigenvalues to the norm of loss gradient, clearly, loss gradient is dominantly in the direction of most dominant eigenvalues in non-batchnorm models
  • The previous point was about L1 energy of Hessian eigenvalues(λ_i here), now talking about the energy of gradients(gradient energy is basically depicted by eigenspectrum of covariance of gradient vector), as the small eigenvalues consisted roughly 50% of L1 energy of Hessian eigenvalues, almost all of the gradient energy is concentrated in the subspace spanned by the outliers. So basically the ones with small eigenvalue compose a small part of gradient energy, but as per the second point, they’re important, so it makes the entire convergence a slow process.
Press enter or click to view image in full size
Figure 12 from Ghorbani et al.⁴, the y-axis is the inner-product of loss gradient vector with loss vector itself, clearly in non-batchnorm network, ‘stochastic ’loss gradient is orthogonal to the actual loss direction
  • As stated earlier, the convergence depends completely on these eigenvalues, the absence of relative outliers allows the use of finely-tuned learning rate based on λ_mx, hence making the network invariant to initialization.
  • Lowering the eigenvalues of the covariance matrix (by keeping the covariance matrix close to the identity matrix, such as in BatchNorm) allows for higher learning rates as shown above
  • Batch norm is said to make the training of all weights happen at equal rates, it occurs because of those eigenvalues not having any outliers, as mentioned in the above points, same learning rate((=1/λ_mx)) for all parameters will give the same rate of convergence.
  • Batch norm can also be seen as re-parametrizing the error surface to make it smoother in every direction

[1]: “Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift”(https://arxiv.org/pdf/1502.03167.pdf)

[2]: “How Does Batch Normalization Help Optimization?”(https://arxiv.org/pdf/1805.11604.pdf)

[3]: “Eigenvalues of Covariance Matrices: Application to Neural Network Learning”(http://yann.lecun.com/exdb/publis/pdf/lecun-kanter-solla-91.pdf)

[4]: “An Investigation into Neural Net Optimization via Hessian Eigenvalue Density”(https://arxiv.org/pdf/1901.10159.pdf)

[5]: “Active Control of Noise and Vibration (Colin Hansen, Scott Snyder”(https://books.google.co.in/books?id=COfqBgAAQBAJ&pg=PA403&lpg=PA403&dq=The+eigenvectors+of+the+input+correlation+matrix+define+the+principal+axes+of+the+error+surface&source=bl&ots=jKSC91Oc_1&sig=ACfU3U2XD6E2ar4WqziymyQYxSGzWLHMDQ&hl=en&sa=X&ved=2ahUKEwjk4Kfb_MflAhVl6nMBHZPFDBkQ6AEwAnoECAYQAQ#v=onepage&q&f=false)

--

--

Harshveer Singh
Harshveer Singh

Written by Harshveer Singh

Working on understanding loss landscapes in DL | Causal inference and biologically plausible learning agents | GitHub - llStringll

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.