What Is GPU Numerical Overflow? Why Inf Appears in Intermediate Calculations and How to Debug It
A GPU calculation can overflow in an intermediate step even when its input and mathematical answer fit the dtype. Learn to distinguish Inf from NaN, find the first failing operation, and choose a safe correction.
What Is GPU Numerical Overflow? Why Inf Appears in Intermediate Calculations and How to Debug It
GPU numerical overflow occurs when a calculation exceeds the finite range of its current dtype, producing positive or negative infinity. An input and final mathematical answer can both fit in a dtype while an intermediate square, product, or sum does not. Because a GPU kernel may not report floating-point exceptions automatically, you often need to locate the first non-finite value yourself.
Overflow, NaN, underflow, and rounding are different
Floating-point formats cannot store every real number. Each has a largest and smallest finite magnitude, and the spacing between representable values changes with magnitude. A result above the maximum finite value generally becomes positive or negative infinity. A value that is too small may be represented as a subnormal or underflow to zero. Values inside the range can also be rounded, losing precision without overflowing.
Do not treat Inf and NaN as interchangeable. Overflow from a valid arithmetic result can produce +Inf or -Inf. Invalid operations such as 0/0 or Inf - Inf can produce NaN; either value can then propagate through later operations. The CUDA Programming Guide 13.2 describes floating-point special values and the GPU's exception behavior.
Integer overflow is separate: integers follow different rules from floating-point formats that represent overflow with Inf. The exact integer behavior depends on the language and operation. This article focuses on floating-point calculations on GPUs.
Each dtype has a different maximum finite value
When choosing a dtype, check its range as well as its precision. BF16 has fewer significant bits than FP16, but a wider exponent and a range close to FP32. That does not remove BF16 rounding error.
| Format | Approximate maximum finite value | What this means for overflow |
|---|---|---|
| FP16 (binary16) | 65,504 | Large activations or intermediate sums can exceed the range relatively easily. |
| BF16 | About 3.39×10³⁸ | Range close to FP32, but fewer significant bits. |
| FP32 | About 3.40×10³⁸ | A common baseline, but not a guarantee that intermediates remain finite. |
| FP64 | About 1.8×10³⁰⁸ | Much wider range; support and performance vary by device and should be checked on the target GPU. |
These are approximate finite maxima from the CUDA Programming Guide's floating-point type table. Also check the accumulation dtype and where conversions occur. Widening only the output after an intermediate overflow cannot recover the finite value.
An intermediate can overflow even when the answer is representable
A vector norm is a useful example. The PyTorch 2.15 numerical-accuracy documentation shows that an FP32 tensor [1e20, 1e20] can produce Inf from norm(), while converting the values to FP64 first produces a norm of about 1.4142e20, which is representable in FP32.
| Quantity | Approximate magnitude | Interpretation |
|---|---|---|
| Each input element | 1×10²⁰ | Within the finite FP32 range. |
| Squared intermediate magnitude | 1×10⁴⁰ | Greater than the FP32 maximum, about 3.4×10³⁸. |
| Exact vector norm | √2×10²⁰ ≈ 1.4142×10²⁰ | The final answer fits in FP32. |
The key lesson is that representable inputs and a representable answer do not guarantee that every intermediate operation is safe. These values and the output are the example documented in PyTorch 2.15 Numerical Accuracy. The square comparison above is a size calculation to explain the issue; it does not claim to describe a particular GPU kernel's internal implementation.
Find the first non-finite value to narrow the cause
CUDA device-side floating-point operations do not report errors through CPU-style global exception flags or errno. NVIDIA therefore advises adding input and output screening when diagnostics are needed. PyTorch's torch.isfinite() returns a Boolean mask that detects both infinities and NaNs. Checking only the final output, however, cannot show which earlier operation first failed.
| Observed value | Likely cause to investigate first | Next check |
|---|---|---|
+Inf or -Inf | A multiply, square, sum, or conversion exceeded the range, or an earlier infinity propagated | Compare the preceding magnitude, dtype, conversion, and accumulation point. |
NaN | An invalid operation such as 0/0 or Inf - Inf, or propagation of an earlier NaN | Find the first NaN and inspect denominators, log/square-root inputs, and earlier infinities. |
| Finite value far from the reference | Rounding, truncation, saturation, or a different accumulation order | Identify the conversion or operation where values first diverge and review the accepted tolerance. |
During debugging, check finiteness after the input, the suspected operation, a reduction or accumulation, and any conversion to the storage dtype. Record dtype, maximum absolute value, and batch or axis size at each point. PyTorch 2.15 torch.isfinite() documents the Boolean mask for non-finite elements.
A more stable formula can avoid unnecessary overflow
One option is to perform only the risky intermediate calculation in a wider dtype. In PyTorch's documented norm example, converting FP32 inputs to FP64 before the calculation produces a finite result. FP64 support and speed differ by GPU, so measure accuracy and runtime on the target device before adopting it.
When possible, reformulate the algorithm so it does not directly square values at their original magnitudes. For a nonzero vector, an explanatory scaled form of the norm is m × sqrt(sum((x/m)²)), where m is the largest absolute element. This brings each ratio to at most 1 before squaring. Handle the all-zero vector separately; and if the true final norm exceeds the dtype's maximum, no formula can produce a finite result in that dtype. This equation illustrates the scaled-sum-of-squares idea; it is not a claim that every GPU library uses this implementation. LAPACK's xLASSQ routines track a scale and a scaled sum to avoid overflow in large squares and underflow in small ones.
Also check units and input bounds. Confusing milliseconds with seconds, repeatedly multiplying unnormalized large values, or dividing by a denominator near zero can create unintended large intermediates. Apply an input limit or clamp only when the application's meaning defines values outside that range as invalid or capped. Arbitrary clipping can hide a faulty calculation and change the result.
FP16 loss scaling is not a general overflow fix
Loss scaling is designed to reduce underflow of small backward-pass gradients in low precision. It temporarily increases the loss and gradients, then restores their scale before the optimizer update. The PyTorch 2.15 documentation warns that some BF16-pretrained models can produce gradients beyond FP16's maximum finite value of 65,504; GradScaler may lower its scale below 1 in response.
So if a large forward activation or sum is already Inf, increasing the loss scale is not a fix. During training, check whether the model and AMP settings fit the FP16 range, and consider BF16 or FP32 for the operation where overflow begins. GradScaler's update behavior belongs to the documented PyTorch AMP workflow; it does not correct every forward-pass numerical problem. See PyTorch 2.15 AMP, Gradient Scaling.
Verify a correction in five steps
**Set a baseline and an acceptance range.** Save outputs, task metrics, and an acceptable numerical error for representative inputs. GPU floating-point results may differ with calculation order or device, so choose a tolerance appropriate to the algorithm.
**Reproduce the issue with boundary inputs.** Check normal data plus large and small values, zero or near-zero denominators, and real service edge cases. Record whether each stage uses FP16, BF16, or FP32.
**Locate the first non-finite operation.** Check `isfinite` after important stages and record where `Inf` or `NaN` first appears, along with magnitude, dtype, shape, and conversions.
**Choose the smallest correction that matches the cause.** Consider a wider dtype for the intermediate, a scaled stable algorithm, correcting units, or handling an invalid denominator. Confirm that clamping or changing precision preserves the application's meaning.
**Recheck the full workload on the target device.** Compare finiteness, error from the reference, task quality or training convergence, memory, and latency under the same conditions. Revalidate when the dtype, compiler, or library changes.
The NVIDIA CUDA C++ Best Practices Guide recommends comparing results with representative reference outputs and an algorithm-appropriate tolerance rather than always demanding bitwise identity. The acceptable tolerance depends on the task; there is no single threshold for every workload.
References
[PyTorch 2.15, Numerical Accuracy — Extremal Values](https://docs.pytorch.org/docs/2.15/notes/numerical_accuracy.html)
[NVIDIA CUDA Programming Guide 13.2, Floating-Point Computation](https://docs.nvidia.com/cuda/cuda-programming-guide/pdf/cuda-programming-guide.pdf)
[PyTorch 2.15, `torch.isfinite()`](https://docs.pytorch.org/docs/2.15/generated/torch.isfinite.html)
[PyTorch 2.15, Automatic Mixed Precision — Gradient Scaling](https://docs.pytorch.org/docs/2.15/amp.html)
[LAPACK 3.12.1, `DLASSQ`: scaled sum of squares](https://netlib.org/lapack/explore-html/db/d2e/dlassq_8f90_source.html)
[NVIDIA CUDA C++ Best Practices Guide 13.5, Numerical Accuracy and Precision](https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/)