Skip to content

Stop non-finite steps before optimizer updates - #4226

Merged
tianyu-l merged 4 commits into
pytorch:mainfrom
taking-lying-flat:agent/fix-nonfinite-before-optimizer
Aug 20, 2026
Merged

tianyu-l merged 4 commits into
pytorch:mainfrom
taking-lying-flat:agent/fix-nonfinite-before-optimizer

Conversation

@taking-lying-flat

@taking-lying-flat taking-lying-flat commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • check loss finiteness on every training step, independent of metric logging frequency
  • combine loss and gradient-norm finiteness flags across the full distributed world
  • stop before optimizer and learning-rate scheduler updates when any rank reports a non-finite value
  • handle both regular tensors and DTensor loss values

Root cause

The existing non-finite loss check lived in the metrics logging path. Non-logging steps skipped it entirely, and logging steps reached the check only after optimizer.step() and lr_scheduler.step(). A NaN or Inf could therefore corrupt model parameters and optimizer state before training stopped.

Impact

Every gradient-accumulation loss and the clipped gradient norm are now checked through device-side flags. A world-wide reduction makes all ranks take the same failure path before the optimizer update, including pipeline stages that do not own the loss.

  • Tradeoff: _assert_async avoids a per-step host sync; on CPU it raises a catchable RuntimeError, while on CUDA a failed assertion invalidates the process.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 19, 2026
@taking-lying-flat
taking-lying-flat marked this pull request as ready for review August 19, 2026 12:17
Comment thread torchtitan/trainer.py Outdated
torch.distributed.all_reduce(
finite_flags,
op=torch.distributed.ReduceOp.MIN,
group=parallel_dims.world_mesh.get_group(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question 1: should be able to use loss_mesh, instead of world_mesh, because e.g. across all TP ranks the value should be the same

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably should let PP last rank always broadcast loss to other ranks @sanketpurandare

Comment thread torchtitan/trainer.py Outdated
finite_flags = torch.stack(
[loss_is_finite, torch.isfinite(grad_norm).all()]
).to(dtype=torch.int32)
torch.distributed.all_reduce(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question 2: do we need to all-reduce before erroring out, or put in another way, do we need all ranks to error out together? I think

  • even if some rank failed, it's going to be detected and all ranks would stop
  • the introduction of this small collective seems not a big deal, but I'd like to understand the tradeoff

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude help review this PR. In particular, comment on my review feedback.

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 18s —— View job


Review: Stop non-finite steps before optimizer updates

  • Read the diff and surrounding trainer code
  • Trace mesh semantics (world_mesh, loss_mesh, PP grad-norm reduction)
  • Answer @tianyu-l's Q1 (loss_mesh vs world_mesh) and Q2 (need for the collective)
  • Flag other issues

The core direction is right: moving the finiteness check ahead of optimizers.step() / lr_schedulers.step() (and maybe_wait_for_staging()) closes a real hole where a NaN/Inf could corrupt params and optimizer state on non-logging steps. Below are answers to your two questions plus a few additional notes.


Q1 — loss_mesh vs world_mesh for the reduction

The two flags being reduced have very different reduction requirements, and it's worth separating them:

grad_norm flag: this needs no reduction at all. In the standard path, dist_utils.clip_grad_norm_ already returns a globally consistent scalar — total_norm.full_tensor() reduces over the whole SPMD mesh (dp/fsdp/tp/cp), and the explicit dist.all_reduce(..., pp_mesh.get_group()) reduces across PP stages (torchtitan/distributed/utils.py:662-673). So torch.isfinite(grad_norm).all() is already identical on every rank in the world. Reducing it again is redundant.

loss flag: the local loss varies only across the dp and cp axes. Across TP it's replicated (your observation is correct), and PP non-last stages return a finite dummy (torch.tensor([-1.0]), trainer.py:869). So the axis set over which the loss flag actually differs is exactly batch x cp — i.e. loss_mesh. So yes, loss_mesh is the correct/sufficient domain for the loss flag, and world_mesh is over-broad.

One caveat if you switch to loss_mesh: loss_mesh does not span PP. A loss that is non-finite only on the last PP stage would not propagate its loss-flag to stage-0 ranks. In practice that case is still caught because a non-finite loss produces non-finite grads -> non-finite grad_norm, which is PP-reduced and therefore trips the (globally consistent) grad-norm flag on every rank. So combined flag stays consistent across PP. The only theoretical gap is "non-finite loss with finite grad_norm," which effectively cannot happen through autograd.

Net: use loss_mesh for the loss flag; the grad-norm flag needs no collective. [Switch reduction to loss_mesh →](https://claude.ai/code?q=In%20torchtitan%2Ftrainer.py%20around%20line%20957%20on%20branch%20agent%2Ffix-nonfinite-before-optimizer%2C%20change%20the%20all_reduce%20group%20from%20parallel_dims.world_mesh.get_group()%20to%20the%20loss%20mesh%20group%20since%20the%20local%20loss%20only%20varies%20across%20dp%2Fcp%20axes%20and%20grad_norm%20is%20already%20globally%20reduced%20by%20clip_grad_norm_&repo=pytorch/torchtitan)


Q2 — do we need the all-reduce before erroring out?

You're right that even without a collective, training would stop — but the failure mode differs, and that's the tradeoff:

  • Without the collective: grad-norm is already global (see Q1), so in the common case (non-finite loss -> non-finite grads) every rank already agrees and raises together with no collective needed. The collective only adds value for a rank-divergent failure (e.g. loss non-finite on some dp/cp ranks but grad_norm finite). In that corner, the failing rank raises RuntimeError and dies, while the others block in optimizers.step() collectives until the NCCL watchdog timeout (~10 min default) and then abort with a confusing "watchdog timeout" stack rather than the real cause.
  • With the collective: a single MIN over a 2-element int32 tensor guarantees every rank takes the same branch and raises the same clear message immediately — no hang, no misleading NCCL timeout logs.

So the collective buys a clean, synchronized, self-explanatory shutdown in the rank-divergent corner. Given grad_norm is already global, its marginal value over "just check the global grad_norm" is small, but it is cheap. My take: keep a collective, but scope it to loss_mesh per Q1 (the grad-norm part doesn't need it).

However — the bigger cost here isn't the all-reduce, it's the per-step host sync. finite_flags.all().item() forces a device-to-host sync on every step. The original code deliberately avoided this: it reused the D2H copy already done for logging and only ran on logging steps (the removed comment: "reuses the D2H copy already done for logging, so it adds no extra sync"). This PR reintroduces a mandatory per-step .item() sync (plus a per-step small collective), which can break compute/comm overlap in the hot path. That's the real tradeoff to weigh, and it's worth a throughput comparison (>=10 steps per CLAUDE.md) before landing. If per-step checking is the goal, some sync is unavoidable, but it should be a conscious, measured cost.


Additional notes

  1. Dropping import math (trainer.py) is correct — confirmed no other math. usage remains in the file.
  2. int32 conversion for the reduction is the right call — NCCL doesn't support bool reductions, and ReduceOp.MIN over {0,1} correctly means "any rank non-finite -> stop." Good.
  3. DTensor loss handling (to_local() branch) is reasonable, but note torch.isfinite(local_loss).all() on a sharded DTensor's local shard only checks the local shard — which is exactly what you want here since the reduction handles the cross-rank combine. Fine.
  4. Testing: per CLAUDE.md this touches distributed + hot-path behavior. Worth (a) a small unit/integration test that injects a NaN loss and asserts the raise happens before optimizers.step(), and (b) a throughput sanity check to quantify the per-step sync cost. Also confirm behavior under PP (last-stage-only non-finite loss).

Summary: solid fix for the actual bug (check now precedes the optimizer update). I'd (1) reduce the loss flag over loss_mesh rather than world_mesh, (2) drop the grad-norm flag from the collective since it's already globally reduced, and (3) measure/justify the new per-step .item() sync that the original code was careful to avoid.
• branch: agent/fix-nonfinite-before-optimizer

Comment thread torchtitan/trainer.py Outdated
Comment on lines +962 to +966
if not finite_flags.all().item():
raise RuntimeError(
"Loss or gradient norm is not finite on at least one rank at "
f"step {self.step}. Stopping training before the optimizer update."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah as claude said, this is very bad as it creates device-host sync -- I think that's the reason we didn't do this before

Comment thread torchtitan/trainer.py Outdated
torch.distributed.all_reduce(
finite_flags,
op=torch.distributed.ReduceOp.MIN,
group=parallel_dims.world_mesh.get_group(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we probably should let PP last rank always broadcast loss to other ranks @sanketpurandare

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 21s —— View job


Re-review: Stop non-finite steps before optimizer updates

  • Diff the current branch vs. the last review
  • Confirm the two prior concerns (per-step host sync, loss_mesh vs world_mesh) are addressed
  • Trace the new PP + loss_mesh reduction for correctness/deadlock
  • Check the unit-test file against the new behavior

The PR changed substantially since the last pass and it now addresses both of your questions well. One concrete blocker remains (a stale unit test that will fail against the new behavior), plus a tradeoff worth a sentence in the PR description.


What's now resolved

Per-step host sync (your main objection) — fixed. The finite_flags.all().item() D2H sync is gone. It's replaced by torch._assert_async(step_is_finite, msg) (trainer.py:979), which enqueues a device-side assert on the stream before optimizers.step() / lr_schedulers.step(). No .item(), no mandatory D2H per step. This is the right shape for the "check every step without a host sync" goal.

loss_mesh vs world_mesh (Q1) — fixed. The loss flag is now reduced over loss_mesh (batch x cp, trainer.py:960-966), and grad_norm is not in the collective — its finiteness is just checked locally (trainer.py:975) since clip_grad_norm_ already makes it globally consistent. Matches the Q1 conclusion.

PP propagation (your follow-up + Q2) — handled. Non-last PP stages skip the loss_mesh reduce (guarded by pp_has_last_stage), then a pp_mesh MIN all-reduce propagates the last-stage result to every stage (trainer.py:967-973). This is safe from deadlock: loss_mesh is a flattened batch x cp submesh within a single PP coordinate, so a last-stage rank's loss_mesh group contains only last-stage ranks — non-last stages correctly don't join it. Combined with grad_norm being globally consistent (SPMD + PP) and the loss being replicated across TP, step_is_finite ends up identical on every rank in the world, so all ranks hit the assert together. That's a clean answer to Q2 — synchronized shutdown, no divergent watchdog timeout.


Blocker: the unit test now contradicts the implementation

Commit 1b441df ("Remove test changes from PR") reverted tests/unit_tests/test_invalid_loss.py to its main state, which encodes the old semantics:

class TestInvalidLoss(unittest.TestCase):
    """Trainer.train_step crashes on a non-finite loss, aligned with logging.
    The finiteness check ... only runs on steps where metrics are logged."""
    ...
    def test_nan_loss_ignored_when_not_logging(self):
        # Detection is gated on logging, so a non-log step must not raise ...
        self._run_step(float("nan"), should_log=False)

But the whole point of this PR is that the check is no longer gated on logging — loss_is_finite is computed on every accumulation step and asserted before the optimizer regardless of should_log. So test_nan_loss_ignored_when_not_logging now asserts the exact behavior the PR removes: on CPU, torch._assert_async evaluates synchronously and raises RuntimeError, so this test should now fail (the CPU Unit Test run is still queued as I write this). The docstring is also now inaccurate.

This needs to be reconciled before landing:

  • Update the docstring to describe the new "checked every step, before the optimizer" behavior.
  • Replace test_nan_loss_ignored_when_not_logging with a test asserting that a non-finite loss on a non-logging step does raise (that's the bug this PR fixes and the most valuable regression test).
  • Consider re-adding the _assert_updates_not_started assertions that 1b441df dropped — asserting optimizers.step / lr_schedulers.step / maybe_wait_for_staging were not called is the strongest proof of the core claim ("stop before optimizer updates"). Note this requires the assert to raise synchronously, which it does on CPU.

[Fix the stale test →](https://claude.ai/code?q=In%20tests%2Funit_tests%2Ftest_invalid_loss.py%20on%20branch%20agent%2Ffix-nonfinite-before-optimizer%2C%20update%20the%20docstring%20and%20tests%20to%20match%20the%20new%20every-step%20behavior%3A%20a%20non-finite%20loss%20on%20a%20non-logging%20step%20must%20raise%2C%20and%20assert%20optimizers.step%2Flr_schedulers.step%2Fmaybe_wait_for_staging%20were%20not%20called%20before%20the%20raise&repo=pytorch/torchtitan)


One tradeoff to document (not necessarily change)

Switching from raise RuntimeError to torch._assert_async changes the failure mode on GPU:

  • A device-side assert taints the CUDA context and aborts the whole process. It cannot be caught, so there's no opportunity for a graceful shutdown / final checkpoint / clean logging — and the surfaced error is sometimes a generic CUDA error: device-side assert triggered rather than your message, depending on how it propagates. The old RuntimeError was catchable and printed the message directly.
  • torch._assert_async is also a private API (leading underscore), so you're taking a small dependency on non-public behavior.

For a "training diverged, stop now" path, an un-catchable hard abort is arguably acceptable — but since this replaces a clean, catchable error, it's worth one line in the PR description explaining the choice (and confirming the message actually surfaces on your target PyTorch/GPU). If graceful teardown matters, the alternative is a single per-step .item() sync gated behind a config flag; but that reintroduces exactly the sync you're trying to avoid, so I'd lean toward keeping _assert_async and just documenting it.


Minor notes

  1. loss_is_finite.logical_and_(torch.isfinite(local_loss).all()) on an int32 tensor is fine (result coerced to 0/1); the int32 choice for NCCL is correct as before.
  2. The DTensor to_local() branch (trainer.py:933-937) checks only the local shard, which is exactly right here since the cross-rank combine is done by the loss_mesh reduction.
  3. Per CLAUDE.md, a >=10-step throughput sanity check is still worth a mention in the PR body to confirm the device-side assert kernel adds no measurable per-step cost (it shouldn't, but the claim in the code comment — "without synchronizing the host on every step" — is the key selling point and cheap to back up).

Summary: the fix is correct and both of your review questions are now properly addressed (sync removed, loss_mesh scoped, PP propagated, synchronized abort). The remaining must-fix is the reverted unit test, which now encodes the old logging-gated behavior and will fail / misrepresent the change. I'd also add one line to the PR body on the _assert_async vs catchable-RuntimeError tradeoff.
• branch: agent/fix-nonfinite-before-optimizer

@tianyu-l

Copy link
Copy Markdown
Contributor

@taking-lying-flat

The remaining must-fix is the reverted unit test, which now encodes the old logging-gated behavior and will fail / misrepresent the change.

Please fix.

I'd also add one line to the PR body on the _assert_async vs catchable-RuntimeError tradeoff.

Let's add this note into the trainer code.

@tianyu-l
tianyu-l merged commit 56e7b65 into pytorch:main Aug 20, 2026
14 of 15 checks passed
@taking-lying-flat
taking-lying-flat deleted the agent/fix-nonfinite-before-optimizer branch August 20, 2026 05:27
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 22, 2026
Our NaN guard runs AFTER self.optimizers.step() and inspects only the loss, so
a NaN gradient is written into the weights before anything notices.

Job 12473142 is the case in point, from our own 80b/README.md:

  grad_norm nan @30, loss nan @31, nan-abort @35

grad_norm went bad a full step before the loss, so the earliest available
signal was one ahead of the one we were watching -- and five more updates
landed on top of it. A separate incident (job 8663177) ran ~370 NaN steps
unbounded.

The existing guard is also weaker than it looks in practice: nan_abort_
consecutive defaults to 0 (off, trainer.py:221) and production omits the flag
ENTIRELY, because the pinned pre-pytorch#3623 clones have no such field and passing
it crashes every rank (killed umbrella 8680578). So today, at production, a
NaN grad is applied and nothing stops the run.

This adds a host-side isfinite check on grad_norm immediately before the step.
Non-finite -> zero_grad, log, skip the step, still advance the lr scheduler.
The model is left unchanged rather than poisoned; the loss guard keeps its
existing job of deciding whether to abort.

grad_norm is already reduced across ranks (and across pp when pp_mesh is
passed) inside clip_grad_norm_, so every rank sees the same value and branches
identically. No new collective. The .item() is on a value already read for
logging a few lines later.

Deliberately NOT torch._assert_async, which upstream's pytorch#4226 uses for the same
purpose: on CUDA a failed device-side assert invalidates the process, which
our failover machinery would read as a crash rather than a clean stop, and its
XPU behavior is undocumented. Upstream's fix also lands in Trainer.train_step,
which FaultTolerantTrainer overrides wholesale -- so merging pytorch#4226 would give
us nothing here. This is the hand-port.

maybe_wait_for_staging() stays outside the branch: it is a checkpoint concern,
and skipping it on a skipped step would leave an async save un-awaited.

nanguard.pbs smokes it. The bar is bit-identity against the parent commit on a
healthy run, seeded and deterministic at 12 ranks / 1 node / seq=2048 -- the
regime where the control actually holds. A guard in the hot path that
perturbs normal training would be worse than no guard.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 22, 2026
…ning fixes validated

Records the trainer.py ordering bug (guard ran after the optimizer step and
only saw loss, while our own 80B data shows grad_norm going bad a step
earlier), why upstream's pytorch#4226 was unmergeable value (patches a train_step we
override; uses torch._assert_async, undocumented on XPU), both smoke results
with an honest note that ~0.3% tps is below what a single 10-step comparison
resolves, and the sync ancestry finding that invalidated my earlier
land-group-1-first advice.
@wwwjn wwwjn mentioned this pull request Sep 9, 2026
2 of 3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants