Skip to content

[profiler] Split Profiler into per-tool configs - #5871

Merged
pianpwk merged 9 commits into
mainfrom
gh/pianpwk/119/head
Nov 23, 2026
Merged

pianpwk merged 9 commits into
mainfrom
gh/pianpwk/119/head

Conversation

@pianpwk

@pianpwk pianpwk commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary (human-written)

Why

Profiler.Config is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with enable_profiling) and memory
snapshots. Adding a tool means editing the config, __enter__, step,
__exit__ and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are X.Config | None fields.

Design

Profiler                                  entry point: builds, steps and closes
|                                         the enabled tools
+-- trace: TraceProfiler | None           torch.profiler.profile schedule +
|   |                                     trace dump
|   +-- KinetoTraceProfiler               CPU + CUDA/XPU/Neuron activities
|   +-- CuspyTraceProfiler                CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
                                          allocator history; OOM dump on exit
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
                cuspy=CuspyProfilerConfig(record_py_stacks=True),
                enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
                memory_snapshot=MemorySnapshotProfiler.Config(freq=50))

User-facing changes

Before After
enable_profiling=True trace=KinetoTraceProfiler.Config()
enable_profiling=True, cuspy=CuspyProfilerConfig(...) trace=CuspyTraceProfiler.Config(...)
save_traces_folder, profile_freq, profiler_{warmup,active,repeat,skip_first,skip_first_wait} save_folder, freq, warmup, active, repeat, skip_first, skip_first_wait
enable_memory_snapshot=True memory_snapshot=MemorySnapshotProfiler.Config()
save_memory_snapshot_folder, memory_snapshot_freq, memory_snapshot_max_entries save_folder, freq, max_entries
memory snapshot freq falls back to profile_freq defaults to 10
Profiler.active() removed (no callers)

Output paths, structured-log span names and
maybe_cuda_graph_annotation_config() are unchanged.

Mechanical, safe to skim: recipe, test and doc migrations (torchtitan_recipes/,
tests/, graph_trainer docs, numerics_debugging skill).

Numerics

Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.

Testing

  • Profiler, trainer and graph_trainer profiler unit tests.
  • New test_memory_snapshot_dumps_every_freq_steps_and_on_oom: the OOM dump
    moved into MemorySnapshotProfiler.close(exc) and had no test.
  • 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
    Cuspy trace with py stacks, write the same files at the same steps as main.

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@pianpwk pianpwk changed the title [profiler] Make profiling tools object-oriented [profiler] Split Profiler into per-tool configs Nov 6, 2026
@pianpwk pianpwk changed the title [profiler] Split Profiler into per-tool configs [profiler] split Profiler into per-tool configs Nov 6, 2026
@pianpwk pianpwk changed the title [profiler] split Profiler into per-tool configs [profiler] Split Profiler into per-tool configs Nov 6, 2026
[ghstack-poisoned]
@pianpwk
pianpwk marked this pull request as ready for review November 6, 2026 00:49
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 6, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 6, 2026 00:49
shuhuayu added a commit that referenced this pull request Nov 11, 2026
Independent PR on `main`.

## Summary (human-written)

On main, an OOM during training closes the profiler as if shutdown were
clean, so the memory profiler never writes its exit snapshot; passing
the exception to the profiler fixes that, which is how I debugged
several full-scale Kimi K3 OOMs.

## Why

#4580 added an OOM branch to `Profiler.__exit__` that writes an exit
memory
snapshot when the exception (or anything in its cause chain) is an
`OutOfMemoryError`. #4773 then replaced the profiler `with` block in
`Trainer.train()` with `engine.start_profiler()` plus
`engine.close_profiler()`
in a `finally`, and `close_profiler()` always calls
`Profiler.__exit__(None, None, None)`. Since then the OOM branch is
unreachable for the main trainer. The exception itself still propagates;
only
the snapshot is lost.

## What changed

- `TrainingEngine.close_profiler(exc: BaseException | None = None)`
passes
  `exc` to `Profiler.__exit__`.
- `Trainer.train()` replaces its `finally` with `except BaseException as
e:
  close_profiler(e); raise` and `else: close_profiler()`.
- `engine.close()` still calls `close_profiler()` with no exception. It
only
reaches an open profiler when `train()` never started it, so nothing is
lost.

## Example

```text
train_step raises an OOM (possibly wrapped in a RuntimeError by PP)
before: close_profiler() -> Profiler.__exit__(None, None, None); no snapshot
after:  close_profiler(e) -> Profiler.__exit__(type(e), e, tb); snapshot written once
the same exception object still propagates to the caller
```

The exception is passed explicitly rather than read from
`sys.exc_info()`,
which would also return an exception an outer frame is still handling
(e.g. a
caller that catches an OOM and retries `train()` would get a bogus
snapshot).
This matches the `close(exc)` shape in #5871.

## Scope

- RL is not covered. `rl/trainer/trainer.py` starts the profiler through
the
shared engine but closes it from its async `close()` endpoint, which has
no
  training exception to pass, so RL OOMs still get no exit snapshot.
- #5871 rewrites `observability/profiler.py` and touches
`tests/unit_tests/cpu/test_trainer.py`; whichever lands second needs a
rebase.
- CUDA-graph stream-lane rendering is not part of this PR; #5526 covers
it.

## User-facing changes

| Before | After |
| --- | --- |
| An OOM in `Trainer.train()` writes no exit memory snapshot. | The
existing OOM branch writes it once. |

## Numerics

None. Only profiler shutdown on a training failure changes.

## Testing

`test_train_passes_failure_to_profiler_close` runs the real
`Trainer.train`,
`TrainingEngine.close_profiler`, and `Profiler.__exit__` with the
snapshot
writer mocked, for three cases: normal exit (no snapshot), a plain OOM,
and an
OOM wrapped in a RuntimeError as PP does (snapshot once, and the same
exception
object is re-raised). All 57 tests in
`tests/unit_tests/cpu/test_trainer.py`
pass; `pre-commit` passes.

Each of these breakages fails the test: `train()` not passing the
exception,
`close_profiler()` ignoring it, a snapshot on every close, and
swallowing the
exception after closing.

Not verified: writing a real GPU OOM snapshot.
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Nov 20, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
`Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with `enable_profiling`) and memory
snapshots. Adding a tool means editing the config, `__enter__`, `step`,
`__exit__` and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are `X.Config | None` fields.

## Design
```
Profiler                                  entry point: builds, steps and closes
|                                         the enabled tools
+-- trace: TraceProfiler | None           torch.profiler.profile schedule +
|   |                                     trace dump
|   +-- KinetoTraceProfiler               CPU + CUDA/XPU/Neuron activities
|   +-- CuspyTraceProfiler                CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
                                          allocator history; OOM dump on exit
```

```python
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
                cuspy=CuspyProfilerConfig(record_py_stacks=True),
                enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
                memory_snapshot=MemorySnapshotProfiler.Config(freq=50))
```

## User-facing changes
| Before | After |
| --- | --- |
| `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` |
| `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` |
| `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` |
| `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` |
| `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` |
| memory snapshot freq falls back to `profile_freq` | defaults to 10 |
| `Profiler.active()` | removed (no callers) |

Output paths, structured-log span names and
`maybe_cuda_graph_annotation_config()` are unchanged.

Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`,
`tests/`, graph_trainer docs, numerics_debugging skill).

## Numerics
Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.

## Testing
- Profiler, trainer and graph_trainer profiler unit tests.
- New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump
  moved into `MemorySnapshotProfiler.close(exc)` and had no test.
- 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
  Cuspy trace with py stacks, write the same files at the same steps as main.

ghstack-source-id: a8f54dd
Pull Request resolved: #5871
@pianpwk
pianpwk changed the base branch from gh/pianpwk/119/base to main November 20, 2026 19:41

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm, thanks

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 11s —— View job


Approve -- please address the two small must-fix items before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The split keeps behavior identical to main. I checked the trace schedule, the activities, the export paths, the memory-snapshot step and OOM-exit numbering, the span names and the annotation config. Net LoC goes down, and the next PR in the stack needs the per-tool structure.

What this PR does. It replaces the flat Profiler.Config with two optional per-tool configs:

  • trace: TraceProfiler.Config | None, an abstract base with Kineto and Cuspy subclasses that each pick their activities and export format;
  • memory_snapshot: MemorySnapshotProfiler.Config | None.

Profiler now only builds, steps and closes whichever tools are set. The OOM exit dump moves into MemorySnapshotProfiler.close(exc).

Example.

# main: snapshots every profile_freq=100 steps (inherited fallback)
Profiler.Config(enable_profiling=True, profile_freq=100, enable_memory_snapshot=True)
# this PR: traces every 100 steps, snapshots every 10 unless freq is set
Profiler.Config(trace=KinetoTraceProfiler.Config(freq=100),
                memory_snapshot=MemorySnapshotProfiler.Config(freq=100))

OOM at step 4 with global_step=1: both versions write step_000000000004_exit. On main, step(exit_ctx=True) increments the counter and then subtracts 1. Here, close() uses _step_num directly. The new test checks this.

Must fix

  1. PR description: the "Summary (human-written)" section is still the empty template. The author needs to write it (CLAUDE.md, PR expectations #2).
  2. torchtitan/observability/profiler.py:56 -- an unrelated rename drops the _ prefix from a function used only in this module (inline).

Should consider

  • torchtitan/experiments/graph_trainer/.claude/CLAUDE.md:258-263 -- the rewritten paragraph still gives the wrong output paths (inline; already wrong on main).
Details
  • Gate. The problem is real: adding the always-on span tool from the next PR to the flat config would mean editing the config, __enter__, step, __exit__ and the annotation helper. The PR follows the X.Config | None and select-by-config-type rules in config.md. TraceProfiler has two subclasses, so the ABC isn't a single-subclass base. I found no overlapping open PR.
  • Equivalences I checked against main.
    • with_stack is now device_type == "neuron". That is the same as main in practice, because Cuspy needs CUDA and the Kineto CUDA/XPU branches come before the neuron one.
    • torch.profiler.profile.__exit__ ignores its arguments, so passing None, None, None in TraceProfiler.close changes nothing.
    • get_rank() is still skipped when no tool is enabled.
    • The deepseek_v4 and transformers_modeling_backend profiler blocks had enable_profiling=False and no memory snapshot, so deleting them is a no-op.
  • Callsites. TrainingEngine.start_profiler, the torchft trainer, graph_trainer tests and all recipes are updated. Nothing else in the repo uses the removed fields or Profiler.active(). docs/benchmarks/ still mentions --profiler.profile_freq, but that is a historical benchmark page.
  • Tests. The deleted tests only re-read defaults or checked the profile_freq fallback, which no longer exists. The new memory-snapshot test covers close(exc) with a PP-style wrapped OOM, which nothing else covered.

Not verified: the GPU runs and the bitwise-identical loss claim (no GPU here). A maintainer still needs to review, since this touches core observability code.

Comment thread torchtitan/observability/profiler.py Outdated


def _cuspy_unavailable_reasons(config: CuspyProfilerConfig) -> list[str]:
def cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This rename from _cuspy_unavailable_reasons is unrelated to the split. The function is still only called inside this module (line 328), and the tests patch it by its string path, which works fine with a private name. Per the naming rule ("leading _ for names used only inside their module"), keep the underscore and revert the two mock.patch targets in tests/unit_tests/cpu/observability/test_profiler.py (lines 111 and 162).

Suggested change
def cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]:
def _cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]:

Comment on lines 258 to 263
Set `config.profiler.memory_snapshot = MemorySnapshotProfiler.Config()` in the
recipe to capture a memory snapshot.
The snapshot fires at every `freq`-th step (default: 10) and is saved to
`{dump_folder}/memory_snapshot/` (default: `./outputs/memory_snapshot/`).
Each rank produces its own file:
`iteration_{step}/rank{N}_memory_snapshot.pickle`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional, since these lines were already wrong on main: this paragraph is being rewritten, and the output paths in it don't match profiler.py. Memory snapshots go to {dump_folder}/profiling/memory_snapshot/step_{step:012d}/{rank:06d}_step_{step}.pickle (MEMORY_DIR / MEMORY_STEP_DIR / MEMORY_FILE), not memory_snapshot/iteration_{step}/rank{N}_memory_snapshot.pickle. Traces (line 250) go to {dump_folder}/profiling/traces/iteration_{step}/rank{N}_trace.json.gz, not profile_traces/. Agents read this file, so a wrong path sends them looking in the wrong place.

@tianyu-l

Copy link
Copy Markdown
Contributor

@pianpwk please address claude comments and merge

[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Nov 23, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
`Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with `enable_profiling`) and memory
snapshots. Adding a tool means editing the config, `__enter__`, `step`,
`__exit__` and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are `X.Config | None` fields.

## Design
```
Profiler                                  entry point: builds, steps and closes
|                                         the enabled tools
+-- trace: TraceProfiler | None           torch.profiler.profile schedule +
|   |                                     trace dump
|   +-- KinetoTraceProfiler               CPU + CUDA/XPU/Neuron activities
|   +-- CuspyTraceProfiler                CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
                                          allocator history; OOM dump on exit
```

```python
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
                cuspy=CuspyProfilerConfig(record_py_stacks=True),
                enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
                memory_snapshot=MemorySnapshotProfiler.Config(freq=50))
```

## User-facing changes
| Before | After |
| --- | --- |
| `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` |
| `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` |
| `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` |
| `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` |
| `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` |
| memory snapshot freq falls back to `profile_freq` | defaults to 10 |
| `Profiler.active()` | removed (no callers) |

Output paths, structured-log span names and
`maybe_cuda_graph_annotation_config()` are unchanged.

Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`,
`tests/`, graph_trainer docs, numerics_debugging skill).

## Numerics
Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.

## Testing
- Profiler, trainer and graph_trainer profiler unit tests.
- New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump
  moved into `MemorySnapshotProfiler.close(exc)` and had no test.
- 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
  Cuspy trace with py stacks, write the same files at the same steps as main.

ghstack-source-id: 02ee207
Pull Request resolved: #5871
[ghstack-poisoned]
[ghstack-poisoned]
@pianpwk
pianpwk merged commit 3980031 into main Nov 23, 2026
21 of 22 checks passed
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 24, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
`Profiler.Config` is one flat config for three tools: Kineto traces, Cuspy
traces (a nested config that only applies with `enable_profiling`) and memory
snapshots. Adding a tool means editing the config, `__enter__`, `step`,
`__exit__` and the annotation helper. The next PR in this stack adds
always-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are `X.Config | None` fields.

## Design
```
Profiler                                  entry point: builds, steps and closes
|                                         the enabled tools
+-- trace: TraceProfiler | None           torch.profiler.profile schedule +
|   |                                     trace dump
|   +-- KinetoTraceProfiler               CPU + CUDA/XPU/Neuron activities
|   +-- CuspyTraceProfiler                CPU + Cuspy CUDA, pftrace, py stacks
|
+-- memory_snapshot: MemorySnapshotProfiler | None
                                          allocator history; OOM dump on exit
```

```python
# before
Profiler.Config(enable_profiling=True, profile_freq=100,
                cuspy=CuspyProfilerConfig(record_py_stacks=True),
                enable_memory_snapshot=True, memory_snapshot_freq=50)
# after
Profiler.Config(trace=CuspyTraceProfiler.Config(freq=100, record_py_stacks=True),
                memory_snapshot=MemorySnapshotProfiler.Config(freq=50))
```

## User-facing changes
| Before | After |
| --- | --- |
| `enable_profiling=True` | `trace=KinetoTraceProfiler.Config()` |
| `enable_profiling=True, cuspy=CuspyProfilerConfig(...)` | `trace=CuspyTraceProfiler.Config(...)` |
| `save_traces_folder`, `profile_freq`, `profiler_{warmup,active,repeat,skip_first,skip_first_wait}` | `save_folder`, `freq`, `warmup`, `active`, `repeat`, `skip_first`, `skip_first_wait` |
| `enable_memory_snapshot=True` | `memory_snapshot=MemorySnapshotProfiler.Config()` |
| `save_memory_snapshot_folder`, `memory_snapshot_freq`, `memory_snapshot_max_entries` | `save_folder`, `freq`, `max_entries` |
| memory snapshot freq falls back to `profile_freq` | defaults to 10 |
| `Profiler.active()` | removed (no callers) |

Output paths, structured-log span names and
`maybe_cuda_graph_annotation_config()` are unchanged.

Mechanical, safe to skim: recipe, test and doc migrations (`torchtitan_recipes/`,
`tests/`, graph_trainer docs, numerics_debugging skill).

## Numerics
Loss and grad_norm are bitwise identical to main for 20 steps of the llama3
debug model. Setup: flex attention, seed 42, deterministic, 2 GPUs, Kineto
trace and memory snapshot enabled.

## Testing
- Profiler, trainer and graph_trainer profiler unit tests.
- New `test_memory_snapshot_dumps_every_freq_steps_and_on_oom`: the OOM dump
  moved into `MemorySnapshotProfiler.close(exc)` and had no test.
- 2-GPU debug model runs: the Kineto trace with memory snapshots, and the
  Cuspy trace with py stacks, write the same files at the same steps as main.

ghstack-source-id: 9d9d8bf
Pull Request resolved: pytorch/torchtitan#5871
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Nov 30, 2026
…filer flags in benchmarks

- maybe_install_optim_load_dtype_workaround now runs in ezpz/__init__.py, so
  the RL overlays (which never build EzpzTrainingEngine) get it on old torch.
- benchmark_agpt_replicated_tt{,_aurora}.sh passed --profiler.* flags that
  upstream pytorch#5871 removed and failed at config parse. Profiling is recipe-only
  now; BENCH_PROFILE / BENCH_MEMORY_SNAPSHOT=1 exit with that message, and
  profiling defaults off.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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