Repository navigation
[profiler] Split Profiler into per-tool configs - #5871
Conversation
[ghstack-poisoned]
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]
## 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
|
@claude review |
There was a problem hiding this comment.
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
- PR description: the "Summary (human-written)" section is still the empty template. The author needs to write it (CLAUDE.md, PR expectations #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 theX.Config | Noneand select-by-config-type rules inconfig.md.TraceProfilerhas two subclasses, so the ABC isn't a single-subclass base. I found no overlapping open PR. - Equivalences I checked against main.
with_stackis nowdevice_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 passingNone, None, NoneinTraceProfiler.closechanges nothing.get_rank()is still skipped when no tool is enabled.- The deepseek_v4 and transformers_modeling_backend profiler blocks had
enable_profiling=Falseand 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 orProfiler.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_freqfallback, which no longer exists. The new memory-snapshot test coversclose(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.
|
|
||
|
|
||
| def _cuspy_unavailable_reasons(config: CuspyProfilerConfig) -> list[str]: | ||
| def cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]: |
There was a problem hiding this comment.
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).
| def cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]: | |
| def _cuspy_unavailable_reasons(config: "CuspyTraceProfiler.Config") -> list[str]: |
| 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`. |
There was a problem hiding this comment.
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.
|
@pianpwk please address claude comments and merge |
[ghstack-poisoned]
## 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]
## 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
…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.
Stack from ghstack (oldest at bottom):
Summary (human-written)
Why
Profiler.Configis one flat config for three tools: Kineto traces, Cuspytraces (a nested config that only applies with
enable_profiling) and memorysnapshots. Adding a tool means editing the config,
__enter__,step,__exit__and the annotation helper. The next PR in this stack addsalways-on kernel spans, which would be a fourth tool. Following #5775, each
tool now owns its config, and optional tools are
X.Config | Nonefields.Design
User-facing changes
enable_profiling=Truetrace=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_waitenable_memory_snapshot=Truememory_snapshot=MemorySnapshotProfiler.Config()save_memory_snapshot_folder,memory_snapshot_freq,memory_snapshot_max_entriessave_folder,freq,max_entriesprofile_freqProfiler.active()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
test_memory_snapshot_dumps_every_freq_steps_and_on_oom: the OOM dumpmoved into
MemorySnapshotProfiler.close(exc)and had no test.Cuspy trace with py stacks, write the same files at the same steps as main.