AdamW with linear warmup and cosine decay

HardOptimizersPro

LLM pre-training uses AdamW plus a learning-rate schedule: ramp up linearly, then decay along a cosine curve.

Schedule for step t (1-based) with peak lr_max, warmup W, total T:
- t <= W: lr = lr_max * t / W
- otherwise: lr = lr_min + 0.5 (lr_max - lr_min)(1 + cos(pi (t - W) / (T - W)))

AdamW step: do the normal Adam update with that lr (b1=0.9, b2=0.999, eps=1e-8), and separately apply decoupled weight decay w -= lr * wd * w, using w from before this step.

Write train_adamw(grad_fn, w0, lr_max, lr_min, W, T, wd). Run T steps and return (final_w, list_of_lrs).

Signaturedef train_adamw(grad_fn, w0, lr_max, lr_min, W, T, wd)

Understand the idea

Large models train with a learning-rate schedule: start small and ramp up linearly (warmup) while Adam's statistics settle, then glide down along half a cosine to lr_min. AdamW also shrinks weights directly by lr x wd x w, separate from the gradient, which keeps the decay from being cancelled by Adam's per-parameter scaling. Worked example: lr_max = 0.001, lr_min = 0, W = 2, T = 6. t = 1: 0.0005. t = 2: 0.001. t = 3: progress (3 - 2)/(6 - 2) = 0.25, cos(pi x 0.25) = 0.707, lr = 0.5 x 0.001 x 1.707 = 0.000854. t = 4: cos(pi/2) = 0, lr = 0.0005. t = 5: 0.000146. t = 6: cos(pi) = -1, lr = 0. Decay example: w = 2, lr = 0.001, wd = 0.1 removes 0.0002. Rule: warmup lr = lr_max t / W; after it lr = lr_min + 0.5 (lr_max - lr_min)(1 + cos(pi (t - W) / (T - W))); Adam step plus w -= lr wd w_old. LLM pre-training commonly uses exactly this setup.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: scheduletrain_adamw(_g, [0.0, 0.0], 0.1, 0.01, 3, 10, 0.1)[1]
  • Sample 2: final weightstrain_adamw(_g, [0.0, 0.0], 0.1, 0.01, 3, 10, 0.1)[0]