The (1 − 2ηλ) shrink term
Easy TrainingImplement SGD with L2 regularization (weight decay) from scratch. Adding a penalty λΣw² to the loss contributes 2λw to each weight's gradient, so every step multiplies the weight by a factor just below 1 — it decays toward (but never exactly to) zero.
Implement the class below. Use only basic PyTorch operations.
Use this code to debug before submitting. With grad = 0 each step should scale w by (1 − 2·lr·lam).
Try solving it yourself first! Click below to reveal the solution.
For interactive practice with auto-grading, run TorchCode locally:pip install torch-judge then use check("weight_decay")
L2 penalty → multiplicative weight decay: every step shrinks w by (1 − 2·lr·λ). This equals PyTorch's weight_decay=2λ (which adds wd·w to the gradient); L1 instead subtracts a constant and drives weights to exactly 0. Covered in DL Module 7 §12.