Your loss explodes after a few steps. What do you check first?
Question
This code learns delivery time from distance with one weight w and gradient descent. The best answer is w = 10 minutes per km. Instead, the loss grows at every step:
step 0: w=0.0, loss=467 step 1: w=28.0, loss=1512 step 2: w=-22.4, loss=4899 step 3: w=68.3, loss=15872
Why does the loss explode? What do you check first? Which learning rates are safe for this data?
x = [1, 2, 3] # distance, km y = [10, 20, 30] # delivery time, minutes w, lr = 0.0, 0.3 for step in range(4): errors = [w * xi - yi for xi, yi in zip(x, y)] loss = sum(e * e for e in errors) / len(x) # mean squared error print(f"step {step}: w={w:.1f}, loss={loss:.0f}") grad = 2 * sum(e * xi for e, xi in zip(errors, x)) / len(x) w -= lr * grad
Show hints (3)
- "WATCH W"
The best
wis 10. Look wherewlands after each step: 28, then −22.4, then 68.3. Is the direction of the step wrong, or its size? - "SHAPE OF THE LOSS"
As a function of
w, this loss is a parabola:(14/3) × (w − 10)². Each step multiplies the distance to 10 by1 − lr × 28/3. What is that atlr0.3? - "THE LIMIT"
The distance shrinks only when
lr × 28/3is between 0 and 2. Solve that forlr.
Show checked explanation
The learning rate is too high. Each step points the right way but jumps past the minimum and lands farther away, so the loss grows. Here every step multiplies the distance to the best w by −1.8. Check the learning rate first: try one 10 times smaller. On this data, any lr below 3/14 ≈ 0.214 works.
x = [1, 2, 3] # distance, km y = [10, 20, 30] # delivery time, minutes # The loss is a parabola in w. Its curvature sets the largest safe step. curvature = 2 * sum(xi * xi for xi in x) / len(x) print(f"curvature {curvature:.2f}, lr must stay below {2 / curvature:.3f}") for lr in [0.3, 0.1]: w, losses = 0.0, [] for step in range(4): errors = [w * xi - yi for xi, yi in zip(x, y)] losses.append(sum(e * e for e in errors) / len(x)) grad = 2 * sum(e * xi for e, xi in zip(errors, x)) / len(x) w -= lr * grad print(f"lr={lr}: loss " + ", ".join(f"{loss:.1f}" for loss in losses))
curvature 9.33, lr must stay below 0.214 lr=0.3: loss 466.7, 1512.0, 4898.9, 15872.4 lr=0.1: loss 466.7, 2.1, 0.0, 0.0
Code run on CPython 3.12 against the example above. Checked by an editor other than the author.
Walkthrough
Write the loss as a function of w. With distances 1, 2 and 3 it is (14/3) × (w − 10)²: a parabola with its bottom at 10. How steep it is, the curvature, is 2 × mean(x²) = 28/3 ≈ 9.33.
A gradient step moves w by lr × gradient. On a parabola, that multiplies the distance to the bottom by 1 − lr × 9.33:
| lr | factor | what happens |
|---|---|---|
| 0.05 | 0.53 | slow, steady approach |
| 0.1 | 0.07 | fast approach |
| 0.15 | −0.4 | jumps over 10, still gets closer |
| 0.3 | −1.8 | jumps over 10, lands farther away |
The loss is the squared distance times 14/3, so it changes by the factor squared. At lr 0.3 that is 3.24. That is why 467 becomes 1512, then 4899. The minus sign is why w swings from 28 to −22.4 to 68.3.
The distance shrinks when the factor is between −1 and 1. So lr × 28/3 must be between 0 and 2, which means lr < 3/14 ≈ 0.214. At exactly 3/14, w would bounce between 0 and 20 forever. This exact limit is for plain gradient descent with a fixed lr on this loss. With many weights, the steepest direction sets it: lr < 2 / largest curvature.
The usual causes of an exploding loss all make the step too long:
- The learning rate itself. Check it first, because it is the cheapest to change.
- Unscaled features. Measure distance in metres (1000, 2000, 3000), and the curvature grows a million times. Now even
lr0.1 explodes. Scale the features. - A summed loss instead of a mean. The gradient grows with the number of rows. Here, with 3 rows,
lr0.1 on the summed loss acts like 0.3 on the mean.
Common mistakes
- Rewriting the gradient code first. Here the gradient points toward 10 at every step. The steps are just too long. Try a smaller learning rate before you change anything else.
- Switching from a mean loss to a sum, or using bigger batches with a summed loss, and keeping the same learning rate. Each step gets longer.
- Forgetting to scale features. A learning rate that works with km explodes with metres.
- Waiting for an exploded run to recover. Once a weight is
nan, every later step isnantoo. Stop the run, lower the learning rate and restart from the last good checkpoint.
Follow-up questions
- "The loss turned into nan. What happened?" Often the same explosion. The numbers grew until they overflowed to
inf, and then a step likeinf − infgavenan. Find the first step where the loss jumps. Also check the data fornanvalues and the loss for alog(0). - "Do Adam or gradient clipping fix this?" They help. Gradient clipping caps the size of the gradient, so one steep spot can't throw the weights far away. Adam scales each weight's step by the size of its recent gradients. Both still need a sensible learning rate, and neither fixes unscaled features or bad data.
- "The model has two parameters,
wandb. How do you update them?" Compute both gradients from the same oldwandb, then update both. If you use the newwto compute the gradient forb, you run a different algorithm.
What a strong answer covers
Reads the swinging w as overshooting, not as a wrong gradient. Explains the factor 1 − lr × curvature and the limit lr < 2 / curvature. Checks in order: the learning rate, feature scale, a summed versus a mean loss, then the data.
Open in interactive practice deck →