Neural Training Incident: Loss Becomes NaN
NaN is the alarm, not the diagnosis. Freeze the run, walk the ordered numeric path, and stop at the first evidenced non-finite boundary before changing the system.
- Authorship
- InterviewsVector
- Published / updated
- 2026-08-25 / 2026-08-25
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.
The decision in one pass
When training becomes non-finite, hold the optimizer update and preserve the failing run, step, checkpoint, optimizer, scaler, batch, data position, objective, precision, distributed, and random state. Instrument an ordered path—input, forward, loss, backward, optimizer—and identify the earliest stage with evidenced NaN or infinity. Bind every stage to the same run, step, model, data, batch, objective, optimizer, precision, loss-scale version and value, owners, element counts, finite magnitude range, workload policy, and complete evidence hash. Then replay and discriminate causes locally. The first non-finite boundary narrows the search and determines containment; it does not prove overflow, bad data, an objective bug, or optimizer corruption by itself.
Why this matters
Incident pressure encourages broad changes: lower the learning rate, add clipping, disable mixed precision, skip the batch. Any may hide the symptom while destroying the only reproducible evidence or corrupting optimizer state. An ordered, fail-closed runbook turns a vague loss became NaN page into a bounded investigation with safe stopping rules and named owners.
You will be able to
- Separate non-finite detection, containment, localization, root-cause testing, recovery, and prevention.
- Trace numeric evidence across input, forward, loss, backward, and optimizer boundaries.
- Explain autocast, reduction precision, loss scaling, unscaling, clipping, and optimizer state as distinct mechanisms.
- Bind complete run, step, model, data, batch, objective, optimizer, precision, loss-scale, evidence, owner, and workload identity.
- Design replay and adversarial tests that fail on missing, reordered, stale, duplicated, non-finite, subnormal, forged, or oversized evidence.
Your Vector Loop for this lab
- 01
Model
Freeze the failing state and draw ordered input, forward, loss, backward, and optimizer trust boundaries.
- 02
Derive
Relate representable range, reductions, scaled loss, unscaled gradients, clipping, and updates without assuming a mechanism.
- 03
Build
Capture typed stage telemetry and issue a HOLD at the earliest content-addressed non-finite boundary.
- 04
Stress
Attack ordering, scope, ownership, counts, scale evidence, identities, numeric resolution, state transitions, and work bounds.
- 05
Operate
Replay the smallest failing state, recover from a known-good checkpoint, and add a targeted preventive control.
- 06
Defend
Defend containment and evidence while stating which root causes remain observationally indistinguishable.
Contain before the bad value edits more state
Find the first failed training contract
Inspect one ordered ingress, batch, forward, backward, optimizer, and validation scenario; identify the earliest failed contract, then reveal why downstream symptoms do not move that boundary.
Training incident lab
Find the first evidenced failure boundary
Read the telemetry in execution order. Identify the first stage whose observed value violates its declared contract, while keeping localization separate from an unobserved root-cause claim.
Evidence discipline
- Compare observed values with the local contract.
- Respect execution order; do not start at the loudest symptom.
- Call the boundary evidenced, not the cause proven.
| Order | Stage | Measured signal | Contract | Observed |
|---|---|---|---|---|
| 01 | Ingress | Manifest rows loaded | 120,000 rows | 120,000 rows |
| 02 | Batch assembly | Finite feature cells | 100.00% | 99.72% |
| 03 | Forward pass | Finite activations | 100.00% | 91.40% |
| 04 | Backward pass | Finite gradients | 100.00% | 88.10% |
| 05 | Optimizer step | Committed updates | 4,000 steps | 1,184 steps |
| 06 | Validation | Completed evaluation shards | 24 shards | 0 shards |
Boundary rule: choose the earliest row where observed telemetry no longer satisfies the row's contract. Later rows help establish blast radius; they do not move the first observable boundary upstream.
Make a prediction, then check it against the current evidence.
The laboratory is a general contract-ordering exercise: it grades only the first failed stage across ingress, batch, forward, backward, optimizer, and validation. It does not ask for a containment choice and it is not the artifact's numeric telemetry schema. The executable runbook later narrows the path to input, forward, loss, backward, and optimizer, where non-finite counts determine a HOLD action.
- 01Hold the updateDo not step the optimizer or silently skip forward without recording the decision. A non-finite gradient can contaminate moments and parameters.
- 02Preserve the boundaryCapture run and step IDs, checkpoint, optimizer, scheduler, scaler, batch identity, loader cursor, random state, environment, and distributed topology.
- 03Mark the last known-good stateRetain a recovery point whose model, optimizer, scheduler, scaler, and data position were verified together.
- 04Choose replay authorityAssign one incident owner and stage owners; avoid multiple responders changing learning rate, data, and precision at once.
Walk the numeric path in execution order
| Stage | Evidence to capture | Examples of hypotheses—not conclusions |
|---|---|---|
| input | raw/decoded ranges, masks, labels, counts | corrupt record, invalid transform, empty denominator |
| forward | first bad activation, logits, normalization stats | overflow, invalid domain, unstable custom kernel |
| loss | per-example terms, reductions, denominators | log zero, mask divide-by-zero, excessive reduction |
| backward | scaled/unscaled gradients by parameter | overflow, bad derivative, detach or reduction issue |
| optimizer | moments, update, parameters before/after | corrupt state, excessive update, wrong unscale order |
Check complete tensors or a declared, bounded summary whose finite and non-finite element counts reconcile. A finite maximum alone cannot prove a tensor is finite because a reduction may ignore NaN, sample the wrong slice, or run after the value was replaced. Name the tensor set and probe source at every boundary.
Keep mixed-precision mechanisms in the right order
Lscaled = S·L; gscaled = S·∂L/∂θ; g = gscaled/S
Loss scaling moves small gradients into a representable range. The scale must be finite, positive, versioned, and paired with the step. It does not repair a non-finite forward value.
- 01Autocast selected operationsReduced precision can accelerate safe kernels while reductions or sensitive functions remain at a wider type.
- 02Scale before backwardA declared scaler multiplies the loss so small gradient components are less likely to underflow.
- 03Unscale before clipping or inspectionThresholds and finite checks intended for real gradients must see the unscaled magnitude unless explicitly defined otherwise.
- 04Step only after qualificationIf the framework detects non-finite gradients, record the skipped update and scaler transition as evidence rather than calling the run recovered.
Build a runbook that holds on evidence, not intuition
1 actions = {2 "input": "hold-and-inspect-input-data-contract",3 "forward": "hold-and-replay-forward-activations",4 "loss": "hold-and-inspect-objective-reduction",5 "backward": "hold-and-inspect-gradient-path-and-loss-scaling",6 "optimizer": "hold-and-inspect-optimizer-state-and-update",7 }8 return IncidentReport(9 contract_content_id=contract.content_id,10 evidence_id=evidence.evidence_id,11 evidence_content_id=evidence.evidence_content_id,12 decision="HOLD" if earliest is not None else "CONTINUE_BOUNDED_DIAGNOSTICS",13 earliest_nonfinite_stage=earliest,14 action=actions[earliest] if earliest is not None else "no-nonfinite-evidenced-check-other-signals",15 root_cause_claim="NONE_SYMPTOM_LOCATION_IS_NOT_CAUSALITY",16 )Expected output
example=illustrative_only
contract_version=training-incident-v1
run=run-2026-08-25-001
step=1842
evidence_content_id=training-incident-evidence@sha256:9e972d95a21289528822637d157b32eee66be582d614bc2ed5d4beb6e08ffcc9
earliest_nonfinite=backward
decision=HOLD
action=hold-and-inspect-gradient-path-and-loss-scaling
root_cause_claim=NONE_SYMPTOM_LOCATION_IS_NOT_CAUSALITYVerify: python3 -m unittest discover courses/ai-engineering/reference-impl/neural_training_incident
The excerpt is literal source. The artifact requires concrete immutable records for all five stages, validates their exact order, owners, reconciled element counts, and observed/not-run transitions, and binds the run, step, model, data, batch, objective, optimizer, precision, loss-scale evidence, and probe sources. It rejects duplicate telemetry and tensor-set identities, recomputes the complete evidence hash, revalidates constructor-bypass mutations, caps per-stage and total work, and rejects booleans, NaN, infinity, sub-resolution summaries, unsafe scales, and excessive finite magnitudes. A later stage can be explicitly NOT_RUN only after an earlier non-finite boundary.
Replay locally and discriminate mechanisms
- 01Reproduce without an updateLoad the complete pre-step state and failing batch, enable deterministic settings where feasible, and confirm the first bad boundary.
- 02Shrink the graphRun one example, then one layer or loss term around the earliest boundary while preserving the triggering values.
- 03Change one mechanismCompare precision, loss scale, reduction, input record, or implementation one at a time under the same replay contract.
- 04Inspect upstream finite extremesA stage can remain finite yet enter a range that guarantees the next exponential, division, square, or reduction will overflow.
- 05Prove recoveryResume from a known-good state, replay the fixed case, run a bounded continuation, and verify quality and state integrity before reopening the run.
| Candidate intervention | What it tests | What it can conceal |
|---|---|---|
| wider precision replay | range or rounding sensitivity | objective or data bug that remains finite |
| lower loss scale | backward scaling overflow | forward/loss invalidity |
| gradient clipping | excess finite update magnitude | non-finite gradients and wrong derivatives |
| stable log-sum-exp | unstable exponential reduction | incorrect targets or masks |
| different batch | batch-specific trigger | systematic corruption in a rare slice |
Convert the incident into a preventive boundary
- Add a named finite/range assertion immediately before and after the confirmed failing operation, with bounded sampling overhead.
- Create a regression fixture from sanitized triggering values and test the exact precision, reduction, scaler, and optimizer order.
- Checkpoint model, optimizer, scheduler, scaler, random, and data-loader state atomically enough for the promised recovery level.
- Alert on finite extremes and skipped updates before aggregate loss becomes non-finite, while retaining stage and slice support.
- Document rollback, quarantine, resume, and data-remediation authority so incident containment does not become an improvised product decision.
The runbook performs O(S) validation for five stage summaries and stores O(S) report evidence; collecting those summaries can be O(number of inspected elements). The contract therefore caps each stage and the total. Real incident tooling should balance complete finite checks at critical boundaries with sampled distributions elsewhere, then retain full tensors only under controlled diagnostic capture.
Operate at three altitudes
Production lens
- — Guard critical input, forward, loss, unscaled-gradient, optimizer-state, update, and parameter boundaries before corrupted state propagates.
- — Capture the complete pre-failure checkpoint, scaler, batch, loader position, random state, environment, and distributed topology promised by replay.
- — Record skipped steps, loss-scale transitions, clipping order, gradient accumulation, and reduction precision as algorithm state.
- — Resume only after the triggering replay, bounded continuation, optimizer integrity, and downstream quality gates pass.
Staff lens
- — Define one ordered failure tree and telemetry vocabulary across data, model, objective, runtime, optimizer, and platform teams.
- — Assign decision rights for holding jobs, quarantining data, rolling back code, restoring checkpoints, and reopening training.
- — Require checkpoint-resume drills that prove the actual recovery point objective rather than assuming serialization is complete.
- — Review instrumentation overhead, evidence retention, privacy, and access before an incident forces unsafe tensor capture.
Interview defense
A mixed-precision training loss becomes NaN. How do you debug it?
I first hold the optimizer update and capture the failing run, step, full pre-step state, batch, objective, precision, scaler, and environment. I check ordered boundaries—input, forward, loss, backward, optimizer—and locate the earliest evidenced non-finite tensor with reconciled counts. Then I replay the smallest failing case and vary one mechanism at a time: input validation, sensitive forward operation, objective reduction, loss-scale and unscale order, gradients, or optimizer state. I do not assume mixed precision is the cause from the symptom. I recover from a known-good complete checkpoint and add a targeted assertion and regression before resuming.
Expect the interviewer to press on
- — Why must clipping usually inspect unscaled gradients?
- — What state is needed for an exact replay?
- — Why can skipping the batch make diagnosis harder?
Misconceptions to remove
“NaN loss means the learning rate is too high.”
It is one hypothesis. Invalid input, forward domain errors, unstable reductions, bad derivatives, scaling order, and corrupted optimizer state can produce the same symptom.
“Gradient clipping fixes non-finite gradients.”
Clipping bounds finite magnitude under a declared norm. NaN or infinity must be detected and the update held.
“If mixed precision fails, switching the entire run to float32 proves the cause.”
A wider replay shows range or rounding sensitivity. It may also mask an invalid computation, so the earliest boundary and mechanism still need isolation.
Check your model
1. Why check input before forward even when loss is the first visible NaN?
The loss is downstream. Non-finite or out-of-contract input can propagate through apparently opaque operations; the earliest boundary determines the useful local replay.
2. What does the first non-finite stage prove?
Only that this is the earliest instrumented boundary with supported non-finite evidence for the bound run and step. It narrows investigation but does not identify root cause.
3. Why bind the loss-scale value and version?
They determine scaled gradient magnitude and skipped-step behavior. Evidence from a different scaler state cannot certify this backward path.
Prove the mechanism
Create an ordered incident fixture across input, forward, loss, backward, and optimizer. Bind run, step, model, data, batch, objective, optimizer, precision, loss-scale, probe, owner, numeric, and workload evidence. Return HOLD at the earliest non-finite boundary and add tests for every boundary, missing or reordered stages, invalid NOT_RUN transitions, duplicate IDs, stale scopes, wrong owners, bool, NaN, infinity, subnormal and excessive summaries, unreconciled counts, tampered hashes, and workload overflow.
Add a production constraint
Integrate framework hooks that capture parameter-group gradient summaries before and after unscale and clipping. Add distributed rank evidence, atomic checkpoint manifests, privacy-aware triggering-tensor capture, and a deterministic replay command; prove that the recovered run matches a clean control for a bounded continuation.
Artifact: Neural training incident runbook
courses/ai-engineering/reference-impl/neural_training_incident/training_incident_triage.py
Download reference implementationPrimary references and next links
References
- 1. Mixed Precision Training
Micikevicius et al.. Primary paper grounding reduced-precision arithmetic, wider accumulation, master weights, and loss scaling.
- 2. Automatic Mixed Precision package
PyTorch. Official documentation used to check autocast, gradient scaling, unscaling, and skipped-step responsibilities.
- 3. tf.debugging.check_numerics
TensorFlow. Official API reference used to check fail-fast NaN and infinity detection at named tensor boundaries.
Continue through the graph
- Backpropagation as Local Contracts →
Use local derivative contracts to isolate a backward-stage failure.
- Read Optimization Dynamics →
Distinguish harmful update dynamics from non-finite execution.
- Numerical Stability Is Part of the Algorithm →
Repair sensitive reductions and representable-range failures at the algorithm boundary.
Glossary: non-finite · autocast · loss scaling · unscale · gradient clipping · optimizer state · replay · containment · earliest evidenced boundary