Simple Algorithm
Deep Learning · Emergence · 28 min

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 ϵ^=ρ∇L/∥∇L∥\hat{\boldsymbol\epsilon}=\rho\nabla\loss/\norm{\nabla\loss} 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 ρ22λmax⁡\frac{\rho^2}2\lambda_{\max}.
  • State what full-batch and stochastic SAM provably minimize near a manifold of minimizers, λmax⁡(H)\lambda_{\max}(H) versus Tr⁡H\Tr H, 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.

DerivationThe SAM update
  1. ϵ^=arg max⁡∥ϵ∥p≤ρϵ⊤g=ρ sign⁡(g)⊙∣g∣q−1∥g∥q q−1,max⁡∥ϵ∥p≤ρϵ⊤g=ρ∥g∥q\hat{\boldsymbol\epsilon}=\argmax_{\norm{\boldsymbol\epsilon}_p\le\rho}\boldsymbol\epsilon^\top\mathbf g=\rho\,\frac{\sign(\mathbf g)\odot\abs{\mathbf g}^{q-1}}{\norm{\mathbf g}_q^{\,q-1}},\qquad\max_{\norm{\boldsymbol\epsilon}_p\le\rho}\boldsymbol\epsilon^\top\mathbf g=\rho\norm{\mathbf g}_q

    Linearize inside the maximum, L(θ+ϵ)≈L(θ)+ϵ⊤g\loss(\boldsymbol\theta+\boldsymbol\epsilon)\approx\loss(\boldsymbol\theta)+\boldsymbol\epsilon^\top\mathbf g with g=∇L(θ)\mathbf g=\nabla\loss(\boldsymbol\theta). Maximizing a linear function over a pp-norm ball is a dual-norm problem, with 1/p+1/q=11/p+1/q=1:

  2. p=2:ϵ^=ρ ∇L(θ)∥∇L(θ)∥2p=2:\quad\hat{\boldsymbol\epsilon}=\rho\,\frac{\nabla\loss(\boldsymbol\theta)}{\norm{\nabla\loss(\boldsymbol\theta)}_2}

    For p=2p=2 the perturbation is the gradient rescaled to length ρ\rho; for p=∞p=\infty it is ρ sign⁡(g)\rho\,\sign(\mathbf g).

  3. ∇θL(θ+ϵ^)=(I+∂ϵ^∂θ) ⁣⊤∇L(θ+ϵ^),∂ϵ^∂θ=ρ∥g∥(I−g^g^⊤)H\nabla_{\boldsymbol\theta}\loss(\boldsymbol\theta+\hat{\boldsymbol\epsilon})=\Big(I+\frac{\partial\hat{\boldsymbol\epsilon}}{\partial\boldsymbol\theta}\Big)^{\!\top}\nabla\loss(\boldsymbol\theta+\hat{\boldsymbol\epsilon}),\qquad\frac{\partial\hat{\boldsymbol\epsilon}}{\partial\boldsymbol\theta}=\frac{\rho}{\norm{\mathbf g}}\big(I-\hat{\mathbf g}\hat{\mathbf g}^\top\big)H

    Differentiate L(θ+ϵ^(θ))\loss(\boldsymbol\theta+\hat{\boldsymbol\epsilon}(\boldsymbol\theta)) by the chain rule. The perturbation itself depends on θ\boldsymbol\theta, through the Hessian HH:

  4. ∇LSAM(θ)≈∇L(θ)∣θ+ϵ^\nabla\loss^{\text{SAM}}(\boldsymbol\theta)\approx\nabla\loss(\boldsymbol\theta)\big|_{\boldsymbol\theta+\hat{\boldsymbol\epsilon}}

    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:

python
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 ϵ^\hat{\boldsymbol\epsilon} from its own shard of the batch (next steps).

Predict before you look

SAM with ρ=0.05\rho=0.05 and p=2p=2 sees the mini-batch gradient g=(3,4)\mathbf g=(3,4) on a two-parameter model. What is the first coordinate of the perturbation ϵ^\hat{\boldsymbol\epsilon}?

Show the answer

0.03

ϵ^=ρ g/∥g∥=0.05⋅(3,4)/5=(0.03,0.04)\hat{\boldsymbol\epsilon}=\rho\,\mathbf g/\norm{\mathbf g}=0.05\cdot(3,4)/5=(0.03,0.04). Its length is exactly ρ\rho whatever the size of the gradient: SAM always probes the same distance, only the direction depends on g\mathbf g. With p=∞p=\infty the perturbation would be ρ sign⁡(g)=(0.05,0.05)\rho\,\sign(\mathbf g)=(0.05,0.05).

What SAM actually minimizes

DerivationTwo readings of the objective
  1. L(θ+ρg^)≈L(θ)+ρ∥∇L(θ)∥+ρ22 g^⊤Hg^\loss(\boldsymbol\theta+\rho\hat{\mathbf g})\approx\loss(\boldsymbol\theta)+\rho\norm{\nabla\loss(\boldsymbol\theta)}+\frac{\rho^2}{2}\,\hat{\mathbf g}^\top H\hat{\mathbf g}

    Expand the loss at the perturbed point to second order, with ϵ^=ρg^\hat{\boldsymbol\epsilon}=\rho\hat{\mathbf g} and g^=g/∥g∥\hat{\mathbf g}=\mathbf g/\norm{\mathbf g}:

  2. LSAM≈L+ρ∥∇L∥(∥∇L∥≫ρ λmax⁡)\loss^{\text{SAM}}\approx\loss+\rho\norm{\nabla\loss}\qquad(\norm{\nabla\loss}\gg\rho\,\lambda_{\max})

    Far from a minimum the middle term dominates: SAM behaves like gradient descent on the loss plus a penalty ρ∥∇L∥\rho\norm{\nabla\loss}, a cousin of the implicit regularizer η4∥∇L∥2\frac\eta4\norm{\nabla\loss}^2 of plain gradient descent (Gradient Noise, Batch Size & Scaling Rules).

  3. max⁡∥ϵ∥≤ρL(θ+ϵ)−L(θ)≈ρ22 λmax⁡(H)\max_{\norm{\boldsymbol\epsilon}\le\rho}\loss(\boldsymbol\theta+\boldsymbol\epsilon)-\loss(\boldsymbol\theta)\approx\frac{\rho^2}{2}\,\lambda_{\max}(H)

    At a minimum the gradient vanishes, and the exact inner maximum of the quadratic model is attained along the top eigenvector of HH: the objective then measures worst-direction sharpness.

  4. RρAsc=L(θ+ρg^)−L(θ) ≠ RρMax=max⁡∥ϵ∥≤ρL(θ+ϵ)−L(θ)R^{\text{Asc}}_\rho=\loss(\boldsymbol\theta+\rho\hat{\mathbf g})-\loss(\boldsymbol\theta)\ \ne\ R^{\text{Max}}_\rho=\max_{\norm{\boldsymbol\epsilon}\le\rho}\loss(\boldsymbol\theta+\boldsymbol\epsilon)-\loss(\boldsymbol\theta)

    But the algorithm does not compute that maximum. Its ϵ^\hat{\boldsymbol\epsilon} follows the gradient, so taken literally it penalizes the ascent-direction sharpness ρ22g^⊤Hg^\frac{\rho^2}2\hat{\mathbf g}^\top H\hat{\mathbf g}, 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.

Check your understanding

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?

  1. Both minimize the trace of the Hessian
  2. Full-batch SAM minimizes the smallest nonzero Hessian eigenvalue, as its ascent-direction objective suggests; 1-SAM the largest
  3. Neither: near the manifold the perturbation vanishes and SAM reduces to gradient descent
  4. 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 λ1(∇2L)\lambda_1(\nabla^2\loss): worst-direction sharpness. With one example per perturbation the directions vary from step to step and the effect averages into Tr⁡∇2L\Tr\nabla^2\loss. 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 mm examples, and the resulting gradients are averaged. Foret et al. found that smaller mm tends to generalize better, and that m-sharpness with mm 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 ∥Tθ−1ϵ∥≤ρ\norm{T_{\boldsymbol\theta}^{-1}\boldsymbol\epsilon}\le\rho with a diagonal normalization TθT_{\boldsymbol\theta} built from the magnitudes of the weights: elementwise Tθ=diag⁡(∣θ1∣,…,∣θk∣)T_{\boldsymbol\theta}=\diag(\abs{\theta_1},\dots,\abs{\theta_k}), 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

FindingWhat it showsCaveat
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 stepBaselines 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 biasesStrong 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
SAM's gains are robust; the explanation for them is not. SAM may help through its gradient-norm penalty, its per-example perturbations or other implicit biases, rather than through flatness itself.

Key takeaways

  • SAM minimizes max⁡∥ϵ∥≤ρL(θ+ϵ)\max_{\norm{\boldsymbol\epsilon}\le\rho}\loss(\boldsymbol\theta+\boldsymbol\epsilon). Linearizing gives ϵ^=ρ g/∥g∥\hat{\boldsymbol\epsilon}=\rho\,\mathbf g/\norm{\mathbf g} (dual-norm form for other pp), and dropping the Hessian term gives the update: the gradient at θ+ϵ^\boldsymbol\theta+\hat{\boldsymbol\epsilon}, applied at θ\boldsymbol\theta, for two passes per step.
  • To second order the objective is L+ρ∥∇L∥+ρ22g^⊤Hg^\loss+\rho\norm{\nabla\loss}+\frac{\rho^2}2\hat{\mathbf g}^\top H\hat{\mathbf g}; at a minimum the exact inner maximum is ρ22λmax⁡(H)\frac{\rho^2}2\lambda_{\max}(H). Near a manifold of minimizers, full-batch SAM provably minimizes λmax⁡\lambda_{\max} 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.

Question 1

Which describes one SAM step with p=2p=2?

  1. Add Gaussian noise of scale ρ\rho to the parameters, compute the gradient there, and step
  2. Compute g\mathbf g, move to θ+ρ g/∥g∥\boldsymbol\theta+\rho\,\mathbf g/\norm{\mathbf g}, compute the gradient there, and apply it at θ\boldsymbol\theta, ignoring how ϵ^\hat{\boldsymbol\epsilon} depends on θ\boldsymbol\theta
  3. Compute g\mathbf g, move to θ−ρ g/∥g∥\boldsymbol\theta-\rho\,\mathbf g/\norm{\mathbf g}, and take the step from there
  4. Compute the Hessian's top eigenvector and step along it
Show the answer

B. Compute g\mathbf g, move to θ+ρ g/∥g∥\boldsymbol\theta+\rho\,\mathbf g/\norm{\mathbf g}, compute the gradient there, and apply it at θ\boldsymbol\theta, ignoring how ϵ^\hat{\boldsymbol\epsilon} depends on θ\boldsymbol\theta

The perturbation climbs uphill to the (linearized) worst point of the ρ\rho-ball; the descent direction is the gradient at that point, applied to the unperturbed parameters. The Jacobian of ϵ^\hat{\boldsymbol\epsilon}, which contains the Hessian, is dropped.

Question 2

At a minimum of a quadratic loss with Hessian HH, what does the exact SAM sharpness max⁡∥ϵ∥2≤ρL(θ+ϵ)−L(θ)\max_{\norm{\boldsymbol\epsilon}_2\le\rho}\loss(\boldsymbol\theta+\boldsymbol\epsilon)-\loss(\boldsymbol\theta) equal?

  1. ρ22Tr⁡H\frac{\rho^2}{2}\Tr H
  2. ρ∥∇L∥\rho\norm{\nabla\loss}, which is zero at a minimum
  3. ρ22λmax⁡(H)\frac{\rho^2}{2}\lambda_{\max}(H)
  4. ρ22λmin⁡(H)\frac{\rho^2}{2}\lambda_{\min}(H)
Show the answer

C. ρ22λmax⁡(H)\frac{\rho^2}{2}\lambda_{\max}(H)

With zero gradient, the excess loss is 12ϵ⊤Hϵ\frac12\boldsymbol\epsilon^\top H\boldsymbol\epsilon, maximized over the ball by the top eigenvector: ρ22λmax⁡\frac{\rho^2}2\lambda_{\max}. The trace appears for averages over random directions, and for stochastic SAM's implicit bias.

Question 3

What did Andriushchenko et al. (2023) find about sharpness and generalization in modern settings?

  1. Adaptive sharpness correlates strongly and positively with test error in every setting
  2. 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
  3. Sharpness is meaningless because it can always be made zero by rescaling
  4. 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).