Skip to main content
© 2026 ePowerAI — instrumented learning, no login required.
CoursesContact
ePOWERAI
CoursesContact
Week 12: Sharpness and SAM
Adv. Optimization
01Week 1: Optimality Conditions Revisited
02Week 2: Lagrangian Duality in Depth
03Week 3: KKT and Sensitivity
04Week 4: LP, QP, and Conic Form
05Week 5: Semidefinite Programming
06Week 6: Interior-Point Methods
07Week 7: Proximal Methods and ADMM
08Week 8: Newton and Quasi-Newton
09Week 9: Variance Reduction
10Week 10: Large-Batch and Distributed Training
11Week 11: Automatic Differentiation
12Week 12: Sharpness and SAM
13Week 13: Landscapes and Implicit Bias
14Week 14: Capstone — Structure Meets Scale
Week 12· Adv. Optimization· Geometry & training science7 min read

Week 12: Sharpness and SAM

Learning Outcomes
  • Describe flat vs sharp minima qualitatively and connect them to generalisation
  • State the SAMSharpness-Aware Minimization objective: min⁡wmax⁡∥ε∥≤ρL(w+ε)\min_w \max_{\|\varepsilon\| \leq \rho} L(w + \varepsilon)minw​max∥ε∥≤ρ​L(w+ε)
  • Write the practical SAM gradient step (ascent to find ε∗\varepsilon^*ε∗, then descent on www)
  • Relate large-batch training to sharpness research without overclaiming causality
Prerequisites

Background: Week 10 (large-batch training, generalisation gap). Week 11 (AD/computing gradients). Intermediate Optim Week 12 (nonconvex landscapes intro). Familiarity with the idea that different minima of the training loss can have different test performance.

Later weeks: Sharpness is a key ingredient in Week 13's discussion of implicit bias and the open gaps between convex theory and deep learning practice.

  • Also see: Optimization Week 13: Nonconvex Deep Learning — the landscape this sharpness measure describes.

Loss Geometry Beyond Value#

Two weight vectors w1w_1w1​ and w2w_2w2​ can achieve the same training loss L(w1)≈L(w2)L(w_1) \approx L(w_2)L(w1​)≈L(w2​) but differ dramatically in test performance. Why?

Consider a 1D loss L(w)L(w)L(w) with a broad, shallow basin at w1w_1w1​ and a narrow, steep basin at w2w_2w2​. Both are local minima with similar loss values. But:

  • At w1w_1w1​ (flat): a small perturbation ε\varepsilonε raises the loss by O(∥ε∥2)O(\|\varepsilon\|^2)O(∥ε∥2) with a small coefficient — the Hessian has small eigenvalues.
  • At w2w_2w2​ (sharp): the same perturbation raises the loss by a much larger amount — the Hessian has large eigenvalues.

A model at a flat minimum is robust to parameter perturbations. Since inference involves numerical noise, quantisation, and distribution shift, flatness is a proxy for stability. The empirical observation: flat minima tend to generalise better.

Measuring Sharpness#

The sharpness of the loss at www within a neighbourhood of radius ρ\rhoρ is:

Sρ(w)=max⁡∥ε∥≤ρL(w+ε)−L(w)S_\rho(w) = \max_{\|\varepsilon\| \leq \rho} L(w + \varepsilon) - L(w)Sρ​(w)=max∥ε∥≤ρ​L(w+ε)−L(w)

Sρ(w)S_\rho(w)Sρ​(w) measures the worst-case loss increase from a bounded perturbation. A small SρS_\rhoSρ​ means the basin is flat; a large SρS_\rhoSρ​ means steep walls surround the minimum.

For small ρ\rhoρ, a second-order approximation gives:

Sρ(w)≈ρ22λmax⁡(∇2L(w))S_\rho(w) \approx \frac{\rho^2}{2} \lambda_{\max}(\nabla^2 L(w))Sρ​(w)≈2ρ2​λmax​(∇2L(w))

where λmax⁡\lambda_{\max}λmax​ is the largest Hessian eigenvalue. Sharpness is dominated by the most sensitive direction — a single sharply curving direction makes the entire basin sharp, even if other directions are flat.

SAM#

A sharp minimum versus a flat minimum, with neighbourhood balls drawn

Sharpness measures how quickly the loss rises as you move away from a minimum. SAM explicitly minimises the worst loss in a neighbourhood rather than the loss at a point, pushing solutions toward wide, flat basins that tend to generalise better.

Sharpness-Aware Minimisation (SAMSharpness-Aware Minimization) explicitly optimises for flat minima by solving a min-max problem:

min⁡w  max⁡∥ε∥≤ρL(w+ε)\min_w \; \max_{\|\varepsilon\| \leq \rho} L(w + \varepsilon)minw​max∥ε∥≤ρ​L(w+ε)

The inner maximisation finds the worst perturbation ε∗\varepsilon^*ε∗ within radius ρ\rhoρ. The outer minimisation drives down the loss at the perturbed point, which forces the optimiser toward regions where the loss is uniformly low in a neighbourhood — i.e., flat basins.

Practical SAM step (first-order approximation):

  1. Ascent: Compute the gradient at www, and take a step in that direction: ε∗=ρ∇L(w)∥∇L(w)∥\varepsilon^* = \rho \frac{\nabla L(w)}{\|\nabla L(w)\|}ε∗=ρ∥∇L(w)∥∇L(w)​ This is the worst-case perturbation to first order (the gradient direction is steepest ascent).

  2. Descent: Compute the gradient at the perturbed point w+ε∗w + \varepsilon^*w+ε∗, and apply the optimiser update: w←w−η ∇L(w+ε∗)w \leftarrow w - \eta \,\nabla L(w + \varepsilon^*)w←w−η∇L(w+ε∗)

The key difference from standard SGD/AdamAdaptive Moment Estimation (optimizer): the gradient is evaluated at w+ε∗w + \varepsilon^*w+ε∗, not at www. This costs roughly twice as much per step (two forward/backward passes), but the improvement in generalisation often justifies the overhead. In practice, SAM is typically applied on top of an existing optimiser (SGDStochastic Gradient Descent or AdamAdaptive Moment Estimation (optimizer)), replacing the gradient in step 2.

Role of ρ\rhoρ. The radius ρ\rhoρ controls how wide a neighbourhood is considered:

  • Too small: SAM reduces to standard training (no sharpness penalty).
  • Too large: the perturbation overshoots the basin entirely, and the ascent step may point toward a different basin — unhelpful noise.
  • A typical range for ρ\rhoρ in image classification is 0.050.050.05 to 0.20.20.2 (for normalised inputs); it requires tuning.

Large-Batch Connection#

Week 10 noted that large-batch training often converges to sharper minima. The mechanism: large batches produce lower-variance gradient estimates, which behave more like full-batch gradient descent. Full-batch GD gravitates toward the nearest local minimum — often a sharp one — while noisy SGDStochastic Gradient Descent can "bounce out" of sharp basins and into flatter ones.

SAM can be seen as explicitly injecting the flatness-seeking behaviour that small-batch noise provides implicitly. Several studies have shown that SAM + large-batch training can recover (or exceed) the generalisation of small-batch training while retaining the computational benefits of large batches.

Limits of the Story#

The flatness–generalisation connection, while empirically useful, has well-documented caveats:

  1. Flatness definitions disagree. Hessian-based sharpness, adversarial sharpness (max⁡∥ε∥≤ρ\max_{\|\varepsilon\| \leq \rho}max∥ε∥≤ρ​), and PAC-Bayes sharpness can rank minima differently. There is no single agreed-upon metric.
  2. Sharp minima can generalise. By rescaling weights (e.g., multiplying one layer by α\alphaα and the next by 1/α1/\alpha1/α), one can make a network arbitrarily sharp or flat without changing its function — a reminder that parameter-space geometry does not perfectly capture function-space behaviour.
  3. Correlation, not causation. Flatness and generalisation are correlated in standard training regimes, but correlation weakens under distribution shift, architecture changes, and non-standard data augmentation.
  4. SAM is not a silver bullet. It improves generalisation in many settings but adds computational cost and an extra hyperparameter (ρ\rhoρ). For some tasks, standard training with good regularisation (weight decay, data augmentation, dropout) matches or exceeds SAM.

Despite these caveats, the flatness lens is a productive diagnostic tool — when your model is not generalising as expected, checking the sharpness of the converged solution can reveal whether the optimiser is getting stuck in overly narrow basins.

Knowledge check#

Exercise · Fill in the blank

In one SAM iteration, the correct order of operations is: first compute $\varepsilon^*$ via gradient ____, then compute the descent gradient at $w + \varepsilon^*$.

Question 1 of 3

The SAM objective $min_w max_{| arepsilon| leq ho} L(w + arepsilon)$ encourages the optimiser to find:

The global minimum
Sharp minima
Flat minima where the loss is uniformly low in a neighbourhood
Minima with zero loss

Browser lab#

On a 1D loss with both a deep sharp basin and a wide flat basin, compare GD vs SAM-style steps from the same three starts. Plot the trajectories and final positions. The interesting panel is the one started on the ridge between the two basins: GD rolls down into the sharp minimum, while SAM's ascent step lands on the far side of the ridge, so its descent points into the flat basin instead. SAM pays for this — it ends with a higher loss than GD, which is the honest trade: it buys a flatter neighbourhood, not a better training loss.

python · runs in browser
import numpy as np
import matplotlib.pyplot as plt

# A landscape with BOTH kinds of basin: a deep narrow one (curvature ~24) and a
# wide shallow one (curvature ~2.4). Both are genuine local minima with a ridge
# between them, so "which minimum an optimizer finds" is a real question.
def loss(w):
    return 0.02 * w**2 - 3.0 * np.exp(-4.0 * (w + 1.0)**2) - 2.4 * np.exp(-0.5 * (w - 0.2)**2)

def grad(w):
    return (0.04 * w
            + 24.0 * (w + 1.0) * np.exp(-4.0 * (w + 1.0)**2)
            + 2.4 * (w - 0.2) * np.exp(-0.5 * (w - 0.2)**2))

eta, rho, n_steps = 0.05, 0.2, 400
init_vals = [-1.4, -0.1, 0.7]

def sam_escape(w0):
    """GD and SAM trajectories from the same start."""
    w_gd, w_sam = w0, w0
    path_gd, path_sam = [w_gd], [w_sam]
    for _ in range(n_steps):
        w_gd = w_gd - eta * grad(w_gd)
        g = grad(w_sam)
        eps = rho * g / (np.abs(g) + 1e-8)   # ascent step of size rho
        w_sam = w_sam - eta * grad(w_sam + eps)
        path_gd.append(w_gd)
        path_sam.append(w_sam)
    return path_gd, path_sam

fig, axes = plt.subplots(1, 3, figsize=(15, 5))
final = {}
for idx, w0 in enumerate(init_vals):
    path_gd, path_sam = sam_escape(w0)
    final[w0] = (path_gd[-1], path_sam[-1])

    ax = axes[idx]
    w_plot = np.linspace(-2.0, 1.6, 500)
    ax.plot(w_plot, loss(w_plot), "k-", linewidth=1, alpha=0.4, label="Loss $L(w)$")
    ax.scatter(path_gd, loss(np.array(path_gd)), c="blue", s=4, alpha=0.5, label="GD")
    ax.scatter(path_sam, loss(np.array(path_sam)), c="red", s=4, alpha=0.5, label="SAM")
    ax.plot(path_gd[-1], loss(path_gd[-1]), "bo", markersize=8, label=f"GD final ({path_gd[-1]:.2f})")
    ax.plot(path_sam[-1], loss(path_sam[-1]), "ro", markersize=8, label=f"SAM final ({path_sam[-1]:.2f})")
    ax.set_xlabel("$w$")
    ax.set_ylabel("$L(w)$")
    ax.set_title(f"Start $w_0 = {w0}$")
    ax.legend(fontsize=8)
    ax.grid(True, alpha=0.2)

plt.tight_layout()
plt.show()

print("Final positions and losses:")
for w0 in init_vals:
    w_gd, w_sam = final[w0]
    print(f"  w0={w0:4}: GD -> w={w_gd:.3f}, L={loss(w_gd):.3f}"
          f" | SAM -> w={w_sam:.3f}, L={loss(w_sam):.3f}")

# How sharp is each basin? Max loss rise inside a radius-rho ball around its floor.
print("\nBasin sharpness (max loss rise within rho):")
for name, w0 in [("sharp basin", -1.4), ("flat basin", 0.7)]:
    wb = w0
    for _ in range(n_steps):
        wb = wb - eta * grad(wb)
    print(f"  {name}: w={wb:.3f}, L={loss(wb):.3f}, "
          f"sharpness={max(loss(wb + rho), loss(wb - rho)) - loss(wb):.3f}")

print("Notice: from the ridge at w0=-0.1 GD rolls into the deep sharp basin, while SAM's "
      "ascent step lands on the flat side and it settles in the wide flat basin -- a higher "
      "loss (-2.41 vs -4.19) bought for a much flatter neighbourhood (measured sharpness "
      "0.031 vs 0.458).")

Further Reading#

  • Pierre Foret, Ariel Kleiner, Hossein Mobahi & Behnam Neyshabur, "Sharpness-Aware Minimization for Efficiently Improving Generalization" (ICLR 2021) — the SAM paper. Freely available at arXiv:2010.01412.
  • Sepp Hochreiter & Jürgen Schmidhuber, "Flat Minima" (Neural Computation, 1997) — the original flatness argument.
  • Nitish Shirish Keskar et al., "On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima" (ICLR 2017) — sharpness and generalisation.
← Previous
Week 11: Automatic Differentiation
Next →
Week 13: Landscapes and Implicit Bias
On this page
  • Loss Geometry Beyond Value
  • Measuring Sharpness
  • SAM
  • Large-Batch Connection
  • Limits of the Story
  • Knowledge check
  • Browser lab
  • Further Reading