Unit 5 of 9 · about 4 hours · measure

Overflow, underflow and finding the first invalid value

A NaN loss names no culprit. The only cheap evidence is the first invalid value and the operation that made it, and both need instrumentation in place before the failure.

You'll be able to

  • Explain why mathematically identical floating-point computations may differ bitwise across batches, slices and backends.
  • Enable anomaly detection to name the first backward function that produces NaN, with its forward traceback.
  • Place isfinite checks so an invalid value is caught at creation, not ten steps later.

Covers

Nonassociativity, overflow and underflowFirst-invalid-value instrumentation
1

Read

In this order, only the parts listed

0 of 3 done

  1. Nonassociativity, batches, slices and extremal valuesPyTorch - checkpointing, numerical accuracy and CUDA semantics

    Opening paragraphs on limited accuracy and nonassociativity; Batched computations or slice computations with the bmm and sum examples; Extremal values with the norm overflow example and the isfinite advice

  2. Anomaly detection referencePyTorch - checkpointing, numerical accuracy and CUDA semantics

    detect_anomaly and set_detect_anomaly: forward traceback of the failing operation plus the check_nan error on NaN generated in backward; debug-only slowdown warning

  3. Debugging APIs stay off in timed runsPyTorch - reliability and performance recipes

    General optimizations, Disable debugging APIs: anomaly detection, profiler hooks and gradcheck off for regular training

2

Focus on

  • Floating point addition and multiplication are not associative. Batching, slicing and backend choice change reduction order, so bitwise identity is never promised.
  • Overflow can strike intermediates while the final value is representable. The fp32 norm of [1e20, 1e20] is inf while the fp64 norm is finite.
  • Anomaly detection answers which backward made NaN, not which forward looked odd. check_nan fires on NaN generated inside backward.
  • Detection and profiling both slow execution. Neither belongs in a timed run or a production loop.
Common mistakes · 3
  • Asserting bitwise equality across batch sizes, slices or devices. The docs promise nothing here; compare with a tolerance.
  • Expecting anomaly detection to flag NaN flowing from forward. Log of a negative is NaN forward with a finite grad of -1, and check_nan stays silent because backward generated nothing invalid.
  • Leaving anomaly detection or the profiler on while timing. Both add overhead, so a slow profiled run proves nothing about the clean run.
3

Try it yourself

Closed-book, before checking anything

On CPU, show torch.tensor([1e20, 1e20]).norm() gives inf while the double version is finite. Then run (x / x).backward() at x = 0 under autograd.detect_anomaly() and record the exact error naming DivBackward0 and its NaN output.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Under detect_anomaly, (x / x).backward() at x = 0 names DivBackward0. What does that name identify?Answer

    The backward function whose output went NaN, hence the forward division. The mode also prints the traceback of that forward call.

  2. 2.torch.log of -1.0 gives NaN forward and grad -1.0 with no anomaly error. Why silent?Answer

    check_nan fires on NaN generated by backward computation. Here backward computed the finite value , so there is nothing to report.

  3. 3.(A@B)[0] equaled A[0]@B[0] bitwise on your machine. May a test assert == across batchings?Answer

    No. Bitwise identity across batched and unbatched paths is not guaranteed, so assert allclose with an explicit tolerance.

  4. 4.Times look bad with anomaly detection and the profiler enabled. What is the first correction?Answer

    Disable both for timed runs. Both are debug-only overhead, so their timings do not describe the clean run.

5

Practice

  • TrenTorch: FP16/BF16 Representable Range

    Implement cast_to_dtype, detect_underflow and detect_overflow with NumPy float16

    In float16, magnitudes below about 3e-8 round to 0 and values from 65,520 up overflow to inf. The section mini-project then adds first-invalid capture and seeded NaN diagnosis with fixed-batch replay.

You're done when

You can produce the named DivBackward0 error on demand, and every equality in your checks carries an explicit tolerance.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 7 more in the section
  • PyTorch - reliability and performance recipesPyTorch · primary

    Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.

  • PyTorch - checkpointing, numerical accuracy and CUDA semanticsPyTorch · required

    Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.

Also in this section

  • PyTorch - compiler troubleshootingPyTorch · required

    Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.

  • Deep Learning Training DebuggerRoadmap-Final · reference

    Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.

  • TensorTonic - mixed-precision memory and transformer FLOPsTensorTonic · support

    Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.

  • Learn PyTorch - profiler walkthroughDaniel Bourke · optional

    Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.

  • TrenTorch - precision, checkpointing and resumeTrenTorch · support

    Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.

  • Python os - `os.replace`Python Software Foundation · reference

    Read os.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, then replace the final name.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.