REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Own both passes of a sharpness-aware optimizer step

Execute one SAM update with the supplied optimizer. closure returns a differentiable scalar loss and does not call backward. Compute the global first-pass norm, perturb trainable parameters in that direction by rho, recompute gradients, restore exact original parameter values and apply exactly one optimizer step using second-pass gradients. Always restore parameters and clear gradients if the second pass fails. Reject invalid rho, nonfinite losses/gradients, duplicate or incomplete optimizer ownership. This fixture uses deterministic layers without BatchNorm or dropout; stateful stochastic layers need a separate replay/buffer policy.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Own both passes of a sharpness-aware optimizer step →

Your task

Execute one SAM update with the supplied optimizer. closure returns a differentiable scalar loss and does not call backward. Compute the global first-pass norm, perturb trainable parameters in that direction by rho, recompute gradients, restore exact original parameter values and apply exactly one optimizer step using second-pass gradients. Always restore parameters and clear gradients if the second pass fails. Reject invalid rho, nonfinite losses/gradients, duplicate or incomplete optimizer ownership. This fixture uses deterministic layers without BatchNorm or dropout; stateful stochastic layers need a separate replay/buffer policy.

Starter

import math
import torch

def sam_step(model, optimizer, closure, rho=.05):
    # TODO: implement sam_step under the declared contract.
    return None
Inspect the worked answer
import math
import torch

def sam_step(model, optimizer, closure, rho=.05):
    if not math.isfinite(rho) or rho<0:raise ValueError('rho must be finite and nonnegative.')
    params=[p for p in model.parameters() if p.requires_grad]
    owners=[p for g in optimizer.param_groups for p in g['params']]
    if not params or len(owners)!=len(params) or {id(p) for p in owners}!={id(p) for p in params}:
        raise ValueError('Each trainable parameter must have exactly one optimizer owner.')
    original=[p.detach().clone() for p in params]
    optimizer.zero_grad(set_to_none=True)
    try:
        first=closure()
        if first.numel()!=1 or not torch.isfinite(first):raise ValueError('Loss must be finite and scalar.')
        first.backward()
        gradients=[p.grad for p in params if p.grad is not None]
        if not gradients or any(not torch.isfinite(g).all() for g in gradients):raise ValueError('Finite gradients required.')
        norm=torch.stack([g.detach().double().norm() for g in gradients]).norm().item()
        with torch.no_grad():
            for p in params:
                if p.grad is not None:p.add_(p.grad,alpha=rho/(norm+1e-12))
        optimizer.zero_grad(set_to_none=True)
        second=closure()
        if second.numel()!=1 or not torch.isfinite(second):raise ValueError('Second loss must be finite.')
        second.backward()
        if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in params):raise ValueError('Second gradients must be finite.')
    except BaseException:
        with torch.no_grad():
            for p,v in zip(params,original):p.copy_(v)
        optimizer.zero_grad(set_to_none=True)
        raise
    with torch.no_grad():
        for p,v in zip(params,original):p.copy_(v)
    optimizer.step()
    return {'loss':first.detach().item(),'perturbed_loss':second.detach().item(),'norm':norm}

About this algorithm

How Own both passes of a sharpness-aware optimizer step works

The idea

Sharpness-aware minimization, SAM, looks for weights that sit in a wide, flat valley of the loss instead of a narrow one, because flat minima often hold up better on new data. To get there, each update uses the gradient at the worst nearby point in place of the gradient at the current weights.

That takes two passes. The first gradient points uphill, so sam_step moves the weights a total distance of rho in that direction, using one norm computed over all gradients. The second pass computes the loss and gradient at that perturbed point. The weights are then restored exactly, and the optimizer takes its single step with the second gradient. If the second pass fails, the original weights are still put back and the gradients cleared.

How it works

  1. Check rho and that every trainable parameter belongs to exactly one optimizer group, then clone the parameters into original.
  2. Call closure() and backward() for the first gradients, rejecting a non-finite loss or gradient.
  3. Compute one global norm over all gradients and add rho * grad / (norm + 1e-12) to each parameter under no_grad.
  4. Zero the gradients, then call closure() and backward() again at the perturbed weights.
  5. Copy original back into the parameters; on any exception, do the same, clear the gradients and re-raise.
  6. Call optimizer.step() once with the second-pass gradients and return loss, perturbed_loss and norm.

What it costs

Passes
2 forward, 2 backward
Optimizer
1 step per update
Memory
one copy of the weights

Each update costs about twice a normal training step, because the loss and its gradient are computed at two points.

Where it is used

  • Foret and co-authors introduced SAM in 2020 and reported better accuracy for image classifiers on CIFAR and ImageNet.
  • Chen, Hsieh and Gong showed that with SAM, Vision Transformers trained from scratch on ImageNet can outperform ResNets of similar size.
  • Optax, the gradient processing library for JAX, includes a SAM implementation in optax.contrib.

Watch out for

  • Calling optimizer.step() while the weights are still perturbed, so the update is applied from the wrong starting point.
  • Normalising each parameter's gradient separately: the perturbation needs one global norm so that its total length is rho.
  • Using it unchanged with BatchNorm or dropout: running statistics update twice and the two passes draw different masks. This Lab's fixture has neither.