There are two ways to clip a gradient and they're often treated as the same thing. Take the gradient (0.3, 0.4, 12). Its length is 12.01 and nearly all of that is in the last entry. If you clip each value to 1 you get (0.3, 0.4, 1), which points 24.2 degrees away from where you started. If you clip the norm to 1 you get (0.025, 0.033, 0.999), and the angle is zero.
import numpy as np
def clip_value(g, c): return np.clip(g, -c, c)
def clip_norm(g, c): return g * min(1.0, c / np.linalg.norm(g))
g = np.array([0.3, 0.4, 12.0])
for f in (clip_value, clip_norm):
h = f(g, 1.0)
cos = h @ g / np.linalg.norm(h) / np.linalg.norm(g)
print(f.__name__, h.round(4), np.degrees(np.arccos(min(1, cos))).round(1))
When you clip the norm you're taking a shorter step the same way. When you clip the values you've cut down the one big entry and left the others alone, so they count for far more than they did.
With more parameters it's worse
Real gradients have heavy tails, so I drew 2,000 random ones with 1,000 entries each from a Student t with 2 degrees of freedom and clipped every value to 1. The median angle between the clipped gradient and the original was 51 degrees. I wouldn't read too much into that exact number since your gradients won't follow a Student t, but it does show you how far off you can be without anything looking wrong.
It isn't always a bad thing to change the direction (Adam does, because it divides each entry by its own running scale). I just think you'd want to know that you're doing it. Also, value clipping doesn't limit the length of the step in the way people expect. Three entries clipped to 1 could still be 1.73 long, and a million of them could be 1,000.
Clip all the layers together
The other mistake I'd look for is clipping the norm one layer at a time. Suppose one layer's gradient is (3, 4) and another's is (0.3, 0.4). If you clip each to 1 on its own you get (0.6, 0.8) and (0.3, 0.4), so a layer that was ten times the size is now only twice the size. If you work out one norm over both and scale them together you get (0.597, 0.796) and (0.060, 0.080), and they've kept their ratio. In PyTorch clip_grad_norm_ does that for you as long as you pass it all the parameters in one call.
Make sure you clip after the backward pass and before the optimiser step, and if you're using mixed precision you need to unscale the gradients first. I'd also log the norm before clipping, because if you're clipping on nearly every step then your learning rate's probably too high.
There's a version you can run with tests, and the questions you might be asked on it, at https://academicquant.co.uk/ml-gradient-clipping?utm_source=devto&utm_medium=post&utm_campaign=devto-gradient-clipping-direction
Top comments (0)