AI Logic

Optimizers

Sharpness-Aware Minimization (SAM)

Updated:

How SAM works. Left: the flow of shifting the weights by radius ρ using the first gradient, then updating the original weights with a second gradient computed at the shifted point. Right: a graph comparing a 1D loss with a sharp valley and a flat valley against the SAM loss, which takes the maximum within radius ρ, showing that the flat valley becomes the minimum under the SAM loss

Background and Overview

SAM (Sharpness-Aware Minimization) is a training procedure that minimizes not only the value of the loss but also the "sharpness" of the loss around the weights. It was presented by Foret et al. at ICLR in 2021.

Modern deep learning models have a very large number of parameters and can drive the training loss close to 0. However, even among minima with similarly low training loss, generalization (performance on test data) can differ greatly. Building on prior work on the relationship between the flatness of the loss landscape and generalization, the paper takes the following view.

  • Sharp minima: The loss rises steeply when the weights shift even slightly. Performance is thought to degrade easily under small differences between training and test data.
  • Flat minima: The loss stays low for nearby weights as well. Performance is thought to be maintained even when the data changes slightly.

SAM looks for weights at which the loss is low everywhere within a radius ρ\rho. It only requires computing the gradient twice per update and can be used on top of ordinary optimizers such as SGD.

An analogy is choosing a campsite at the bottom of a valley: a wide basin, even if somewhat shallower, is safer than a narrow, deep ravine in case you slip.

Theory (Objective and Computation in One Step)

Since an upper bound on the generalization error (Theorem 1) is controlled by "the worst training loss in the neighborhood" and the magnitude of the weights, the paper proposes solving the following problem (Eq. (1)).

min⁡w  LSSAM(w)+λ∥w∥22,LSSAM(w)=max⁡∥ϵ∥p≤ρLS(w+ϵ)\min_w\; L^{\mathrm{SAM}}_S(w) + \lambda \|w\|_2^2, \qquad L^{\mathrm{SAM}}_S(w) = \max_{\|\epsilon\|_p \le \rho} L_S(w + \epsilon)

LSSAM(w)−LS(w)L^{\mathrm{SAM}}_S(w) - L_S(w) corresponds to "sharpness" and measures how quickly the loss rises when moving to nearby points. λ∥w∥22\lambda \|w\|_2^2 is ordinary L2 regularization. The paper shows experimentally that p=2p = 2 works well.

Approximating the inner maximization with the first-order term of a Taylor expansion gives the point reached by moving a distance ρ\rho in the gradient direction (Eq. (2) with p=2p = 2). Further dropping the second-order term, the gradient at the shifted point is used as the gradient of the SAM loss (Eq. (3)).

ϵ^(w)=ρ ∇wLS(w)∥∇wLS(w)∥2,∇wLSSAM(w)≈∇wLS(w)∣w+ϵ^(w)\hat{\epsilon}(w) = \rho\, \frac{\nabla_w L_S(w)}{\|\nabla_w L_S(w)\|_2}, \qquad \nabla_w L^{\mathrm{SAM}}_S(w) \approx \nabla_w L_S(w)\big|_{w + \hat{\epsilon}(w)}

Following Algorithm 1 of the paper, each step performs the following computation.

  1. Take a minibatch BB and compute the gradient ∇wLB(wt)\nabla_w L_B(w_t) at the current weights wtw_t.
  2. Compute ϵ^\hat{\epsilon} by scaling the gradient to magnitude ρ\rho, and temporarily shift the weights to wt+ϵ^w_t + \hat{\epsilon}.
  3. At the shifted point, compute the gradient gg again on the same minibatch.
  4. Restore the weights to wtw_t and update them with gg (for SGD, wt+1=wt−ηgw_{t+1} = w_t - \eta g).

SAM can be viewed as applying the idea of adversarial examples to the weights rather than the inputs. Just as FGSM shifts the input in the gradient direction to increase the loss, SAM shifts the weights in the gradient direction to create "the worst nearby point" and learns to reduce the loss there.

Why It Works (Choosing Flat Minima)

The right side of the figure at the top shows an example in which the SAM loss max⁡∣ϵ∣≤ρL(w+ϵ)\max_{|\epsilon| \le \rho} L(w + \epsilon) is computed for a 1D loss with a sharp valley (around w=−1.5w = -1.5) and a flat valley (around w=1.5w = 1.5) (ρ=0.5\rho = 0.5).

  • Looking only at the loss, the sharp valley is the minimum: The loss at the bottom is lower in the sharp valley.
  • Under the SAM loss, the flat valley is the minimum: In the sharp valley, regions of high loss fall within radius ρ\rho, so the SAM loss stays high. In the flat valley, the surroundings also have low loss, so the SAM loss is low as well.

The paper confirms this difference in real networks too. Examining the eigenvalues of the Hessian (the second derivative of the loss) of a WideResNet trained on CIFAR-10, the largest eigenvalue at the end of training was about 24 with SGD and about 1.0 with SAM. The ratio of the largest to the fifth eigenvalue, a commonly used measure of sharpness, was also 2.6 for SAM versus up to 11.4 for SGD, indicating that SAM converged to minima with less curvature (flatter minima).

The paper also introduces the notion of m-sharpness. In practice, SAM computes ϵ^\hat{\epsilon} not over the entire training set but per minibatch, or per group of mm examples within it. In small CIFAR-10 experiments, smaller mm gave better generalization, and as a sharpness measure it also correlated well with the generalization gap.

Experimental Results

The paper examines how image classification error rates change when ordinary training (SGD) is simply replaced by SAM. Since SAM requires two backward passes per update, the SGD baseline was also run with twice the number of epochs, and the better result is reported.

ImageNet ResNet (top-1 error %, mean of 5 runs) (Table 2 of the paper). ρ=0.05\rho = 0.05, batch size 4096, cosine learning rate, momentum 0.9, Label Smoothing 0.1.

ModelEpochsSAMSGD
ResNet-5010022.522.9
ResNet-5040020.922.3
ResNet-10140019.022.3
ResNet-15220018.520.3
ResNet-15240018.420.9

While SGD's error rate often rose when training was extended from 200 to 400 epochs (overfitting), SAM's kept decreasing.

CIFAR (test error %) (excerpt from Table 1 of the paper; AA is AutoAugment)

ModelAugmentationCIFAR-10 SAMCIFAR-10 SGDCIFAR-100 SAMCIFAR-100 SGD
WRN-28-10 (200 epochs)Basic2.73.516.518.8
WRN-28-10 (1800 epochs)AA1.62.212.816.1
Shake-Shake (26 2x96d)AA1.61.912.814.1
PyramidNet + ShakeDropAA1.41.610.310.6

SAM achieved lower error than SGD in all 15 settings in Table 1.

Other results are as follows.

  • Fine-tuning: Error rates dropped in every case when fine-tuning EfficientNet-B7 and EfficientNet-L2 on 9 datasets (for EfficientNet-L2, e.g., 0.30% on CIFAR-10, 3.92% on CIFAR-100, and 11.39% on ImageNet).
  • Robustness to label noise: For ResNet-32 trained on CIFAR-10 with a portion of labels randomly flipped, accuracy at 80% noise was 77.9% with SAM versus 26.2% with SGD, outperforming most existing methods designed specifically for noisy labels.

Practical Considerations

SAM computes the gradient twice per update, so for the same number of epochs training takes roughly twice as long. The paper also compares against SGD after allowing it twice the number of epochs. Keep this in mind when comparing under the same compute budget.

  • A good default for ρ\rho is 0.05: The paper selects it from {0.01,0.02,0.05,0.1,0.2,0.5}\{0.01, 0.02, 0.05, 0.1, 0.2, 0.5\} on validation data and states that 0.05 was a solid default. The ImageNet experiments also use 0.05.
  • PyTorch has no built-in implementation: The paper's official implementation is in JAX. In PyTorch, wrap the base optimizer and write the two stages, "shift" and "restore and update," as in the code example below.
  • In distributed training, compute ϵ^\hat{\epsilon} per device: The paper splits the minibatch across devices, computes the SAM gradient on each, and then averages them. Because not synchronizing ϵ^\hat{\epsilon} improves performance (m-sharpness), data parallelism is recommended.
  • Drop the second-order term: The paper reports that including the second-order term arising from the dependence of ϵ^\hat{\epsilon} on the weights actually hurt performance.
  • Apply weight decay separately: The λ∥w∥22\lambda \|w\|_2^2 term in Eq. (1) is handled by the base optimizer as ordinary L2 regularization (weight decay).

Comparison with Other Methods

The table below compares modifications to the training procedure aimed at improving generalization from the same perspective.

MethodWhat it changesGradient computations per updateMain effectExtra hyperparameters
SGD (+ momentum)-1Baseline-
SAMThe point where the gradient is computed (weights shifted by radius ρ\rho)2Selects flat minimaρ\rho
LookaheadHow updates are made (interpolate slow weights)1Reduces variance for stabilitykk, α\alpha
Weight averaging (SWA, etc.)Average the weights at the end of training1Moves toward flatter solutionsHow to average
Data augmentation such as MixupInput data1Smooths decision boundariesAugmentation strength

The paper reports that adding SAM on top of models already using data augmentation (Cutout, AutoAugment) or regularization (Shake-Shake, ShakeDrop) still lowered error rates, so SAM can be combined with these methods.

Rough guidelines for choosing are as follows.

  • If compute allows and any gain in generalization is worthwhile, use SAM: Existing training settings can be used almost as is.
  • If compute should not increase, start with data augmentation or weight averaging: The number of gradient computations does not increase.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class SAM:
    # Algorithm 1 of the paper (p = 2). base is the original optimizer that updates the weights, e.g. SGD
    def __init__(self, params, base_cls, rho=0.05, **kwargs):
        self.params = [p for p in params]
        self.base = base_cls(self.params, **kwargs)
        self.rho = rho

    def zero_grad(self):
        self.base.zero_grad()

    @torch.no_grad()
    def first_step(self):
        # compute ε̂ = ρ ∇L / ||∇L||_2 and shift the weights to w + ε̂
        grads = [p.grad for p in self.params if p.grad is not None]
        norm = torch.norm(torch.stack([g.norm(2) for g in grads]), 2)
        self.eps = []
        for p in self.params:
            e = torch.zeros_like(p) if p.grad is None else p.grad * (self.rho / (norm + 1e-12))
            p.add_(e)
            self.eps.append(e)

    @torch.no_grad()
    def second_step(self):
        # restore the weights to w and update with the gradient computed at the shifted point
        for p, e in zip(self.params, self.eps):
            p.sub_(e)
        self.base.step()


model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 10))
optimizer = SAM(model.parameters(), torch.optim.SGD, rho=0.05,
                lr=0.1, momentum=0.9, weight_decay=5e-4)

model.train()
x = torch.randn(32, 20)
y = torch.randint(0, 10, (32,))

# first gradient: at the current weights w
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.first_step()

# second gradient: at the shifted weights w + ε̂ (same minibatch)
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.second_step()

FAQ

Q. What value should ρ be?
A.

The paper treats 0.05 as a solid default, and the ImageNet experiments also use ρ=0.05\rho = 0.05. For CIFAR, it is selected from {0.01,0.02,0.05,0.1,0.2,0.5}\{0.01, 0.02, 0.05, 0.1, 0.2, 0.5\} on validation data. Experiments with heavy label noise also use 0.1.

Q. Is SAM a replacement for an optimizer?
A.

No. It adds a step that "shifts the point at which the gradient is computed" to a base optimizer (such as SGD or SGD with momentum). The weight update itself is performed by the base optimizer.

Q. How much longer does training take?
A.

Each update performs two forward and two backward passes, so for the same number of epochs it takes roughly twice as long. The paper reports that SAM still had lower error even when SGD was given twice the number of epochs.

References

  1. P. Foret, A. Kleiner, H. Mobahi, and B. Neyshabur, "Sharpness-Aware Minimization for Efficiently Improving Generalization," ICLR, 2021.
  2. Google Research, "sam" (official implementation of the paper, JAX), GitHub.