I noticed something odd when I was training some models the other day -- something
that went against my understanding of how PyTorch's Automatic Mixed Precision (AMP)
training tools worked. In particular, I believed that the GradScaler
class filtered out non-finite gradients -- that was based on this comment in the
AMP recipe page:
However, I was finding that the weights of a model I was training were all being set to NaNs, and while I could see ways that could happen even with finite gradients, none of those appeared to be happening.
Understanding your tools properly is an essential part of engineering, so I decided
to dig in and find out what was happening -- in particular, what I was misunderstanding
about what was going on. This post has the details, but so as not to bury the lede,
while the GradScaler does not let non-finite gradients through, that's more a side-effect
of its real purpose -- and if it gets into a sufficiently degenerate state, it will actually
filter non-finite gradients, but respond to good, finite ones by trashing your weights!
The good news is that it's only likely to do this if your model is in such a messed up state that your training run is doomed anyway. I don't think it can reasonably be called a bug, as a well-designed training run should have errored out anyway before it kicks in.
Here's how it works.
I was training a weight-tied model as part of my yak-shaving trajectory towards exploring the logit lens. Weight-tied models are fiddly to train -- you need to get your hyperparameters and the like just right, or they head off into infinite loss territory. But I'd spotted that the weights -- not just the loss -- in the last checkpoint for one of my failed training runs were all NaNs.
Now, I was using AMP, which -- as I said -- I believed would be filtering out non-finite gradients, so I was initially quite surprised by that. I was getting NaN for my loss, which would have led to NaN gradients, but those would have never been applied to the weights; only the finite gradients would. How could finite updates to finite weights make them non-finite?
Only one possibility came to mind: a non-finite value can wind up in a float because it overflowed. So you can imagine (slightly handwavily) that the training run might wind up in a regime where it kept bumping weights up, step after step, and eventually they would all overflow.
As a mechanism, it seemed plausible, so I decided to see if it was happening.
I added a new optional training parameter, log_model_norms, and if it was set,
in rank zero just after the code
to step the optimiser and the learning rate scheduler, we'd log the current model norms to a JSONL file:
if log_model_norms and rank == 0:
with torch.no_grad():
norms = {name: p.norm().item() for name, p in model.named_parameters()}
with open(run_dir / "model-norms.jsonl", "a") as f:
json.dump(
{"global_step": global_step, "norms": norms},
f
)
f.write("\n")
So: we'd log the L2 norm for each named parameter in the model. A named parameter in this sense is a parameter tensor: an unbiased linear layer would have just one, the weights matrix, while a biased one would have two, one for the weights and one for the biases. The L2 norm of a set of numbers is the square root of the sum of their squares, so it is a good proxy for the size of the numbers that make up each tensor.
With that, I kicked off another training run, ran it until it diverged, then asked Claude for some charting code to plot the norms over time for everything, treating their initial values as 100 so that they all worked in the same chart.
Here's what happened:
So that was entirely different to what I'd expected! All of the norms grew steadily but appeared to be settling down, but then it looked like they all blipped up to NaN on the same step. I checked the raw numbers to be sure -- and indeed, prior to step 17,186, the norms were finite, and then they all switched over to NaN in one go.
How could that happen if non-finite gradients were being filtered out by the
GradScaler? The answer lies in what the scaler is actually doing under the hood.
GradScaler works
Up until this point I'd been treating the GradScaler pretty much as a black box.
By following the recipe,
I knew that in order to use AMP, you would change a training step like this:
logits = model(inputs)
loss = torch.nn.functional.cross_entropy(
logits.flatten(0, 1), targets.flatten()
)
loss.backward()
optimizer.step()
...to this:
scaler = torch.amp.GradScaler()
with torch.amp.autocast(device_type=device.type, dtype=torch.float16):
logits = model(inputs)
loss = torch.nn.functional.cross_entropy(
logits.flatten(0, 1), targets.flatten()
)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
The torch.amp.autocast context manager would do calculations in 16-bit floating
point in cases where that would be relatively harmless, and in 32-bit if needed -- and the
scaler would... do something to make that work smoothly. I'd not really dug into
what. That felt like a gap!
Unfortunately the PyTorch docs are very light on what happens. There's the
recipe I linked to above,
which just says how to use it, and the
API docs for the GradScaler itself,
which just define the signature of the constructors for two deprecated versions of it,
both of which look like this:
class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True)
See torch.amp.GradScaler. torch.cuda.amp.GradScaler(args...) is deprecated. Please use torch.amp.GradScaler("cuda", args...) instead.
The text torch.amp.GradScaler is not a link, and as far as I've been able to discover
with copious searching, there is no docs page to see for it.
So I had to look elsewhere, and I found two pages on ApX Machine Learning that were invaluable:
After reading through those, I had the idea of asking an agent to dig around for the PyTorch
docs for the torch.amp.GradScaler. It also could not find them, but had the bright idea of checking the source --
and there we have
a nice docstring that explains things for us; I guess something went wrong in whatever
pipeline they use to generate the docs.
Let's try to summarise how it works, anyway. What is gradient scaling and why do we do it?
What we're trying to do is train a model with 32-bit floating point (FP32) weights, but do some of our calculations in 16-bit FP16 so that we get better performance. AMP does the FP16 calculations selectively, based on how important precision is for a particular operation, but for the purposes of this explanation, I'll just write as if all of the forward and backward pass happens in FP16.
The underlying issue is that FP16 has a smaller range than FP32. The Wikipedia page has lots of interesting details, but the relevant ones for our purposes are that FP16 can only handle numbers in the range from -65,504 to +65,504, and that there are similar issues in how small a number they can represent. Asking NumPy for the differences:
>>> import numpy as np
>>> info = np.finfo(np.float16)
>>> print(info.max)
6.55e+04
>>> print(info.min)
-6.55e+04
>>> print(info.smallest_normal)
6.104e-05
>>> print(info.smallest_subnormal)
6e-08
(The smallest "normal" number is the smallest one the format can support without losing precision -- if we trade off precision for scaling down, then we get into "subnormal" numbers.)
Let's compare that to FP32:
>>> info = np.finfo(np.float32)
>>> print(info.max)
3.4028235e+38
>>> print(info.min)
-3.4028235e+38
>>> print(info.smallest_normal)
1.1754944e-38
>>> print(info.smallest_subnormal)
1e-45
It has a much bigger range, and that mismatch can cause problems! In FP16, small values that would be representable in FP32 can underflow to zero, and likewise large ones can overflow to infinity.
Now, for the forward pass, we're kind of on our own -- if we get an overflow, we'll get infinity in our results and therefore non-finite values in our loss, and likewise underflows will just get rounded to zeros.
But in deep networks, very small or very large gradients are not uncommon even for "sane" loss values -- the classic problems of vanishing or exploding gradients. And the scaler can help with the backward pass that takes us from the loss to the gradients.
Let's say that normally we would have a loss of , so we would work out our gradient for a weight like this:
If there are numbers within the backward pass that works out the gradient that are represented in FP16, they might overflow or underflow. Let's imagine that in a particular case, the gradients are small enough to underflow.
Now imagine that instead, we multiplied the loss by some scaling factor before doing the partial derivative:
We'll imagine that is large enough it bumps up the numbers in the backward pass enough so that there's now no underflow. So we have a gradient -- great! -- but it's the wrong one, rather than .
However, because is just a constant scaling factor and is not expressed in terms of the on the bottom of the partial derivative, we can pull it out and rewrite that equation above as:
...which means that we can just substitute in from the first equation:
Or, to put it less mathematically -- if we scale up the loss by multiplying by , then work out our gradients, and then divide them by , we get the same results as we would without scaling. But, with the right value for , we dodge the risk of underflowing during our backward pass. Clearly, with , the same applies -- we'll scale the loss down and the resulting gradients up, so we can use that to try to avoid overflows.
This is exactly what the GradScaler does. You do your forward pass, and then call
scaler.scale(loss).backward()
...to scale it by a scaling factor and then do the backward pass. It starts off with set
to some particular value --
that init_scale=65536.0 in the docs above. After the backward pass
has worked out the gradients, you call the scaler's step function:
scaler.step(optimizer)
It checks for any NaN/infinite gradients, and:
Then you call update:
scaler.update()
That checks the notes from the call to step: if there were any NaN/infinite values, then it
assumes that the scaling factor is too large, and reduces it
by multiplying it by a constant -- that backoff_factor=0.5 in the docs.
Let's imagine that starts too high; in each step we get an overflow, so it will halve. This happens every time until it reaches an acceptable value. Additionally, if the correct value of changes over the course of the training run so that it needs to be reduced, the same backoff will happen over one or more steps.
Now, you've probably noticed that while this handles overflows, it doesn't do anything with underflows. That's because those are "invisible" to the scaler. An overflow will manifest as a NaN/infinity in a gradient, which is obviously a sign of a problem that the scaler can check for. But an underflow will just mean that something that should be small but non-zero is zero instead -- and zero is a perfectly fine value for a gradient.
Underflows are handled by the growth_factor=2.0 and the growth_interval=2000 in the docs. Let's say that the
scaler has been running for growth_interval steps with no reductions in the scale. That may be a sign that it's
doing its job, and the scale is calibrated correctly -- but it might be a sign that your
training run is getting underflows and doing nothing. So after growth_interval successful steps, update will
multiply the scaling factor by growth_factor so that the next step will try a higher one.
That might cause an overflow in the next step, of course -- but that would be immediately corrected by
a reduction in the scale, which would (hopefully) get things back into the right range. So the net effect
is that every growth_interval it will try making the scale a bit higher, so it will rise
gradually until it hits the maximum level it can be at without causing overflows, then
sit there, blipping up to an unsustainable number every growth_interval steps.
That's unbalanced, of course -- if we overflow, we rescale immediately, but if we're underflowing,
we rescale after a bunch of steps. But given that only overflows are visible to the scaler, it's
a reasonable balance. After all, if we rescaled upwards every time there were no non-finite values (that
is, set growth_interval to 1) then if we got to the right value, we'd be bouncing up to a higher
one every other step, and skipping half of them due to overflows.
Now, that does mean that if the scale factor is set too low at the start, then you'll
wind up with a bunch of wasted steps -- I think that is why the default starting value is
surprisingly high, at 65536.0 -- better to start with too high a value so that it will halve
each step until it's within range, than to start with too low a value and only scale it up
after 2,000 steps, and again after 2,000 more, and so on.
So, that's how the GradScaler works. It does, as I thought, skip non-finite gradients -- but
it's more as a side effect of its dynamic adjustment of the scaling factor than it is
an explicit feature. And that, finally, answers a question I had way back in February
when I was looking into gradient clipping --
why is the feature to skip non-finite gradients implemented as part of a tool designed for handling mixed-precision training?
It's not there as a deliberate choice -- it's just there as a result of how that tool
detects overflows.
Now that we know how it works, let's think about how it can fail.
Let's revisit the simplified AMP training loop:
with torch.amp.autocast(device_type=device.type, dtype=torch.float16):
logits = model(inputs)
loss = torch.nn.functional.cross_entropy(
logits.flatten(0, 1), targets.flatten()
)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
We know that the call to scaler.scale has multiplied our loss by , then we
did the (hopefully non-overflowing) backward pass, and then we call the scaler's
step and update.
step will skip the step, and update will reduce to try to bring
it within range.growth_interval
of them -- or will bump it up if it has reached that target.
What would happen if was zero?
If becomes zero, but we have finite gradients, then when we divide the gradients by , we get NaNs. And the NaN check has already happened, before the division -- so the scaler will ask the optimiser to apply NaN updates to the weights.
Obviously, you wouldn't set the scale to zero directly. But it can become zero with a long-enough series of dynamic backoffs. Imagine, for example, that you got repeated NaN losses on the forward pass, or the gradients repeatedly exploded to NaNs or infinity on the backward.
The scale is stored as a 32-bit float, so for the sake of argument, let's assume that for a particular step, it's set to 4096.0 (that specific number will become relevant later). If you get a series of non-finite gradients, then each time it will halve -- and eventually it will underflow and reach zero:
>>> import torch
>>> scale = torch.tensor(4096.0, dtype=torch.float32)
>>> for ii in range(10_000):
... scale = scale * 0.5
... if scale == 0:
... print(f"Zero after {ii + 1} steps")
... break
...
Zero after 162 steps
And it actually gets a bit worse. If we look at the code, it (as of this writing) scales the gradients down by using a reciprocal, like this:
inv_scale = (
self._scale.double().reciprocal().float()
if self._scale.device != torch.device("mps:0")
else self._scale.reciprocal()
)
found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device)
optimizer_state["found_inf_per_device"] = self._unscale_grads_(
optimizer, inv_scale, found_inf, False
)
self._scale is our , and (if we're not on Apple's GPU backend, which is the mps bit), it
works out inv_scale by converting to FP64, taking its reciprocal, and then converting back to FP32
-- then it multiplies gradients
by that reciprocal downstream in self._unscale_grads_. How small does self._scale
need to be before that becomes infinite?
>>> scale = torch.tensor(4096.0, dtype=torch.float32)
>>> for ii in range(10_000):
... scale = scale * 0.5
... if scale.double().reciprocal().float() == torch.inf:
... print(f"Hit an inf after {ii + 1} iterations at {scale}")
... break
...
Hit an inf after 140 iterations at 2.938735877055719e-39
So, if we start with a scale of 4096.0, a long string of steps where there are NaNs in the gradients can cause the scaler to adjust its scale to zero after 162 bad steps, or even just to a number that is so small that it's essentially zero -- in terms of what happens when you try to use it -- after 140 steps.
But wait, it gets worse again! You don't even need those NaN steps to be consecutive. Remember,
the scaler only adjusts the scale upwards after growth_interval steps of non-NaN
updates. The default interval is 2,000, so if you get, say, 140 steps with NaNs in
the loss after starting with 4096.0, so long as there are fewer than 2,000 steps with non-NaN loss between each of
them, you're in this death spiral. The scaler will keep reducing its scale factor, and
you'll wind up with garbage weights. This would happen even with one NaN, then up to 1,999
OK steps, then another NaN, then up to another 1,999 OK steps, and so on. So it's more
plausible than you might think!
So now let's take a look at what was happening in my training run -- the one that started all of this investigation.
Let's take a look at those weight norms again:
I really like Matplotlib's XKCD mode; the slightly wobbly hand-drawn lines reflect the uncertainty of measured values quite nicely. But this is a case where that's fighting against us. Let's look at how it would look if plotted normally (I'll stick to these more boring plots for the rest of this post):
There's something very clear there: you can see a tiny blip shortly after step 15,000, and then everything is completely flat. The norms don't change until they explode to NaNs at step 17,186. Looking at the raw data, I found that the point where the norms "locked" was just after step 15,368 -- for every step thereafter, they were identical, until the explosion.
So, that means that the norms were locked for the 1,817 steps from 15,369 to 17,185 inclusive. What was going on then?
I added code to log the losses (I was doing gradient accumulation over 16 microbatches, so each step had 16 losses) and the scaler's scaling factor:
if detailed_training_logging and rank == 0:
with torch.no_grad():
norms = {name: p.norm().item() for name, p in model.named_parameters()}
with open(run_dir / "detailed-log.jsonl", "a") as f:
data = {
"global_step": global_step,
"norms": norms,
"losses": train_losses[-gradient_accumulation_steps:],
}
if scaler is not None:
data["scaler_scale"] = scaler.get_scale()
json.dump(data, f)
f.write("\n")
...and kicked off the run again. When it was done, I asked Claude for some updated charting code to see what the results looked like.
The scaling factor first:
You can see that it bimbled around a bit (technical term) up until somewhere after step 15,000, then dropped off a cliff. Zooming in:
To be precise: the scale dropped to a level where dividing by it (specifically in the code, that reciprocal) would result in
infinity at step 15,509, and then fell to zero by step 15,531. And very neatly:
Those match up with the tests above -- when we started with 4096.0, then halved it each time until the reciprocals started failing, and until it reached zero. The reason for that starting point of 4096.0 was (as I assume you've guessed) that's what the scaler's scale happened to be for the step where the norms stopped changing.
That would suggest that every step from step 15,369 until 15,531, we got NaNs somewhere in the backward pass. Now, a NaN can potentially appear in the gradients even if the loss was finite, due to an exploding gradient overflowing. But the opposite does not hold: a NaN loss will always cause NaN gradients. So what did our losses look like?
My logging code was including them, so we can see a chart. Because each step had 16 losses, one for each microbatch in the step, the chart shows the average of the finite losses, and then has a red flag at the top if there are one or more non-finite losses.
...and zooming in to the area in question again:
You can (hopefully) see that from step 15,369 onwards, every step had at least one NaN. There were a couple of NaNs shortly prior to that (they're specifically at steps 15,352 and 15,360), and it recovered for a few steps, but then blew up completely. Additionally, the average finite losses had been declining reasonably smoothly over the run, but that first NaN at step 15,352 seemed to kick it into an upward trend, and then they got stuck at somewhere around 9 -- unsurprisingly not changing much, given that the model's weights were not changing, and we were just seeing the results of changing training data. The scaler was blocking all updates due to non-finite gradients.
Digging into the logs, the losses told the same story -- for every step after 15,368, there was at least one NaN in the losses. The model was broken, our losses were frequently NaNs, and the scaler wasn't allowing any updates through.
Additionally, looking at step 15,352 -- that first NaN loss above -- the scaler's scale was 524,288.0 there. Although the only NaN losses before the complete collapse at 15,369 were at steps 15,352 and 15,360, the scale also halved on steps 15,354, 15,356, 15,359, 15,361, and 15,364. That implies that even with the finite losses, we were pretty frequently getting non-finite gradients over that period -- like I said, NaN can potentially appear in the gradients even if the loss was finite, due to an exploding gradient overflowing.
So what happened at step 17,186 that triggered the update where all of the weights got trashed? That's where the NaN issue temporarily stopped. Let's look at its raw losses from the logs:
[8.589940071105957, 10.134101867675781, 7.456259250640869, 8.580881118774414, 8.039091110229492, 9.646912574768066, 8.769637107849121, 6.42511510848999, 9.974699974060059, 9.117472648620605, 9.377853393554688, 9.64299201965332, 9.239002227783203, 6.830324649810791, 10.035568237304688, 10.625506401062012]
They're all finite! And so now, we have our explanation:
And with that we were done. Guaranteed-finite gradients had overwritten all of our weights with NaNs due to a divide-by-zero in the scaler.
While researching this problem, I came across
this comment
from ptrblck on the PyTorch forums, writing to someone who'd seen a similar issue:
If your model outputs NaN values, the training is generally broken and I don’t know if the model can somehow recover from it. [...]
That's a really good point. Understanding this was an interesting puzzle -- and, at
least for me, has been a good way of getting to understand the reasoning behind and the
implementation of the GradScaler. But the issue with finite gradients trashing the model's
weights with NaNs is a downstream symptom of the real problem -- that the model had started
diverging and returning results that got NaN losses. Even in the worst-possible case
I outlined above, where NaNs appear with as many as growth_interval - 1 good steps between them, I think you
can make a solid case that something in the model is broken and that is what needs fixing.
The model I was working with when I hit this problem was one using weight tying, which I've found is very finicky about the hyperparameters and general training setup, and this specific training run used what I think is too low a value for the weight decay. And that's the underlying problem to fix.
But at least I now understand why it's failing in the specific counterintuitive way that it is. And that, I think, is worth a lot.