Skip to content

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.

Quick answer

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.
Infrastructure#pytorch-lightning#fp16#bf16#mixed-precision#nan#amp

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.

Live diagnosis, no signup

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.

training_logs.txt
No log to hand? Try one:

Upload your log file. Large files are processed in your browser. Only selected evidence is submitted when you run diagnosis.

3 free cloud diagnoses per day

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.

SymptomPossible 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 functionsFP16 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

  1. 1If running on A100, L40S, RTX 4090, H100, B200, or RTX 5090 (sm_80+), switch Trainer(precision='bf16-mixed').
  2. 2Replace hardcoded -1e9 attention masks and compute custom softmax or cross-entropy losses in FP32.
  3. 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.

Use your company email, for example alex@yourcompany.com.

Who qualifies?

Company email domains activate the free 30-day Team evaluation (up to 50 diagnoses a day) after an email and domain check, whatever mail provider you use. If we cannot verify your domain automatically, support reviews it: write to support@denpex.com. Free local diagnosis in the editor extension needs no account.

Using a personal email (Gmail, Outlook, Naver, QQ) or solo cluster? Create a free $0 account (no work email required) to save 7-day history and unlock AI fallback, or send a cluster crash log for a live walkthrough.
Already have an account? Sign in

Searchable error signature

search key
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 logs

No 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

snippet
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 / StackRecommendationNotes
Ampere / Hopper / Blackwell GPUsUse precision='bf16-mixed'Eliminates FP16 max=65504 overflow and GradScaler tuning.
Volta / Turing (FP16 only)Keep loss/masks in FP32 + grad clipNever hardcode attention masks like -1e9 into FP16 tensors.

With the fix vs without the fix

DimensionWith the fixWithout the fix
Precision formatprecision='bf16-mixed' on sm_80+ GPUsprecision='16-mixed' on large logits or long runs
Debugging NaN originTrainer(detect_anomaly=True) on bounded stepsRestarting 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

Lightning FP16 NaN diagnostic decision
train_loss=nan -> GPU >= sm_80? -> switch precision='bf16-mixed' | older GPU? -> check -1e9 masks + cast loss to FP32
Match numeric format to hardware exponent capabilities and keep sensitive reductions in 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 extension

PyTorch 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 errors

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?
BF16 shares the same 8-bit exponent width as FP32, so normal training gradients and activations do not underflow to zero or overflow above 65,504.
Can gradient clipping prevent all FP16 NaN losses?
No. Gradient clipping runs after backward gradients exist; if forward activations already overflowed FP16 or NaN entered before unscaling, clipping cannot repair corrupted forward tensors.

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.