Simulate a dynamic loss scaler for mixed-precision training

Why it matters Every fp16 mixed-precision training run relies on a dynamic loss scaler, and its log of skipped steps is the first thing to check when loss spikes.

In fp16 training, small gradients underflow to zero, so the loss is multiplied by a large scale before backward. If any gradient overflows, the step is skipped and the scale is cut; after a run of clean steps the scale grows again.

Write loss_scaler(overflow, init_scale, growth_interval, min_scale=1.0). overflow is a list of booleans, one per step. Keep a counter of consecutive clean steps. At each step, record the scale used. If overflow: skip the step, halve the scale (but not below min_scale) and reset the counter. Otherwise: apply the step, add 1 to the counter, and if the counter reaches growth_interval, double the scale and reset the counter. Return (scales_used, applied_steps, final_scale) where applied_steps lists the indices of steps that were applied.

Signaturedef loss_scaler(overflow, init_scale, growth_interval, min_scale=1.0)

Example

overflow [False, False, True, False, False, False], init 8, interval 2 gives ([8, 8, 16, 8, 8, 16], [0, 1, 3, 4, 5], 16).

Understand the idea

A loss scaler is like adjusting a microphone's volume. Too low and quiet voices (tiny gradients) are lost as zero; too high and loud voices clip (overflow to infinity). The scaler turns the volume up slowly after a quiet stretch and cuts it in half the moment anything clips, throwing away that one recording. Worked example: start at 8, grow every 2 clean steps. Steps 0 and 1 are clean, so the scale doubles to 16. Step 2 overflows at 16: skipped, scale back to 8, counter reset. Steps 3 and 4 are clean, so 16 again for step 5. Rule: overflow, so s = max(min, s / 2) and reset; else count, and double after N clean steps. bf16 has a much wider range, which is why bf16 training usually does not need this.

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

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

  • Sample 1: exampleloss_scaler([False, False, True, False, False, False], 8, 2)
  • Sample 2: counter resetloss_scaler([False, True, False, False, True, False, False, False], 1024, 3)