Skip to content

CrossEntropyLoss NaN on Pure Ignore-Index Batch

When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0). This results in 0/0, which is NaN.

Quick answer

When using `torch.

Symptom
RuntimeError: unscale_() expected input to not be nan
Root cause
When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0).
Recommended fix
Skip the batch or handle the reduction manually valid_mask = (targets != -100) if not valid_mask.any(): return torch.tensor(0.0, requires_grad=True) else: return criterion(outputs, targets) Bypasses the loss calculation when there are no valid targets to evaluate, preventing the division by zero.
How Denpex helps
Denpex investigates CrossEntropyLoss NaN on Pure Ignore-Index Batch 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.
Loss#Empty Batch Division

What this failure is

CrossEntropyLoss NaN on Pure Ignore-Index Batch is a Loss failure seen during ML training runs. When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0). This results in 0/0, which is NaN. Common tags: Empty Batch Division.

Live diagnosis, no signup

Is this what broke your run? Paste your log.

You're reading about CrossEntropyLoss NaN on Pure Ignore-Index Batch. 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 diagnoses/day

Why it happens (the mechanism)

Since it only happens on specific batches based on data distribution, it looks like a corrupted data sample rather than a PyTorch edge case.

What you'll observe

  • Loss equals exactly nan
  • RuntimeError: unscale_() expected input to not be nan

Common symptoms and what they mean

SymptomWhy it happens
Training occasionally outputs a single `nan` loss on specific batches, often highly padded batches or fully masked out labels.When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0). This results in 0/0, which is NaN.
Subsequent training continues, but if gradients are unscaled and stepped, weights become corrupted.When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0). This results in 0/0, which is NaN.

Which systems are affected

  • PyTorch

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.

  • ✓Check the unique values of `target` tensors when loss is NaN.
  • ✓Add a condition: `if (targets != -100).sum() == 0: print("Empty batch detected")`

Root cause

  • When using `torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='mean')`, if every target in the batch happens to equal `-100`, PyTorch calculates the sum of the valid losses (which is 0) and divides by the number of valid targets (which is also 0). This results in 0/0, which is NaN.

The fix and how to prevent it

Searchable error signature

search key
RuntimeError: unscale_() expected input to not be 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.

The fix and the prevention pattern

The root cause is on this page and stays free. A free account adds the exact remediation steps, saved history, and the fix on every entry in the encyclopedia.

Sign up free. Unlock the full analysis

No credit card. Daily allowance follows verified trust tier. Instant access.

Diagnose this failure in VS Code

Select the traceback or open the failed terminal, then run Denpex locally to see the initiating rank, collateral failures, exact fix, and verification command without uploading the log.

Install the free VS Code extension

Don't just read the fix, diagnose your run

The encyclopedia tells you what went wrong. Denpex tells you what went wrong in YOUR training run. With your logs, your config, and your stack.