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 of a network with parameters has 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 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 . 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 caps the learning rate, so a direction with contracts only by 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 spectrum | Where it comes from | Main evidence |
|---|---|---|
| Bulk near zero, widening with | redundant directions; the residual term (next step) supplies most of its mass | Sagun et al. (2016, 2018); Papyan (2018) |
| About large outliers | class-mean structure of the Gauss–Newton term | Papyan (2019, 2020); Fort & Ganguli (2019) |
| Large negative eigenvalues at initialization | random networks are far from any minimum | Ghorbani et al. (2019): gone within 1% of training |
| Outliers far from the bulk | networks without batch normalization | Ghorbani et al. (2019); nuanced by Yao et al. (2020) |
The Gauss–Newton structure
Write the loss as with outputs (logits) and Jacobians . Differentiating once more gives two terms:
For the squared loss 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:
For softmax cross-entropy with probabilities , the output Hessian is : positive semidefinite, with the all-ones vector in its kernel. So , its rank is at most , and every negative eigenvalue of must come from the residual term.
Both cross-entropy terms carry a factor that vanishes as predictions become confident, in one and in the other, so neither dominates automatically. Measured on large networks, the outliers belong to , while the residual term, nearly symmetric about zero, carries most of the bulk; it was never negligible and late in training could exceed (Papyan, 2018).
Why about outliers? 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 and by logit . Papyan (2020) then traced each feature of the spectrum to one piece of a class/cross-class decomposition of : the second moment of the global mean gives a single top outlier; the between-class covariance a cluster of outliers below it; the between-cross-class covariance a "mini-bulk" of about 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 high-curvature directions, and the confinement of gradients to them, with a simple model of gradients clustered by class.
A deep linear network maps inputs in with full-rank covariance through hidden layers of widths and to outputs, under the squared loss: 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 , where is the rank of the input covariance and the smallest of , the hidden widths and . What is the rank?
Show the answer
1000
Here , so the rank is : positive Gauss–Newton curvature in at most 0.33% of the 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 , differentiating through the gradient computation once more gives exactly, at a few times the cost of a gradient and without ever forming (Pearlmutter, 1994). Three estimators are built on it:
- 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 for a shift , or using Lanczos, separates the two ends.
- Lanczos. steps, one Hessian–vector product each, build an orthonormal basis of the Krylov space spanned by , in which becomes an tridiagonal matrix . The extreme eigenvalues of converge quickly to those of , so a few dozen steps resolve the outliers.
- Stochastic Lanczos quadrature. Diagonalize . Its eigenvalues and the squared first components 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 starts estimates the whole density. Ghorbani et al. (2019) used steps; the cost is full-batch Hessian–vector products, and for a ResNet-18 on ImageNet one draw took about half the time of training the model.
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 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.
You want the spectral density of a network's Hessian by stochastic Lanczos quadrature with Lanczos steps and random starts. Roughly what does it cost?
- One eigendecomposition of the Hessian
- About full-batch Hessian–vector products, plus the negligible cost of diagonalizing ten matrices
- About gradient evaluations in total
- Hessian–vector products, one per column of
Show the answer
B. About full-batch Hessian–vector products, plus the negligible cost of diagonalizing ten matrices
Each Lanczos step needs one Hessian–vector product, so the cost is of them, each a few gradients' worth on the full training set. The tridiagonal matrices are tiny. Forming or diagonalizing itself, with 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 , 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 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. and 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 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.
- with . For the squared loss at interpolation; for cross-entropy , the outliers come from , 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, from between-class covariance, a mini-bulk of about from cross-class covariance. In deep linear networks the Gauss–Newton rank is exactly , so hidden layers wider than 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.
Which description of the Hessian spectrum of a trained -class classifier is best supported by measurements?
- Eigenvalues spread evenly over a wide positive range, as for a well-conditioned quadratic
- A bulk concentrated near zero, a few outliers, roughly of them, and small negative eigenvalues
- Exactly nonzero eigenvalues and all others exactly zero
- Mostly large negative eigenvalues, since training ends at saddle points
Show the answer
B. A bulk concentrated near zero, a few outliers, roughly 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 isolated outliers attributable to the class structure of the Gauss–Newton term, and small negative eigenvalues from the residual term.
For softmax cross-entropy, why is the Gauss–Newton term positive semidefinite with rank at most ?
- Because cross-entropy is convex in the parameters
- Because the Jacobians are orthogonal
- Because equals the full Hessian at a minimum
- Because each is the covariance of a one-hot draw from , hence positive semidefinite, with the all-ones vector in its kernel, so it has rank at most
Show the answer
D. Because each is the covariance of a one-hot draw from , hence positive semidefinite, with the all-ones vector in its kernel, so it has rank at most
is positive semidefinite whenever is, and its rank is at most that of . Summing such terms of rank at most gives rank at most , and never more than . The negative eigenvalues of must come from the residual term.
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?
- At initialization large negative eigenvalues dominate the spectrum, and power iteration returns the eigenvalue of largest magnitude
- The code is wrong, since a Hessian has no negative eigenvalues
- The network is at a local maximum
- 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 for a shift or use Lanczos, which resolves both ends of the spectrum.
According to Ghorbani et al. (2019), why do large outlier eigenvalues slow down training in networks without batch normalization?
- They make the loss nonconvex
- 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
- They create local minima that trap SGD
- 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 , so a direction with eigenvalue contracts by at best 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).