Compute the Noam warmup learning rate

Why it matters Warmup then inverse-sqrt decay is still the default for many seq2seq trainers.

The original transformer used a schedule that rises linearly during warmup, then decays with the inverse square root of the step.

Write noam_lr(step, d_model, warmup, factor=1.0). Return factor * d_model^-0.5 * min(step^-0.5, step * warmup^-1.5) for step >= 1.

Signaturedef noam_lr(step, d_model, warmup, factor=1.0)

Example

noam_lr(4000, 512, 4000) is 512^-0.5 * 4000^-0.5, about 0.000699.

Understand the idea

Transformers are fragile at the start of training, so the learning rate first rises linearly during a warmup period, then decays like one over the square root of the step. The peak sits exactly at the end of warmup, and the size is scaled down for wider models by d_model^-0.5. Worked example: d_model 256 (so 256^-0.5 = 1/16 = 0.0625), warmup 100, factor 1. Note 100^-1.5 = 0.001. Step 25: min(25^-0.5, 25 * 0.001) = min(0.2, 0.025) = 0.025, giving 0.0625 * 0.025 = 0.00156. Step 100: min(0.1, 0.1) = 0.1, giving 0.00625, the peak. Step 400: min(0.05, 0.4) = 0.05, giving 0.003125. Rule: lr = factor * d_model^-0.5 * min(step^-0.5, step * warmup^-1.5) for step >= 1. Using max instead of min gives a huge rate at step 1. Used in: the original transformer for translation, and warmup plus decay schedules that most LLM training still uses in some form.

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

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplenoam_lr(4000, 512, 4000)
  • Sample 2: warmupnoam_lr(100, 512, 4000)
  • Test 3: decaynoam_lr(40000, 512, 4000, 2.0)