All courses

Gradient clipping and loss spikes

Clip the global gradient norm to a threshold and explain how this bounds the size of each update. Describe loss spikes in large runs and common responses: skipping batches or rewinding to a checkpoint.

Builds on: Vanishing and exploding gradients, The LLM training loop

▶ Watch this lesson Start the whole course

What the animation says

One bad step

A big training run: loss falls smoothly for days. Then, within a few steps, it jumps up. That's a loss spike. Sometimes loss recovers. Sometimes it diverges, and every step since the last good checkpoint is wasted. Watch the lower chart: the gradient norm often surges first. So how do we stop one huge gradient from throwing the model off course?

A speed limit

Gradient descent moves the parameters against the gradient, scaled by the learning rate. Normally the gradient is short, so the step is small. But a bad batch, or exploding gradients, can return a gradient a thousand times longer. One step lands far away, where loss is high. Gradient clipping is a speed limit. If the gradient is longer than a threshold c, shrink it to length c. Same direction, shorter arrow. Now a gradient of length 0.4 arrives, and c is 1. What does clipping do?

One norm over everything

Right: short gradients pass untouched. A model has many tensors. Take two: a bias gradient, three and zero, and a weight gradient, zero and four. Treat all entries as one vector. Its length: square root of nine plus sixteen, which is five. With c equal to one, every entry is multiplied by one fifth. That gives 0.6 and 0.8, total length one. Now suppose each tensor is clipped to one separately. What comes out?

Global keeps direction

Per tensor, you get one-zero and zero-one. The three-to-four ratio becomes one-to-one, so the arrow bends. Global clipping uses one scale for all tensors, so the direction is kept exactly. And the step is bounded. With plain gradient descent and learning rate 0.1, this update has size 0.1 instead of 0.5. In general, each step is at most learning rate times c. A typical c is 1. Optimizers covered later rescale each parameter, so they don't inherit this bound exactly.

Where it runs

In code, it's a few short lines. These two lines sum the squares of every tensor, then take one square root: the global norm. This line picks the scale: one, or c over the norm, whichever is smaller. The max guards against dividing by zero. Then every tensor is multiplied by that same scale. Now place it in the training loop. Drag clip into the right slot.

When a spike hits anyway

Backward, clip, then step. Clipping caps each step, but a spike can still build up over many steps, and the cause may be a bad batch. First response: skip the batch. If the norm is extreme, say over a hundred, drop that update entirely. Second: rewind. Reload a checkpoint from before the spike, and resume on different batches, skipping the ones seen around it. Sometimes with a lower learning rate, too. Remember: one global norm, one shared scale. And when a spike hits, skip or rewind.

One bad step can wreck a long run

In a big training run, loss falls smoothly for days, then jumps up within a few steps. This is a **loss spike**. Sometimes loss recovers. Sometimes it **diverges**, and every step since the last saved good state is wasted. A spike often shows first as a surge in the gradient norm. How do you stop one huge gradient from throwing the parameters off course? And what do you do when a spike happens anyway?

Cap the step's length, keep its direction

Sometimes one backward pass returns a gradient 1000× larger than usual. This can come from **exploding gradients** or from an unusual batch. Gradient descent moves the parameters by $-\eta g$, so a single such step can land far from where training was, in a region where loss is high. **Gradient clipping** is a speed limit. If the whole gradient is longer than a threshold $c$, shrink it to length $c$. The direction stays the same. Normal-sized gradients pass through untouched.

Global-norm clipping and the update bound

Treat every gradient entry in the model as one long vector $g$: $$\|g\| = \sqrt{\textstyle\sum_i g_i^2}\quad(\text{over all tensors})$$ $$\hat g = g\cdot\min\!\left(1,\ c/\|g\|\right)$$ Then $\|\hat g\| = \min(\|g\|, c) \le c$. With plain gradient descent, $\Delta\theta = -\eta\hat g$, so $\|\Delta\theta\| \le \eta c$ on every step. Using one **global** norm rescales all tensors by the same factor, so the direction is kept exactly. A typical value is $c = 1.0$. (This exact bound is for plain gradient descent. Optimizers covered later rescale each parameter's step and don't inherit it exactly.)

Clipping a two-tensor gradient

Take a bias gradient $[3, 0]$ and a weight gradient $[0, 4]$. 1. Global norm: $\sqrt{9+16} = 5$. 2. With $c = 1$, the scale is $1/5 = 0.2$, giving $[0.6, 0]$ and $[0, 0.8]$, with norm 1. 3. With $\eta = 0.1$, the update has size $0.1$ instead of $0.5$. If you clipped each tensor separately to 1, you would get $[1,0]$ and $[0,1]$. The 3:4 ratio becomes 1:1, so the direction is distorted.

Clip between backward and step; skip extremes

Clipping goes after the backward pass and before the optimizer step. It caps each step, but a spike can still build up, and its cause may be a bad batch. Common responses: - **Skip the batch:** drop the update when the norm is extreme. - **Rewind:** reload a checkpoint from before the spike and resume on *different* batches, skipping the ones seen around it, sometimes with a lower $\eta$.
import numpy as np
def clip_global(grads, c):
    norm = np.sqrt(sum((g**2).sum() for g in grads))
    scale = min(1.0, c / max(norm, 1e-12))
    return [g * scale for g in grads], norm

# in the loop: backward pass -> clip_global -> optimizer step
grads = [np.array([3.0, 0.0]), np.array([[0.0], [4.0]])]
clipped, norm = clip_global(grads, c=1.0)
print(norm, *[g.ravel() for g in clipped])  # 5.0 [0.6 0. ] [0.  0.8]
skip = norm > 100.0  # extreme norm: drop this update entirely
print(skip)          # False

What to remember

Compute one norm over all gradients. If it exceeds $c$, scale the whole gradient down to length $c$. The direction is kept, and each plain gradient-descent step is at most $\eta c$. Clipping tames single bad steps but not every loss spike. When a spike hits, skip the offending batch, or rewind to an earlier checkpoint and resume on different batches.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.