{"slug": "the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights", "title": "The GradScaler implosion: how filtered-out NaN gradients became NaN weights", "summary": "A developer found that PyTorch's Automatic Mixed Precision GradScaler can drive model weights to NaN even though it filters non-finite gradients, because the scaler's real purpose is overflow avoidance and in a sufficiently degenerate state it responds to finite gradients by overflowing the weights. The developer added a log_model_norms training parameter that records each named parameter's L2 norm to a JSONL file at rank zero after each optimizer and learning-rate-scheduler step, and traced the failure while training a weight-tied model. The developer concluded the behavior is not reasonably a bug, since a well-designed training run should have errored out before reaching that state.", "body_md": "I noticed something odd when I was training some models the other day -- something\nthat went against my understanding of how PyTorch's Automatic Mixed Precision (AMP)\ntraining tools worked.  In particular, I believed that the [`GradScaler`](https://docs.pytorch.org/docs/2.15/amp.html#torch.cuda.amp.GradScaler)\nclass filtered out non-finite gradients -- that was based on this comment in the\n[AMP recipe page](https://docs.pytorch.org/tutorials/recipes/recipes/amp_recipe.html):\n\n```\n# ``scaler.step()`` first unscales the gradients of the optimizer's assigned parameters.\n# If these gradients do not contain ``inf`` s or ``NaN`` s, optimizer.step() is then called,\n# otherwise, optimizer.step() is skipped.\n```\n\nHowever, 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.\n\nUnderstanding your tools properly is an essential part of engineering, so I decided\nto dig in and find out what was happening -- in particular, what I was misunderstanding\nabout what was going on.  This post has the details, but so as not to bury the lede,\nwhile the `GradScaler` does not let non-finite gradients through, that's more a side-effect\nof its real purpose -- and if it gets into a sufficiently degenerate state, it will actually\nfilter non-finite gradients, but respond to good, finite ones by trashing your weights!\n\nThe 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.\n\nHere's how it works.\n\nI was training a weight-tied model as part of my [yak-shaving](https://www.gilesthomas.com/2026/11/yak-shaving)\ntrajectory towards exploring the [logit lens](https://www.lesswrong.com/posts/AcKRB8wDpdaN6v6ru/interpreting-gpt-the-logit-lens).\nWeight-tied models are fiddly to train -- you need to get your hyperparameters and the like\njust right, or they head off into infinite loss territory.  But I'd spotted that\nthe weights -- not just the loss -- in the last checkpoint for one of my failed training runs were all NaNs.\n\nNow, 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?\n\nOnly 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.\n\nAs a mechanism, it seemed plausible, so I decided to see if it was happening.\nI added a new optional training parameter, `log_model_norms`, and if it was set,\nin rank zero just after [the code](https://github.com/gpjt/ddp-base-model-from-scratch/blob/41ed23b8887e137789c9af05f10b86744b226d6d/ddp_train.py#L490)\nto step the optimiser and the learning rate scheduler, we'd log the current model norms to a JSONL file:\n\n```\n        if log_model_norms and rank == 0:\n            with torch.no_grad():\n                norms = {name: p.norm().item() for name, p in model.named_parameters()}\n                with open(run_dir / \"model-norms.jsonl\", \"a\") as f:\n                    json.dump(\n                        {\"global_step\": global_step, \"norms\": norms},\n                        f\n                    )\n                    f.write(\"\\n\")\n```\n\nSo: 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.\n\nWith that, I kicked off another training run, ran it until it diverged, then\nasked Claude for [some charting code](https://github.com/gpjt/ddp-base-model-from-scratch/blob/1c850909846d222dffe71e429237cee5042c5bfc/plot_model_norms.py)\nto plot the norms over time for everything, treating their\ninitial values as 100 so that they all worked in the same chart.\n\nHere's what happened:\n\nSo 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.\n\nHow could that happen if non-finite gradients were being filtered out by the\n`GradScaler`?  The answer lies in what the scaler is actually doing under the hood.\n\n`GradScaler` works\nUp until this point I'd been treating the `GradScaler` pretty much as a black box.\nBy following the [recipe](https://docs.pytorch.org/tutorials/recipes/recipes/amp_recipe.html),\nI knew that in order to use AMP, you would change a training step like this:\n\n```\n    logits = model(inputs)\n    loss = torch.nn.functional.cross_entropy(\n        logits.flatten(0, 1), targets.flatten()\n    )\n    loss.backward()\n    optimizer.step()\n```\n\n...to this:\n\n```\nscaler = torch.amp.GradScaler()\n\n    # ...into the training loop\n\n    with torch.amp.autocast(device_type=device.type, dtype=torch.float16):\n        logits = model(inputs)\n        loss = torch.nn.functional.cross_entropy(\n            logits.flatten(0, 1), targets.flatten()\n        )\n    scaler.scale(loss).backward()\n    scaler.step(optimizer)\n    scaler.update()\n```\n\nThe `torch.amp.autocast` context manager would do calculations in 16-bit floating\npoint in cases where that would be relatively harmless, and in 32-bit if needed -- and the\n`scaler` would... do something to make that work smoothly.  I'd not really dug into\nwhat.   That felt like a gap!\n\nUnfortunately the PyTorch docs are very light on what happens.  There's the\nrecipe I linked to above,\nwhich just says how to use it, and the\n[API docs for the `GradScaler` itself](https://docs.pytorch.org/docs/2.15/amp.html#torch.cuda.amp.GradScaler),\nwhich just define the signature of the constructors for two deprecated versions of it,\nboth of which look like this:\n\n`class torch.cuda.amp.GradScaler(init_scale=65536.0, growth_factor=2.0, backoff_factor=0.5, growth_interval=2000, enabled=True)`\n\nSee `torch.amp.GradScaler`. `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler(\"cuda\", args...)` instead.\n\nThe text `torch.amp.GradScaler` is not a link, and as far as I've been able to discover\nwith copious searching, there *is* no docs page to see for it.\n\nSo I had to look elsewhere, and I found two pages on ApX Machine Learning that were invaluable:\n\nAfter reading through those, I had the idea of asking an agent to dig around for the PyTorch\ndocs for the `torch.amp.GradScaler`.  It also could not find them, but had the bright idea of checking the source --\nand [there](https://github.com/pytorch/pytorch/blob/31a77fc9c0a7c6fff15a1ff58c743f53b1a9d457/torch/amp/grad_scaler.py#L54) we have\na nice docstring that explains things for us; I guess something went wrong in whatever\npipeline they use to generate the docs.\n\nLet's try to summarise how it works, anyway. What is gradient scaling and why do we do it?\n\nWhat 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.\n\nThe underlying issue is that FP16 has a smaller range than FP32.\nThe [Wikipedia page](https://en.wikipedia.org/wiki/Half-precision_floating-point_format)\nhas lots of interesting details, but the relevant ones for our purposes are that\nFP16 can only handle numbers in the range from -65,504 to +65,504, and that there are similar\nissues in how small a number they can represent.  Asking NumPy for the differences:\n\n``` python\n>>> import numpy as np\n>>> info = np.finfo(np.float16)\n>>> print(info.max)\n6.55e+04\n>>> print(info.min)\n-6.55e+04\n>>> print(info.smallest_normal)\n6.104e-05\n>>> print(info.smallest_subnormal)\n6e-08\n```\n\n(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.)\n\nLet's compare that to FP32:\n\n```\n>>> info = np.finfo(np.float32)\n>>> print(info.max)\n3.4028235e+38\n>>> print(info.min)\n-3.4028235e+38\n>>> print(info.smallest_normal)\n1.1754944e-38\n>>> print(info.smallest_subnormal)\n1e-45\n```\n\nIt 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.\n\nNow, 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.\n\nBut 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.\n\nLet's say that normally we would have a loss of , so we would work out our gradient for a weight like this:\n\nIf 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.\n\nNow imagine that instead, we multiplied the loss by some scaling factor before doing the partial derivative:\n\nWe'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 .\n\nHowever, 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:\n\n...which means that we can just substitute in from the first equation:\n\nOr, 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.\n\nThis is exactly what the `GradScaler` does.  You do your forward pass, and then call\n\n```\nscaler.scale(loss).backward()\n```\n\n...to scale it by a scaling factor  and then do the backward pass.  It starts off with  set\nto some particular value --\nthat `init_scale=65536.0` in the docs above.  After the backward pass\nhas worked out the gradients, you call the scaler's `step` function:\n\n```\n    scaler.step(optimizer)\n```\n\nIt checks for any NaN/infinite gradients, and:\n\nThen you call `update`:\n\n```\n    scaler.update()\n```\n\nThat checks the notes from the call to `step`: if there were any NaN/infinite values, then it\nassumes that the scaling factor is too large, and reduces it\nby multiplying it by a constant -- that `backoff_factor=0.5` in the docs.\n\nLet'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.\n\nNow, 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.\n\nUnderflows are handled by the `growth_factor=2.0` and the `growth_interval=2000` in the docs.  Let's say that the\nscaler has been running for `growth_interval` steps with no reductions in the scale.  That may be a sign that it's\ndoing its job, and the scale is calibrated correctly -- but it might be a sign that your\ntraining run is getting underflows and doing nothing.  So after `growth_interval` successful steps, `update` will\nmultiply the scaling factor by `growth_factor` so that the next step will try a higher one.\n\nThat might cause an overflow in the next step, of course -- but that would be immediately corrected by\na reduction in the scale, which would (hopefully) get things back into the right range.  So the net effect\nis that every `growth_interval` it will try making the scale a bit higher, so it will rise\ngradually until it hits the maximum level it can be at without causing overflows, then\nsit there, blipping up to an unsustainable number every `growth_interval` steps.\n\nThat's unbalanced, of course -- if we overflow, we rescale immediately, but if we're underflowing,\nwe rescale after a bunch of steps.  But given that only overflows are visible to the scaler, it's\na reasonable balance.  After all, if we rescaled upwards every time there were no non-finite values (that\nis, set `growth_interval` to 1) then if we got to the right value, we'd be bouncing up to a higher\none every other step, and skipping half of them due to overflows.\n\nNow, that does mean that if the scale factor is set too low at the start, then you'll\nwind up with a bunch of wasted steps -- I think that is why the default starting value is\nsurprisingly high, at `65536.0` -- better to start with too high a value so that it will halve\neach step until it's within range, than to start with too low a value and only scale it up\nafter 2,000 steps, and again after 2,000 more, and so on.\n\nSo, that's how the `GradScaler` works.  It does, as I thought, skip non-finite gradients -- but\nit's more as a side effect of its dynamic adjustment of the scaling factor than it is\nan explicit feature.  And that, finally, answers a question I had way back in February\n[when I was looking into gradient clipping](https://www.gilesthomas.com/2026/02/llm-from-scratch-32b-interventions-gradient-clipping#grumble) --\nwhy is the feature to skip non-finite gradients implemented as part of a tool designed for handling mixed-precision training?\nIt's not there as a deliberate choice -- it's just there as a result of how that tool\ndetects overflows.\n\nNow that we know how it works, let's think about how it can fail.\n\nLet's revisit the simplified AMP training loop:\n\n```\nwith torch.amp.autocast(device_type=device.type, dtype=torch.float16):\n    logits = model(inputs)\n    loss = torch.nn.functional.cross_entropy(\n        logits.flatten(0, 1), targets.flatten()\n    )\nscaler.scale(loss).backward()\nscaler.step(optimizer)\nscaler.update()\n```\n\nWe know that the call to `scaler.scale` has multiplied our loss by , then we\ndid the (hopefully non-overflowing) backward pass, and then we call the scaler's\n`step` and `update`.\n\n`step` will skip the step, and `update` will reduce  to try to bring\nit within range.`growth_interval`\nof them -- or will bump it up if it has reached that target.\nWhat would happen if was zero?\n\nIf 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.\n\nObviously, 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.\n\nThe 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:\n\n``` python\n>>> import torch\n>>> scale = torch.tensor(4096.0, dtype=torch.float32)\n>>> for ii in range(10_000):\n...     scale = scale * 0.5\n...     if scale == 0:\n...         print(f\"Zero after {ii + 1} steps\")\n...         break\n...\nZero after 162 steps\n```\n\nAnd it actually gets a bit worse.  If we look at\n[the code](https://github.com/pytorch/pytorch/blob/31a77fc9c0a7c6fff15a1ff58c743f53b1a9d457/torch/amp/grad_scaler.py#L351), it\n(as of this writing) scales the gradients down by  using a reciprocal, like this:\n\n```\n        inv_scale = (\n            self._scale.double().reciprocal().float()\n            if self._scale.device != torch.device(\"mps:0\")\n            else self._scale.reciprocal()\n        )\n        found_inf = torch.full((), 0.0, dtype=torch.float32, device=self._scale.device)\n\n        optimizer_state[\"found_inf_per_device\"] = self._unscale_grads_(\n            optimizer, inv_scale, found_inf, False\n        )\n```\n\n`self._scale` is our , and (if we're not on Apple's GPU backend, which is the `mps` bit), it\nworks out `inv_scale` by converting to FP64, taking its reciprocal, and then converting back to FP32\n-- then it multiplies gradients\nby that reciprocal downstream in `self._unscale_grads_`.  How small does `self._scale`\nneed to be before that becomes infinite?\n\n```\n>>> scale = torch.tensor(4096.0, dtype=torch.float32)\n>>> for ii in range(10_000):\n...     scale = scale * 0.5\n...     if scale.double().reciprocal().float() == torch.inf:\n...         print(f\"Hit an inf after {ii + 1} iterations at {scale}\")\n...         break\n...\nHit an inf after 140 iterations at 2.938735877055719e-39\n```\n\nSo, 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.\n\nBut wait, it gets worse again!  You don't even need those NaN steps to be consecutive.  Remember,\nthe scaler only adjusts the scale upwards after `growth_interval` steps of non-NaN\nupdates.  The default interval is 2,000, so if you get, say, 140 steps with NaNs in\nthe loss after starting with 4096.0, so long as there are fewer than 2,000 steps with non-NaN loss between each of\nthem, you're in this death spiral.  The scaler will keep reducing its scale factor, and\nyou'll wind up with garbage weights.  This would happen even with one NaN, then up to 1,999\nOK steps, then another NaN, then up to another 1,999 OK steps, and so on.  So it's more\nplausible than you might think!\n\nSo now let's take a look at what was happening in my training run -- the one that started all of this investigation.\n\nLet's take a look at those weight norms again:\n\nI 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):\n\nThere'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.\n\nSo, that means that the norms were locked for the 1,817 steps from 15,369 to 17,185 inclusive. What was going on then?\n\nI 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:\n\n```\n        if detailed_training_logging and rank == 0:\n            with torch.no_grad():\n                norms = {name: p.norm().item() for name, p in model.named_parameters()}\n                with open(run_dir / \"detailed-log.jsonl\", \"a\") as f:\n                    data = {\n                        \"global_step\": global_step,\n                        \"norms\": norms,\n                        \"losses\": train_losses[-gradient_accumulation_steps:],\n                    }\n                    if scaler is not None:\n                        data[\"scaler_scale\"] = scaler.get_scale()\n                    json.dump(data, f)\n                    f.write(\"\\n\")\n```\n\n...and kicked off the run again.  When it was done, I asked Claude for some\n[updated charting code](https://github.com/gpjt/ddp-base-model-from-scratch/blob/b9ad5348c544ede9e0e896a2ca72fc91958a1155/plot_detailed_log.py) to see what the results looked like.\n\nThe scaling factor first:\n\nYou can see that it bimbled around a bit (technical term) up until somewhere after step 15,000, then dropped off a cliff. Zooming in:\n\nTo be precise: the scale dropped to a level where dividing by it (specifically in the code, that `reciprocal`) would result in\ninfinity at step 15,509, and then fell to zero by step 15,531.  And very neatly:\n\nThose 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.\n\nThat 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?\n\nMy 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.\n\n...and zooming in to the area in question again:\n\nYou 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.\n\nDigging 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.\n\nAdditionally, 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.\n\nSo 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:\n\n```\n[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]\n```\n\nThey're all finite! And so now, we have our explanation:\n\nAnd 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.\n\nWhile researching this problem, I came across\n[this comment](https://discuss.pytorch.org/t/scaler-get-scale-becomes-zeros-and-loss-is-still-nan-under-autocast/83506/2)\nfrom `ptrblck` on the PyTorch forums, writing to someone who'd seen a similar issue:\n\nIf your model outputs NaN values, the training is generally broken and I don’t know if the model can somehow recover from it. [...]\n\nThat's a really good point.  Understanding this was an interesting puzzle -- and, at\nleast for me, has been a good way of getting to understand the reasoning behind and the\nimplementation of the `GradScaler`.  But the issue with finite gradients trashing the model's\nweights with NaNs is a downstream symptom of the real problem -- that the model had started\ndiverging and returning results that got NaN losses.  Even in the worst-possible case\nI outlined above, where NaNs appear with as many as `growth_interval - 1` good steps between them, I think you\ncan make a solid case that something in the model is broken and that is what needs fixing.\n\nThe 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.\n\nBut at least I now understand *why* it's failing in the specific counterintuitive way\nthat it is.  And that, I think, is worth a lot.", "url": "https://wpnews.pro/news/the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights", "canonical_source": "https://www.gilesthomas.com/2026/12/gradscaler-implosion-nans-from-filtered-nans", "published_at": "2026-12-04 18:00:00+00:00", "updated_at": "2026-12-04 18:16:13.144552+00:00", "lang": "en", "topics": ["machine-learning", "large-language-models", "ai-research"], "entities": ["PyTorch", "GradScaler", "Automatic Mixed Precision (AMP)", "log_model_norms"], "also_reported_by": [], "takeaway": "GradScaler's non-finite-gradient filtering is a side effect of overflow avoidance, not a guarantee: in a degenerate state it can apply finite gradients that overflow weights to NaN, so log per-parameter L2 norms after each optimizer step to catch the blow-up before it corrupts a checkpoint.", "recommendation": {"advice": "Log per-parameter L2 norms to JSONL after each optimizer step when training with AMP, so you can spot weights growing toward overflow before a checkpoint is saved as all NaN.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights", "markdown": "https://wpnews.pro/news/the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights.md", "text": "https://wpnews.pro/news/the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights.txt", "jsonld": "https://wpnews.pro/news/the-gradscaler-implosion-how-filtered-out-nan-gradients-became-nan-weights.jsonld"}}