PythiloLesson 2 of 8 · progress kept in this browser

Practice in Lab: Own both passes of a sharpness-aware optimizer step →

Own both passes of a sharpness-aware optimizer step

Sharpness-aware training evaluates a nearby parameter vector before making the real update. Two forward passes are not two optimizer steps. The second gradient belongs to the perturbed model, while momentum and weight decay must update the original model exactly once. Reversing a floating-point perturbation by subtraction can leave rounding residue, so this exercise owns exact snapshots. Exception handling is part of the algorithm: a failed closure must never leave the live model perturbed.

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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.