pytorch - 💡(How to fix) Fix Add torch.utils.nan_guard for forward-pass NaN/Inf debugging [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#182156Fetched 2026-05-02 05:26:58
View on GitHub
Comments
0
Participants
1
Timeline
5
Reactions
0
Author
Participants
Timeline (top)
labeled ×5

Error Message

propagators. on_detect="warn" for non-raising mode. Leaks hooks on exception.

Fix Action

Fix / Workaround

Motivation PyTorch ships torch.autograd.detect_anomaly for the backward pass, but there's no lightweight forward-only equivalent. When forward activations go NaN, the standard workaround is a copy-pasted snippet:

RAW_BUFFERClick to expand / collapse

🚀 The feature, motivation and pitch

Feature

A forward-pass NaN/Inf debugger for nn.Module:

from torch.utils.nan_guard import NaNGuard

with NaNGuard(model):
    out = model(x)
# NaNGuardError: detected NaN/Inf in output of submodule '3.attn'
# (MultiheadAttention):
#   [0]: shape=(8, 128, 512) dtype=torch.float32 device=cuda:0 nan=512 inf=0
Walks every submodule of model, scans its output (handling tuples / dicts /
nested structures via pytree), and raises naming the first offending
submodule, the path inside its output structure, and tensor stats. Optional
check_inputs=True distinguishes the producer of NaN/Inf from downstream
propagators. on_detect="warn" for non-raising mode.

Motivation
PyTorch ships torch.autograd.detect_anomaly for the backward pass, but
there's no lightweight forward-only equivalent. When forward activations go
NaN, the standard workaround is a copy-pasted snippet:


for n, m in model.named_modules():
    m.register_forward_hook(lambda mod, inp, out, n=n: ...)
Every reinvention of this gets at least one of the following wrong:

Doesn't handle non-tensor outputs (dicts, tuples, dataclasses).
Doesn't separate producers from propagators — every downstream module fires.
Leaks hooks on exception.
Doesn't skip integer / empty / sparse tensors.
Doesn't tell you the path inside a structured output.
A correct version belongs in torch.utils.*.

Pitch
Pure-Python utility next to other debug helpers under torch.utils. No C++,
no autograd-engine changes, no new top-level API surface. Composes with
nn.Module's existing forward-hook machinery — no new abstractions. Cost is
opt-in (only inside the with block) and the docstring is explicit that it's
a debugging tool, not for steady-state training.

Complements torch.autograd.detect_anomaly rather than replacing it.



cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki

extent analysis

TL;DR

Implement a forward-pass NaN/Inf debugger for nn.Module using the proposed NaNGuard utility.

Guidance

  • Use the NaNGuard context manager to wrap the model and x in a with block to detect NaN/Inf in the output of submodules.
  • Set check_inputs=True to distinguish between the producer of NaN/Inf and downstream propagators.
  • Use the on_detect="warn" parameter for non-raising mode to issue warnings instead of raising exceptions.
  • Ensure the NaNGuard utility is used within the torch.utils namespace to maintain consistency with other debug helpers.

Example

from torch.utils.nan_guard import NaNGuard

model = ...  # define the model
x = ...  # define the input
with NaNGuard(model, check_inputs=True, on_detect="warn"):
    out = model(x)

Notes

The implementation of NaNGuard is not provided in the issue, so the example code snippet is based on the usage described in the issue.

Recommendation

Apply the proposed NaNGuard utility as a workaround to detect NaN/Inf in the forward pass of nn.Module instances, as it provides a lightweight and opt-in solution for debugging purposes.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

pytorch - 💡(How to fix) Fix Add torch.utils.nan_guard for forward-pass NaN/Inf debugging [1 participants]