Sharpness-Aware Minimization
Optimizing for flat minima: the SAM update, what it regularizes and the flatness debate.
Do flat minima generalize better than sharp ones? Sharpness-aware minimization (SAM) stops asking and optimizes for flatness directly: before each step it climbs a short distance uphill, then descends with the gradient it finds there. This two-pass update often improves generalization, dramatically so for vision transformers, at twice the cost per step. What it actually minimizes turns out to be subtle, and whether flatness is why it helps is still debated.
What you’ll learn
- Formulate SAM's min–max objective, derive its first-order perturbation and its dual-norm generalization, and identify the Hessian term the update drops.
- Expand the SAM objective to second order and relate it to a gradient-norm penalty and to the worst-direction sharpness .
- State what full-batch and stochastic SAM provably minimize near a manifold of minimizers, versus , and explain m-sharpness and adaptive (scale-invariant) sharpness.
- Weigh the evidence: gains for vision transformers and under label noise, against the weak correlation between sharpness and generalization in modern settings.
From flat minima to a min–max objective
Hochreiter & Schmidhuber (1997) argued that flat minima, wide regions where the loss stays low, need fewer bits to specify and should therefore generalize better. Keskar et al. (2017) observed that large-batch training tends to end in sharper minima and to generalize worse, a gap later attributed largely to tuning and number of steps. Two facts complicate the story. Sharpness is not invariant to reparameterization: rescaling consecutive ReLU layers in opposite directions changes the Hessian arbitrarily without changing the function (Dinh et al., 2017). Yet in a study of over 40 complexity measures across more than 10,000 convolutional networks, sharpness-based measures correlated best with generalization (Jiang et al., 2020).
Sharpness-aware minimization turns the hypothesis into an objective: make the loss small everywhere in a neighborhood of the parameters.
Linearize inside the maximum, with . Maximizing a linear function over a -norm ball is a dual-norm problem, with :
For the perturbation is the gradient rescaled to length ; for it is .
Differentiate by the chain rule. The perturbation itself depends on , through the Hessian :
SAM drops the second term, which would cost Hessian–vector products; Foret et al. report that keeping it even hurt in an initial experiment. What remains is the gradient taken at the perturbed point, fed to any base optimizer:
import torch
def sam_step(model, loss_fn, x, y, base_opt, rho=0.05):
loss_fn(model(x), y).backward() # pass 1: gradient at θ
params = [p for p in model.parameters() if p.grad is not None]
grad_norm = torch.stack([p.grad.norm() for p in params]).norm()
eps = []
with torch.no_grad():
for p in params:
e = rho * p.grad / (grad_norm + 1e-12)
p.add_(e) # climb to θ + ε̂
eps.append(e)
base_opt.zero_grad()
loss_fn(model(x), y).backward() # pass 2: gradient at θ + ε̂
with torch.no_grad():
for p, e in zip(params, eps):
p.sub_(e) # return to θ
base_opt.step() # descend with the SAM gradient
base_opt.zero_grad()Two forward–backward passes per step, so SAM costs about twice as much as its base optimizer; Foret et al. gave their baselines twice as many epochs for a fair comparison. On several devices, each computes from its own shard of the batch (next steps).
SAM with and sees the mini-batch gradient on a two-parameter model. What is the first coordinate of the perturbation ?
Show the answer
0.03
. Its length is exactly whatever the size of the gradient: SAM always probes the same distance, only the direction depends on . With the perturbation would be .
What SAM actually minimizes
Expand the loss at the perturbed point to second order, with and :
Far from a minimum the middle term dominates: SAM behaves like gradient descent on the loss plus a penalty , a cousin of the implicit regularizer of plain gradient descent (Gradient Noise, Batch Size & Scaling Rules).
At a minimum the gradient vanishes, and the exact inner maximum of the quadratic model is attained along the top eigenvector of : the objective then measures worst-direction sharpness.
But the algorithm does not compute that maximum. Its follows the gradient, so taken literally it penalizes the ascent-direction sharpness , whose explicit bias near a minimum points toward the smallest nonzero eigenvalue. Both approximations in SAM's derivation (linearizing the maximum, dropping the Hessian term) are individually misleading, so what the update really does has to be analyzed directly.
A complementary picture comes from Bartlett, Long & Bousquet (2023). On a convex quadratic, SAM does not converge to the minimum: for most initializations it settles into a cycle that bounces between the two sides of the valley along the direction of largest curvature. On a non-quadratic loss those oscillations act, through third derivatives, like gradient descent with a small step on the spectral norm of the Hessian, so SAM drifts toward wider minima. Both analyses agree that SAM's flatness-seeking is a slow, second-order effect layered on top of ordinary descent.
Near a manifold of minimizers, under the assumptions of Wen, Ma & Li, which quantities do full-batch SAM and stochastic SAM with batch size 1 implicitly minimize?
- Both minimize the trace of the Hessian
- Full-batch SAM minimizes the smallest nonzero Hessian eigenvalue, as its ascent-direction objective suggests; 1-SAM the largest
- Neither: near the manifold the perturbation vanishes and SAM reduces to gradient descent
- Full-batch SAM minimizes the largest Hessian eigenvalue; 1-SAM minimizes the trace of the Hessian
Show the answer
D. Full-batch SAM minimizes the largest Hessian eigenvalue; 1-SAM minimizes the trace of the Hessian
Full-batch SAM's normalized gradient aligns with the top eigenvector, so it follows a flow on : worst-direction sharpness. With one example per perturbation the directions vary from step to step and the effect averages into . Batch size changes which notion of sharpness SAM regularizes.
m-sharpness, scale invariance and cost
m-sharpness. With data parallelism, each device computes its own perturbation from its shard of examples, and the resulting gradients are averaged. Foret et al. found that smaller tends to generalize better, and that m-sharpness with smaller than the training set correlates better with the generalization gap than full-set sharpness. Andriushchenko & Flammarion (2022) found the same amplification and showed, for diagonal linear networks, that SAM's implicit bias selects solutions that generalize better than gradient descent's for a class of problems; they also proved convergence of SAM with stochastic gradients on nonconvex objectives. The batch-size-1 result above gives one mechanism: per-example perturbations regularize the trace of the Hessian rather than its top eigenvalue.
Scale invariance. Ordinary sharpness changes under the rescalings of Dinh et al. ASAM (Kwon, Kim, Park & Choi, 2021) measures the perturbation relative to the parameters' own scale, maximizing over with a diagonal normalization built from the magnitudes of the weights: elementwise , or each filter's norm for the weights of that filter. The resulting adaptive sharpness is invariant to those rescalings and comes with its own generalization bound.
Cost. Two passes per step double the compute. Variants reuse the ascent direction across steps or perturb only some parameters to cut the overhead, at some loss of fidelity to the original update.
Evidence and debate
| Finding | What it shows | Caveat |
|---|---|---|
| SAM improved accuracy across CIFAR, ImageNet and fine-tuning benchmarks, and gave robustness to label noise on par with methods built for noisy labels (Foret et al., 2021) | A consistent practical gain at twice the cost per step | Baselines got twice the epochs; gains vary with architecture and augmentation |
| ViT-B/16 and Mixer-B/16 trained from scratch on ImageNet without strong augmentation converge to extremely sharp minima; SAM adds 5.3 and 11.0 points of top-1 accuracy (Chen, Hsieh & Gong, 2022) | Largest gains where models lack convolutional inductive biases | Strong augmentation or large-scale pretraining shrink the gap |
| Across ImageNet and CIFAR-10 training, CLIP and BERT fine-tuning, even adaptive sharpness correlates weakly with generalization, tracks training settings such as the learning rate, and sometimes correlates negatively with out-of-distribution error (Andriushchenko et al., 2023) | Flatness, as measured, is not a reliable predictor of generalization | "The right sharpness measure is highly data-dependent," in the authors' words |
Key takeaways
- SAM minimizes . Linearizing gives (dual-norm form for other ), and dropping the Hessian term gives the update: the gradient at , applied at , for two passes per step.
- To second order the objective is ; at a minimum the exact inner maximum is . Near a manifold of minimizers, full-batch SAM provably minimizes and batch-size-1 SAM the trace of the Hessian.
- Per-shard perturbations (m-sharpness) amplify SAM's benefit, and adaptive sharpness (ASAM) fixes scale invariance.
- SAM's gains are real, largest for vision transformers trained from scratch and under label noise, but sharpness itself correlates weakly with generalization in modern settings: why SAM helps is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which describes one SAM step with ?
- Add Gaussian noise of scale to the parameters, compute the gradient there, and step
- Compute , move to , compute the gradient there, and apply it at , ignoring how depends on
- Compute , move to , and take the step from there
- Compute the Hessian's top eigenvector and step along it
Show the answer
B. Compute , move to , compute the gradient there, and apply it at , ignoring how depends on
The perturbation climbs uphill to the (linearized) worst point of the -ball; the descent direction is the gradient at that point, applied to the unperturbed parameters. The Jacobian of , which contains the Hessian, is dropped.
At a minimum of a quadratic loss with Hessian , what does the exact SAM sharpness equal?
- , which is zero at a minimum
Show the answer
C.
With zero gradient, the excess loss is , maximized over the ball by the top eigenvector: . The trace appears for averages over random directions, and for stochastic SAM's implicit bias.
What did Andriushchenko et al. (2023) find about sharpness and generalization in modern settings?
- Adaptive sharpness correlates strongly and positively with test error in every setting
- Even adaptive sharpness correlates only weakly with generalization, tracks training choices such as the learning rate, and can correlate negatively with out-of-distribution error
- Sharpness is meaningless because it can always be made zero by rescaling
- SAM does not improve accuracy on any modern architecture
Show the answer
B. Even adaptive sharpness correlates only weakly with generalization, tracks training choices such as the learning rate, and can correlate negatively with out-of-distribution error
Their experiments on ImageNet and CIFAR-10 training and on CLIP and BERT fine-tuning found weak correlations, which flip sign in some out-of-distribution evaluations. That challenges flatness as the explanation of generalization; it does not contradict SAM's measured gains.
Further reading
- P. Foret, A. Kleiner, H. Mobahi & B. Neyshabur, "Sharpness-aware minimization for efficiently improving generalization," ICLR (2021).
- K. Wen, T. Ma & Z. Li, "How sharpness-aware minimization minimizes sharpness?," ICLR (2023); preprint arXiv:2211.05729.
- M. Andriushchenko & N. Flammarion, "Towards understanding sharpness-aware minimization," ICML (2022).
- X. Chen, C.-J. Hsieh & B. Gong, "When vision transformers outperform ResNets without pre-training or strong data augmentations," ICLR (2022).
- M. Andriushchenko, F. Croce, M. Müller, M. Hein & N. Flammarion, "A modern look at the relationship between sharpness and generalization," ICML (2023).