Simple Algorithm
Deep Learning · Emergence · 28 min

The Hessian of a Deep Network

Bulk and outliers, Gauss–Newton structure and what the spectrum reveals.

The Hessian of a deep network has as many rows as the network has parameters, far too many to store, yet its spectrum can be measured, and it has a strikingly regular shape: a huge bulk of eigenvalues near zero, a few large outliers, roughly one per class, and small negative eigenvalues. This lesson explains where that shape comes from, how to compute spectra of models with millions of parameters from Hessian–vector products alone, and what the spectrum is used for.

What you’ll learn

  • Describe the measured Hessian spectrum of trained classifiers (bulk, outliers, negative eigenvalues), how it changes during training, and how batch normalization affects it.
  • Derive the Gauss–Newton decomposition for the squared loss and softmax cross-entropy, bound the rank of the Gauss–Newton term, and explain the class structure behind the outliers.
  • Compute Hessian–vector products, the top eigenvalue by power iteration or Lanczos, the trace by Hutchinson's estimator and the spectral density by stochastic Lanczos quadrature.
  • Explain how spectra inform learning rates, optimizer design, quantization, pruning and influence estimates, and what remains open.

Bulk and outliers

The Hessian H=∇2L(θ)H=\nabla^2\loss(\boldsymbol\theta) of a network with PP parameters has P2P^2 entries, but its spectrum can be estimated, and measurements on trained classifiers agree on its shape.

  • A bulk near zero. Sagun, Bottou & LeCun (2016) and Sagun, Evci, Güney, Dauphin & Bottou (2018) computed full spectra of small networks: almost all eigenvalues lie in a bulk concentrated around zero. Adding parameters with the data fixed scaled the bulk, while changing the data, for example adding clusters, moved only the large eigenvalues. For a ResNet-32 on CIFAR-10, Ghorbani, Krishnan & Xiao (2019) found more than 99.99% of the eigenvalues close to zero for most of training. Overparameterization shows up as flatness (Loss Landscapes derives at least P−nP-n exact zeros at an interpolating minimum).
  • A few outliers, about one per class. Isolated large eigenvalues sit far above the bulk, and Sagun et al. observed that their number often equals the number of classes CC. Papyan (2018) confirmed this spiked shape for networks with tens of millions of parameters.
  • Negative eigenvalues. At initialization large negative eigenvalues dominate; they vanish within less than 1% of training (Ghorbani et al., 2019). Small ones remain. On CIFAR-10 they end much smaller than the positive ones, but on ImageNet, where no network reaches zero loss, Ghorbani et al. found the negative eigenvalues' total magnitude comparable to the positive ones' at the end of training: the end point is not a minimum in the strict sense.

Batch normalization and gradient concentration. In networks without batch normalization, Ghorbani et al. saw the outliers appear rapidly and grow far from the bulk, with almost all of the gradient's energy in the outlier subspace, as Gur-Ari, Roberts & Dyer (2018) had observed. With batch normalization both effects nearly vanished. Their account of why outliers slow training is quadratic. A large λ1\lambda_1 caps the learning rate, so a direction with λi≪λ1\lambda_i\ll\lambda_1 contracts only by 1−2λi/λ11-2\lambda_i/\lambda_1 per step even at the largest stable step; yet such directions carry much of the loss (for a converged ResNet-32 without batch normalization, a small ball around zero held almost half of the eigenvalues' total magnitude), and the gradient barely points along them. PyHessian (Yao, Gholami, Keutzer & Mahoney, 2020), which measures top eigenvalues, traces and densities, found the picture less uniform: batch normalization does not always make the landscape smoother, especially in shallower networks.

Feature of the spectrumWhere it comes fromMain evidence
Bulk near zero, widening with PPredundant directions; the residual term (next step) supplies most of its massSagun et al. (2016, 2018); Papyan (2018)
About CC large outliersclass-mean structure of the Gauss–Newton termPapyan (2019, 2020); Fort & Ganguli (2019)
Large negative eigenvalues at initializationrandom networks are far from any minimumGhorbani et al. (2019): gone within 1% of training
Outliers far from the bulknetworks without batch normalizationGhorbani et al. (2019); nuanced by Yao et al. (2020)
The empirical picture for classifiers. Language models and other losses have been measured far less systematically.

The Gauss–Newton structure

DerivationTwo terms of the Hessian
  1. H=1n∑i=1nJi⊤(∇z2ℓi)Ji⏟G (Gauss–Newton)+1n∑i=1n∑k=1C∂ℓi∂zik ∇θ2zik⏟residual termH=\underbrace{\frac1n\sum_{i=1}^nJ_i^\top\big(\nabla^2_{\mathbf z}\ell_i\big)J_i}_{G\ \text{(Gauss–Newton)}}+\underbrace{\frac1n\sum_{i=1}^n\sum_{k=1}^C\frac{\partial\ell_i}{\partial z_{ik}}\,\nabla^2_{\boldsymbol\theta}z_{ik}}_{\text{residual term}}

    Write the loss as L(θ)=1n∑iℓ(zi,yi)\loss(\boldsymbol\theta)=\frac1n\sum_i\ell(\mathbf z_i,y_i) with outputs (logits) zi=f(xi;θ)∈RC\mathbf z_i=f(\mathbf x_i;\boldsymbol\theta)\in\R^C and Jacobians Ji=∂zi/∂θ∈RC×PJ_i=\partial\mathbf z_i/\partial\boldsymbol\theta\in\R^{C\times P}. Differentiating ∇L=1n∑iJi⊤∇zℓi\nabla\loss=\frac1n\sum_iJ_i^\top\nabla_{\mathbf z}\ell_i once more gives two terms:

  2. ∇z2ℓ=I,∂ℓ∂z=z−y⟹H=G=1n∑iJi⊤Ji  when every zi=yi\nabla^2_{\mathbf z}\ell=I,\qquad\frac{\partial\ell}{\partial\mathbf z}=\mathbf z-\mathbf y\qquad\Longrightarrow\qquad H=G=\frac1n\sum_iJ_i^\top J_i\ \ \text{when every }\mathbf z_i=\mathbf y_i

    For the squared loss ℓ=12∥z−y∥2\ell=\frac12\norm{\mathbf z-\mathbf y}^2 the output Hessian is the identity and the residual term is weighted by the residuals. At an interpolating minimum they vanish, and the Hessian is the Gauss–Newton matrix:

  3. ∇z2ℓ=diag⁡(p)−pp⊤,∂ℓ∂z=p−ey⟹rank⁡G≤min⁡(P,  n(C−1))\nabla^2_{\mathbf z}\ell=\diag(\mathbf p)-\mathbf p\mathbf p^\top,\qquad\frac{\partial\ell}{\partial\mathbf z}=\mathbf p-\mathbf e_y\qquad\Longrightarrow\qquad\rank G\le\min\big(P,\;n(C-1)\big)

    For softmax cross-entropy with probabilities pi\mathbf p_i, the output Hessian is diag⁡(p)−pp⊤\diag(\mathbf p)-\mathbf p\mathbf p^\top: positive semidefinite, with the all-ones vector in its kernel. So G⪰0G\succeq0, its rank is at most n(C−1)n(C-1), and every negative eigenvalue of HH must come from the residual term.

  4. 1−py→0:∥diag⁡(p)−pp⊤∥ and ∥p−ey∥ both =O(1−py)1-p_{y}\to0:\qquad\norm{\diag(\mathbf p)-\mathbf p\mathbf p^\top}\ \text{and}\ \norm{\mathbf p-\mathbf e_y}\ \text{both}\ =\order{1-p_{y}}

    Both cross-entropy terms carry a factor that vanishes as predictions become confident, diag⁡(p)−pp⊤\diag(\mathbf p)-\mathbf p\mathbf p^\top in one and p−ey\mathbf p-\mathbf e_y in the other, so neither dominates automatically. Measured on large networks, the outliers belong to GG, while the residual term, nearly symmetric about zero, carries most of the bulk; it was never negligible and late in training could exceed GG (Papyan, 2018).

Why about CC outliers? GG is a second moment of the per-example gradients of the logits, weighted by the softmax. Papyan (2019) showed that it is not a covariance, so the means of these gradients matter, and that the means have a two-way structure, by true class cc and by logit c′c'. Papyan (2020) then traced each feature of the spectrum to one piece of a class/cross-class decomposition of GG: the second moment of the global mean gives a single top outlier; the between-class covariance a cluster of C−1C-1 outliers below it; the between-cross-class covariance a "mini-bulk" of about C(C−1)C(C-1) smaller outliers; and the variation within each (class, logit) group the main bulk. Knocking out each piece removed its feature. Class-averaged gradients therefore approximate the top eigenvectors without any eigenanalysis, and Fort & Ganguli (2019) reproduced the CC high-curvature directions, and the confinement of gradients to them, with a simple model of gradients clustered by class.

Predict before you look

A deep linear network maps inputs in R100\R^{100} with full-rank covariance through hidden layers of widths 500500 and 500500 to K=10K=10 outputs, under the squared loss: P=305,000P=305{,}000 weights. Singh, Bachmann & Hofmann (2021) proved that, when every weight matrix has maximal rank (as at a typical random initialization), the rank of its Gauss–Newton matrix is q(r+K−q)q(r+K-q), where rr is the rank of the input covariance and qq the smallest of rr, the hidden widths and KK. What is the rank?

Show the answer

1000

Here q=min⁡(100,500,500,10)=10q=\min(100,500,500,10)=10, so the rank is 10×(100+10−10)=1,00010\times(100+10-10)=1{,}000: positive Gauss–Newton curvature in at most 0.33% of the 305,000305{,}000 directions. Widening the hidden layers adds parameters but only exact zeros to the spectrum. Singh et al. found that the same counts also estimate the numerical rank of ReLU and tanh networks well.

Spectra without the matrix

Everything starts from the Hessian–vector product. Since Hv=∇θ(∇L(θ)⊤v)H\mathbf v=\nabla_{\boldsymbol\theta}\big(\nabla\loss(\boldsymbol\theta)^\top\mathbf v\big), differentiating through the gradient computation once more gives HvH\mathbf v exactly, at a few times the cost of a gradient and without ever forming HH (Pearlmutter, 1994). Three estimators are built on it:

vt+1=Hvt∥Hvt∥,Tr⁡H=Ev[v⊤Hv]  (vj=±1 at random),ϕ(λ)≈1k∑j=1k∑i=1mωi(j) N(λ; ℓi(j),σ2)\mathbf v_{t+1}=\frac{H\mathbf v_t}{\norm{H\mathbf v_t}},\qquad\Tr H=\E_{\mathbf v}\big[\mathbf v^\top H\mathbf v\big]\ \ (v_j=\pm1\text{ at random}),\qquad\phi(\lambda)\approx\frac1k\sum_{j=1}^{k}\sum_{i=1}^{m}\omega^{(j)}_i\,\mathcal N\big(\lambda;\,\ell^{(j)}_i,\sigma^2\big)
Power iteration, the Hutchinson estimator of the trace, and the smoothed spectral density of stochastic Lanczos quadrature from kk random starts, with nodes ℓi\ell_i and weights ωi\omega_i defined below.
  • Power iteration converges to the eigenvalue of largest magnitude, at a rate set by its gap to the next one. Early in training that can be a large negative eigenvalue; iterating with H−sIH-sI for a shift ss, or using Lanczos, separates the two ends.
  • Lanczos. mm steps, one Hessian–vector product each, build an orthonormal basis of the Krylov space spanned by v,Hv,…,Hm−1v\mathbf v,H\mathbf v,\dots,H^{m-1}\mathbf v, in which HH becomes an m×mm\times m tridiagonal matrix TT. The extreme eigenvalues of TT converge quickly to those of HH, so a few dozen steps resolve the outliers.
  • Stochastic Lanczos quadrature. Diagonalize T=UΛU⊤T=U\Lambda U^\top. Its eigenvalues ℓi\ell_i and the squared first components ωi=U1i2\omega_i=U_{1i}^2 are the nodes and weights of a Gaussian quadrature for the spectral measure seen from the random start; replacing each node by a narrow Gaussian and averaging over kk starts estimates the whole density. Ghorbani et al. (2019) used m=90m=90 steps; the cost is mkmk full-batch Hessian–vector products, and for a ResNet-18 on ImageNet one draw took about half the time of training the model.
python
import torch

def top_eigenvalue(loss_fn, params, iters=100):
    """Eigenvalue of largest magnitude of the Hessian of loss_fn(), by power iteration."""
    v = [torch.randn_like(p) for p in params]
    for _ in range(iters):
        norm = torch.sqrt(sum((x * x).sum() for x in v))
        v = [x / norm for x in v]
        grads = torch.autograd.grad(loss_fn(), params, create_graph=True)
        Hv = torch.autograd.grad(grads, params, grad_outputs=v)   # H v by double backprop
        lam = sum((h * x).sum() for h, x in zip(Hv, v))            # Rayleigh quotient vᵀHv
        v = [h.detach() for h in Hv]
    return lam.item()

Hessian–vector products by double backpropagation: torch.autograd.grad with create_graph=True, then a second grad against the vector. Averaging v⊤Hv\mathbf v^\top H\mathbf v over random sign vectors with the same two lines gives Hutchinson's trace estimate. Libraries such as PyHessian package these estimators, including Lanczos and stochastic Lanczos quadrature.

Check your understanding

You want the spectral density of a network's Hessian by stochastic Lanczos quadrature with m=90m=90 Lanczos steps and k=10k=10 random starts. Roughly what does it cost?

  1. One eigendecomposition of the P×PP\times P Hessian
  2. About 900900 full-batch Hessian–vector products, plus the negligible cost of diagonalizing ten 90×9090\times90 matrices
  3. About 9090 gradient evaluations in total
  4. PP Hessian–vector products, one per column of HH
Show the answer

B. About 900900 full-batch Hessian–vector products, plus the negligible cost of diagonalizing ten 90×9090\times90 matrices

Each Lanczos step needs one Hessian–vector product, so the cost is mk=900mk=900 of them, each a few gradients' worth on the full training set. The tridiagonal matrices are tiny. Forming or diagonalizing HH itself, with P2P^2 entries, is out of the question for a large network.

What the spectrum is used for

  • Learning rates and stability. Gradient descent is stable only while λmax⁡<2/η\lambda_{\max}<2/\eta, and full-batch training drives the sharpness up to that threshold and holds it there (progressive sharpening and the edge of stability, in Loss Landscapes). Measuring λmax⁡\lambda_{\max} is the direct way to tell which regime a run is in.
  • Optimizer design. Outliers that soak up the gradient slow progress in the bulk, and normalization that suppresses them speeds training. Spectra that differ wildly between parameter blocks are one explanation of why Adam beats SGD on transformers (Why Adam Beats SGD on Transformers), and K-FAC and Shampoo are structured approximations of the Gauss–Newton or Fisher matrix (Curvature-Aware Optimizers: K-FAC & Shampoo).
  • Quantization. HAWQ (Dong, Yao, Gholami, Mahoney & Keutzer, 2019) ranks layers by the top eigenvalue of their Hessian blocks and keeps more bits in the sharper layers (Quantization in Depth).
  • Pruning. Optimal Brain Damage and Optimal Brain Surgeon estimate the loss increase from deleting a weight with the diagonal or the inverse of the Hessian (Pruning, Sparsity & Lottery Tickets).
  • Influence and attribution. Influence functions need inverse-Hessian–vector products, computed with the same machinery (Influence Functions & Data Attribution).
  • Flatness and generalization. λmax⁡\lambda_{\max} and Tr⁡H\Tr H are the usual sharpness measures; whether they predict generalization, given that rescaling symmetries change them freely, is debated (Sharpness-Aware Minimization).

Key takeaways

  • Trained classifiers have Hessian spectra with a bulk near zero (more than 99.99% of the eigenvalues in a ResNet-32), about CC outliers, and small negative eigenvalues. Large negative curvature disappears early in training; outliers grow far from the bulk without batch normalization and soak up the gradient.
  • H=G+residualH=G+\text{residual} with G=1n∑iJi⊤(∇z2ℓ)Ji⪰0G=\frac1n\sum_iJ_i^\top(\nabla^2_{\mathbf z}\ell)J_i\succeq0. For the squared loss H=GH=G at interpolation; for cross-entropy rank⁡G≤n(C−1)\rank G\le n(C-1), the outliers come from GG, and the residual term carries most of the bulk and all negative curvature.
  • The outliers trace back to class means of the logit gradients: one top outlier from the global mean, C−1C-1 from between-class covariance, a mini-bulk of about C(C−1)C(C-1) from cross-class covariance. In deep linear networks the Gauss–Newton rank is exactly q(r+K−q)q(r+K-q), so hidden layers wider than min⁡(r,K)\min(r,K) add only zero eigenvalues.
  • Hessian–vector products cost a few gradients; power iteration (largest magnitude), Lanczos (both ends), Hutchinson (trace) and stochastic Lanczos quadrature (density) build on them, and spectra guide learning rates, optimizers, quantization, pruning and influence estimates.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which description of the Hessian spectrum of a trained CC-class classifier is best supported by measurements?

  1. Eigenvalues spread evenly over a wide positive range, as for a well-conditioned quadratic
  2. A bulk concentrated near zero, a few outliers, roughly CC of them, and small negative eigenvalues
  3. Exactly CC nonzero eigenvalues and all others exactly zero
  4. Mostly large negative eigenvalues, since training ends at saddle points
Show the answer

B. A bulk concentrated near zero, a few outliers, roughly CC of them, and small negative eigenvalues

Sagun et al., Papyan and Ghorbani et al. all find a bulk near zero holding nearly all eigenvalues, about CC isolated outliers attributable to the class structure of the Gauss–Newton term, and small negative eigenvalues from the residual term.

Question 2

For softmax cross-entropy, why is the Gauss–Newton term G=1n∑iJi⊤(diag⁡(pi)−pipi⊤)JiG=\frac1n\sum_iJ_i^\top(\diag(\mathbf p_i)-\mathbf p_i\mathbf p_i^\top)J_i positive semidefinite with rank at most n(C−1)n(C-1)?

  1. Because cross-entropy is convex in the parameters
  2. Because the Jacobians JiJ_i are orthogonal
  3. Because GG equals the full Hessian at a minimum
  4. Because each diag⁡(p)−pp⊤\diag(\mathbf p)-\mathbf p\mathbf p^\top is the covariance of a one-hot draw from p\mathbf p, hence positive semidefinite, with the all-ones vector in its kernel, so it has rank at most C−1C-1
Show the answer

D. Because each diag⁡(p)−pp⊤\diag(\mathbf p)-\mathbf p\mathbf p^\top is the covariance of a one-hot draw from p\mathbf p, hence positive semidefinite, with the all-ones vector in its kernel, so it has rank at most C−1C-1

J⊤MJJ^\top MJ is positive semidefinite whenever MM is, and its rank is at most that of MM. Summing nn such terms of rank at most C−1C-1 gives rank at most n(C−1)n(C-1), and never more than PP. The negative eigenvalues of HH must come from the residual term.

Question 3

You run power iteration with Hessian–vector products on a freshly initialized network and obtain a large negative number. What is the most likely explanation?

  1. At initialization large negative eigenvalues dominate the spectrum, and power iteration returns the eigenvalue of largest magnitude
  2. The code is wrong, since a Hessian has no negative eigenvalues
  3. The network is at a local maximum
  4. The learning rate is too large
Show the answer

A. At initialization large negative eigenvalues dominate the spectrum, and power iteration returns the eigenvalue of largest magnitude

Ghorbani et al. found large negative eigenvalues at initialization that vanish early in training. Power iteration converges to the eigenvalue of largest magnitude; to get the largest positive one, iterate with H−sIH-sI for a shift ss or use Lanczos, which resolves both ends of the spectrum.

Question 4

According to Ghorbani et al. (2019), why do large outlier eigenvalues slow down training in networks without batch normalization?

  1. They make the loss nonconvex
  2. They force a small learning rate, under which the many small-curvature directions that hold much of the loss contract slowly, and the gradient's energy concentrates in the outlier directions instead of those
  3. They create local minima that trap SGD
  4. They make the gradients explode
Show the answer

B. They force a small learning rate, under which the many small-curvature directions that hold much of the loss contract slowly, and the gradient's energy concentrates in the outlier directions instead of those

Stability requires η<2/λ1\eta<2/\lambda_1, so a direction with eigenvalue λi\lambda_i contracts by at best 1−2λi/λ11-2\lambda_i/\lambda_1 per step. Those directions carry much of the loss, yet the gradient points mostly along the outliers. Batch normalization suppresses the outliers and the concentration, and training speeds up.

Further reading

  • L. Sagun, U. Evci, V. U. Güney, Y. Dauphin & L. Bottou, "Empirical analysis of the Hessian of over-parametrized neural networks," ICLR Workshop (2018).
  • B. Ghorbani, S. Krishnan & Y. Xiao, "An investigation into neural net optimization via Hessian eigenvalue density," ICML (2019).
  • V. Papyan, "Measurements of three-level hierarchical structure in the outliers in the spectrum of deepnet Hessians," ICML (2019).
  • V. Papyan, "Traces of class/cross-class structure pervade deep learning spectra," Journal of Machine Learning Research 21(252), 1–64 (2020).
  • Z. Yao, A. Gholami, K. Keutzer & M. W. Mahoney, "PyHessian: Neural networks through the lens of the Hessian," IEEE BigData (2020).