PyTorch Lightning FP16 NaN Mixed Precision Loss
Fix FP16 NaN loss spikes and grad scaler underflow in PyTorch Lightning. Use bf16-mixed on Ampere and newer GPUs and detect overflow earlier.
PyTorch Lightning training runs with precision='16-mixed' hit NaN or Inf losses when activations overflow FP16's narrow exponent range (+/-65504) or custom manual optimizations skip GradScaler checks. On Ampere (A100), Ada, Hopper (H100/H200), and Blackwell GPUs, switch to precision='bf16-mixed'; otherwise keep softmax/normalization/loss math in FP32 and verify gradient clipping.
- Symptom
Epoch 0: 4%|4 | 120/3000 [01:12<28:54, 1.66it/s, v_num=0, train_loss=nan]- Root cause
- FP16 dynamic range (+/-65504) overflowed during forward logits or backward gradient scaling, or manual optimization bypassed Lightning's GradScaler unscaling/clipping lifecycle.
- Recommended fix
- Switch Trainer(precision='bf16-mixed') on Ampere (sm_80) and newer GPUs so exponent range matches FP32 (+/-3.4e38) without requiring a GradScaler.
- How Denpex helps
- Denpex investigates PyTorch Lightning FP16 NaN Mixed Precision Loss using the evidence you provide or your connected workload collects. Earlier rank, host or application evidence is needed to distinguish an initiating failure from a downstream report.
What this failure is
Numerical overflow or gradient-scaler instability during PyTorch Lightning automatic mixed precision (16-mixed) training resulting in NaN loss or skipped optimizer steps.
Is this what broke your run? Paste your log.
You're reading about PyTorch Lightning FP16 NaN Mixed Precision Loss. Paste your own traceback and relevant evidence for an investigation of your workload, with a next action or a specific missing fact. A reference entry does not establish your cause. No account or card for the free diagnosis. Review data handling before submitting sensitive logs.
Before uploading, review cloud data handling and local options.
Upload your log file. Large files are processed in your browser. Only selected evidence is submitted when you run diagnosis.
Why it happens (the mechanism)
IEEE 754 FP16 reserves only 5 exponent bits, capping finite values at 65,504. Large transformer attention logits, unmasked padding (-1e9 instead of -1e4), high learning rates without warmup, or manual optimization steps calling optimizer.step() without scaler unscale cause weights to jump straight to NaN.
What you'll observe
- Training starts normally for dozens or thousands of steps, then train_loss suddenly becomes NaN or validation metrics collapse.
- GradScaler repeatedly halves scale factors until zero updates occur or NaN gradients corrupt optimizer momentum buffers.
Common symptoms and what they mean
Check possible explanations against the incident evidence. A matching symptom alone does not establish its cause.
| Symptom | Possible explanation |
|---|---|
| loss=nan in PyTorch Lightning progress bar under precision='16-mixed' | FP16 dynamic range (+/-65504) overflowed during forward logits or backward gradient scaling, or manual optimization bypassed Lightning's GradScaler unscaling/clipping lifecycle. |
| detect_anomaly reports NaN gradients inside attention softmax, LayerNorm, or custom loss functions | FP16 dynamic range (+/-65504) overflowed during forward logits or backward gradient scaling, or manual optimization bypassed Lightning's GradScaler unscaling/clipping lifecycle. |
Which systems are affected
- PyTorch Lightning Trainer configurations using precision='16-mixed' or '16-true'
- Transformers, diffusion models, and custom CUDA layers running on NVIDIA GPUs
How to confirm this is the problem
Use this checklist to test the hypothesis against a small reproduction. No single line proves the root cause, so preserve the preceding events and compare one variable at a time.
- ✓Reproduce the failing checkpoint window with precision='bf16-mixed' or fp32 sanity test (limit_train_batches=50).
- ✓Confirm train_loss remains finite and gradient norms stay bounded across warmup and peak learning rate.
Root cause
- FP16 dynamic range (+/-65504) overflowed during forward logits or backward gradient scaling, or manual optimization bypassed Lightning's GradScaler unscaling/clipping lifecycle.
The fix and how to prevent it
How to fix it
- Switch Trainer(precision='bf16-mixed') on Ampere (sm_80) and newer GPUs so exponent range matches FP32 (+/-3.4e38) without requiring a GradScaler.
- If hardware requires FP16, replace extreme mask literals (-1e9) with torch.finfo(tensor.dtype).min and wrap custom loss/softmax reductions in autocast(enabled=False) using .float().
- Ensure gradient clipping (gradient_clip_val=1.0) is enabled and manual optimization calls self.manual_backward(loss) followed by scaler step/update.
- Temporarily run with Trainer(detect_anomaly=True) on a short failing slice to capture the exact first forward/backward op producing NaN.
Step-by-step remediation
- 1If running on A100, L40S, RTX 4090, H100, B200, or RTX 5090 (sm_80+), switch Trainer(precision='bf16-mixed').
- 2Replace hardcoded -1e9 attention masks and compute custom softmax or cross-entropy losses in FP32.
- 3Enable detect_anomaly=True on a small batch slice from the checkpoint just before divergence.
How to prevent it
- Standardize on bf16-mixed for Ampere, Ada, Hopper, and Blackwell clusters.
- Log gradient norms and GradScaler scale values every N steps to catch exploding scales before weights diverge.
Save this diagnosis and catch the next crash automatically
All root cause, fix, and prevention steps above are free to read. Create a free account with any email or GitHub to keep your saved diagnosis history across the encyclopedia and run cloud checks, or use a work email below for the 30-day Team evaluation. No card required.
Or start a 30-day free Team trial (work email)
Verified work email unlocks all 14 fleet diagnostic tools, Slack alerts, and team history for 30 days. No card and no automatic charge.
Searchable error signature
Epoch 0: 4%|4 | 120/3000 [01:12<28:54, 1.66it/s, v_num=0, train_loss=nan]Use this text as a lookup key in logs and upstream issue trackers. It is not presented as a captured customer log. Confirm the cause from your own preceding events, versions, configuration and the cited references.
Diagnose your own log automatically
The root cause and fix steps above stay free. Create a free account to analyze full job logs, attribute the first failed rank, and keep saved incident history.
Sign up free. Analyze your cluster logsNo credit card. Daily allowance follows verified trust tier. Instant access.
Why the recommended fix works
BF16 preserves FP32's 8-bit exponent range, eliminating FP16 exponent overflow and GradScaler instability while keeping Tensor Core speedup.
Code examples
import lightning as L
# Prefer bf16-mixed on Ampere (A100), Ada (L40S/4090), Hopper (H100), Blackwell
trainer = L.Trainer(
accelerator="gpu",
precision="bf16-mixed",
gradient_clip_val=1.0,
)This snippet illustrates the entry-specific check. Verify the installed versions, permissions, target and workload context before using it. A command or API example is not proof of recovery.
Best practices by model family
| Model / Stack | Recommendation | Notes |
|---|---|---|
| Ampere / Hopper / Blackwell GPUs | Use precision='bf16-mixed' | Eliminates FP16 max=65504 overflow and GradScaler tuning. |
| Volta / Turing (FP16 only) | Keep loss/masks in FP32 + grad clip | Never hardcode attention masks like -1e9 into FP16 tensors. |
With the fix vs without the fix
| Dimension | With the fix | Without the fix |
|---|---|---|
| Precision format | precision='bf16-mixed' on sm_80+ GPUs | precision='16-mixed' on large logits or long runs |
| Debugging NaN origin | Trainer(detect_anomaly=True) on bounded steps | Restarting training blindly after checkpoints corrupt |
Diagnostic note
“Grounded in PyTorch Lightning Trainer mixed-precision documentation and IEEE 754 BF16/FP16 numerical dynamic-range behavior.”
Visual fingerprint
train_loss=nan -> GPU >= sm_80? -> switch precision='bf16-mixed' | older GPU? -> check -1e9 masks + cast loss to FP32
Diagnose this failure in VS Code
Select the traceback or open the failed terminal, then run Denpex locally to inspect matched failure patterns, supporting evidence and next checks without uploading the log. Verify recommendations against your workload before changing production.
Install the free VS Code extensionPyTorch GPU errors in context
PyTorch training errors commonly originate at tensor device placement, DataLoader /dev/shm IPC, or checkpoint state restoration.
Compare related pytorch gpu errorsRelated failures to investigate next
Frequently asked questions
Questions engineers and on-call staff commonly ask about this failure.
Why does bf16-mixed rarely need GradScaler compared to 16-mixed?
Can gradient clipping prevent all FP16 NaN losses?
Don't just read the fix, diagnose your run
The encyclopedia explains documented failure patterns. Denpex investigates your logs, configuration and stack, shows the supporting evidence, and asks for missing details when needed.
Related Infrastructure errors
Dual ISP BGP Route Withdrawal Causing Complete GPU Cloud Region Outage
Infrastructure · critical
Routine UPS Maintenance Triggering Cascading Power and Cooling Failure Across GPU Cloud Region
Infrastructure · critical
Remediation Storm Prevention via Circuit Breaker Pattern in AutoClusters
Infrastructure · high
Network Storage Volume Causing Process Hangs on H100 GPU Nodes
Infrastructure · high