Troubleshooting

NaN loss in mixed precision: causes and fixes

NaN loss in mixed precision usually means a value overflowed the float16 range (maximum 65504) or bad data reached the loss. Check that GradScaler wraps backward and step, log its scale, and test inputs with torch.isfinite. Run a few steps under torch.autograd.detect_anomaly to find the first op that produced NaN. Where the GPU supports it, bf16 avoids most overflow.

NEURAMESH / COMPUTE FIELD NOTES00 / 10

The symptom: loss prints nan or inf

The training log looks normal for some steps, then the loss reads nan or inf and never recovers. Sometimes it is nan from the very first step. Accuracy drops to chance, and saved checkpoints after that point contain NaN weights.

Under float16 autocast with a gradient scaler, there is a quieter version of the same problem. The loss stays finite, but the scaler keeps shrinking its scale factor and skipping optimizer steps, so the model stops learning. Both cases have the same root: a value left the range the number format can hold, or a NaN entered from outside the model.

PyTorch’s own AMP documentation gives the first instruction: if you encounter NaNs in your loss or gradients when running with AMP and fp16, verify that your model is compatible. The rest of this guide is how to do that check quickly.

References: PyTorch automatic mixed precision package (torch.amp)

Why fp16 overflows and bf16 usually does not

Float16 has a narrow range. Its largest finite value is 65504, which PyTorch’s AMP page calls out directly. Activations, attention scores or loss values above that become inf, and inf minus inf or zero times inf becomes NaN. Small gradients have the opposite problem: they underflow to zero, which is why fp16 training needs gradient scaling.

Bfloat16 keeps the same dynamic range as float32 at roughly half the memory, according to Google’s bfloat16 documentation. It gives up precision instead of range, so overflow is rare. PyTorch’s examples pair float16 autocast with GradScaler, while the bf16 examples use autocast alone.

The AMP page adds a warning that matters for fine-tuning: most bf16-pretrained models cannot operate in the fp16 numerical range and will cause gradients to overflow instead of underflow. If you fine-tune a model released in bf16 on a GPU without bf16 support, expect trouble in fp16.

Why fp16 overflows and bf16 usually does not
Propertyfloat16 (fp16)bfloat16 (bf16)
Largest finite value65504Same range as float32
Main failure modeOverflow to inf, underflow to zeroRounding error from lower precision
Gradient scalingNeeded: autocast plus GradScalerPyTorch examples use autocast alone
Typical NaN sourceLarge activations or a bf16-trained modelBad data or a too-high learning rate

References: PyTorch automatic mixed precision package (torch.amp) · Google Cloud TPU: the bfloat16 numerical format

Causes of NaN loss in mixed precision, most common first

Work down this list in order. The cheap checks sit at the top, and the first two account for most cases.

First, the gradient scaler is missing or wired wrong: backward is called on the unscaled loss, optimizer.step() is called directly instead of scaler.step(), or gradients are clipped before scaler.unscale_(). Second, a bf16-pretrained model is running in fp16 and overflowing. Third, the learning rate is too high or warmup is missing, so training diverges in any precision.

Fourth, the data contains NaN or inf: a corrupt sample, a division by zero in preprocessing, or a log of zero in a custom loss. Fifth, custom code runs a sensitive op in half precision outside autocast’s control, such as a hand-written softmax, exp or norm on a tensor cast with .half(). Last and rarest is a hardware memory error; on data center GPUs the driver logs it, as covered in NVIDIA Xid errors.

References: PyTorch automatic mixed precision package (torch.amp) · PyTorch CUDA automatic mixed precision examples

Diagnostic commands that find the first NaN

Start with the data. Before the forward pass, assert torch.isfinite(inputs).all() and the same for targets. If the assertion fires, the model is not the problem. Then log scaler.get_scale() every 50 steps. A scale that falls step after step, far below its 65536 starting value, means fp16 is overflowing on most iterations.

Next, find the op. Wrap a few training steps in with torch.autograd.detect_anomaly(): and run the failing batch. PyTorch documents two effects: the backward pass prints a traceback of the forward operation that created the failing backward function, and with check_nan, which defaults to True, any backward computation that generates nan raises an error. The docs warn this mode slows execution, so use it only while debugging.

Finally, run the same batch with autocast(enabled=False). If float32 is finite and fp16 is not, the cause is range. If float32 also produces NaN, look at data, learning rate or the loss function itself.

References: PyTorch torch.autograd: anomaly detection · PyTorch automatic mixed precision package (torch.amp)

Symptom, check and fix table

Use this as a first pass. Change one thing at a time and rerun the same seed and batch, so you can tell which change mattered.

Symptom, check and fix table
SymptomCheckFix
Loss is nan from step onetorch.isfinite on inputs and targetsClean or skip the bad samples; fix preprocessing
Loss finite, model stops improving in fp16Log scaler.get_scale(); it keeps fallingSwitch to bf16 or keep the overflowing layer in float32
nan after enabling gradient clippingIs unscale_() called before clip_grad_norm_?Call scaler.unscale_(optimizer), then clip, then scaler.step
nan only in fp16, fine in float32Same batch with autocast(enabled=False)Use bf16, or GradScaler with float16 autocast
nan after a few hundred steps in any precisionLoss curve spikes before the nanLower learning rate, add warmup, clip gradients
Traceback points at a custom opdetect_anomaly output names the forward opRemove manual .half() casts; compute in float32

References: PyTorch automatic mixed precision package (torch.amp) · PyTorch CUDA automatic mixed precision examples · PyTorch torch.autograd: anomaly detection

Fixes: GradScaler, bf16 and float32 islands

For float16, follow PyTorch’s canonical loop. Create one GradScaler at the start, run forward and loss under torch.autocast(device_type='cuda', dtype=torch.float16), call scaler.scale(loss).backward(), then scaler.step(optimizer) and scaler.update(). The deprecated torch.cuda.amp.GradScaler form still works, but the docs point you to torch.amp.GradScaler('cuda').

scaler.step() unscales the gradients and calls optimizer.step() only if they contain no infs or NaNs; otherwise that step is skipped. To clip, call scaler.unscale_(optimizer) first, then clip the unscaled gradients as usual. Call unscale_ once per optimizer per step; a second call raises a RuntimeError.

If the GPU supports bf16, switching dtype to torch.bfloat16 is often the whole fix. Ampere and newer data center GPUs such as the A100 and H100 do. Where you must stay in fp16, let autocast handle sensitive ops: on CUDA it already runs softmax, log_softmax, layer_norm, exp, sum, cross_entropy and mse_loss in float32. Remove manual .half() casts that bypass it.

References: PyTorch automatic mixed precision package (torch.amp) · PyTorch CUDA automatic mixed precision examples

How GradScaler behaves when it works

Knowing normal behavior keeps you from chasing a non-problem. The scaler starts at a scale of 65536, multiplies it by 2 after 2000 clean steps in a row, and multiplies it by 0.5 when it finds infs or NaNs. Those are the documented defaults for init_scale, growth_factor, growth_interval and backoff_factor.

Occasional skipped steps are expected. PyTorch’s AMP examples note that step skipping occurs rarely, every several hundred iterations, and should not impede convergence. A skipped step now and then is the scaler doing its job.

The warning sign is a trend: the scale falling below 1, or skipped steps on most iterations. The AMP docs say the scale may drop under 1 when a model overflows, and that GradScaler does not guarantee performance in that state. At that point, change precision rather than tuning the scaler.

How GradScaler behaves when it works
GradScaler settingDefaultWhat it does
init_scale65536.0Starting multiplier for the loss
growth_factor2.0Scale increase after a clean run of steps
backoff_factor0.5Scale decrease when infs or NaNs appear
growth_interval2000Clean steps needed before the scale grows

References: PyTorch automatic mixed precision package (torch.amp) · PyTorch CUDA automatic mixed precision examples

Prevention and what to ask a GPU provider

Prevent the next NaN loss in mixed precision with three habits. Check data for non-finite values when you build the dataset, not during training. Log loss, gradient norm and scaler scale every few dozen steps so a trend shows before the nan. Save checkpoints often enough that a divergence costs minutes, as GPU training checkpoints explains.

Before renting, ask the provider three questions. Does the GPU support bf16? Older generations may not, and torch.cuda.is_bf16_supported() answers it on the machine. Which driver and CUDA versions are installed, so your PyTorch build matches? And does the card have ECC memory, and will they share driver logs if you suspect a memory fault? For choosing between bf16-capable cards, see H100 vs A100.

References: PyTorch automatic mixed precision package (torch.amp)

Checklist and next step

Assert finite inputs and targets. Log scaler.get_scale(). Run the bad batch under detect_anomaly. Compare the same batch in float32. Use scaler.step, scaler.update and unscale_ before clipping. Prefer bf16 on GPUs that support it. Lower the learning rate and add warmup if NaNs appear in every precision.

Once the run is stable, size the hardware to it. NeuraMesh rents bf16-capable data center GPUs by the hour: choose a GPU, plan, count, hours and region on rent GPUs and you receive a confirmed quotation, typically within one business day, with nothing charged until you approve. Not sure which GPU fits your model? Ask the compute advisor.

NeuraMesh prices for these GPUs

NeuraMesh prices per GPU-hour in USD, excluding taxes, as of 2026-11-27. Live prices are on the rental pages.
GPUMemoryData centerValue
RTX 409024 GB$0.46$0.40
L40S48 GB$1.26$0.54
A10080 GB$1.56$0.98
H10080 GB$2.88$2.00

Every order is confirmed in a quotation before you pay. See all GPU prices.

Questions readers ask

Why is my loss NaN only with mixed precision?

Most often float16 overflowed. Its largest finite value is 65504, and larger activations become inf, then NaN. Run the same batch with autocast disabled; if float32 is finite, switch to bf16 or make sure GradScaler wraps backward and step.

Does bf16 need GradScaler?

PyTorch’s examples use GradScaler with float16 autocast and autocast alone for bf16. Bfloat16 has the same dynamic range as float32, so gradient underflow, the problem scaling solves, is rarely an issue.

How do I find which layer causes NaN loss in mixed precision?

Run the failing batch inside torch.autograd.detect_anomaly(). The backward pass prints the traceback of the forward op that created the failing function, and with check_nan enabled it raises an error at the first NaN. Expect it to run slower.

Is it normal for GradScaler to skip steps?

Yes, occasionally. PyTorch notes skipping happens rarely, every several hundred iterations, and should not hurt convergence. Skips on most steps, or a scale falling below 1, mean the model overflows in fp16.

Can a faulty GPU cause NaN loss?

It is possible but rare. Uncorrectable memory errors on data center GPUs are logged by the driver as Xid events. Rule out data, precision and learning rate first, then check the kernel log for NVRM Xid lines.

Sources and editorial notes

Primary documentation reviewed November 24, 2026. Provider descriptions reflect published documentation. Recommendations are our analysis; worked figures are illustrative unless explicitly stated otherwise. No independent provider benchmark or uptime ranking is claimed.

Read the editorial policy.

Need this GPU? Rent it from NeuraMesh: choose a GPU and plan, get a confirmed quotation, and pay only when you approve. See pricing.