Skip to content

[WIP][numerics] Add activation tracer - #3190

Closed
yushangdi wants to merge 1 commit into
mainfrom
sy_debug_md
Closed

yushangdi wants to merge 1 commit into
mainfrom
sy_debug_md

Conversation

@yushangdi

@yushangdi yushangdi commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

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_numerics flag, with first-class support for both eager and aot_fx_trace compile 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 (a TorchDispatchMode) intercepts every dispatched op; _should_capture filters by a denylist _EXCLUDED_OPS (creation/view/permutation/indexing/comm) and a numel/dtype floor. Captured tensors are cloned and keyed module_fqn/op_N_opname.
    • _patch_model monkeypatches every nn.Module.forward to set three ContextVars (module name, stack frames, autograd-grad-fn map) before delegating to the real forward. After forward returns, _record_grad_fn BFS-walks the autograd graph from each output to record grad_fn → module_fqn so backward ops can be attributed correctly.
  • NumericsDebugger — driven from the existing Profiler.step(); arms the tracer one step before the capture step and dumps to {dump_folder}/numerics/rank_{rank}_activations.log after.

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:

Mode Phase Phase determined by Stack location determined by Module FQN determined by
Eager Forward No autograd node + no override → "forward" _current_stack_frames set by _patch_model.wrapped_forward from inspect.getfile(type(module).forward) _current_module_name set by _patch_model.wrapped_forward
Eager Backward _current_autograd_node() is non-None → "backward" Monkeypatched forwards don't fire (C++ autograd bypasses Python). Falls back to _current_autograd_node().metadata["traceback_"] — the forward traceback, saved by autograd because ActivationTracer.__enter__ enables set_detect_anomaly(True, check_nan=False). Parsed via _parse_stack_trace. _current_module_name is None during backward → falls back to _grad_fn_to_module[autograd_node] (built during forward by _record_grad_fn BFS)
Traced (gm(*inputs)) Either node.meta["autograd_backward"] → sets _current_phase_override node.meta["stack_trace"] parsed via _parse_stack_trace → sets _current_stack_frames node.meta["custom"]["module_fqn"] → sets _current_module_name

For traced replay, gm(*inputs) bypasses module forwards entirely, so the monkeypatch never fires. The FQNInterpreter (in debug_utils.py) walks the graph node by node and pushes/pops context vars from each node's meta so 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 with traceback.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:

  • FSDP wraps each module's forward and dispatches the wrapped forward via C++ hooks (parameter all-gather, post-backward reduce-scatter). By the time the op reaches __torch_dispatch__, the C++ runtime has broken the Python call chain — attention.forward and decoder.forward are 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.
  • Activation checkpointing has the same issue: recompute runs inside torch.autograd.function.BackwardCFunction.apply (a C function), so the model-level frames are gone there too.
  • Even when frames are on the stack, the live traceback can only point at some line inside the module's forward; the line that actually corresponds to the dispatched op is hard to recover reliably (multiple ops per source line, fused dispatches, etc.).

_resolve_module_location works around this by computing the location once at patch time, from the module's class definition — inspect.getfile(type(module).forward) plus inspect.getsourcelines gives 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 because node.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_capture for cases where neither _current_stack_frames nor an autograd-saved traceback is available.

How _record_grad_fn attributes backward ops to modules

The _grad_fn_to_module mapping in the table above is built by _record_grad_fn during 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:

  1. Input boundary (input_grad_fns) — captured before the real forward runs by walking args/kwargs for any tensor with a grad_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.

  2. Already-mapped boundary — by the time a parent module's wrapped_forward runs _record_grad_fn, every child module nested inside it has already finished its own _record_grad_fn call (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:

stack = [t.grad_fn]
visited = set()
while stack:
    fn = stack.pop()                   # LIFO → DFS
    if fn in visited or fn in input_grad_fns:
        continue                       # boundary: caller's autograd nodes
    visited.add(fn)
    if fn not in _grad_fn_to_module:
        _grad_fn_to_module[fn] = module_name   # claim only unclaimed nodes
    for parent, _ in fn.next_functions:
        if parent is not None and parent not in visited:
            stack.append(parent)       # walk upstream toward inputs

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 is w2(silu(w1(x)) * w3(x)). The silu and mul are called directly inside FeedForward.forward — they are not inside any child module — so they need to be attributed to FeedForward, even though they sit sandwiched between child-module subgraphs in the autograd reverse graph:

              forward direction (data flow) ─────────────►

   x ──┬──► [w1.forward] ──► h1 ──► silu ──► s ──┬──► mul ──► p ──► [w2.forward] ──► y
       │     (claims mm,                          │           ▲      (claims mm
       │      Tback, AccGrad                      │           │       Tback, AccGrad
       │      for w1)                             │           │       for w2)
       └──► [w3.forward] ──► h3 ──────────────────┘           │
             (claims mm,                                      │
              Tback, AccGrad                                  │
              for w3)

The actual autograd reverse graph (verified by walking y.grad_fn.next_functions on a real FeedForward(dim=8, hidden=16) with bias=False linears):

              ◄───────── BFS direction (autograd reverse graph)

   MmBackward0 [w2] ─┬─► MulBackward0 [?] ─┬─► SiluBackward0 [?] ─► MmBackward0 [w1] ─┬─► AccumulateGrad (w1.weight)
        ↑            │                     │                                          └─► TBackward0 ─► AccumulateGrad
        already      │                     └─► MmBackward0 [w3] ─┬─► TBackward0 ─► AccumulateGrad (w3.weight)
        claimed      │                                            (input x is a leaf, x.grad_fn is None,
        by w2        └─► TBackward0 ─► AccumulateGrad (w2.weight)  so BFS terminates at AccumulateGrads)

(TBackward0 is the weight-transpose backward inserted because nn.Linear computes x @ weight.T; AccumulateGrad is the leaf accumulator for each parameter.)

When FeedForward.wrapped_forward runs its _record_grad_fn (after every child has already run theirs), the autograd graph state is:

  MmBackward0   [w2]            ← already claimed by w2 (along with its TBackward0/AccumulateGrad)
  MulBackward0  [    ]          ← UNCLAIMED — happened in FeedForward, not a child
  SiluBackward0 [    ]          ← UNCLAIMED — same
  MmBackward0   [w1]            ← already claimed by w1 (along with its TBackward0/AccumulateGrad)
  MmBackward0   [w3]            ← already claimed by w3 (along with its TBackward0/AccumulateGrad)

The walk starts from the output's grad_fn (MmBackward0 [w2]), sees it's already claimed, doesn't overwrite, but follows next_functions upstream. It reaches MulBackward0 and SiluBackward0 — both unclaimed — and stamps them with feed_forward. Continuing upstream it hits MmBackward0 [w1] and MmBackward0 [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 leaf AccumulateGrad nodes (no next_functions). End state:

  MmBackward0   [w2]            ← unchanged (child)
  MulBackward0  [feed_forward]  ← claimed by parent
  SiluBackward0 [feed_forward]  ← claimed by parent
  MmBackward0   [w1]            ← unchanged (child)
  MmBackward0   [w3]            ← unchanged (child)

Without the "walk through already-claimed nodes" rule, the traversal would have stopped at MmBackward0 [w2] and MulBackward0/SiluBackward0 would have stayed unattributed (showing up as <none> in the log). Without the "don't overwrite already-claimed" rule, feed_forward would have stomped over the more-specific child attributions for w1/w2/w3 (and all the per-parameter TBackward0/AccumulateGrad nodes underneath them).

next_functions points 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_capture reads _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_log parses the human-readable log format produced by dump_captures_to_file.
  • match_entries pairs ops between the two logs in three passes, each progressively more relaxed:
    1. Same op key — exact module_fqn/op_N_opname match. Catches the bulk of forward ops.
    2. Fuzzy op key — strips the per-module counter (mod/op_3_mm ↔ mod/op_1_mm). Backward ops often interleave differently between modes, so the counter drifts.
    3. Stats — matches by 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_diffs scales each stat against its own column (via symmetric relative diff with a 1e-30 floor), so an L2 diff is judged on L2's magnitude rather than on the tensor's L1 norm.
  • generate_html renders 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 (default run1/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 — adds Profiler.Config.dump_numerics (a new --profiler.dump_numerics flag); adds a model kwarg to Profiler.__init__; builds a NumericsDebugger inside __enter__, calls step() from Profiler.step(), and tears it down in __exit__. Capture step is reused from cfg.profile_freq.

  • torchtitan/trainer.py — passes model_parts[0] into profiler.build(...) so the debugger can monkeypatch its forwards.

  • torchtitan/experiments/graph_trainer/make_fx_tracer.py — run_traced and run_traced_train_step accept an interpreter_cls kwarg. When set, replay goes through interpreter_cls(gm).run(...) instead of gm(*flat_inputs). Default None leaves the fast path untouched.

  • torchtitan/experiments/graph_trainer/trainer.py — _get_interpreter_cls() returns FQNInterpreter only when is_numerics_capture_active() is true (set by NumericsDebugger). Threaded into the run_traced_train_step call. Normal compiled training pays zero overhead.

  • torchtitan/experiments/graph_trainer/debug_utils.py — adds FQNInterpreter, a torch.fx.Interpreter subclass that reads node.meta["custom"]["module_fqn"], node.meta["stack_trace"], and node.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

# Eager mode
NGPU=1 MODULE=llama3 CONFIG=llama3_debugmodel \
    ./run_train.sh \
    --profiler.dump_numerics \
    --profiler.profile_freq 2 \
    --training.steps 2

# aot_fx_trace mode
NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel \
    ./run_train.sh \
    --profiler.dump_numerics \
    --profiler.profile_freq 2 \
    --training.steps 2 \
    --compile.mode aot_fx_trace

# Multi-GPU
NGPU=8 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel \
    ./run_train.sh \
    --profiler.dump_numerics \
    --profiler.profile_freq 2 \
    --training.steps 2 \
    --compile.mode aot_fx_trace \
    --parallelism.data_parallel_shard_degree=4 \
    --parallelism.tensor_parallel_degree=2

Output: {dump_folder}/numerics/rank_{N}_activations.log

Compare 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.html

Commands used to generate the current HTML

https://www.internalfb.com/intern/px/p/9LGvr/

cd torchtitan

# Run both modes with same seed, deterministic, float32, no FSDP
NGPU=1 MODULE=llama3 CONFIG=llama3_debugmodel \
    ./run_train.sh \
    --dump_folder ./outputs_numerics/eager \
    --training.steps 2 \
    --profiler.dump_numerics \
    --profiler.profile_freq 2 \
    --debug.seed 42 \
    --debug.deterministic \
    --training.mixed_precision_param float32

NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel \
    ./run_train.sh \
    --dump_folder ./outputs_numerics/traced \
    --training.steps 2 \
    --profiler.dump_numerics \
    --profiler.profile_freq 2 \
    --compile.mode aot_fx_trace \
    --debug.seed 42 \
    --debug.deterministic \
    --training.mixed_precision_param float32

# Generate comparison HTML
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.html

Run tests

python -m unittest tests.unit_tests.test_activation_tracer -v

Output format

[layers.0.attention.qkv_linear.wq/op_0_mm]
  Shape: torch.Size([16384, 256]), Dtype: torch.float32
  L1 norm:  1.066932e+06
  L2 norm:  6.550494e+02
  Min:      -1.275938e+00
  Max:      1.309514e+00
  Location: common/attention.py:534
  Phase: backward

Why not just diff?

A naive diff of two activation logs doesn't work because:

  1. Op keys don't match between modes. Eager and traced backward ops
    have different op counter sequences (e.g. wq/op_3_mm vs wq/op_1_mm)
    because AC recomputation inserts extra ops in eager that shift all
    counters. compare_numerics.py uses 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.

  2. Not all differences matter equally. A Mean diff of 1.29e-20
    vs -1.28e-20 is floating-point noise when the tensor's L1 norm is
    1e+3 — both values are effectively zero. But a Min diff of
    -1.28 vs -4.28 is a real divergence. compare_numerics.py scales
    diff 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.

  3. Different FQN formats. Eager FQNs include _checkpoint_wrapped_module
    from 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_mul vs
    feed_forward/op_5_mul) due to autograd graph mapping vs FX node
    metadata 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. FQNInterpreter walks
the graph node-by-node, setting _current_module_name from
node.meta["custom"]["module_fqn"] and _current_stack_frames from
node.meta["stack_trace"].

Backward FQN via autograd graph mapping: During forward, builds a
grad_fn → module_fqn mapping via boundary-aware BFS. During backward,
looks up _current_autograd_node() in the mapping. Input grad_fns act
as 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 saves
forward tracebacks on backward nodes. During backward,
_current_autograd_node().metadata["traceback_"] provides the forward
source location.

CPU float64 stats: dump_captures_to_file computes norms on CPU in
float64 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.md for full details. Key points:

  • Forward ops: Match by key. Small diffs possible in bfloat16 (use
    float32 + deterministic for bitwise match).
  • Backward FQN granularity: Boundary-aware BFS approximates the
    traced graph's module_fqn but may differ for ops at module
    boundaries.
  • Op counts: Eager captures forward + AC recomputation ops (all
    tagged backward). Traced captures forward + explicit backward ops.
  • Loss ops: Eager uses ChunkedCELoss (chunked lm_head), traced
    forces CrossEntropyLoss (full lm_head). Different shapes/norms.
  • Fuzzy matching: compare_numerics.py matches backward ops by
    module + op type (ignoring counter), and by shape + L1 norm for
    remaining unmatched ops.

PR authored with Claude.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 30, 2026
@yushangdi
yushangdi force-pushed the sy_debug_md branch 7 times, most recently from 13e20eb to 4602220 Compare May 2, 2026 01:30
@yushangdi
yushangdi force-pushed the sy_debug_md branch 3 times, most recently from 340ade9 to 74f4f6f Compare May 9, 2026 01:11
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]>
@tianyu-l tianyu-l closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu 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