Repository navigation
Conversation
yushangdi
force-pushed
the
sy_debug_md
branch
7 times, most recently
from
May 2, 2026 01:30
13e20eb to
4602220
Compare
yushangdi
force-pushed
the
sy_debug_md
branch
3 times, most recently
from
May 9, 2026 01:11
340ade9 to
74f4f6f
Compare
yushangdi
added a commit
that referenced
this pull request
May 22, 2026
# PR Summary: DebugMode-Based Numerics Debugger ## Overview Example output: llama3: https://www.internalfb.com/intern/px/p/9N1sk/ qwen3: https://www.internalfb.com/intern/px/p/9N2ph/ <img width="1456" height="741" alt="Screenshot 2026-05-12 at 2 33 05 PM" src="https://github.com/user-attachments/assets/1642b110-3c07-48d9-8bce-fc57e547b175" /> This PR adds a DebugMode-backed numerics debugger for TorchTitan training runs. It introduces a `--profiler.dump_numerics` flag that captures per-op activation metadata during a selected training step and a `torchtitan.tools.compare_numerics` CLI that compares two capture logs and writes an interactive HTML diff. It can be used to compare bit-wise equivalent numerics 1) between different eager runs 2) between different traced runs 3) between eager and traced runs under the same seed, deterministic settings, precision, and parallelism. An alternative implementation that uses a standalone activation tracker is at #3190. However, it has some problem with eager code source line tracking. It also doesn't track input hashes and input sources (i.e. which op produced the input). As I add those features, I feel like I'm re-inventing DebugMode, so I just switched back to DebugMode implementation. **I do not expect the default and deterministic matching algorithm to perfectly match all the ops, especially when comparing eager vs traced runs. But agent should do a pretty good job and use manual override to update the visualization.** ## What Changed ### Per-op numerics capture - Added `torchtitan/tools/activation_tracer.py`. - Captures per-op output stats: - shape and dtype - output DebugMode norm hash, L2 norm, min, max, mean - input DebugMode norm hashes - input producer attribution where available - module FQN, source location, and forward/backward phase - Uses `torch.utils._debug_mode.DebugMode` with: - `record_nn_module=True` for eager module attribution - `record_stack_trace=True` for source locations and autograd forward traces - `record_ids=True` for tensor ID based producer tracking - `DebugMode.log_tensor_hashes(hash_fn="norm", hash_inputs=True)` for output and pre-op input hashes - Computes tensor stats inline during dispatch instead of retaining tensor clones, keeping memory bounded during capture. - For tuple/list outputs, records all output tensor hashes from DebugMode; shape/dtype and secondary stats are taken from the first captureable tensor output. - Tracks skipped excluded ops and writes them into the log header so the HTML report can show what was intentionally filtered. ### Profiler integration - Added `Profiler.Config.dump_numerics`, exposed as `--profiler.dump_numerics`. - The profiler now builds a `NumericsDebugger` when numerics dumping is enabled. - Capture is aligned with `--profiler.profile_freq`; for example, `--training.steps 2 --profiler.profile_freq 2` captures step 2. - `Trainer` now passes `model_parts[0]` into the profiler so the debugger can install module hooks needed for FQN attribution. - Output path: ```text {dump_folder}/numerics/rank_{rank}_activations.log ``` Example log format: ``` For tuple/list outputs, `Output hash` is comma-separated and includes every captureable tensor output. [layers.0._checkpoint_wrapped_module.attention.qkv_linear.wq/op_0_mm] Shape: torch.Size([16384, 256]), Dtype: torch.bfloat16 L2 norm: 6.348642e+02 Min: -1.140625e+00 Max: 1.242188e+00 Mean: -2.894286e-03 Output hash: 1.038582e+06 Input hashes: 3.125000e+05, 8.441234e+04 Input producers: layers.0.attention_norm/op_0__fused_rms_norm; Location: torchtitan/train.py:66 ``` ### Graph trainer support - Added `FQNInterpreter` in `torchtitan/experiments/graph_trainer/debug_utils.py`. - `GraphTrainer` uses `FQNInterpreter` only while numerics capture is active. - Normal graph-trainer execution stays on the direct `gm(*inputs)` path when capture is not active. - During traced replay, `FQNInterpreter` restores per-node metadata into context vars so traced captures carry comparable module FQNs, stack locations, and forward/backward phase. ### HTML comparison tool - Added `torchtitan/tools/compare_numerics.py`. - Parses two activation logs. - Matches ops across runs using: - manual overrides from `--override` - exact normalized op keys - fuzzy op keys with per-module counters stripped - stats-based fallback matching - Produces a self-contained HTML report with: - forward/backward sections - match, diff, run1-only, and run2-only filters - match-strategy chips - output and input hash comparison - per-cell relative-diff coloring - input-producer hover tooltips - skipped-op chips for excluded dispatched ops ### Tests - Added `tests/unit_tests/test_activation_tracer.py`. - Added `tests/unit_tests/test_compare_numerics.py`. - Added `torchtitan/experiments/graph_trainer/tests/test_numerics_debugger_e2e.py` and wired it into the 8-GPU graph-trainer integration workflow. - Coverage includes capture filtering, FQN cleanup, stack parsing, DebugMode capture behavior, tuple-output hash capture, profiler-driven dumping, traced replay context propagation, log parsing, matching strategies, override handling, input producer rendering, skipped-op rendering, HTML escaping, and an eager-vs-`aot_fx_trace` Llama3 E2E check with minimum match-quality assertions. ## How Phase, Stack Location, and Module FQN Are Determined The capture path combines DebugMode metadata, graph-trainer FX metadata, and an autograd-node-to-module map. The source depends on whether the op runs in eager or traced replay, and whether it is a forward or backward op. | Mode | Phase | Phase source | Stack location source | Module FQN source | | --- | --- | --- | --- | --- | | Eager | Forward | No active autograd node, so `record_hook` labels it `forward`. | DebugMode live dispatch traceback from `record_stack_trace=True`, filtered to remove torch internals, DebugMode frames, checkpoint plumbing, and interpreter frames. | DebugMode `current_nn_module_stack` from `record_nn_module=True`; the root model-class prefix is stripped so keys match `named_modules()` style. | | Eager | Backward | `torch._C._current_autograd_node()` is non-null, so `record_hook` labels it `backward`. | DebugMode autograd-saved forward traceback, parsed and filtered. This is available because stack recording enables anomaly metadata without enabling nan checking. | `_grad_fn_to_module[autograd_node]`, populated during forward by global module hooks and `_record_grad_fn`. | | `aot_fx_trace` replay | Forward or backward | `FQNInterpreter` reads `node.meta["autograd_backward"]` and sets `_current_phase_override`. | `FQNInterpreter` reads `node.meta["stack_trace"]`, parses it, and sets `_current_stack_frames`. | `FQNInterpreter` reads `node.meta["custom"]["module_fqn"]` and sets `_current_module_name`. | The priority order inside `DebugModeTracer.record_hook` is: 1. Use context vars set by `FQNInterpreter` when replaying traced graphs. 2. Fall back to DebugMode `ModTracker` for eager forward ops. 3. Fall back to `_grad_fn_to_module` for eager backward ops. 4. Use `"<none>"` only if no attribution source is available. ## How Matching Works in `compare_numerics` `torchtitan.tools.compare_numerics` parses both activation logs into ordered `OpEntry` lists, then `match_entries` aligns them with progressively more relaxed passes. Earlier passes claim entries first, and the final HTML keeps first-log order for paired and first-only rows. 1. Manual overrides: if `--override <csv>` is provided, each `<log1_key>, <log2_key>` pair is forced before automatic matching. This handles known structural attribution differences such as activation-checkpoint recompute FQNs, FSDP collective renaming, and layer counter shifts. 2. Exact key match: compares normalized `module_fqn/op_N_opname` keys. Normalization strips a leading root class segment like `FSDPLlama3Model.` so eager DebugMode keys match traced metadata keys. 3. Fuzzy key match: strips the per-module op counter, so `layers.0.feed_forward/op_7_mul` can match another `layers.0.feed_forward/mul` when counters drift between modes. 4. Stats match: falls back to `(op_type, Shape, output_hash)`, which catches semantically identical ops whose FQN differs across backends. Once a pair is found, `_compute_match_status` decides whether it is a match or diff using only shape, output hash, and input hashes. L2/min/max/mean are still shown and colored in the HTML, but they do not drive the match/diff classification because they are secondary summaries of the same tensor. ## How `_record_grad_fn` Attributes Backward Ops to Modules Backward ops run through the C++ autograd engine, so eager module forward stacks are no longer active when those ops dispatch. To recover module attribution, `DebugModeTracer` installs global module forward pre/post hooks while capture is armed. The pre-hook records input `grad_fn`s for the module. Those input nodes define the boundary to the caller or sibling modules. The post-hook calls `_record_grad_fn(output, module_fqn, input_grad_fns)`. `_record_grad_fn` walks backward from each output tensor's `grad_fn` through `next_functions`: ```python stack = [output.grad_fn] visited = set() while stack: fn = stack.pop() if fn in visited or fn in input_grad_fns: continue visited.add(fn) if fn not in _grad_fn_to_module: _grad_fn_to_module[fn] = module_fqn for parent, _ in fn.next_functions: if parent is not None and parent not in visited: stack.append(parent) ``` Two details matter: - It does not overwrite an existing mapping. Child modules finish their post-hooks before parent modules, so child-owned ops keep the more specific FQN. - It still walks through already-mapped nodes. This lets a parent module claim "glue" ops that happen between child modules, such as `silu` and `mul` inside a feed-forward block, without taking ownership of the child linear ops. During backward capture, `record_hook` looks up the current autograd node in `_grad_fn_to_module` and uses the mapped FQN for the captured op. ## Expected Workflow ```text +-------------------------------------------------------------+ | 1. Run two comparable training jobs | | | | - same seed | | - deterministic debug mode | | - same precision and parallelism | | - `--profiler.dump_numerics` | | - same capture step via `--profiler.profile_freq` | +-------------------------------------------------------------+ | v +-------------------------------------------------------------+ | 2. Generate the comparison HTML | | | | - run `python -m torchtitan.tools.compare_numerics` | | - inspect matched rows, diffs, run-only rows, input hashes, | | and producer links | +-------------------------------------------------------------+ | v +-------------------------------------------------------------+ | 3. Triage the comparison | +-------------------------------------------------------------+ | | | v v v +----------------------+ +----------------------+ +----------------------+ | 3a. Real discrepancy | | 3b. Bad match | | 3c. Numerics match | | | | | | | | - fix implementation | | - ask agent for | | - done | | - recapture runs | | override pairs | | | | | | - regenerate HTML | | | +----------------------+ +----------------------+ +----------------------+ | | | | v v back to step 1 back to step 2 ``` Manual overrides use this format: ```csv # Format: <first_log_key>, <second_log_key> feed_forward/op_0_silu, layers.5.feed_forward/op_2_silu layers.0/op_1_add, layers.0/op_0_add tok_embeddings/op_0__allgather_base_, tok_embeddings/op_1_all_gather_into_tensor_out layers.0/op_1__allgather_base_, layers.0.attention_norm/op_1_wait_tensor ``` An example override CSV is available at [P2321486470](https://www.internalfb.com/phabricator/paste/view/P2321486470). It covers activation-checkpoint recompute pairings, layer-level counter shifts, and FSDP collective renaming/lowering, including traced `wait_tensor` rows for synchronized collective results. This workflow is agent-friendly. In practice, asking an agent to explain discrepancies or batch-generate candidate manual overrides from the two logs usually works well; the reviewer still needs to sanity-check that each override pairs semantically equivalent ops before accepting the regenerated comparison. ## Example Usage The full example script is: ```bash ./agent_space/run_numerics_debug_mode.sh ``` It runs eager and `aot_fx_trace` captures with the same seed and deterministic settings, then generates an HTML diff. ### Eager capture ```bash NGPU=${NGPU:-2} DP_SHARD=${DP_SHARD:-2} SEED=42 DUMP_FOLDER=./outputs_numerics_debug_mode NGPU=$NGPU MODULE=llama3 CONFIG=llama3_debugmodel \ ./run_train.sh \ --dump_folder $DUMP_FOLDER/eager \ --training.steps 2 \ --profiler.dump_numerics \ --profiler.profile_freq 2 \ --debug.seed $SEED \ --debug.deterministic \ --parallelism.data_parallel_shard_degree $DP_SHARD \ --training.mixed_precision_param float32 ``` ### `aot_fx_trace` capture ```bash NGPU=$NGPU MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel \ ./run_train.sh \ --dump_folder $DUMP_FOLDER/traced \ --training.steps 2 \ --profiler.dump_numerics \ --profiler.profile_freq 2 \ --compile.mode aot_fx_trace \ --debug.seed $SEED \ --debug.deterministic \ --parallelism.data_parallel_shard_degree $DP_SHARD \ --training.mixed_precision_param float32 ``` For `aot_fx_trace`, step 1 traces and step 2 replays. Capturing step 2 makes the log represent replay execution, with `FQNInterpreter` restoring node-level metadata while the traced graph runs. ### Generate the HTML diff ```bash python3 -m torchtitan.tools.compare_numerics \ $DUMP_FOLDER/eager/numerics/rank_0_activations.log \ $DUMP_FOLDER/traced/numerics/rank_0_activations.log \ --name1 eager_debug_mode \ --name2 traced_debug_mode \ --override agent_space/overrides.csv \ --output $DUMP_FOLDER/diff.html ``` The override file is optional. It is useful when eager and traced runs produce semantically equivalent ops with different attribution, such as activation-checkpoint recompute FQNs, FSDP collective renaming, or layer-level op counter shifts. ## Expected Outputs After running the example script: ```text outputs_numerics_debug_mode/ eager/numerics/rank_0_activations.log traced/numerics/rank_0_activations.log diff.html ``` Open `diff.html` in a browser to inspect matched ops, diffs, run-only ops, input hashes, and producer links. ## Notes for Reviewers - The core training path is unchanged unless `--profiler.dump_numerics` is set. - Graph-trainer replay uses `FQNInterpreter` only while numerics capture is active. - The capture uses deterministic settings in the example script and avoids `--debug.deterministic_warn_only`. - The implementation intentionally keeps comparison tooling under `torchtitan/tools/` and graph-trainer-specific replay metadata bridging under `torchtitan/experiments/graph_trainer/`. --------- Co-authored-by: Shangdi Yu <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Summary
Adds a numerics-debugging tool that captures per-op activation statistics during a training step and renders an interactive diff between two runs. Driven by a new
--profiler.dump_numericsflag, with first-class support for both eager andaot_fx_tracecompile modes.torchtitan/tools/activation_tracer.py(new, 762 LOC)Core capture machinery. Two pieces:
ActivationTracer— context manager that combines two mechanisms to capture per-op outputs and keep them attributed to the model code:_CaptureDispatchMode(aTorchDispatchMode) intercepts every dispatched op;_should_capturefilters by a denylist_EXCLUDED_OPS(creation/view/permutation/indexing/comm) and a numel/dtype floor. Captured tensors are cloned and keyedmodule_fqn/op_N_opname._patch_modelmonkeypatches everynn.Module.forwardto set threeContextVars (module name, stack frames, autograd-grad-fn map) before delegating to the real forward. After forward returns,_record_grad_fnBFS-walks the autograd graph from each output to recordgrad_fn → module_fqnso backward ops can be attributed correctly.NumericsDebugger— driven from the existingProfiler.step(); arms the tracer one step before the capture step and dumps to{dump_folder}/numerics/rank_{rank}_activations.logafter.How phase and stack location are determined
This was the trickiest part of the design — different mode/phase combinations bypass different layers of the Python call stack, so the source is different in each cell:
"forward"_current_stack_framesset by_patch_model.wrapped_forwardfrominspect.getfile(type(module).forward)_current_module_nameset by_patch_model.wrapped_forward_current_autograd_node()is non-None →"backward"_current_autograd_node().metadata["traceback_"]— the forward traceback, saved by autograd becauseActivationTracer.__enter__enablesset_detect_anomaly(True, check_nan=False). Parsed via_parse_stack_trace._current_module_nameis None during backward → falls back to_grad_fn_to_module[autograd_node](built during forward by_record_grad_fnBFS)gm(*inputs))node.meta["autograd_backward"]→ sets_current_phase_overridenode.meta["stack_trace"]parsed via_parse_stack_trace→ sets_current_stack_framesnode.meta["custom"]["module_fqn"]→ sets_current_module_nameFor traced replay,
gm(*inputs)bypasses module forwards entirely, so the monkeypatch never fires. TheFQNInterpreter(indebug_utils.py) walks the graph node by node and pushes/pops context vars from each node'smetaso the dispatch-mode capture sees the right FQN/stack/phase per op.Why we can't just call
traceback.extract_stack()inside__torch_dispatch__The obvious approach would be: when an op fires inside
_CaptureDispatchMode.__torch_dispatch__, walk the live Python call stack withtraceback.extract_stack()and that's our location. This works in plain eager mode, but fails silently under FSDP and activation checkpointing, which are the production configurations we actually care about:__torch_dispatch__, the C++ runtime has broken the Python call chain —attention.forwardanddecoder.forwardare not on the Python stack.extract_stack()returns only the entry point (train.py:main) plus dispatch-mode framework frames, which is useless for finding the model code that produced the op.torch.autograd.function.BackwardCFunction.apply(a C function), so the model-level frames are gone there too._resolve_module_locationworks around this by computing the location once at patch time, from the module's class definition —inspect.getfile(type(module).forward)plusinspect.getsourcelinesgives the file and line where the forward method is defined. That's stable regardless of how the runtime invokes it (FSDP wrap, AC, raw eager). The trade-off is that we get module-level granularity (the forward's header line) rather than the exact op line — and for the traced path that's not a problem becausenode.meta["stack_trace"]from AOTAutograd captures the per-op line at trace time, when the Python stack is intact.Live
traceback.extract_stack()is still kept as a last-resort fallback inside_maybe_capturefor cases where neither_current_stack_framesnor an autograd-saved traceback is available.How
_record_grad_fnattributes backward ops to modulesThe
_grad_fn_to_modulemapping in the table above is built by_record_grad_fnduring forward. It walks the autograd reverse graph (DFS via an explicit stack — order doesn't matter for correctness, since the "claim only if unclaimed" check is order-independent) and has to navigate two delicate boundaries:Input boundary (
input_grad_fns) — captured before the real forward runs by walkingargs/kwargsfor any tensor with agrad_fn. These are autograd nodes belonging to the caller (sibling or parent module). The BFS must not cross into them, otherwise the current module would over-claim ops that aren't its responsibility.Already-mapped boundary — by the time a parent module's
wrapped_forwardruns_record_grad_fn, every child module nested inside it has already finished its own_record_grad_fncall (children's_orig(...)runs to completion before the parent's post-forward block). Their grad_fns are already mapped to the child FQN, so the parent must not overwrite them.The walk itself, starting from each output tensor's
grad_fn:Why "claim only unclaimed" but still walk through. When the parent's traversal hits a node a child already claimed, it does not overwrite — the child is more specific. But the walk continues through that child node into its
next_functions. This is deliberate: between child-module subgraphs there can be operations the parent module performed itself. If the walk stopped at every already-mapped node, those parent-only ops would never get claimed.The clearest example is
FeedForward, whose forward isw2(silu(w1(x)) * w3(x)). Thesiluandmulare called directly insideFeedForward.forward— they are not inside any child module — so they need to be attributed toFeedForward, even though they sit sandwiched between child-module subgraphs in the autograd reverse graph:The actual autograd reverse graph (verified by walking
y.grad_fn.next_functionson a realFeedForward(dim=8, hidden=16)withbias=Falselinears):(
TBackward0is the weight-transpose backward inserted becausenn.Linearcomputesx @ weight.T;AccumulateGradis the leaf accumulator for each parameter.)When
FeedForward.wrapped_forwardruns its_record_grad_fn(after every child has already run theirs), the autograd graph state is:The walk starts from the output's
grad_fn(MmBackward0 [w2]), sees it's already claimed, doesn't overwrite, but followsnext_functionsupstream. It reachesMulBackward0andSiluBackward0— both unclaimed — and stamps them withfeed_forward. Continuing upstream it hitsMmBackward0 [w1]andMmBackward0 [w3](already claimed, skip the claim, but the walk continues into their parameter-side subtrees, which are also already claimed by the children), and eventually terminates at the leafAccumulateGradnodes (nonext_functions). End state:Without the "walk through already-claimed nodes" rule, the traversal would have stopped at
MmBackward0 [w2]andMulBackward0/SiluBackward0would have stayed unattributed (showing up as<none>in the log). Without the "don't overwrite already-claimed" rule,feed_forwardwould have stomped over the more-specific child attributions for w1/w2/w3 (and all the per-parameterTBackward0/AccumulateGradnodes underneath them).next_functionspoints upstream toward inputs (autograd's reverse graph), so the sweep goes from output back toward the module's input boundary — exactly the territory this module's forward produced. Net effect: each autograd node is mapped to the innermost module whose forward produced it; parents claim only the "glue" ops between children. During backward,_maybe_capturereads_grad_fn_to_module[autograd_node]and gets the correct, tightly-scoped FQN.torchtitan/tools/compare_numerics.py(new, 659 LOC)Standalone CLI tool that diffs two activation logs and produces a self-contained interactive HTML report.
parse_logparses the human-readable log format produced bydump_captures_to_file.match_entriespairs ops between the two logs in three passes, each progressively more relaxed:module_fqn/op_N_opnamematch. Catches the bulk of forward ops.mod/op_3_mm↔mod/op_1_mm). Backward ops often interleave differently between modes, so the counter drifts.op_type + Shape + L1 norm. Last-resort match for ops whose FQN differs between modes (e.g. autograd-internal grad-accumulation adds).Eager-side rows are emitted in original log order regardless of which pass matched them; traced-only rows trail at the end.
_compute_diffsscales each stat against its own column (via symmetric relative diff with a1e-30floor), so an L2 diff is judged on L2's magnitude rather than on the tensor's L1 norm.generate_htmlrenders a single self-contained HTML page with collapsible Forward/Backward sections, per-cell white-to-red coloring on a log-scale relative diff, hover-row highlighting, filter checkboxes, a "Match method" column showing how each pair was paired, and configurable run names via--name1/--name2(defaultrun1/run2).Two test files (
test_activation_tracer.py,test_compare_numerics.py) cover capture filtering, phase tagging, the three matching passes, eager-order preservation, the match-method column, run-name handling, and HTML escape safety.Changes to existing trainer / graph_trainer / profiler
Wiring to drive the tracer from the existing training loop:
torchtitan/tools/profiler.py— addsProfiler.Config.dump_numerics(a new--profiler.dump_numericsflag); adds amodelkwarg toProfiler.__init__; builds aNumericsDebuggerinside__enter__, callsstep()fromProfiler.step(), and tears it down in__exit__. Capture step is reused fromcfg.profile_freq.torchtitan/trainer.py— passesmodel_parts[0]intoprofiler.build(...)so the debugger can monkeypatch its forwards.torchtitan/experiments/graph_trainer/make_fx_tracer.py—run_tracedandrun_traced_train_stepaccept aninterpreter_clskwarg. When set, replay goes throughinterpreter_cls(gm).run(...)instead ofgm(*flat_inputs). DefaultNoneleaves the fast path untouched.torchtitan/experiments/graph_trainer/trainer.py—_get_interpreter_cls()returnsFQNInterpreteronly whenis_numerics_capture_active()is true (set byNumericsDebugger). Threaded into therun_traced_train_stepcall. Normal compiled training pays zero overhead.torchtitan/experiments/graph_trainer/debug_utils.py— addsFQNInterpreter, atorch.fx.Interpretersubclass that readsnode.meta["custom"]["module_fqn"],node.meta["stack_trace"], andnode.meta["autograd_backward"]and pushes them onto the activation tracer's context vars for the duration of each node's execution. This is the bridge that lets traced replay produce captures with the same FQN/stack/phase attribution that the eager path gets via the monkeypatch.Usage
Capture numerics
Output:
{dump_folder}/numerics/rank_{N}_activations.logCompare two logs
python -m torchtitan.tools.compare_numerics \ outputs_numerics/eager/numerics/rank_0_activations.log \ outputs_numerics/traced/numerics/rank_0_activations.log \ -o numerics_diff.htmlCommands used to generate the current HTML
https://www.internalfb.com/intern/px/p/9LGvr/
Run tests
Output format
Why not just
diff?A naive
diffof two activation logs doesn't work because:Op keys don't match between modes. Eager and traced backward ops
have different op counter sequences (e.g.
wq/op_3_mmvswq/op_1_mm)because AC recomputation inserts extra ops in eager that shift all
counters.
compare_numerics.pyuses three-pass matching: exact key →fuzzy key (strip counter, match by module + op type) → numeric match
(same shape + L1 norm). This recovers ~80 additional backward pairs
that naive key comparison misses.
Not all differences matter equally. A
Meandiff of1.29e-20vs
-1.28e-20is floating-point noise when the tensor's L1 norm is1e+3— both values are effectively zero. But aMindiff of-1.28vs-4.28is a real divergence.compare_numerics.pyscalesdiff highlighting relative to the tensor's L1 norm: negligible diffs
get white/near-invisible text, real diffs get bright red with a red
background tint, and shape mismatches are always full red.
Different FQN formats. Eager FQNs include
_checkpoint_wrapped_modulefrom AC wrapping. Traced FQNs don't. The logs clean this at dump time,
but backward FQNs can still differ (e.g.
feed_forward.w2/op_4_mulvsfeed_forward/op_5_mul) due to autograd graph mapping vs FX nodemetadata using different attribution strategies.
Key design decisions
Two capture mechanisms:
ActivationTracer(TorchDispatchMode, per-op)for the main capture path, and
ModuleLevelDebugger(module hooks, per-module)as a standalone utility for FSDP-compatible gradient inspection.
FQNInterpreter for traced mode: The traced graph replays via
gm(*inputs)which bypasses module forwards.FQNInterpreterwalksthe graph node-by-node, setting
_current_module_namefromnode.meta["custom"]["module_fqn"]and_current_stack_framesfromnode.meta["stack_trace"].Backward FQN via autograd graph mapping: During forward, builds a
grad_fn → module_fqnmapping via boundary-aware BFS. During backward,looks up
_current_autograd_node()in the mapping. Input grad_fns actas BFS stop points to prevent child modules from claiming parent-scope
ops.
detect_anomaly for backward locations: Enables
torch.autograd.set_detect_anomaly(check_nan=False)so autograd savesforward tracebacks on backward nodes. During backward,
_current_autograd_node().metadata["traceback_"]provides the forwardsource location.
CPU float64 stats:
dump_captures_to_filecomputes norms on CPU infloat64 for deterministic reductions (CUDA reductions are
non-deterministic due to parallel summation order).
Global flag for interpreter routing:
is_numerics_capture_active()is a module-level bool that
GraphTrainer._get_interpreter_cls()checks.No callbacks or trainer references needed.
Known differences between modes
See
NUMERICS_DEBUGGER.mdfor full details. Key points:float32 + deterministic for bitwise match).
traced graph's
module_fqnbut may differ for ops at moduleboundaries.
tagged backward). Traced captures forward + explicit backward ops.
ChunkedCELoss(chunked lm_head), tracedforces
CrossEntropyLoss(full lm_head). Different shapes/norms.compare_numerics.pymatches backward ops bymodule + op type (ignoring counter), and by shape + L1 norm for
remaining unmatched ops.
PR authored with Claude.