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.
Prepare offline
Choose Download entire course or Download entire category first. After completion, code and checks run locally on CPU. The independent example needs no account, remote service or API key.
import torch
w = torch.tensor([3., 4.])
print(w / w.norm())Review the evidence
Explain which gradient is used and when optimizer state advances. A stochastic or stateful model additionally needs an explicit policy for randomness and running buffers; passing this deterministic fixture does not resolve that policy.
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.
The explanation opens here once every check passes.