Optimization · Generalization

SAM optimizer: Sharpness-Aware Minimization for Efficiently Improving Generalization

Take each gradient at the highest-loss point near the current weights, and training settles where the loss is flat.

SAM adds one move to every training step. It shifts the weights a short distance ρ in the direction that raises the loss fastest, computes the gradient at that shifted point, and applies that gradient to the original weights. A step costs two gradient computations instead of one.

Explaining the paperSharpness-Aware Minimization for Efficiently Improving GeneralizationForet, Kleiner, Mobahi, Neyshabur · ICLR 2021 · arXiv:2010.01412 ↗

A Google Research paper from October 2020 that turned the idea that flat minima generalize into a change of four lines to SGD, with one hyperparameter and a default of ρ = 0.05.

Pierre Foret, Ariel Kleiner, Hossein Mobahi and Behnam Neyshabur posted the paper in October 2020, and it appeared at ICLR 2021. Its starting point is a fact about modern networks: they can fit their training set almost perfectly, even when the labels are random (the result behind Rethinking Generalization), so a low training loss says little about test error. A large network has many weight settings that all reach near-zero training loss and differ in how well they do on new data. SAM chooses among them with a geometric test: prefer weights whose whole neighborhood has low loss.

The name is unrelated to Segment Anything, the 2023 segmentation model also called SAM. This page covers the optimizer in this order:

  1. what sharp and flat minima are, and why flatness is a plausible proxy for generalization;
  2. the SAM objective, the worst training loss within a radius ρ of the weights;
  3. the first-order approximation that turns it into two gradient computations per step;
  4. m-sharpness, the per-device version the experiments actually ran;
  5. the results, and how much of them the paper's theory accounts for.

Sharp and flat minima

Write the model's weights as one long vector ww with dd entries, and its training loss as the average per-example loss over the nn training examples:

LS(w)=1n∑i=1nl(w,xi,yi)L_S(w) = \frac{1}{n}\sum_{i=1}^{n} l(w, x_i, y_i)

What we care about is the population loss LD(w)L_{\mathcal D}(w), the expected loss on a fresh example from the same distribution. Training can only see LSL_S. For a deep network LSL_S has many minima of nearly equal depth, and they can differ a lot in LDL_{\mathcal D}.

A minimum is sharp when the training loss rises quickly as the weights move away from it, and flat when the loss stays low over a wide neighborhood. Curvature is the formal version. The Hessian is the d×dd \times d matrix of second derivatives of the loss; its largest eigenvalue λmax⁡\lambda_{\max} is the curvature along the steepest direction. Near a minimum the loss grows like 12λmax⁡t2\tfrac12 \lambda_{\max} t^2 along that direction for a step of length tt, so a minimum with λmax⁡=24\lambda_{\max} = 24 rises 24 times faster than one with λmax⁡=1\lambda_{\max} = 1 (those are the two values the paper measures later, without and with SAM).

There are two standard arguments that flatness should help. The first treats the test loss as the training loss displaced a little, because a finite sample of data does not pin down the landscape exactly. Under a small displacement the bottom of a sharp minimum lands on a steep wall, while a flat minimum is still near its floor. The second, from Hochreiter and Schmidhuber (1997), counts bits: a flat minimum tolerates imprecise weights, so the weights can be written down with fewer bits, which is a description-length notion of a simpler model.

An engineering analogy fits the first argument. A part whose function survives a wide manufacturing tolerance is more likely to work under conditions nobody tested; a part that works only at exactly its nominal dimensions is fragile. The analogy breaks on how distance is measured. A tolerance in millimeters means the same thing for every part, but distance in weight space depends on how the network is parameterized: Dinh et al. (2017) showed that a ReLU network can be rescaled to make any minimum look arbitrarily sharp without changing the function it computes. The theory section comes back to this.

The empirical case predates SAM. Keskar et al. (2016) found that training with very large batches converges to sharper minima and generalizes worse than small-batch training. Jiang et al. (2019) trained more than 10,000 convolutional networks and compared over 40 measures that might predict their generalization; the SAM paper summarizes the finding as a sharpness-based measure having the highest correlation with generalization. The SAM paper's related-work section describes the sharpness measures proposed before it as hard to compute and to differentiate through; SAM needs one extra gradient per step.

Figure 1 is a one-dimensional cartoon of the first argument. The teal curve is a training loss with a narrow pit at w=−1w = -1 and a wide, slightly shallower basin near w=0.9w = 0.9. The dashed amber curve is the same loss shifted right, standing in for the test loss. At ρ=0\rho = 0 the training minimum is the pit, with training loss 0.16 and test loss 0.67 at the default shift of 0.15. The violet curve is the SAM objective of the next section, the highest training loss within distance ρ. Its minimum moves to the wide basin once ρ passes about 0.06, where training loss is 0.27 and test loss 0.30.

Figure 1 · the objective SAM minimizes
0.25
0.15
Training loss, a shifted copy standing in for the test loss, and the SAM objective max|ε|≤ρ L(w+ε); the shaded band is the ρ-window around its minimum. Drag ρ to 0 and both pick the pit; drag it to 1.5 and the window is wider than the basin, so the minimum drifts uphill. The button adds the one-step estimate SAM computes in practice.

The SAM minimum accepts a higher training loss (0.27 instead of 0.16) in exchange for a neighborhood where no point is much worse. With the shift at 0 the test curve is the training curve and the pit wins on test loss too, 0.16 against 0.27; from a shift of 0.06 upward the wide basin wins, and at 0.15 the gap is 0.67 against 0.30. At the far end of the ρ slider the window covers most of the basin, and the objective's minimum moves to w≈0.3w \approx 0.3, where training loss is 0.57, higher than at either minimum.

The SAM objective

The paper motivates its objective with a generalization bound, stated informally as Theorem 1. For any ρ>0\rho > 0, with high probability over the draw of the training set,

LD(w)≤max⁡∥ϵ∥2≤ρLS(w+ϵ)+h ⁣(∥w∥22/ρ2)L_{\mathcal D}(w) \le \max_{\|\epsilon\|_2 \le \rho} L_S(w + \epsilon) + h\!\left(\|w\|_2^2/\rho^2\right)LD(w)≤max⁡∥ϵ∥2≤ρLS(w+ϵ)+h ⁣(∥w∥22/ρ2)\begin{aligned} L_{\mathcal D}(w) &\le \max_{\|\epsilon\|_2 \le \rho} L_S(w + \epsilon) \\ &\quad + h\!\left(\|w\|_2^2/\rho^2\right) \end{aligned}

where hh is some strictly increasing function and some technical conditions hold. In words: the test loss is at most the worst training loss anywhere within Euclidean distance ρ of ww, plus a penalty that grows with the size of the weights. Adding and subtracting LS(w)L_S(w) splits the right-hand side into three parts:

[max⁡∥ϵ∥2≤ρLS(w+ϵ)−LS(w)]+LS(w)+h ⁣(∥w∥22/ρ2)\Big[\max_{\|\epsilon\|_2 \le \rho} L_S(w+\epsilon) - L_S(w)\Big] + L_S(w) + h\!\left(\|w\|_2^2/\rho^2\right)[max⁡∥ϵ∥2≤ρLS(w+ϵ)−LS(w)]+LS(w)+h ⁣(∥w∥22/ρ2)\begin{aligned} &\Big[\max_{\|\epsilon\|_2 \le \rho} L_S(w+\epsilon) - L_S(w)\Big] \\ &\quad + L_S(w) + h\!\left(\|w\|_2^2/\rho^2\right) \end{aligned}

The bracket is the sharpness at ww: how much the training loss can rise if the weights move by at most ρ. It is the quantity Figure 1 shades. The second term is the ordinary training loss and the third depends only on ∥w∥\|w\|. Since the exact form of hh comes from details of the proof, the authors replace it with the standard L2 penalty λ∥w∥22\lambda\|w\|_2^2 (weight decay) and define the SAM problem:

min⁡w  LSSAM(w)+λ∥w∥22,LSSAM(w)≜max⁡∥ϵ∥p≤ρLS(w+ϵ)\min_{w}\; L_S^{SAM}(w) + \lambda\|w\|_2^2, \qquad L_S^{SAM}(w) \triangleq \max_{\|\epsilon\|_p \le \rho} L_S(w + \epsilon)min⁡w  LSSAM(w)+λ∥w∥22,LSSAM(w)≜max⁡∥ϵ∥p≤ρLS(w+ϵ)\begin{gathered} \min_{w}\; L_S^{SAM}(w) + \lambda\|w\|_2^2, \\ L_S^{SAM}(w) \triangleq \max_{\|\epsilon\|_p \le \rho} L_S(w + \epsilon) \end{gathered}
(1)

(1) is a min-max problem with the shape of adversarial training, except that the adversary perturbs the weights instead of the input image. It has two hyperparameters. ρ ≥ 0 is the radius of the neighborhood, measured in the same units as the weights. The norm p∈[1,∞]p \in [1, \infty] sets its shape: p=2p = 2 is a round ball, p=∞p = \infty a box in which every weight may move by up to ρ. The paper allows any pp but its experiments found p=2p = 2 best, so in practice SAM has one hyperparameter. With a Euclidean ball, ρ = 0.05 is small compared to a network's weights. ResNet-50 has about 25.6 million weights, and a length-0.05 vector spread evenly over them would move each weight by about 10−510^{-5}. SAM's perturbation instead points along the gradient, as the next section shows, so most of its length goes to the weights with the largest gradients.

An obvious alternative is to penalize curvature directly, for example with a term proportional to λmax⁡\lambda_{\max}. That needs Hessian information at every step. For ResNet-50 the Hessian has (2.56×107)2≈6.6×1014(2.56\times 10^{7})^2 \approx 6.6\times 10^{14} entries, and even estimating its top eigenvalue takes an iterative method with several Hessian-vector products, each roughly the cost of an extra backward pass. Earlier flatness-seeking methods such as Entropy-SGD (Chaudhari et al., 2016) ran an inner sampling loop per step. The maximum in (1) can be approximated with one extra gradient.

How SAM works: one update, two gradients

The inner maximum in (1) is a non-convex maximization over all dd weights at once. SAM solves an easier problem in its place. Inside a small ball the loss is close to its first-order Taylor expansion, a linear function of ϵ\epsilon:

ϵ∗(w)≈arg⁡max⁡∥ϵ∥p≤ρLS(w)+ϵ⊤∇wLS(w)=arg⁡max⁡∥ϵ∥p≤ρϵ⊤∇wLS(w)\epsilon^*(w) \approx \arg\max_{\|\epsilon\|_p \le \rho} L_S(w) + \epsilon^{\top}\nabla_w L_S(w) = \arg\max_{\|\epsilon\|_p \le \rho} \epsilon^{\top}\nabla_w L_S(w)ϵ∗(w)≈arg⁡max⁡∥ϵ∥p≤ρLS(w)+ϵ⊤∇wLS(w)=arg⁡max⁡∥ϵ∥p≤ρϵ⊤∇wLS(w)\begin{aligned} \epsilon^*(w) &\approx \arg\max_{\|\epsilon\|_p \le \rho} L_S(w) + \epsilon^{\top}\nabla_w L_S(w) \\ &= \arg\max_{\|\epsilon\|_p \le \rho} \epsilon^{\top}\nabla_w L_S(w) \end{aligned}

LS(w)L_S(w) does not depend on ϵ\epsilon, so it drops out of the argmax. What remains is to find the vector in the ρ-ball with the largest dot product with the gradient g=∇wLS(w)g = \nabla_w L_S(w). Hölder's inequality bounds that dot product: ϵ⊤g≤∥ϵ∥p∥g∥q\epsilon^\top g \le \|\epsilon\|_p \|g\|_q, where qq is the dual exponent, 1/p+1/q=11/p + 1/q = 1. The bound is reached by

ϵ^(w)=ρ sign⁡ ⁣(∇wLS(w)) ∣∇wLS(w)∣q−1/(∥∇wLS(w)∥qq)1/p\hat\epsilon(w) = \rho\,\operatorname{sign}\!\big(\nabla_w L_S(w)\big)\,\big|\nabla_w L_S(w)\big|^{q-1} \Big/ \Big(\|\nabla_w L_S(w)\|_q^q\Big)^{1/p}ϵ^(w)=ρ sign⁡ ⁣(∇wLS(w)) ∣∇wLS(w)∣q−1/(∥∇wLS(w)∥qq)1/p\begin{aligned} \hat\epsilon(w) &= \rho\,\operatorname{sign}\!\big(\nabla_w L_S(w)\big)\,\big|\nabla_w L_S(w)\big|^{q-1} \\ &\quad \Big/ \Big(\|\nabla_w L_S(w)\|_q^q\Big)^{1/p} \end{aligned}
(2)

with the sign, absolute value and power applied elementwise. Two cases matter. For p=q=2p = q = 2 the formula reduces to ϵ^=ρ g/∥g∥2\hat\epsilon = \rho\, g/\|g\|_2: the gradient rescaled to length ρ, the uphill direction. For p=∞p = \infty, q=1q = 1 and ϵ^=ρ sign⁡(g)\hat\epsilon = \rho\,\operatorname{sign}(g): every weight moves by exactly ρ in the direction of its own gradient's sign, the same formula the fast gradient sign method uses to build adversarial images. In both cases the linearized loss rises by ϵ^⊤g=ρ∥g∥q\hat\epsilon^\top g = \rho\|g\|_q.

A worked example with two weights fixes the numbers. Take the loss L(w)=12(10 w12+w22)L(w) = \tfrac12(10\,w_1^2 + w_2^2), a valley ten times steeper along w1w_1 than along w2w_2, at w=(0.1, 1.0)w = (0.1,\ 1.0) with the paper's default ρ = 0.05:

Next comes the gradient of the SAM objective. Substituting ϵ^(w)\hat\epsilon(w) into (1) and differentiating with the chain rule gives two terms, because ϵ^\hat\epsilon itself depends on ww:

∇wLSSAM(w)≈∇wLS(w)∣w+ϵ^(w)+dϵ^(w)dw ∇wLS(w)∣w+ϵ^(w)\nabla_w L_S^{SAM}(w) \approx \nabla_w L_S(w)\big|_{w+\hat\epsilon(w)} + \frac{d\hat\epsilon(w)}{dw}\,\nabla_w L_S(w)\big|_{w+\hat\epsilon(w)}∇wLSSAM(w)≈∇wLS(w)∣w+ϵ^(w)+dϵ^(w)dw ∇wLS(w)∣w+ϵ^(w)\begin{aligned} \nabla_w L_S^{SAM}(w) &\approx \nabla_w L_S(w)\big|_{w+\hat\epsilon(w)} \\ &\quad + \frac{d\hat\epsilon(w)}{dw}\,\nabla_w L_S(w)\big|_{w+\hat\epsilon(w)} \end{aligned}

The second term contains the derivative of ϵ^\hat\epsilon, which is built from the gradient, so it involves the Hessian. Automatic differentiation can compute it through Hessian-vector products without forming the Hessian, but the authors drop it to save the cost and keep only the first term:

∇wLSSAM(w)≈∇wLS(w)∣w+ϵ^(w)\nabla_w L_S^{SAM}(w) \approx \nabla_w L_S(w)\big|_{w+\hat\epsilon(w)}
(3)

Algorithm 1 of the paper combines (2) and (3). Each step takes a minibatch, computes its gradient at the current weights, rescales it to length ρ, computes the gradient of the same minibatch's loss at the perturbed weights, and hands that second gradient to an ordinary optimizer, which applies it at the original weights:

# One SAM step (Algorithm 1). Both gradients use the same minibatch B.
g     = grad(L_B, w)              # pass 1: gradient at the current weights
e_hat = rho * g / norm(g)         # Eq. (2) with p = 2: rescale g to length rho
g_sam = grad(L_B, w + e_hat)      # pass 2: gradient at the perturbed weights
w     = w - lr * g_sam            # update the ORIGINAL weights, not w + e_hat

In the two-weight example the gradient at the perturbed point is (1.354, 1.035)(1.354,\ 1.035). Compared with the plain gradient (1.0, 1.0)(1.0,\ 1.0), the steep coordinate grew by 35% and the shallow one by 3.5%, and the step direction turned by 7.6°. For a quadratic this is exact: the gradient at w+ϵ^w + \hat\epsilon is g+Hϵ^g + H\hat\epsilon, and with H=diag⁡(10,1)H = \operatorname{diag}(10, 1) the extra term is ten times larger along the steep axis.

Figure 2 draws one update on the same valley. The white dot is ww, the violet arrow is ϵ^\hat\epsilon to the edge of the ρ-ball, the gray arrow is the plain gradient step, and the bright teal arrow is the SAM step computed at w+ϵ^w + \hat\epsilon and applied at ww. It opens at ρ = 0.3 so the arrows are visible; at that radius the perturbed loss is 1.222 against a linear estimate of 0.974, because the curvature term grows with ρ2\rho^2.

Figure 2 · one SAM update
0.30
Drag on the plot to move ww. The perturbation ε̂ lands on the edge of the ρ-ball (circle for p = 2, square for p = ∞); the SAM step uses the gradient there, the gray SGD step the gradient at w. Both arrows use the same step size. The top line compares the true perturbed loss with its linear estimate.

Move ww up the shallow axis, to (0,1.2)(0, 1.2) say, and the gradient points straight along w2w_2; the perturbation is then along a low-curvature direction, the SAM step barely differs from the SGD step, and the angle readout drops to 0°. Switch to p=∞p = \infty and ϵ^\hat\epsilon jumps to a corner of the square. Its length is ρ2\rho\sqrt 2 in two dimensions and ρd\rho\sqrt d in dd, which is one reason the box perturbation is much larger than the ball for a network with millions of weights.

Why the perturbed gradient favors flat regions

Expanding (3) one more order shows what the update does. For small ρ, the gradient at w+ϵ^w + \hat\epsilon is the gradient at ww plus the Hessian times the perturbation:

∇LS(w+ϵ^)≈g+ρ Hg∥g∥2=∇w(LS(w)+ρ ∥∇wLS(w)∥2)\nabla L_S(w+\hat\epsilon) \approx g + \rho\,H\frac{g}{\|g\|_2} = \nabla_w\Big(L_S(w) + \rho\,\|\nabla_w L_S(w)\|_2\Big)∇LS(w+ϵ^)≈g+ρ Hg∥g∥2=∇w(LS(w)+ρ ∥∇wLS(w)∥2)\begin{aligned} \nabla L_S(w+\hat\epsilon) &\approx g + \rho\,H\frac{g}{\|g\|_2} \\ &= \nabla_w\Big(L_S(w) + \rho\,\|\nabla_w L_S(w)\|_2\Big) \end{aligned}

The second equality uses ∇∥g∥2=Hg/∥g∥2\nabla\|g\|_2 = Hg/\|g\|_2, which follows from differentiating g⊤g\sqrt{g^\top g}. So, to first order in ρ, the SAM update is gradient descent on the training loss plus ρ times the length of its gradient, which is the linearized SAM objective LS+ρ∥g∥2L_S + \rho\|g\|_2 from the previous section. This is a reading of (3), not a formula from the paper. A gradient-length penalty favors flat regions because on the walls of a sharp basin the gradient grows quickly with distance from the bottom: at distance tt along a direction of curvature λ\lambda it has length λt\lambda t. SGD noise keeps the weights moving around a minimum rather than sitting on it, and a basin with large λ\lambda charges a large penalty for every such excursion.

At the bottom of a minimum the gradient is zero and the first-order picture breaks down. There the exact sharpness of a quadratic basin is 12ρ2λmax⁡\tfrac12\rho^2\lambda_{\max}: the worst point in the ball lies along the steepest direction, at distance ρ. The exact SAM objective therefore penalizes the top Hessian eigenvalue directly, which is the quantity Section 4.2 of the paper measures. In practice the minibatch gradient is never exactly zero, so ϵ^\hat\epsilon is always defined.

If ϵ\epsilon were the exact maximizer of the inner problem, Danskin's theorem says the gradient of the maximum is the gradient at the maximizer with ϵ\epsilon held fixed, so the dropped term would be exactly zero: a maximizer on the ball's surface can only slide along the surface, perpendicular to the gradient there.ϵ^\hat\epsilon maximizes the linearized problem instead, and the term survives. For a quadratic it works out to

(dϵ^dw) ⁣⊤∇LS(w+ϵ^)=ρ2∥g∥2 H(I−g^g^⊤)Hg^,g^=g/∥g∥2\Big(\frac{d\hat\epsilon}{dw}\Big)^{\!\top}\nabla L_S(w+\hat\epsilon) = \frac{\rho^2}{\|g\|_2}\,H\big(I - \hat g\hat g^{\top}\big)H\hat g, \qquad \hat g = g/\|g\|_2(dϵ^dw) ⁣⊤∇LS(w+ϵ^)=ρ2∥g∥2 H(I−g^g^⊤)Hg^,g^=g/∥g∥2\begin{gathered} \Big(\frac{d\hat\epsilon}{dw}\Big)^{\!\top}\nabla L_S(w+\hat\epsilon) = \frac{\rho^2}{\|g\|_2}\,H\big(I - \hat g\hat g^{\top}\big)H\hat g, \\ \hat g = g/\|g\|_2 \end{gathered}

which is second order in ρ. It is zero when gg lies along an eigenvector of HH, and it has a factor 1/∥g∥21/\|g\|_2 that grows as the gradient shrinks. In the two-weight example it is (0.056, −0.006)(0.056,\ -0.006), so the full gradient would be (1.410, 1.030)(1.410,\ 1.030) instead of SAM's (1.354, 1.035)(1.354,\ 1.035), about 4% different along the steep axis. Appendix C.4 of the paper ran both versions on a WideResNet-40-2 on CIFAR-10. The two updates had cosine similarity close to 1 for the first half of training and became less similar near convergence, consistent with the 1/∥g∥21/\|g\|_2 factor, and the cheaper first-order version reached the lower test error. The authors call the reason unclear.

The curve that the button under Figure 1 adds, labeled one-step L(w+ε̂), is the value L(w+ϵ^(w))L(w + \hat\epsilon(w)) that the algorithm effectively descends. On smooth stretches it tracks the exact maximum. Just past the ridge that separates the pit from the wide basin (its top is at w≈−0.62w \approx -0.62), it falls below the exact maximum: there the uphill direction points back over the ridge, so a step of length ρ overshoots onto the pit's wall. At the default ρ=0.25\rho = 0.25 and w=−0.59w = -0.59, the step lands at w=−0.84w = -0.84, where the loss is 0.67 against an exact maximum of 1.00.

m-sharpness: one perturbation per slice of the batch

The derivation above maximizes over one ϵ\epsilon for the whole training set. Algorithm 1 already replaces that with one ϵ\epsilon per minibatch, and the experiments go one step further. When a batch is split across accelerators, each accelerator computes the first gradient on its own slice, builds its own ϵ^\hat\epsilon from it, and computes the second gradient at its own perturbed weights; only the second gradients are averaged across devices. The official JAX code has a flag to sync the perturbations, and it is off by default. In the CIFAR runs a batch of 256 was split across 8 GPUs, so each perturbation was computed from 32 examples. On ImageNet, 4,096 images over 32 TPU cores gives 128 per core, if the batch is split evenly there too.

The paper calls the resulting quantity m-sharpness, where mm is the number of examples per independent maximization. Split the training set into disjoint groups S1,…,Sn/mS_1, \dots, S_{n/m} of size mm; then the objective being minimized is

LSSAM,m(w)=1n∑j=1n/m  max⁡∥ϵj∥2≤ρ  ∑i∈Sjl(w+ϵj,xi,yi)L^{SAM,m}_S(w) = \frac{1}{n}\sum_{j=1}^{n/m}\;\max_{\|\epsilon_j\|_2 \le \rho}\;\sum_{i \in S_j} l(w + \epsilon_j, x_i, y_i)LSSAM,m(w)=1n∑j=1n/mmax⁡∥ϵj∥2≤ρ  ∑i∈Sjl(w+ϵj,xi,yi)\begin{aligned} L^{SAM,m}_S(w) &= \frac{1}{n}\sum_{j=1}^{n/m} \\ &\quad \max_{\|\epsilon_j\|_2 \le \rho}\;\sum_{i \in S_j} l(w + \epsilon_j, x_i, y_i) \end{aligned}

(the paper defines it in words; this is that definition in symbols). With m=nm = n it is (1). With smaller mm each group chooses its own worst direction, and since the maximum of a sum is at most the sum of the maxima, LSSAM,mL^{SAM,m}_S is never below LSSAML^{SAM}_S.

Figure 3 shows the mechanism on a toy batch of 16 two-dimensional gradients. The dashed white arrow is the batch-mean gradient, which sets the single perturbation of m=16m = 16. Under the linear approximation each group's sharpness is ρ times the length of its mean gradient. At m=16m = 16 that is ρ × 0.41; at m=1m = 1, where every example perturbs on its own, the average is ρ × 1.02, two and a half times as large, and the 16 perturbations point all around the circle.

Figure 3 · m-sharpness on a toy batch
m = 4
Left: 16 per-example gradients, colored by group, with each group's mean drawn thick. Right: the direction of each group's perturbation on the ρ-ball. Slide mm from 16 (one group, one perturbation along the dashed batch mean) down to 1. The second-pass cost per example does not change with m.

On real models smaller mm helped. The paper trained a small ResNet on CIFAR-10 over a range of mm and found that smaller values tended to give lower test error (its Figure 3, middle). It also measured how well m-sharpness predicts a model's generalization gap, using the two public tasks of the NeurIPS 2020 Predicting Generalization in Deep Learning competition, and found the prediction improves as mm decreases. So the version of SAM that worked best is not the one the bound describes, which is m=nm = n. For a fixed global batch, more devices means a smaller mm, so the device count changes SAM's test error as well as its speed.

Results

Every experiment swaps the optimizer of an existing training recipe for SAM and changes nothing else. ρ was chosen by grid search over {0.01, 0.02, 0.05, 0.1, 0.2, 0.5} on 10% of the training set held out, and Appendix C.3 reports that the default ρ = 0.05 gives nearly the same numbers. To account for the doubled cost per step, each non-SAM baseline was also trained for twice as many epochs, and the better of its two runs is the one reported. Each number is the mean of five runs, with a 95% confidence interval.

CIFAR from scratch. On a WideResNet-28-10 trained for 1,800 epochs with AutoAugment, SAM gives 1.6% test error on CIFAR-10 against 2.2% for SGD, and 12.8% against 16.1% on CIFAR-100. The improvement holds in all 30 CIFAR settings of Table 1. The smallest CIFAR-100 gain is on the most heavily regularized model: PyramidNet with ShakeDrop and AutoAugment goes from 10.6% to 10.3% on CIFAR-100, which the paper reports as the best result on that dataset without extra data.

ImageNet. ResNet-50, -101 and -152 were trained with batch size 4,096, an initial learning rate of 1.0 on a cosine schedule, momentum 0.9, label smoothing 0.1, weight decay 0.0001 and, for SAM, ρ = 0.05. The headline number is ResNet-152 going from 20.3% top-1 error to 18.4%. That compares standard training's best run (200 epochs) with SAM's best (400 epochs). Figure 4 plots all nine pairs. Standard training gets worse from 200 to 400 epochs (ResNet-101 goes from 20.9% to 22.3%), while SAM keeps improving (19.4% to 19.0%). At equal gradient computations, SAM at 200 epochs against standard training at 400, ResNet-152 is at 18.5% against 20.9%.

Figure 4 · two result tables
Values from Tables 2 and 4 of the paper. ImageNet view: SAM and standard training at 100, 200 and 400 epochs; pick a model below. Noisy-label view: clean-test accuracy of ResNet-32 on CIFAR-10 as the fraction of flipped training labels grows; MentorMix is a literature result, the rest are the authors' runs.

Fine-tuning. Starting from public EfficientNet checkpoints, SAM lowered the error on every target dataset in Table 3. The largest model, EfficientNet-L2 (pretrained on ImageNet plus unlabeled JFT, 88.2% ImageNet accuracy before fine-tuning), reaches 11.39% top-1 error on ImageNet with SAM against 11.8% without, and 0.30% and 3.92% error on CIFAR-10 and CIFAR-100. The previous best ImageNet number in the table is 11.45%, from the Vision Transformer. The checkpoints come from the EfficientNet family; for ImageNet the models were fine-tuned for 10 epochs at learning rate 0.1 with ρ = 0.05.

Noisy labels. A ResNet-32 was trained for 200 epochs on CIFAR-10 with 20% to 80% of the training labels replaced at random, and tested on the clean test set. With 80% of labels flipped, plain SGD reaches 26.2% test accuracy and SAM 77.9%. Bootstrapping (training once, then retraining from scratch on the first model's predicted labels) raises SAM to 79.9%, close to MentorMix's 81.0%, a method built for noisy labels. SAM used ρ = 0.1, and 0.05 at 80% noise for more stable training. The paper's explanation is a hypothesis: noise in the labels perturbs the loss landscape, and solutions robust to weight perturbations may also be robust to that.

Curvature. To check that SAM finds flatter minima, the authors estimated the Hessian spectrum of a WideResNet-40-10 on CIFAR-10 with the Lanczos method, training without batch normalization, which they say obscures the interpretation of the Hessian. At convergence λmax⁡\lambda_{\max} was about 24 without SAM and 1.0 with it, and the ratio λmax⁡/λ5\lambda_{\max}/\lambda_5 was up to 11.4 without SAM and 2.6 with it.

The appendix tables contain one row where SAM is worse: Shake-Shake on SVHN with AutoAugment, 1.07% error against 1.03% for the baseline (Table 5).

What the theory does and does not explain

The full version of Theorem 1, in Appendix A, holds with probability 1−δ1-\delta over the training set:

LD(w)≤max⁡∥ϵ∥2≤ρLS(w+ϵ)+klog⁡ ⁣(1+∥w∥22ρ2(1+log⁡nk)2)+4log⁡nδ+O~(1)n−1L_{\mathcal D}(w) \le \max_{\|\epsilon\|_2\le\rho} L_S(w+\epsilon) + \sqrt{\frac{k\log\!\Big(1+\tfrac{\|w\|_2^2}{\rho^2}\big(1+\sqrt{\tfrac{\log n}{k}}\big)^2\Big) + 4\log\frac{n}{\delta} + \tilde O(1)}{n-1}}LD(w)≤max⁡∥ϵ∥2≤ρLS(w+ϵ)+klog⁡ ⁣(1+∥w∥22ρ2(1+log⁡nk)2)+4log⁡nδ+O~(1)n−1\begin{aligned} L_{\mathcal D}(w) &\le \max_{\|\epsilon\|_2\le\rho} L_S(w+\epsilon) \\ &\quad + \sqrt{\frac{\begin{gathered} k\log\!\Big(1+\tfrac{\|w\|_2^2}{\rho^2}\big(1+\sqrt{\tfrac{\log n}{k}}\big)^2\Big) \\ + 4\log\frac{n}{\delta} + \tilde O(1) \end{gathered}}{n-1}} \end{aligned}
(4)

where kk is the number of parameters and nn the number of training examples. The theorem also assumes that adding Gaussian noise to the weights does not lower the test loss, which the authors expect to hold at a trained solution but not everywhere. It is a PAC-Bayesian bound: it compares a Gaussian distribution of weights centered on ww with a Gaussian prior centered at zero.

For a real network the bound is vacuous. The loss in the proof is bounded by 1, and with ResNet-50 on ImageNet, k≈2.56×107k \approx 2.56\times 10^7 parameters against n≈1.28×106n \approx 1.28\times 10^6 images, the first term under the square root alone exceeds k/(n−1)≈20k/(n-1) \approx 20 as soon as the logarithm is above 1, which it is for any ∥w∥2\|w\|_2 above 0.07 at ρ = 0.05. The square root is then above 4.4, and the right-hand side is larger than the largest possible loss.

The proof's leading term is first derived as the expected training loss under Gaussian weight noise; the maximum over the ball enters afterward as an upper bound on that expectation. So the same argument supports training with random weight noise. Andriushchenko and Flammarion (2022) tested the variants the bound suggests on ResNet-18 (CIFAR-10) and ResNet-34 (CIFAR-100) at batch size 128. Random perturbations and full-batch n-SAM barely beat standard training; only low-m SAM (m = 128) improved test error substantially. Since LSSAM,mL^{SAM,m}_S is never below LSSAML^{SAM}_S (smaller mm gives a larger maximum), a version of the bound written with m-sharpness has its largest right-hand side at m = 128, so it would predict 128-SAM to generalize worst of the three, the opposite of what was measured.

The sharpness measure itself is not invariant to reparameterization. Multiply one ReLU layer's weights by 100 and divide the next layer's by 100, and the network computes the same function, but the loss now changes 100 times faster along the second layer's weights. A fixed ρ-ball measures different things for the two parameterizations. Adaptive SAM (ASAM, Kwon et al. 2021) scales the ball per weight by ∣w∣|w| to remove this dependence.

Two appendix experiments test the approximations directly. Replacing the single ascent step with several steps of projected gradient ascent (Appendix C.6) finds a perturbed loss about 3% higher near convergence on CIFAR-10 with five steps, but test error barely moves: 2.77% with one step and 2.77% with five on CIFAR-10, 16.72% and 16.60% on CIFAR-100. And the p=∞p = \infty box and a random direction of the same length both did worse than the gradient direction with p=2p = 2 (Appendix C.5). The measured facts are lower test error across the tables and lower Hessian curvature at convergence. That flatness causes the lower test error is the paper's motivating hypothesis, and later work found that a flatter minimum by SAM's own measure does not always generalize better.

Implementing SAM

SAM wraps a base optimizer: it changes which gradient the optimizer receives and nothing else, so the base optimizer can be SGD with momentum (as in the paper), Adam, or anything else. A minimal PyTorch version of one step, close to the widely used davda54/sam implementation that the paper's acknowledgments mention:

import torch

def sam_step(model, loss_fn, batch, base_opt, rho=0.05):
    params = [p for p in model.parameters() if p.requires_grad]
    base_opt.zero_grad()
    loss_fn(model, batch).backward()             # pass 1: gradient at w
    with torch.no_grad():
        norm = torch.norm(torch.stack([p.grad.norm() for p in params]))
        eps = [p.grad * (rho / (norm + 1e-12)) for p in params]
        for p, e in zip(params, eps):
            p.add_(e)                            # move to w + e_hat
    base_opt.zero_grad()
    loss_fn(model, batch).backward()             # pass 2: gradient at w + e_hat
    with torch.no_grad():
        for p, e in zip(params, eps):
            p.sub_(e)                            # back to w
    base_opt.step()                              # base optimizer applies g_sam

The function computes the loss twice on the same batch. For a ResNet-50 the second pass costs as much as the first, so wall-clock time per step roughly doubles, and memory grows by one parameter-sized buffer for ϵ^\hat\epsilon (25.6 million floats, about 100 MB in fp32). The norm is taken over all parameters at once, one global length over every layer. The official JAX code makes four choices that a reimplementation should match:

With data-parallel training in PyTorch, the m-sharpness behavior depends on when gradients are averaged. Under DistributedDataParallel the first backward pass all-reduces gradients across devices by default, which gives one synchronized perturbation (mm equal to the global batch). Skipping that synchronization for the first pass (for example with DDP's no_sync() context) restores the per-device perturbations the paper used.

Provenance Verified against primary literatureHow we verify
Eq. (2), footnote 2For p = 2 the dual-norm solution is rho * g / ||g||_2, a rescaling of the gradient to length rho. For p = infinity it is rho * sign(g). The paper reports p = 2 as best in its Appendix C.5 ablation.
Official JAX codegoogle-research/sam, file flax_training.py. dual_vector (lines 454-463) divides the gradient pytree by its global L2 norm, with no epsilon. get_sam_gradient (lines 527-551) runs two value_and_grad passes on the same batch; batch-norm statistics are kept from the first, unperturbed pass. sync_perturbations defaults to False (line 84), so each device normalizes its own gradient (m-sharpness) and only the second gradient is averaged across devices (line 564). The L2 penalty 0.5 * l2_reg * ||w||^2 is part of the loss in both passes (lines 521-522). Clipping by global norm, default 5.0 (lines 45, 567); momentum is Nesterov (line 220).
Tables 1, 6 and 9Table 9 (rho = 0.05 everywhere) lists PyramidNet on CIFAR-10 at 2.1 / 1.6 / 1.4% error, better than the tuned Table 1 row (2.7 / 1.9 / 1.6%), although Table 6 gives 0.05 as that row's tuned rho. This page quotes Table 1.
Appendix AThe bound's leading term is first derived for Gaussian weight noise (Eq. 13); the maximum over the rho-ball is a further upper bound that holds with probability 1 - 1/sqrt(n). The theorem assumes adding Gaussian noise to w does not lower the test loss.
Andriushchenko (2022)Andriushchenko & Flammarion, ICML 2022. On ResNet-18 / CIFAR-10 and ResNet-34 / CIFAR-100 at batch 128, random perturbations and full-batch n-SAM barely improve on standard training; only low-m SAM (128-SAM) improves substantially. A bound extended to m-SAM would rank 128-SAM worst of the three.
Dinh 2017; Kwon 2021Dinh et al. and ASAM (Kwon et al.). Rescaling one ReLU layer by alpha and the next by 1/alpha leaves the function unchanged but makes a minimum arbitrarily sharp, so fixed-radius sharpness is not scale-invariant. ASAM scales the ball per weight by |w|; it is the adaptive=True option of the davda54 PyTorch implementation.
Danskin's theoremFor an exact, unique inner maximizer, the gradient of max_e L(w + e) equals grad L at w + e*, with e* held fixed. The term SAM drops would then be zero; it is nonzero only because e_hat maximizes the linearized problem.
correctionThree slips in the paper's appendices; none changes the method. (1) Appendix C.5 writes the p = 2 perturbation as ρ g / ‖g‖₂² and the random baseline as ρ z / ‖z‖₂². With a squared norm the vector's length is ρ / ‖g‖₂, not ρ, and the random perturbation would not have the "fixed Euclidean norm" the text describes. Eq. (2), footnote 2 ("rescaling the gradient such that its norm is ρ") and the official code (dual_vector) all divide by ‖g‖₂; this page uses ρ g / ‖g‖₂. (2) Table 8 is captioned "validation accuracy" but holds error rates: ρ = 0.1 at 20% noise reads 4.6%, while the matching test accuracy in Table 4 is 95.4%, and the ρ values the text says were chosen (0.1, and 0.05 at 80% noise) are the minima of each column. (3) Appendix Eq. (6) is labeled KL(P‖Q), but the formula, with σ_Q² over σ_P² and log(σ_P²/σ_Q²), is KL(Q‖P), the direction used in Eq. (5).

Questions you might still have

?

Does SAM make training twice as slow?
Per step, yes: every update needs two forward and backward passes on the same batch, plus one extra parameter-sized buffer for the perturbation. The paper charged for this by letting every non-SAM baseline train for twice as many epochs and reporting the better of the two runs. On ImageNet, ResNet-152 with SAM at 200 epochs (18.5% top-1 error) costs the same number of gradient evaluations as standard training at 400 epochs (20.9%).

?

What value of rho should I start with?
The paper's default is 0.05, used for every ImageNet run and reported in Appendix C.3 as close to the tuned value elsewhere. Its grid was {0.01, 0.02, 0.05, 0.1, 0.2, 0.5}, chosen on 10% of the training set held out. The tuned values on CIFAR-100 were often larger (0.1 or 0.2), and 0.5 was too large in every noisy-label setting. rho is a Euclidean length over all weights at once, so its meaning changes if the parameter count or the weight scale changes a lot.

?

Is SAM the same as adding random noise to the weights?
No. The perturbation points along the gradient, the direction in which the loss rises fastest, and its length is fixed at rho. Appendix C.5 compares it with a random direction of the same length and the random version is worse; Andriushchenko and Flammarion (2022) found random perturbations give almost no gain over standard training.

?

Can SAM wrap Adam instead of SGD?
Yes. SAM only changes which gradient is handed to the optimizer: the gradient at w plus e-hat instead of the gradient at w. Any optimizer can apply it. The paper's from-scratch and ImageNet runs used SGD with momentum (Nesterov momentum in the official code), and the code also supports RMSProp for EfficientNet.

?

Does SAM really find flatter minima?
By the paper's measurement, yes: a WideResNet-40-10 trained on CIFAR-10 without batch norm ended with a largest Hessian eigenvalue of about 24 without SAM and 1.0 with it. Whether flatness is why test error drops is a separate question. Later work found that flatter by SAM's own measure does not always mean better generalization, and that the version of SAM the theory describes barely helps.

?

Why does the per-GPU batch size change the result?
Each device computes its own perturbation from its own slice of the batch, and the paper found smaller slices (smaller m) give lower test error. Running the same global batch on fewer devices makes m larger and can make SAM less effective. To get a small m on one device, split the batch into micro-batches and perturb each separately, at the cost of less parallel work per pass.

?

Is this the same SAM as Segment Anything?
No. The name collides. Sharpness-Aware Minimization is a 2020 training method for any network; Segment Anything (Meta, 2023), also called SAM, is a promptable image-segmentation model, covered in its own explainer on this site.

Footnotes & further reading

  1. The paper: Foret, Kleiner, Mobahi & Neyshabur, Sharpness-Aware Minimization for Efficiently Improving Generalization (ICLR 2021; arXiv v3, April 2021). Official JAX code: google-research/sam; the PyTorch implementation by David Samuel: davda54/sam.
  2. Flat minima: Hochreiter & Schmidhuber, Flat Minima (Neural Computation, 1997). Large batches and sharp minima: Keskar et al., On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima (ICLR 2017). The large-scale comparison of generalization measures: Jiang et al., Fantastic Generalization Measures and Where to Find Them (ICLR 2020).
  3. The reparameterization objection: Dinh, Pascanu, Bengio & Bengio, Sharp Minima Can Generalize For Deep Nets (ICML 2017). The scale-invariant variant: Kwon et al., ASAM: Adaptive Sharpness-Aware Minimization for Scale-Invariant Learning of Deep Neural Networks (ICML 2021).
  4. Andriushchenko & Flammarion, Towards Understanding Sharpness-Aware Minimization (ICML 2022), on why m-sharpness and worst-case perturbations matter and why the PAC-Bayes bound does not explain them.
  5. The fast gradient sign method, the input-space analogue of the p=∞p = \infty perturbation: Goodfellow, Shlens & Szegedy, Explaining and Harnessing Adversarial Examples (ICLR 2015). Entropy-SGD: Chaudhari et al., Entropy-SGD: Biasing Gradient Descent Into Wide Valleys (2016).
  6. Danskin's theorem on differentiating a maximum: J. M. Danskin, The Theory of Max-Min and its Application to Weapons Allocation Problems (Springer, 1967); also Bertsekas, Nonlinear Programming, Appendix B. The models in the experiments are covered in the ResNet explainer and its relatives on this site.