{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"nan-inf-and-the-statistics-of-a-tensor","title":"NaN, Inf, and the five numbers to print about any tensor","url":"https://addaly.com/learn/maths-you-need/nan-inf-and-the-statistics-of-a-tensor","position":76,"of":76,"minutes":9,"answer":"NaN arises from 0/0, Inf − Inf, sqrt of a negative or log of a negative, propagates through everything, and is unequal even to itself, so it is found with isnan rather than ==.","keyIdea":"NaN arises from 0/0, Inf − Inf, sqrt of a negative or log of a negative, propagates through everything, and is unequal even to itself, so it is found with isnan rather than ==, traced upstream rather than where it appears, and prevented by the stable log, variance and normalisation forms the earlier lessons gave."},"body":{"format":"markdown","text":"## Two special values, with rules\n\nThe floating-point standard reserves bit patterns for two things that are not numbers. **Inf**, positive or negative, is what overflow produces, and what division of a non-zero number by zero produces. **NaN**, \"not a number\", is what you get when the arithmetic has no defensible answer:\n\n```\n0 / 0          NaN\nInf − Inf      NaN\n0 × Inf        NaN\nInf / Inf      NaN\nsqrt(−1)       NaN\nlog(−1)        NaN\nlog(0)         −Inf   (not NaN, and the distinction is useful)\n```\n\nBoth propagate. Any operation with a NaN input gives NaN, and most operations with Inf give Inf or NaN. One NaN in a gradient becomes a NaN in every weight it touches after one optimiser step, and then in every activation, and then in the loss. A NaN in training is therefore rarely where it appears; it is downstream of its origin, and the work is tracing it back.\n\n## The rule that surprises everyone\n\nNaN is not equal to anything, including itself:\n\n```python\nx = float(\"nan\")\nx == x            # False\n```\n\nThis is by design, and it is the standard test: `x != x` is True exactly when `x` is NaN. It also means `x in some_list`, a `==` filter in pandas, and a dictionary lookup all fail to find a NaN. `np.isnan` and `torch.isnan` are the honest tests; `math.isnan` for scalars.\n\nSorting puts NaN at the end. `np.max` of an array containing one NaN returns NaN; `np.nanmax` skips it. Pandas `mean()` **skips NaN silently**, which is the more dangerous behaviour: a column with 60 per cent missing values reports a confident mean of the other 40 per cent, and nothing says so unless you print `count()` beside it. An accuracy computed over a column with NaN labels is an accuracy over the rows that had labels, which may not be the rows you meant.\n\n## Where NaN comes from in training\n\nEach of the operations above has a training-time source. The ones that account for most incidents:\n\n- **log of zero.** A probability underflowed to 0, then `−log(0) = Inf` in the loss, then NaN in the gradient. Module 5's log-sum-exp is the fix; so is never computing `log(softmax(x))` as two steps.\n- **Square root of a small negative.** A variance computed by cancellation, as in the summation lesson, comes out at `−1e-9`; `sqrt` returns NaN; a normalisation layer spreads it everywhere. Clamp to zero, or compute the variance the stable way.\n- **Division by a zero norm.** Normalising a vector that happens to be all zeros, a padding embedding, gives `0/0`. Add an epsilon to the denominator.\n- **Overflow.** A learning rate too high pushes a weight to `1e20`, an activation to `Inf`, and `Inf − Inf` in the next layer norm gives NaN. Module 3's gradient-norm plot shows this coming several steps early; gradient clipping stops it.\n- **fp16.** Everything above happens at `65,504` instead of `10^38`, which is the half-precision lesson.\n\n## Finding the origin\n\n```python\ntorch.autograd.set_detect_anomaly(True)     # raises at the first backward op producing NaN\n```\n\nThis slows training badly and names the operation, which is what you need once and then never again. Cheaper, and worth leaving on: assert after each step that the loss is finite, and log the step at which it stopped being so, because the first non-finite loss is usually a few steps after the first non-finite gradient, and the gradient-norm history around that step tells the story.\n\n```python\nif not torch.isfinite(loss):\n    raise RuntimeError(f\"non-finite loss at step {step}\")\n```\n\n## The five numbers\n\nFor any tensor you are suspicious of, print five things:\n\n```python\ndef describe(t, name=\"\"):\n    t = t.detach().float()\n    print(name, tuple(t.shape), t.dtype,\n          f\"mean={t.mean():.3g} std={t.std():.3g} maxabs={t.abs().max():.3g}\",\n          f\"nonfinite={(~torch.isfinite(t)).sum().item()}\")\n```\n\nShape and dtype, because half of all bugs are a transposed matrix or an integer where a float was meant. Mean and standard deviation, because the variance lesson said what healthy looks like: activations with mean near 0 and spread near 1, weights at their initialisation scale, gradients with a spread that is stable across steps. Maximum absolute value, because an activation of `10^4` is the overflow of ten steps from now. And the count of non-finite entries, because one is already too many.\n\nCall it on the input batch, the first layer's output, the logits and the loss, in that order, at the step things went wrong. The first tensor whose numbers look wrong is upstream of the fault.\n\n## Inf on purpose\n\n`−Inf` is also a tool. Masking in attention sets the scores of forbidden positions to `−Inf` before the softmax, and `exp(−Inf) = 0` exactly, which is cleaner than any large negative number. `float(\"inf\")` is the right initial value for a running minimum. And a log-probability of `−Inf` for an impossible event is correct, not a bug, as long as nothing downstream subtracts two of them.\n\n## The rule\n\nA NaN is never the problem; it is the problem's last symptom. Test with `isnan`, never with `==`. Print the five numbers, walk upstream, and find the log of zero, the root of a negative, the division by nothing, or the step whose norm doubled three times in a row."},"check":{"question":"A training loss becomes NaN at step 4,210. The gradient norm was rising steeply from step 4,195 and reached 10⁷ at step 4,208. Where should the search for the cause begin?","options":[{"text":"At step 4,210, in the loss function, since that is where the NaN first appears.","correct":false,"tempting":"The NaN is the last symptom; the gradient norm shows the blow-up starting fifteen steps earlier, and the loss only inherited it."},{"text":"At step 4,195, where the norm began to run away: a high learning rate or a missing clip.","correct":true},{"text":"In the data loader, since a corrupt batch at step 4,210 is the usual cause of a sudden NaN.","correct":false,"tempting":"A corrupt batch produces a NaN with no warning in the preceding steps; a norm that grows for fifteen steps is an optimisation instability, not a bad row."},{"text":"In the random seed, since a different seed would likely avoid the batch that triggered it.","correct":false,"tempting":"Changing the seed hides the symptom without finding the cause; the runaway norm will recur at some other step because the dynamics, not the sample, are unstable."}]},"prev":{"slug":"checking-a-gradient-numerically","title":"Checking a gradient with finite differences, and the step size that lies","url":"https://addaly.com/learn/maths-you-need/checking-a-gradient-numerically"},"next":null,"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'NaN, Inf, and the five numbers to print about any tensor', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/nan-inf-and-the-statistics-of-a-tensor (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"NaN, Inf, and the five numbers to print about any tensor","courseTitle":"The Maths You Actually Need","module":{"index":8,"slug":"numbers-in-a-machine","title":"Numbers inside a machine"},"answer":null,"keyIdea":"NaN arises from 0/0, Inf − Inf, sqrt of a negative or log of a negative, propagates through everything, and is unequal even to itself, so it is found with isnan rather than ==, traced upstream rather than where it appears, and prevented by the stable log, variance and normalisation forms the earlier lessons gave.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"two-special-values-with-rules","runs":[{"text":"Two special values, with rules"}]},{"t":"p","runs":[{"text":"The floating-point standard reserves bit patterns for two things that are not numbers. "},{"text":"Inf","b":true},{"text":", positive or negative, is what overflow produces, and what division of a non-zero number by zero produces. "},{"text":"NaN","b":true},{"text":", “not a number”, is what you get when the arithmetic has no defensible answer:"}]},{"t":"code","lang":"","label":"Text","text":"0 / 0          NaN\nInf − Inf      NaN\n0 × Inf        NaN\nInf / Inf      NaN\nsqrt(−1)       NaN\nlog(−1)        NaN\nlog(0)         −Inf   (not NaN, and the distinction is useful)"},{"t":"p","runs":[{"text":"Both propagate. Any operation with a NaN input gives NaN, and most operations with Inf give Inf or NaN. One NaN in a gradient becomes a NaN in every weight it touches after one optimiser step, and then in every activation, and then in the loss. A NaN in training is therefore rarely where it appears; it is downstream of its origin, and the work is tracing it back."}]},{"t":"h2","id":"the-rule-that-surprises-everyone","runs":[{"text":"The rule that surprises everyone"}]},{"t":"p","runs":[{"text":"NaN is not equal to anything, including itself:"}]},{"t":"code","lang":"python","label":"Python","text":"x = float(\"nan\")\nx == x            # False"},{"t":"p","runs":[{"text":"This is by design, and it is the standard test: "},{"text":"x != x","code":true},{"text":" is True exactly when "},{"text":"x","code":true},{"text":" is NaN. It also means "},{"text":"x in some_list","code":true},{"text":", a "},{"text":"==","code":true},{"text":" filter in pandas, and a dictionary lookup all fail to find a NaN. "},{"text":"np.isnan","code":true},{"text":" and "},{"text":"torch.isnan","code":true},{"text":" are the honest tests; "},{"text":"math.isnan","code":true},{"text":" for scalars."}]},{"t":"p","runs":[{"text":"Sorting puts NaN at the end. "},{"text":"np.max","code":true},{"text":" of an array containing one NaN returns NaN; "},{"text":"np.nanmax","code":true},{"text":" skips it. Pandas "},{"text":"mean()","code":true},{"text":" "},{"text":"skips NaN silently","b":true},{"text":", which is the more dangerous behaviour: a column with 60 per cent missing values reports a confident mean of the other 40 per cent, and nothing says so unless you print "},{"text":"count()","code":true},{"text":" beside it. An accuracy computed over a column with NaN labels is an accuracy over the rows that had labels, which may not be the rows you meant."}]},{"t":"h2","id":"where-nan-comes-from-in-training","runs":[{"text":"Where NaN comes from in training"}]},{"t":"p","runs":[{"text":"Each of the operations above has a training-time source. The ones that account for most incidents:"}]},{"t":"ul","items":[[{"text":"log of zero.","b":true},{"text":" A probability underflowed to 0, then "},{"text":"−log(0) = Inf","code":true},{"text":" in the loss, then NaN in the gradient. Module 5’s log-sum-exp is the fix; so is never computing "},{"text":"log(softmax(x))","code":true},{"text":" as two steps."}],[{"text":"Square root of a small negative.","b":true},{"text":" A variance computed by cancellation, as in the summation lesson, comes out at "},{"text":"−1e-9","code":true},{"text":"; "},{"text":"sqrt","code":true},{"text":" returns NaN; a normalisation layer spreads it everywhere. Clamp to zero, or compute the variance the stable way."}],[{"text":"Division by a zero norm.","b":true},{"text":" Normalising a vector that happens to be all zeros, a padding embedding, gives "},{"text":"0/0","code":true},{"text":". Add an epsilon to the denominator."}],[{"text":"Overflow.","b":true},{"text":" A learning rate too high pushes a weight to "},{"text":"1e20","code":true},{"text":", an activation to "},{"text":"Inf","code":true},{"text":", and "},{"text":"Inf − Inf","code":true},{"text":" in the next layer norm gives NaN. Module 3’s gradient-norm plot shows this coming several steps early; gradient clipping stops it."}],[{"text":"fp16.","b":true},{"text":" Everything above happens at "},{"text":"65,504","code":true},{"text":" instead of "},{"text":"10^38","code":true},{"text":", which is the half-precision lesson."}]]},{"t":"h2","id":"finding-the-origin","runs":[{"text":"Finding the origin"}]},{"t":"code","lang":"python","label":"Python","text":"torch.autograd.set_detect_anomaly(True)     # raises at the first backward op producing NaN"},{"t":"p","runs":[{"text":"This slows training badly and names the operation, which is what you need once and then never again. Cheaper, and worth leaving on: assert after each step that the loss is finite, and log the step at which it stopped being so, because the first non-finite loss is usually a few steps after the first non-finite gradient, and the gradient-norm history around that step tells the story."}]},{"t":"code","lang":"python","label":"Python","text":"if not torch.isfinite(loss):\n    raise RuntimeError(f\"non-finite loss at step {step}\")"},{"t":"h2","id":"the-five-numbers","runs":[{"text":"The five numbers"}]},{"t":"p","runs":[{"text":"For any tensor you are suspicious of, print five things:"}]},{"t":"code","lang":"python","label":"Python","text":"def describe(t, name=\"\"):\n    t = t.detach().float()\n    print(name, tuple(t.shape), t.dtype,\n          f\"mean={t.mean():.3g} std={t.std():.3g} maxabs={t.abs().max():.3g}\",\n          f\"nonfinite={(~torch.isfinite(t)).sum().item()}\")"},{"t":"p","runs":[{"text":"Shape and dtype, because half of all bugs are a transposed matrix or an integer where a float was meant. Mean and standard deviation, because the variance lesson said what healthy looks like: activations with mean near 0 and spread near 1, weights at their initialisation scale, gradients with a spread that is stable across steps. Maximum absolute value, because an activation of "},{"text":"10^4","code":true},{"text":" is the overflow of ten steps from now. And the count of non-finite entries, because one is already too many."}]},{"t":"p","runs":[{"text":"Call it on the input batch, the first layer’s output, the logits and the loss, in that order, at the step things went wrong. The first tensor whose numbers look wrong is upstream of the fault."}]},{"t":"h2","id":"inf-on-purpose","runs":[{"text":"Inf on purpose"}]},{"t":"p","runs":[{"text":"−Inf","code":true},{"text":" is also a tool. Masking in attention sets the scores of forbidden positions to "},{"text":"−Inf","code":true},{"text":" before the softmax, and "},{"text":"exp(−Inf) = 0","code":true},{"text":" exactly, which is cleaner than any large negative number. "},{"text":"float(\"inf\")","code":true},{"text":" is the right initial value for a running minimum. And a log-probability of "},{"text":"−Inf","code":true},{"text":" for an impossible event is correct, not a bug, as long as nothing downstream subtracts two of them."}]},{"t":"h2","id":"the-rule","runs":[{"text":"The rule"}]},{"t":"p","runs":[{"text":"A NaN is never the problem; it is the problem’s last symptom. Test with "},{"text":"isnan","code":true},{"text":", never with "},{"text":"==","code":true},{"text":". Print the five numbers, walk upstream, and find the log of zero, the root of a negative, the division by nothing, or the step whose norm doubled three times in a row."}]}],"check":{"question":[{"text":"A training loss becomes NaN at step 4,210. The gradient norm was rising steeply from step 4,195 and reached 10⁷ at step 4,208. Where should the search for the cause begin?"}],"options":[{"text":[{"text":"At step 4,210, in the loss function, since that is where the NaN first appears."}],"correct":false,"tempting":[{"text":"The NaN is the last symptom; the gradient norm shows the blow-up starting fifteen steps earlier, and the loss only inherited it."}]},{"text":[{"text":"At step 4,195, where the norm began to run away: a high learning rate or a missing clip."}],"correct":true,"tempting":null},{"text":[{"text":"In the data loader, since a corrupt batch at step 4,210 is the usual cause of a sudden NaN."}],"correct":false,"tempting":[{"text":"A corrupt batch produces a NaN with no warning in the preceding steps; a norm that grows for fifteen steps is an optimisation instability, not a bad row."}]},{"text":[{"text":"In the random seed, since a different seed would likely avoid the batch that triggered it."}],"correct":false,"tempting":[{"text":"Changing the seed hides the symptom without finding the cause; the runaway norm will recur at some other step because the dynamics, not the sample, are unstable."}]}],"order":[2,1,0,3],"why":null},"prev":{"slug":"checking-a-gradient-numerically","title":"Checking a gradient with finite differences, and the step size that lies","minutes":9},"next":null}}