Repository navigation
[profiler] Add always-on CUDA kernel span collection with Cuspy - #5792
Conversation
[ghstack-poisoned]
Add Profiler.Config.kernel_span_ring: every training step, each rank records every CUDA kernel's GPU start/end time, CUDA graph node id and stream with a Cuspy observer, files the kernels into training steps, and writes them every steps_per_file steps (default 100) to a per-rank .npz, deleting the oldest files written by the run beyond num_steps_retained (default 1000). A slow step can then be inspected after the fact without having scheduled a profiling window for it. Kernels are named from the CUDA graph nodes they replay: a graph instantiate hook records each node's kernel name, launch geometry and graph annotations (mark_kernels regions, c10d collective metadata) once per graph, and each file embeds the table for the graphs its steps ran. scripts/kernel_span_ring_to_trace.py joins kernels to that table and writes a Chrome/Perfetto trace for chosen steps and ranks. - KernelSpanRecorder runs from Profiler.step() on the training thread: record the step's host end time, flush CUPTI without a device sync, and cut the delivered kernels (kept sorted by start time) at the end of every step for which a later kernel has arrived. _KernelSpanRing buffers finished steps, writes a file every steps_per_file steps and evicts old files. - Requires accelerator graphs (validated in TrainingEngine.Config) and CUDA graph node ids (CUDA 13.1+ driver or cuda-compat). Kineto windowed profiling cannot run alongside it; Cuspy windowed profiling can, with graph annotations keyed by exec-graph node id. - Rename _cuspy_unavailable_reasons to cuspy_unavailable_reasons, now used from kernel_span_ring.py. 4x GB300, FSDP over 4 GPUs, CUDA graphs, cuda-compat 13.1. Baseline and kernel_span_ring runs alternated, 2 rounds each. Llama 3 8B: seq 8192, 60 steps, medians over steps 21-60. Qwen3 32B: seq 4096, full activation recompute, 40 steps, medians over steps 16-40. Both runs are GPU-bound. steps_per_file=20 so files are written inside the measured window (5x more often than the default). Performance: | Model (kernels/step) | Round | Step time, baseline | Step time, ring | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, ring | |---|---|---|---|---|---|---| | Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 | | Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 | | Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 | | Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 | Tokens/s is averaged over the logged steps in the window (every 10 steps), so it is noisier than the median step time. Memory and disk, per rank: | Model | GPU peak reserved, baseline -> ring | Host peak RSS, baseline -> ring | Disk per step (steps_per_file=100) | Disk at default retention (1000 steps) | |---|---|---|---|---| | Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB | | Qwen3 32B | 145.28 -> 145.28 GiB | 3.66-3.67 -> 3.71 GiB | 188 KB | ~188 MB | Host RSS was sampled every 2 s from each training process. Disk per step includes the node table, which is stored once per file (0.6 MB for 8B, 1.5 MB for 32B). Time taken: | Model | Recorder step(), median per step | Recorder step(), max (includes file writes) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks | |---|---|---|---|---|---| | Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s (0.6 GB peak) | 4.6 s (0.6 GB peak) | | Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s (0.6 GB peak) | 8.2 s (0.7 GB peak) | The recorder runs on the host while it waits on the GPU, so its time is mostly hidden in GPU-bound steps. File write times are page-cache writes to local disk, measured by re-saving the run's files. Conversion runs offline, off the training machines. Numerics: loss and grad_norm match the baseline for 30 steps of the llama3 debug model (seed 42, deterministic, flex attention, 2 GPUs). ghstack-source-id: fd552f0 Pull Request resolved: #5792
[ghstack-poisoned]
Stacked on "[profiler] Make profiling tools object-oriented".
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
A profiling trace only covers the window it was scheduled for. To see why
step 12,345 was slow, you need its kernels after the fact. This adds
`Profiler.Config.kernel_spans`, which records every CUDA kernel's GPU start and
end time, CUDA graph node id and stream on every step. It writes them every
`steps_per_file` steps (default 100) to a per-rank `.npz` and deletes the
oldest files the run wrote beyond `num_steps_retained` (default 1000).
**Example.**
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py outputs/profiling/kernel_spans \
--steps 1050-1052 --ranks 0-3 --output trace.json.gz # open in Perfetto
```
- `torchtitan/observability/kernel_spans.py` (new):
- `KernelSpanRecorder(Configurable)` is the profiling tool, and owns its
config. It holds a Cuspy `NodeTimerObserver`, which is imported when the
recorder is built, so the config imports without cupti-python. Its
`step()` runs on the training thread, and each step it:
- records the step's host end time;
- flushes CUPTI without a device sync;
- cuts the delivered kernels (kept sorted by start time) at the end of
every step that a later kernel has arrived after.
- `_KernelSpanFiles` buffers finished steps, writes a file every
`steps_per_file` steps and evicts old files.
- Kernels are named from CUDA graph nodes. A graph instantiate hook
records each node's kernel name, launch geometry and graph annotations
once per graph, and each file embeds the table for the graphs its steps
ran.
- `torchtitan/observability/profiler.py`:
- `Profiler.Config.kernel_spans: KernelSpanRecorder.Config | None` sits next
to `trace` and `memory_snapshot`.
- `Profiler.Config.__post_init__` rejects it with `KinetoTraceProfiler`:
Kineto's CUPTI init fails once Cuspy holds the subscription. A
`CuspyTraceProfiler` trace can run alongside it.
- `Profiler.Config.maybe_cuda_graph_annotation_config()` keys annotations
by exec-graph node id when kernel spans are on, since spans are named by
those ids. It still records py stacks when the Cuspy trace profiler asks
for them.
- Renames `_cuspy_unavailable_reasons` to public, because `kernel_spans.py`
now uses it.
- `torchtitan/training_engine.py`: `TrainingEngine.Config` rejects
`kernel_spans` when `training.disable_accelerator_graphs` is set.
- `scripts/kernel_spans_to_trace.py` (new): joins spans to the node table and
writes a Chrome/Perfetto trace for chosen steps and ranks.
- `torchtitan/observability/README.md`: "Always-on kernel spans" section.
Requires CUDA graph node ids (CUDA 13.1+ driver or cuda-compat 13.1+), and
the Cuspy requirements (libcupti 13.3+, recent torch nightly). CUDA 13.5 is
not needed.
4x GB300, FSDP over 4 GPUs, CUDA graphs, cuda-compat 13.1. Baseline and
kernel_spans runs alternated, 2 rounds each. Llama 3 8B: seq 8192, 60 steps,
medians over steps 21-60. Qwen3 32B: seq 4096, full activation recompute, 40
steps, medians over steps 16-40. Both runs are GPU-bound. steps_per_file=20
so files are written inside the measured window (5x more often than the
default).
Performance:
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Tokens/s is averaged over the logged steps in the window (every 10 steps), so
it is noisier than the median step time.
Memory and disk, per rank:
| Model | GPU peak reserved, baseline -> spans | Host peak RSS, baseline -> spans | Disk per step (steps_per_file=100) | Disk at default retention (1000 steps) |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66-3.67 -> 3.71 GiB | 188 KB | ~188 MB |
Host RSS was sampled every 2 s from each training process. Disk per step
includes the node table, which is stored once per file (0.6 MB for 8B, 1.5 MB
for 32B).
Time taken:
| Model | Recorder step(), median per step | Recorder step(), max (includes file writes) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s (0.6 GB peak) | 4.6 s (0.6 GB peak) |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s (0.6 GB peak) | 8.2 s (0.7 GB peak) |
The recorder runs on the host while it waits on the GPU, so its time is mostly
hidden in GPU-bound steps. File write times are page-cache writes to local disk,
measured by re-saving the run's files. Conversion runs offline, off the
training machines.
Numerics: loss and grad_norm match the baseline for 30 steps of the llama3
debug model (seed 42, deterministic, flex attention, 2 GPUs).
Cost numbers were measured on an earlier revision of this change. That
revision had the same step cutting and file writing, but the recorder
subclassed `NodeTimerObserver` instead of holding one, and the wiring was
different.
- GPU, 2 GPUs, llama3 debug model, 12 steps, with `CuspyTraceProfiler`, memory
snapshots and `kernel_spans` (`steps_per_file=4`, `num_steps_retained=8`)
all enabled:
- Kernel span files, traces and snapshots are written as expected, and old
span files are evicted (steps 5-8 and 9-12 kept).
- The converter turned steps 10-11 into 2,276 kernel slices. Every graphed
kernel is named; the 228 kernels launched outside graphs are labeled
eager.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy's observer.
- Config-time rejections: `kernel_spans` with
`training.disable_accelerator_graphs=True`, and with `KinetoTraceProfiler`.
- Unit tests:
- `test_profiler_rejects_kineto_with_kernel_spans`;
- a new `test_trainer.py` annotation-config case (kernel spans + Cuspy with
py stacks -> exec keying + py stacks). This guards the combining rule,
which would otherwise silently drop the exec keying kernel spans need.
- The profiler, trainer and graph_trainer profiler tests pass.
ghstack-source-id: cec4ca3
Pull Request resolved: #5792
Stacked on "[profiler] Make profiling tools object-oriented".
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
A profiling trace only covers the window it was scheduled for. To see why
step 12,345 was slow, you need its kernels after the fact. This adds
`Profiler.Config.kernel_spans`, which records every CUDA kernel's GPU start and
end time, CUDA graph node id and stream on every step. It writes them every
`steps_per_file` steps (default 100) to a per-rank `.npz` and deletes the
oldest files the run wrote beyond `num_steps_retained` (default 1000).
**Example.**
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py outputs/profiling/kernel_spans \
--steps 1050-1052 --ranks 0-3 --output trace.json.gz # open in Perfetto
```
- `torchtitan/observability/kernel_spans.py` (new):
- `KernelSpanRecorder(Configurable)` is the profiling tool, and owns its
config. It holds a Cuspy `NodeTimerObserver`, which is imported when the
recorder is built, so the config imports without cupti-python. Its
`step()` runs on the training thread, and each step it:
- records the step's host end time;
- flushes CUPTI without a device sync;
- cuts the delivered kernels (kept sorted by start time) at the end of
every step that a later kernel has arrived after.
- `_KernelSpanFiles` buffers finished steps, writes a file every
`steps_per_file` steps and evicts old files.
- Kernels are named from CUDA graph nodes. A graph instantiate hook
records each node's kernel name, launch geometry and graph annotations
once per graph, and each file embeds the table for the graphs its steps
ran.
- `torchtitan/observability/profiler.py`:
- `Profiler.Config.kernel_spans: KernelSpanRecorder.Config | None` sits next
to `trace` and `memory_snapshot`.
- `Profiler.Config.__post_init__` rejects it with `KinetoTraceProfiler`:
Kineto's CUPTI init fails once Cuspy holds the subscription. A
`CuspyTraceProfiler` trace can run alongside it.
- `Profiler.Config.maybe_cuda_graph_annotation_config()` keys annotations
by exec-graph node id when kernel spans are on, since spans are named by
those ids. It still records py stacks when the Cuspy trace profiler asks
for them.
- Renames `_cuspy_unavailable_reasons` to public, because `kernel_spans.py`
now uses it.
- `torchtitan/training_engine.py`: `TrainingEngine.Config` rejects
`kernel_spans` when `training.disable_accelerator_graphs` is set.
- `scripts/kernel_spans_to_trace.py` (new): joins spans to the node table and
writes a Chrome/Perfetto trace for chosen steps and ranks.
- `torchtitan/observability/README.md`: "Always-on kernel spans" section.
Requires CUDA graph node ids (CUDA 13.1+ driver or cuda-compat 13.1+), and
the Cuspy requirements (libcupti 13.3+, recent torch nightly). CUDA 13.5 is
not needed.
4x GB300, FSDP over 4 GPUs, CUDA graphs, cuda-compat 13.1. Baseline and
kernel_spans runs alternated, 2 rounds each. Llama 3 8B: seq 8192, 60 steps,
medians over steps 21-60. Qwen3 32B: seq 4096, full activation recompute, 40
steps, medians over steps 16-40. Both runs are GPU-bound. steps_per_file=20
so files are written inside the measured window (5x more often than the
default).
Performance:
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Tokens/s is averaged over the logged steps in the window (every 10 steps), so
it is noisier than the median step time.
Memory and disk, per rank:
| Model | GPU peak reserved, baseline -> spans | Host peak RSS, baseline -> spans | Disk per step (steps_per_file=100) | Disk at default retention (1000 steps) |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66-3.67 -> 3.71 GiB | 188 KB | ~188 MB |
Host RSS was sampled every 2 s from each training process. Disk per step
includes the node table, which is stored once per file (0.6 MB for 8B, 1.5 MB
for 32B).
Time taken:
| Model | Recorder step(), median per step | Recorder step(), max (includes file writes) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s (0.6 GB peak) | 4.6 s (0.6 GB peak) |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s (0.6 GB peak) | 8.2 s (0.7 GB peak) |
The recorder runs on the host while it waits on the GPU, so its time is mostly
hidden in GPU-bound steps. File write times are page-cache writes to local disk,
measured by re-saving the run's files. Conversion runs offline, off the
training machines.
Numerics: loss and grad_norm match the baseline for 30 steps of the llama3
debug model (seed 42, deterministic, flex attention, 2 GPUs).
Cost numbers were measured on an earlier revision of this change. That
revision had the same step cutting and file writing, but the recorder
subclassed `NodeTimerObserver` instead of holding one, and the wiring was
different.
- GPU, 2 GPUs, llama3 debug model, 12 steps, with `CuspyTraceProfiler`, memory
snapshots and `kernel_spans` (`steps_per_file=4`, `num_steps_retained=8`)
all enabled:
- Kernel span files, traces and snapshots are written as expected, and old
span files are evicted (steps 5-8 and 9-12 kept).
- The converter turned steps 10-11 into 2,276 kernel slices. Every graphed
kernel is named; the 228 kernels launched outside graphs are labeled
eager.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy's observer.
- Config-time rejections: `kernel_spans` with
`training.disable_accelerator_graphs=True`, and with `KinetoTraceProfiler`.
- Unit tests:
- `test_profiler_rejects_kineto_with_kernel_spans`;
- a new `test_trainer.py` annotation-config case (kernel spans + Cuspy with
py stacks -> exec keying + py stacks). This guards the combining rule,
which would otherwise silently drop the exec keying kernel spans need.
- The profiler, trainer and graph_trainer profiler tests pass.
ghstack-source-id: cec4ca3
Pull Request resolved: #5792
Stacked on "[profiler] Make profiling tools object-oriented".
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
A profiling trace only covers the window it was scheduled for. To see why
step 12,345 was slow, you need its kernels after the fact. This adds
`Profiler.Config.kernel_spans`, which records every CUDA kernel's GPU start and
end time, CUDA graph node id and stream on every step. It writes them every
`steps_per_file` steps (default 100) to a per-rank `.npz` and deletes the
oldest files the run wrote beyond `num_steps_retained` (default 1000).
**Example.**
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py outputs/profiling/kernel_spans \
--steps 1050-1052 --ranks 0-3 --output trace.json.gz # open in Perfetto
```
- `torchtitan/observability/kernel_spans.py` (new):
- `KernelSpanRecorder(Configurable)` is the profiling tool, and owns its
config. It holds a Cuspy `NodeTimerObserver`, which is imported when the
recorder is built, so the config imports without cupti-python. Its
`step()` runs on the training thread, and each step it:
- records the step's host end time;
- flushes CUPTI without a device sync;
- cuts the delivered kernels (kept sorted by start time) at the end of
every step that a later kernel has arrived after.
- `_KernelSpanFiles` buffers finished steps, writes a file every
`steps_per_file` steps and evicts old files.
- Kernels are named from CUDA graph nodes. A graph instantiate hook
records each node's kernel name, launch geometry and graph annotations
once per graph, and each file embeds the table for the graphs its steps
ran.
- `torchtitan/observability/profiler.py`:
- `Profiler.Config.kernel_spans: KernelSpanRecorder.Config | None` sits next
to `trace` and `memory_snapshot`.
- `Profiler.Config.__post_init__` rejects it with `KinetoTraceProfiler`:
Kineto's CUPTI init fails once Cuspy holds the subscription. A
`CuspyTraceProfiler` trace can run alongside it.
- `Profiler.Config.maybe_cuda_graph_annotation_config()` keys annotations
by exec-graph node id when kernel spans are on, since spans are named by
those ids. It still records py stacks when the Cuspy trace profiler asks
for them.
- Renames `_cuspy_unavailable_reasons` to public, because `kernel_spans.py`
now uses it.
- `torchtitan/training_engine.py`: `TrainingEngine.Config` rejects
`kernel_spans` when `training.disable_accelerator_graphs` is set.
- `scripts/kernel_spans_to_trace.py` (new): joins spans to the node table and
writes a Chrome/Perfetto trace for chosen steps and ranks.
- `torchtitan/observability/README.md`: "Always-on kernel spans" section.
Requires CUDA graph node ids (CUDA 13.1+ driver or cuda-compat 13.1+), and
the Cuspy requirements (libcupti 13.3+, recent torch nightly). CUDA 13.5 is
not needed.
4x GB300, FSDP over 4 GPUs, CUDA graphs, cuda-compat 13.1. Baseline and
kernel_spans runs alternated, 2 rounds each. Llama 3 8B: seq 8192, 60 steps,
medians over steps 21-60. Qwen3 32B: seq 4096, full activation recompute, 40
steps, medians over steps 16-40. Both runs are GPU-bound. steps_per_file=20
so files are written inside the measured window (5x more often than the
default).
Performance:
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Tokens/s is averaged over the logged steps in the window (every 10 steps), so
it is noisier than the median step time.
Memory and disk, per rank:
| Model | GPU peak reserved, baseline -> spans | Host peak RSS, baseline -> spans | Disk per step (steps_per_file=100) | Disk at default retention (1000 steps) |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66-3.67 -> 3.71 GiB | 188 KB | ~188 MB |
Host RSS was sampled every 2 s from each training process. Disk per step
includes the node table, which is stored once per file (0.6 MB for 8B, 1.5 MB
for 32B).
Time taken:
| Model | Recorder step(), median per step | Recorder step(), max (includes file writes) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s (0.6 GB peak) | 4.6 s (0.6 GB peak) |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s (0.6 GB peak) | 8.2 s (0.7 GB peak) |
The recorder runs on the host while it waits on the GPU, so its time is mostly
hidden in GPU-bound steps. File write times are page-cache writes to local disk,
measured by re-saving the run's files. Conversion runs offline, off the
training machines.
Numerics: loss and grad_norm match the baseline for 30 steps of the llama3
debug model (seed 42, deterministic, flex attention, 2 GPUs).
Cost numbers were measured on an earlier revision of this change. That
revision had the same step cutting and file writing, but the recorder
subclassed `NodeTimerObserver` instead of holding one, and the wiring was
different.
- GPU, 2 GPUs, llama3 debug model, 12 steps, with `CuspyTraceProfiler`, memory
snapshots and `kernel_spans` (`steps_per_file=4`, `num_steps_retained=8`)
all enabled:
- Kernel span files, traces and snapshots are written as expected, and old
span files are evicted (steps 5-8 and 9-12 kept).
- The converter turned steps 10-11 into 2,276 kernel slices. Every graphed
kernel is named; the 228 kernels launched outside graphs are labeled
eager.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy's observer.
- Config-time rejections: `kernel_spans` with
`training.disable_accelerator_graphs=True`, and with `KinetoTraceProfiler`.
- Unit tests:
- `test_profiler_rejects_kineto_with_kernel_spans`;
- a new `test_trainer.py` annotation-config case (kernel spans + Cuspy with
py stacks -> exec keying + py stacks). This guards the combining rule,
which would otherwise silently drop the exec keying kernel spans need.
- The profiler, trainer and graph_trainer profiler tests pass.
ghstack-source-id: cec4ca3
Pull Request resolved: #5792
Stacked on "[profiler] Make profiling tools object-oriented".
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
A profiling trace only covers the window it was scheduled for. To see why
step 12,345 was slow, you need its kernels after the fact. This adds
`Profiler.Config.kernel_spans`, which records every CUDA kernel's GPU start and
end time, CUDA graph node id and stream on every step. It writes them every
`steps_per_file` steps (default 100) to a per-rank `.npz` and deletes the
oldest files the run wrote beyond `num_steps_retained` (default 1000).
**Example.**
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py outputs/profiling/kernel_spans \
--steps 1050-1052 --ranks 0-3 --output trace.json.gz # open in Perfetto
```
- `torchtitan/observability/kernel_spans.py` (new):
- `KernelSpanRecorder(Configurable)` is the profiling tool, and owns its
config. It holds a Cuspy `NodeTimerObserver`, which is imported when the
recorder is built, so the config imports without cupti-python. Its
`step()` runs on the training thread, and each step it:
- records the step's host end time;
- flushes CUPTI without a device sync;
- cuts the delivered kernels (kept sorted by start time) at the end of
every step that a later kernel has arrived after.
- `_KernelSpanFiles` buffers finished steps, writes a file every
`steps_per_file` steps and evicts old files.
- Kernels are named from CUDA graph nodes. A graph instantiate hook
records each node's kernel name, launch geometry and graph annotations
once per graph, and each file embeds the table for the graphs its steps
ran.
- `torchtitan/observability/profiler.py`:
- `Profiler.Config.kernel_spans: KernelSpanRecorder.Config | None` sits next
to `trace` and `memory_snapshot`.
- `Profiler.Config.__post_init__` rejects it with `KinetoTraceProfiler`:
Kineto's CUPTI init fails once Cuspy holds the subscription. A
`CuspyTraceProfiler` trace can run alongside it.
- `Profiler.Config.maybe_cuda_graph_annotation_config()` keys annotations
by exec-graph node id when kernel spans are on, since spans are named by
those ids. It still records py stacks when the Cuspy trace profiler asks
for them.
- Renames `_cuspy_unavailable_reasons` to public, because `kernel_spans.py`
now uses it.
- `torchtitan/training_engine.py`: `TrainingEngine.Config` rejects
`kernel_spans` when `training.disable_accelerator_graphs` is set.
- `scripts/kernel_spans_to_trace.py` (new): joins spans to the node table and
writes a Chrome/Perfetto trace for chosen steps and ranks.
- `torchtitan/observability/README.md`: "Always-on kernel spans" section.
Requires CUDA graph node ids (CUDA 13.1+ driver or cuda-compat 13.1+), and
the Cuspy requirements (libcupti 13.3+, recent torch nightly). CUDA 13.5 is
not needed.
4x GB300, FSDP over 4 GPUs, CUDA graphs, cuda-compat 13.1. Baseline and
kernel_spans runs alternated, 2 rounds each. Llama 3 8B: seq 8192, 60 steps,
medians over steps 21-60. Qwen3 32B: seq 4096, full activation recompute, 40
steps, medians over steps 16-40. Both runs are GPU-bound. steps_per_file=20
so files are written inside the measured window (5x more often than the
default).
Performance:
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Tokens/s is averaged over the logged steps in the window (every 10 steps), so
it is noisier than the median step time.
Memory and disk, per rank:
| Model | GPU peak reserved, baseline -> spans | Host peak RSS, baseline -> spans | Disk per step (steps_per_file=100) | Disk at default retention (1000 steps) |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66-3.67 -> 3.71 GiB | 188 KB | ~188 MB |
Host RSS was sampled every 2 s from each training process. Disk per step
includes the node table, which is stored once per file (0.6 MB for 8B, 1.5 MB
for 32B).
Time taken:
| Model | Recorder step(), median per step | Recorder step(), max (includes file writes) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s (0.6 GB peak) | 4.6 s (0.6 GB peak) |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s (0.6 GB peak) | 8.2 s (0.7 GB peak) |
The recorder runs on the host while it waits on the GPU, so its time is mostly
hidden in GPU-bound steps. File write times are page-cache writes to local disk,
measured by re-saving the run's files. Conversion runs offline, off the
training machines.
Numerics: loss and grad_norm match the baseline for 30 steps of the llama3
debug model (seed 42, deterministic, flex attention, 2 GPUs).
Cost numbers were measured on an earlier revision of this change. That
revision had the same step cutting and file writing, but the recorder
subclassed `NodeTimerObserver` instead of holding one, and the wiring was
different.
- GPU, 2 GPUs, llama3 debug model, 12 steps, with `CuspyTraceProfiler`, memory
snapshots and `kernel_spans` (`steps_per_file=4`, `num_steps_retained=8`)
all enabled:
- Kernel span files, traces and snapshots are written as expected, and old
span files are evicted (steps 5-8 and 9-12 kept).
- The converter turned steps 10-11 into 2,276 kernel slices. Every graphed
kernel is named; the 228 kernels launched outside graphs are labeled
eager.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy's observer.
- Config-time rejections: `kernel_spans` with
`training.disable_accelerator_graphs=True`, and with `KinetoTraceProfiler`.
- Unit tests:
- `test_profiler_rejects_kineto_with_kernel_spans`;
- a new `test_trainer.py` annotation-config case (kernel spans + Cuspy with
py stacks -> exec keying + py stacks). This guards the combining rule,
which would otherwise silently drop the exec keying kernel spans need.
- The profiler, trainer and graph_trainer profiler tests pass.
ghstack-source-id: cec4ca3
Pull Request resolved: #5792
## 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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py outputs/profiling/kernel_spans \
--steps 1050-1052 --ranks 0-3 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` joins rows to the table and writes
a Chrome/Perfetto trace: one process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: cec4ca3
Pull Request resolved: #5792
| ) | ||
|
|
||
|
|
||
| class _KernelSpanFiles: |
There was a problem hiding this comment.
no idea what to name this and the file lol
[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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 38b7d1c
Pull Request resolved: #5792
## 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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 3f08d5b
Pull Request resolved: #5792
kapilsh
left a comment
There was a problem hiding this comment.
LGTM from my side -- may be someone from Titan might also want to look.
[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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: e8eeeeb
Pull Request resolved: #5792
[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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 4d8c4c3
Pull Request resolved: #5792
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0) (oldest at bottom): * #5792 * __->__ #5871 ## 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-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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. records the host time the step ended;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
CUPTI delivers kernels late, in batches, in the order they ran. A step is
finished once a kernel that started after its end has arrived:
```
step ends (host): |end 41 |end 42 |end 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
## Performance
Setup: 4x GB300, FSDP over 4 GPUs, CUDA graphs. Baseline and kernel_spans runs
alternated, 2 rounds each, both GPU-bound.
- Llama 3 8B: seq 8192, median over steps 21-60.
- Qwen3 32B: seq 4096, full recompute, median over steps 16-40.
- `steps_per_file=20`, so files are written inside the measured window (5x
more often than the default).
| Model (kernels/step) | Round | Step time, baseline | Step time, spans | Change | Tokens/s/GPU, baseline | Tokens/s/GPU, spans |
|---|---|---|---|---|---|---|
| Llama 3 8B (2.3k) | 1 | 377.4 ms | 377.7 ms | +0.1% | 21,802 | 21,662 |
| Llama 3 8B (2.3k) | 2 | 377.7 ms | 382.6 ms | +1.3% | 21,732 | 20,760 |
| Qwen3 32B (5.4k) | 1 | 2,963.0 ms | 2,969.1 ms | +0.2% | 5,528 | 5,514 |
| Qwen3 32B (5.4k) | 2 | 2,963.1 ms | 2,973.5 ms | +0.35% | 5,524 | 5,512 |
Memory and disk, per rank:
| Model | GPU peak reserved | Host peak RSS | Disk per step | Disk at 1000 steps |
|---|---|---|---|---|
| Llama 3 8B | 61.33 -> 61.33 GiB | 3.49 -> 3.52 GiB | 81 KB | ~81 MB |
| Qwen3 32B | 145.28 -> 145.28 GiB | 3.66 -> 3.71 GiB | 188 KB | ~188 MB |
Time taken:
| Model | Recorder step(), median | Recorder step(), max (incl. file write) | Write one 100-step file | Convert 1 step x 4 ranks | Convert 10 steps x 4 ranks |
|---|---|---|---|---|---|
| Llama 3 8B | 2.8-3.5 ms | 12.6-43.0 ms | 3.9 ms (8.1 MB) | 2.3 s | 4.6 s |
| Qwen3 32B | 5.3 ms | 24.5-24.9 ms | 8.5 ms (18.8 MB) | 2.7 s | 8.2 s |
The recorder runs on the host while it waits on the GPU, so its time is
mostly hidden. These numbers come from an earlier revision with the same step
cutting and file writing.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 47ff9f5
Pull Request resolved: #5792
|
@tianyu-l in case you have thoughts |
|
@claude review |
|
Claude finished @tianyu-l's task in 4m 10s —— View job Request changes: steps are cut at host time with no per-step sync, so step numbers likely drift from GPU steps, and restarts break the retention bound. See review |
There was a problem hiding this comment.
Verdict: Request changes -- steps are cut at host time, and the training loop has no per-step sync, so on GPU-bound runs the recorded step numbers likely don't match the GPU steps. Restarts also break the retention bound.
What this PR does. Adds Profiler.Config.kernel_spans (KernelSpanRecorder). It holds a Cuspy NodeTimerObserver on CONCURRENT_KERNEL for the whole run. On every Profiler.step() it records the host time, flushes CUPTI without a device sync, and files delivered kernels into steps by GPU start time versus host step-end time. Every steps_per_file steps it writes a per-rank .npz with the graph node table embedded, and it deletes the oldest files beyond num_steps_retained. scripts/kernel_spans_to_trace.py joins rows to node names and writes a Perfetto trace. Config validation rejects Kineto + kernel_spans and disable_accelerator_graphs + kernel_spans. With kernel spans on, graph annotations are keyed by exec-graph node id.
Example. GPU-bound run, metrics.log_freq=10 (default), host 2 steps ahead of the GPU:
host: step() for 101 at H101, while the GPU is still running step 99
cut: "step 101" = kernels with gpu_start in (H100, H101] -> mostly GPU step 99
file: steps_..._101 labels step-99 work as step 101; step 101's kernels go into "step 103"
A user who opens step 12,345 because it was slow sees the kernels of a different step.
Must fix
- The PR description's "Summary (human-written)" is empty. The author needs to fill it in.
torchtitan/observability/kernel_spans.py:217-- steps are cut at hoststep()time. The host only syncs onshould_logsteps, so the step labels drift by however far the host runs ahead. Cut on a GPU-side boundary instead (a marker on the compute stream, or CUPTI correlation ids). Magnitude unverified.torchtitan/observability/kernel_spans.py:358-- each restart writes into the samerank{r}/dir and never deletes old files. Disk grows without bound, resumed runs produce files with overlapping steps from two timelines, and a same-name file is silently overwritten. Fix: at init, take over the existing files and delete those pastglobal_step.
Should consider
torchtitan/observability/kernel_spans.py:294-- the "finished" check assumes delivery follows start order across streams. A long comm kernel that straddles the step boundary gets filed into the next step. Unverified.torchtitan/observability/README.md:90-- the "under 1% overhead" claim conflicts with the PR's own table (+1.3% step time, -4.5% tokens/s), and the step-time and tokens/s columns don't agree with each other.torchtitan/observability/kernel_spans.py:144-- the three private-API TODOs need an upstream issue link.- The step-assignment (
_close_finished_steps) and eviction (_evict_old_files) logic is plain numpy, and mis-filing would go unnoticed. A CPU unit test with a fake observer, covering out-of-order delivery,close_all, and eviction counts, would protect it better thantest_profiler_rejects_kineto_with_kernel_spans, which only checks that the config raises.
Details
- Host syncs in the step:
trainer.pycalls.item()only inside theshould_logbranch (lines 433/480/493).training_engine.py:750moves inputs withnon_blocking=True.optim_stephas no.item(). Nothing else in the loop blocks the host between log steps, so how far it gets ahead depends on allocator and launch-queue back-pressure, which CUDA graphs mostly remove. step_profiler()runs aftersave_checkpointand validation (trainer.py:538), so step N also holds checkpoint and validation kernels. That's fine, but worth one line in the README caveats.- The core touch is a single cross-field check in
TrainingEngine.Config.__post_init__. It follows the existingdisable_accelerator_graphschecks there, so I'm not flagging it. - Making
cuspy_unavailable_reasonspublic is right, sincekernel_spans.pyimports it. Both test mock paths are updated.
Not verified: CUPTI delivery order across streams, and how far the host runs ahead on GB300. Both need a GPU run. A maintainer still needs to review, since training_engine.py is touched.
| self._open_step_ends.append( | ||
| ( | ||
| self._step, | ||
| self._observer.convert_time(self._observer.now_record_ns()), |
There was a problem hiding this comment.
The step boundary is the host clock at step(), compared against GPU start times. That only lines up when the host waits on the GPU every step, and the main loop doesn't. Trainer.train_step syncs only on should_log steps (.item() at trainer.py:433/480/493, default metrics.log_freq=10). microbatch.to_input_dict(..., non_blocking=True) and graph replays don't block the host. So in a GPU-bound run the host can be several steps ahead. Then "step N" holds mostly kernels of GPU step N-k, and step N's own kernels end up in a later step. The caveat ("a step can include the tail of earlier steps") understates this. This is the main use case ("why was step 12,345 slow"), and the file would name the wrong step.
Unverified how far ahead the host gets in practice. Could you log step() host time against the first kernel of each step's graph replay on the GB300 run with log_freq=10?
Fix: cut on a GPU-side boundary instead of host time. For example, enqueue a marker at step() on the compute stream and split on its GPU start. Or cut by CUPTI correlation id, which follows host launch order: record the latest correlation id at step() and split on it. That needs NodeTimerObserver.drain() to return correlation ids, which is a natural upstream ask.
| complete_steps = [ | ||
| (step, step_end_ns) | ||
| for step, step_end_ns in self._open_step_ends | ||
| if close_all or step_end_ns <= latest_start_ns |
There was a problem hiding this comment.
The rule "finished once a kernel that started after its end has been delivered" assumes delivery follows start order across streams. As far as I know, CUPTI writes a concurrent-kernel record when the kernel completes (unverified for Cuspy's buffering). Take a long NCCL reduce-scatter on the comm stream that starts before step N's end and finishes after a short compute kernel of step N+1 has been delivered. Step N closes without it. The late record then sorts to the front of _unassigned_spans and is filed into step N+1, so step N loses exactly the kernel that straddles the boundary. If a GPU-side cut (comment on line 217) isn't adopted, at least close step N only once every stream that ran in step N has delivered a kernel starting after step_end_ns. Or document this mis-filing.
| # (step, its kernels as _SPAN_DTYPE rows) of complete steps not yet written. | ||
| self._unwritten_steps: list[tuple[int, np.ndarray]] = [] | ||
| # (path, number of steps it holds) of each step file written, oldest first. | ||
| self._files_and_num_steps: deque[tuple[str, int]] = deque() |
There was a problem hiding this comment.
Each run starts with an empty deque, and leaf_folder defaults to "", so every restart writes into the same rank{r}/ directory. That causes three problems:
- Files from earlier runs are never deleted. Disk use grows by up to
num_steps_retainedsteps per restart, about 188 MB/rank each time for Qwen3 32B, and long runs restart often.num_steps_retainedstops being a bound. - After resuming from step 950, the new
steps_000000000951_...overlaps the crashed run'ssteps_000000000901_000000001000. Two files then claim steps 951-1000 from different timelines. - A new file with the same range as an old one is silently overwritten by
np.savez.
Smallest fix (~10 lines): in __init__, list the existing steps_*.npz in files_dir. Delete those whose first step is > global_step, since they come from the abandoned timeline. Seed _files_and_num_steps / _num_steps_on_disk from the rest, sorted by name, so normal eviction covers them.
| torchtitan supports always-on profiling through the Cuspy backend, typically | ||
| adding under 1% overhead in real-scale training. Every step, each rank records |
There was a problem hiding this comment.
"typically adding under 1% overhead" doesn't match the PR's own table. Llama 3 8B round 2 is +1.3% step time, and tokens/s/GPU falls 21,732 -> 20,760 (-4.5%). Step time and tokens/s also disagree with each other: round 1 is +0.1% step time but -0.6% tokens/s. Either the two medians cover different windows, or something besides step time moved. Please explain the gap. Also re-measure on the current revision, since the description says the numbers come from an earlier one. Then state the overhead as measured (e.g. "0.1-1.3% step time on the runs measured") rather than "under 1%".
| ) -> None: | ||
| # Imported here: they need Cuspy and cupti-python, and profiler.py imports | ||
| # this module for the config. | ||
| # TODO: these are private torch APIs; move to a public per-step span |
There was a problem hiding this comment.
This TODO, the one at line 220 (_observer._cuspy.flush), and the one for torch._C._demangle in scripts/kernel_spans_to_trace.py all mark private torch APIs but have no upstream issue link. The repo rule asks for a link. Please file one issue for a public per-step span observer (a public flush(sync=...), plus correlation ids if you take the suggestion on line 217) and link it from all three TODOs.
[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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. replays a one-kernel marker CUDA graph on the current stream;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
The host runs ahead of the GPU, so steps are cut on the GPU: the marker starts
after everything the step enqueued on that stream, and step N holds the
kernels that started between marker N-1 and marker N. CUPTI delivers records
late and in batches, and not in start order across streams, so step N is
filed once marker N+1 has arrived:
```
markers (GPU): |marker 41 |marker 42 |marker 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
- On restart, files holding steps after the resumed step are deleted (they
will be recorded again); older files count toward `num_steps_retained`.
## Performance
Setup: Llama 3 8B, seq 8192, FSDP over one 4x GB300 node, CUDA graphs,
`metrics.log_freq=10`, `steps_per_file=20` (5x more file writes than the
default). Baseline and kernel spans alternated on the same node
(base, spans, base, spans), steps 21-100. Tokens/s/GPU is the mean over the
eight 10-step log windows; step time is the mean wall time per step.
| Revision | Run | Tokens/s/GPU, baseline | Tokens/s/GPU, spans | Change | Step time, baseline | Step time, spans |
|---|---|---|---|---|---|---|
| host-time cut (previous) | 1 | 22,842 | 22,761 | -0.35% | 358.7 ms | 360.3 ms |
| host-time cut (previous) | 2 | 22,861 | 22,741 | -0.52% | 358.5 ms | 360.6 ms |
| GPU marker cut (this) | 1 | 22,990 | 22,917 | -0.32% | 356.4 ms | 357.8 ms |
| GPU marker cut (this) | 2 | 22,984 | 22,909 | -0.33% | 356.5 ms | 358.0 ms |
Recorder `step()` on the host: median 1.8 ms; about 17 ms on the steps that
write a file (one 115 ms outlier, on the first write of one run).
Step cutting, kernels per step on rank 0 (2,323, or 2,331 on log steps):
| Step cut | Kernels per step |
|---|---|
| host time, `log_freq=10` | 31 to 4,555 |
| host time, `log_freq=1` (host syncs every step) | 2,331 |
| GPU marker, `log_freq=10` | 2,323 to 2,331 |
The host-time cut mis-filed kernels whenever the host ran ahead; the marker
cut doesn't depend on it.
The node driver is CUDA 13.0 (580), so these runs put cuda-compat 13.4 on
`LD_LIBRARY_PATH` for graph node ids, in both baseline and spans runs.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- step assignment with a fake observer: steps cut at the markers while the
host runs ahead, a late kernel from another stream stays in its step,
close() files the rest;
- file eviction, and restart takeover (abandoned files deleted, older files
evicted with new ones);
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 8b49f4e
Pull Request resolved: #5792
## 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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. replays a one-kernel marker CUDA graph on the current stream;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
The host runs ahead of the GPU, so steps are cut on the GPU: the marker starts
after everything the step enqueued on that stream, and step N holds the
kernels that started between marker N-1 and marker N. CUPTI delivers records
late and in batches, and not in start order across streams, so step N is
filed once marker N+1 has arrived:
```
markers (GPU): |marker 41 |marker 42 |marker 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
- On restart, files holding steps after the resumed step are deleted (they
will be recorded again); older files count toward `num_steps_retained`.
## Performance
Setup: Llama 3 8B, seq 8192, FSDP over one 4x GB300 node, CUDA graphs,
`metrics.log_freq=10`, `steps_per_file=20` (5x more file writes than the
default). Baseline and kernel spans alternated on the same node
(base, spans, base, spans), steps 21-100. Tokens/s/GPU is the mean over the
eight 10-step log windows; step time is the mean wall time per step.
| Revision | Run | Tokens/s/GPU, baseline | Tokens/s/GPU, spans | Change | Step time, baseline | Step time, spans |
|---|---|---|---|---|---|---|
| host-time cut (previous) | 1 | 22,842 | 22,761 | -0.35% | 358.7 ms | 360.3 ms |
| host-time cut (previous) | 2 | 22,861 | 22,741 | -0.52% | 358.5 ms | 360.6 ms |
| GPU marker cut (this) | 1 | 22,990 | 22,917 | -0.32% | 356.4 ms | 357.8 ms |
| GPU marker cut (this) | 2 | 22,984 | 22,909 | -0.33% | 356.5 ms | 358.0 ms |
Recorder `step()` on the host: median 1.8 ms; about 17 ms on the steps that
write a file (one 115 ms outlier, on the first write of one run).
Step cutting, kernels per step on rank 0 (2,323, or 2,331 on log steps):
| Step cut | Kernels per step |
|---|---|
| host time, `log_freq=10` | 31 to 4,555 |
| host time, `log_freq=1` (host syncs every step) | 2,331 |
| GPU marker, `log_freq=10` | 2,323 to 2,331 |
The host-time cut mis-filed kernels whenever the host ran ahead; the marker
cut doesn't depend on it.
The node driver is CUDA 13.0 (580), so these runs put cuda-compat 13.4 on
`LD_LIBRARY_PATH` for graph node ids, in both baseline and spans runs.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- step assignment with a fake observer: steps cut at the markers while the
host runs ahead, a late kernel from another stream stays in its step,
close() files the rest;
- file eviction, and restart takeover (abandoned files deleted, older files
evicted with new ones);
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: 8b49f4e
Pull Request resolved: #5792
## 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
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact. `profiler.kernel_spans`
records every CUDA kernel's GPU start/end time on every step, and keeps the
last `num_steps_retained` steps on disk per rank.
```python
config.profiler.kernel_spans = KernelSpanRecorder.Config(num_steps_retained=1000)
```
```bash
python scripts/kernel_spans_to_trace.py \
outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \
--steps 1050-1052 --output trace.json.gz # open in Perfetto
```
## Design
```
Profiler
+-- trace: TraceProfiler | None
+-- memory_snapshot: MemorySnapshotProfiler | None
+-- kernel_spans: KernelSpanRecorder | None (new, kernel_spans.py)
+-- NodeTimerObserver Cuspy CUPTI subscription
+-- graph instantiate hook node id -> kernel name,
| grid/block, annotations
+-- _KernelSpanFiles buffer steps, write .npz,
delete oldest
```
Each `Profiler.step()`, the recorder:
1. replays a one-kernel marker CUDA graph on the current stream;
2. flushes CUPTI without a device sync;
3. files the delivered kernels into steps.
The host runs ahead of the GPU, so steps are cut on the GPU: the marker starts
after everything the step enqueued on that stream, and step N holds the
kernels that started between marker N-1 and marker N. CUPTI delivers records
late and in batches, and not in start order across streams, so step N is
filed once marker N+1 has arrived:
```
markers (GPU): |marker 41 |marker 42 |marker 43
kernels (GPU): k k k k k k k k k k k k k k k k k k k k k k ...
<----- step 42 ---->|<----- step 43 ---->| ... not yet
```
Every `steps_per_file` (default 100) finished steps, one file is written per
rank, and the oldest files are deleted beyond `num_steps_retained`:
```
profiling/kernel_spans/rank{r}/steps_{first:012d}_{last:012d}.npz
rank int64 rank that wrote the file
steps int64[S] step numbers
step_offsets int64[S+1] row range of each step
graph_node_id uint64[K] (exec graph id << 32) | node index; 0 = eager
start_ns int64[K] GPU start, unix ns
end_ns int64[K] GPU end, unix ns
stream_id uint64[K] CUDA stream
node_table uint8[] JSON {graph_node_id: {kernel_name, grid, block,
annotations}} for the graphs these steps ran
```
Each file carries its own node table, so it decodes without the training
process. `scripts/kernel_spans_to_trace.py` takes one file per rank plus
`--steps`, joins rows to the table, and writes a Chrome/Perfetto trace: one
process per rank, one track per stream.
Constraints:
- Requires accelerator graphs, because kernels are named from graph nodes.
`TrainingEngine.Config` rejects `disable_accelerator_graphs`.
- It can't run with `KinetoTraceProfiler`, because Kineto can't take CUPTI
once Cuspy holds it; `CuspyTraceProfiler` works. With kernel spans on,
graph annotations are keyed by exec-graph node id.
- Needs CUDA graph node ids, from a CUDA 13.1+ driver or cuda-compat 13.1+,
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
- Steps not yet written to a file are lost if the process is killed.
- On restart, files holding steps after the resumed step are deleted (they
will be recorded again); older files count toward `num_steps_retained`.
## Performance
Setup: Llama 3 8B, seq 8192, FSDP over one 4x GB300 node, CUDA graphs,
`metrics.log_freq=10`, `steps_per_file=20` (5x more file writes than the
default). Baseline and kernel spans alternated on the same node
(base, spans, base, spans), steps 21-100. Tokens/s/GPU is the mean over the
eight 10-step log windows; step time is the mean wall time per step.
| Revision | Run | Tokens/s/GPU, baseline | Tokens/s/GPU, spans | Change | Step time, baseline | Step time, spans |
|---|---|---|---|---|---|---|
| host-time cut (previous) | 1 | 22,842 | 22,761 | -0.35% | 358.7 ms | 360.3 ms |
| host-time cut (previous) | 2 | 22,861 | 22,741 | -0.52% | 358.5 ms | 360.6 ms |
| GPU marker cut (this) | 1 | 22,990 | 22,917 | -0.32% | 356.4 ms | 357.8 ms |
| GPU marker cut (this) | 2 | 22,984 | 22,909 | -0.33% | 356.5 ms | 358.0 ms |
Recorder `step()` on the host: median 1.8 ms; about 17 ms on the steps that
write a file (one 115 ms outlier, on the first write of one run).
Step cutting, kernels per step on rank 0 (2,323, or 2,331 on log steps):
| Step cut | Kernels per step |
|---|---|
| host time, `log_freq=10` | 31 to 4,555 |
| host time, `log_freq=1` (host syncs every step) | 2,331 |
| GPU marker, `log_freq=10` | 2,323 to 2,331 |
The host-time cut mis-filed kernels whenever the host ran ahead; the marker
cut doesn't depend on it.
The node driver is CUDA 13.0 (580), so these runs put cuda-compat 13.4 on
`LD_LIBRARY_PATH` for graph node ids, in both baseline and spans runs.
## Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
## Testing
- 2 GPUs, debug model, with the Cuspy trace, memory snapshots and kernel
spans all on:
- Files are written and evicted as expected.
- The converter names every kernel replayed from a graph (2,048); the other
228 ran outside graphs.
- Importing `torchtitan.observability.profiler` loads neither cupti nor
Cuspy.
- Unit tests:
- step assignment with a fake observer: steps cut at the markers while the
host runs ahead, a late kernel from another stream stays in its step,
close() files the rest;
- file eviction, and restart takeover (abandoned files deleted, older files
evicted with new ones);
- the Kineto + kernel_spans rejection;
- a `test_trainer.py` annotation-config case (kernel spans + Cuspy py
stacks -> exec keying + py stacks).
ghstack-source-id: bd1b094
Pull Request resolved: #5792
|
@claude look again pls |
|
Claude finished @pianpwk's task in 2m 25s —— View job Approve, with two small items to address before merging: the GPU marker cut and the restart file takeover fix both must-fix code issues from the last review. Still needed are the human-written summary and upstream issue links on the private-API TODOs. See review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The GPU marker cut and the restart takeover fix both must-fix code issues from the last review. What's left are small edits.
What changed since the last review. step() no longer records the host time. It replays a one-kernel marker CUDA graph on the current stream, and step N becomes the kernels that started between marker N-1 and marker N. Step N is finished only once marker N+1 has been delivered. _KernelSpanFiles now takes over the files already in rank{r}/: it deletes files that hold steps after global_step and evicts the rest along with new files. The README overhead claim now gives the measured 0.3-0.5%, and CPU unit tests with a fake observer cover step cutting, late cross-stream records, eviction and restart.
Example. The host is 2 steps ahead, with log_freq=10:
before: "step 101" = kernels with gpu_start in (host H100, host H101] -> mostly GPU step 99
after: "step 101" = kernels with gpu_start in (marker 100, marker 101) -> GPU step 101
Earlier findings
- Resolved: host-time step cut (
kernel_spans.py:241, marker graph). - Resolved: restarts break the retention bound and overlap timelines (
kernel_spans.py:398). - Resolved: late record from another stream filed into the wrong step. The extra step of delay plus
test_late_kernel_from_another_stream_stays_in_its_stepcover it, and the remaining case is documented. - Resolved: README "under 1%" claim, and missing unit tests for step assignment and eviction.
- Still open: the empty "Summary (human-written)" (item 1 below).
- Still open: the missing upstream issue links (item 2 below).
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author needs to write it.
kernel_spans.py:153,kernel_spans.py:243andscripts/kernel_spans_to_trace.py:32: the private-API TODOs (torch.profiler._cuspy,_observer._cuspy.flush,torch._C._demangle) still have no upstream issue link. CLAUDE.md principle 3 requires one. File one issue for a public per-step observer withflush(sync=...)and link it from all three.
Should consider
kernel_spans.py:336-- markers are matched to steps by position, so one dropped CUPTI record would shift every later step label by one, with nothing to show it (see inline). Unverified whether Cuspy can drop records.
Details
- Marker ordering:
start_profiler()runs afterdevice_module.set_device(training_engine.py:324) and after checkpoint load. The marker buffer and graph therefore land on the rank's own device. They are captured before the instantiate hook is registered, so they stay out of node tables.step_profiler()runs on the default stream aftertrain_step, checkpoint and validation, so the marker is ordered after the step's graph replays and the FSDP collectives the default stream waits on. _close_finished_stepswith an empty_step_ends:num_finishedis -1, so the loop slices[:-1](empty), andmax(num_finished, 0)keeps the list intact.- Core touch: the
disable_accelerator_graphscross-check inTrainingEngine.Config.__post_init__is unchanged since the last review, and a maintainer (tianyu-l) has approved. - Minor:
_init_step_stateexists only so the tests can build a recorder via__new__and set private attributes. That's acceptable for a test seam. Not flagged.
Not verified: CUPTI/Cuspy record-drop behavior under high kernel rates. That needs a GPU run.
| is_marker = (delivered["graph_node_id"] >> 32) == self._marker_graph_id | ||
| for marker_start_ns in np.sort(delivered["start_ns"][is_marker]).tolist(): | ||
| self._step_ends.append( | ||
| (self._steps_awaiting_marker.popleft(), marker_start_ns) | ||
| ) |
There was a problem hiding this comment.
Each delivered marker is matched to a step by position only (popleft()). If one marker record is ever lost, for example because CUPTI drops records when its activity buffers fill up at 50k-200k kernels/step, every later step is labeled one too low for the rest of the run. Nothing would show it: the files still look normal, but step 12,345 would hold step 12,346's kernels. The host-time cut didn't have this failure mode, since an error there stayed within one step.
Unverified whether Cuspy can drop records in practice. If it can, the smallest fix is to check CUPTI's dropped-record count (cuptiActivityGetNumDroppedRecords, or whatever Cuspy exposes) at each flush and raise once anything is dropped. If Cuspy guarantees no drops, a one-line comment here saying so is enough.
…again #5792 and #6390 merged 10 minutes apart and conflict at the meaning level: #5792 calls get_cuspy_cuda_graph_annotation_config(enable_event_node_ids=True), and #6390 removed that kwarg. Kernel spans look annotations up by exec-graph node id, so pass key_by explicitly: "auto" for the Cuspy trace, "exec" for kernel spans.
…again (#6395) ## 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 #5792 and #6390 merged 10 minutes apart and conflict at the meaning level; git merged them cleanly. #5792 added a kernel-spans call `get_cuspy_cuda_graph_annotation_config(enable_event_node_ids=True, ...)`. #6390, branched before #5792 landed, removed that kwarg. So `main` (a71e607) fails: ``` lint: ERROR Unexpected keyword argument `enable_event_node_ids` in function `torchtitan.distributed.accelerator_graph.get_cuspy_cuda_graph_annotation_config` --> torchtitan/observability/profiler.py:541:21 test: tests/unit_tests/cpu/test_trainer.py::test_training_engine_configures_gradient_accumulation_accelerator_graph (kernel_spans case) TypeError, same kwarg ``` The lint failure shows up on every open PR, since pyrefly checks the whole project. Dropping the kwarg at the call would not be enough. In #5792's helper, `enable_event_node_ids=True` also meant `key_by="exec"`, and kernel spans need that for a reason of their own: `KernelSpanRecorder._record_graph_nodes` looks annotations up by the exec graph's node ids (`tools_id`), the ids CUPTI reports for replayed kernels. With `key_by="auto"`, annotations are keyed by capture-graph ids wherever CUPTI supports `sourceGraphNodeId`, so the lookup would silently find nothing. ## What changed - `get_cuspy_cuda_graph_annotation_config` takes a required `key_by: Literal["auto", "exec"]`. - `CuspyTraceProfiler` passes `"auto"`, as after #6390. Kernel spans pass `"exec"`, as before #6390. **Example.** ``` before #6390 main today this PR Cuspy trace only auto auto auto kernel spans (+ trace) exec TypeError exec ``` ## Testing - `pytest tests/unit_tests/cpu/test_trainer.py tests/unit_tests/cpu/observability`: 210 passed, 1 skipped. This includes the kernel-spans case of `test_training_engine_configures_gradient_accumulation_accelerator_graph`, which expects `key_by: "exec"` and is unchanged. - Pyrefly reports no errors in the touched files.
Stack from ghstack (oldest at bottom):
Summary (human-written)
Why
A profiler trace only covers the steps it was scheduled for. To see why step
12,345 was slow, you need its kernels after the fact.
profiler.kernel_spansrecords every CUDA kernel's GPU start/end time on every step, and keeps the
last
num_steps_retainedsteps on disk per rank.python scripts/kernel_spans_to_trace.py \ outputs/profiling/kernel_spans/rank{0..3}/steps_000000001001_000000001100.npz \ --steps 1050-1052 --output trace.json.gz # open in PerfettoDesign
Each
Profiler.step(), the recorder:The host runs ahead of the GPU, so steps are cut on the GPU: the marker starts
after everything the step enqueued on that stream, and step N holds the
kernels that started between marker N-1 and marker N. CUPTI delivers records
late and in batches, and not in start order across streams, so step N is
filed once marker N+1 has arrived:
Every
steps_per_file(default 100) finished steps, one file is written perrank, and the oldest files are deleted beyond
num_steps_retained:Each file carries its own node table, so it decodes without the training
process.
scripts/kernel_spans_to_trace.pytakes one file per rank plus--steps, joins rows to the table, and writes a Chrome/Perfetto trace: oneprocess per rank, one track per stream.
Constraints:
TrainingEngine.Configrejectsdisable_accelerator_graphs.KinetoTraceProfiler, because Kineto can't take CUPTIonce Cuspy holds it;
CuspyTraceProfilerworks. With kernel spans on,graph annotations are keyed by exec-graph node id.
plus the Cuspy requirements (libcupti 13.3+). CUDA 13.5 is not needed.
will be recorded again); older files count toward
num_steps_retained.Performance
Setup: Llama 3 8B, seq 8192, FSDP over one 4x GB300 node, CUDA graphs,
metrics.log_freq=10,steps_per_file=20(5x more file writes than thedefault). Baseline and kernel spans alternated on the same node
(base, spans, base, spans), steps 21-100. Tokens/s/GPU is the mean over the
eight 10-step log windows; step time is the mean wall time per step.
Recorder
step()on the host: median 1.8 ms; about 17 ms on the steps thatwrite a file (one 115 ms outlier, on the first write of one run).
Step cutting, kernels per step on rank 0 (2,323, or 2,331 on log steps):
log_freq=10log_freq=1(host syncs every step)log_freq=10The host-time cut mis-filed kernels whenever the host ran ahead; the marker
cut doesn't depend on it.
The node driver is CUDA 13.0 (580), so these runs put cuda-compat 13.4 on
LD_LIBRARY_PATHfor graph node ids, in both baseline and spans runs.Numerics
Loss and grad_norm matched the baseline over 30 steps of the llama3 debug
model (seed 42, deterministic, 2 GPUs). This was measured on the earlier
revision; the recorder only reads CUPTI records and doesn't touch compute.
Testing
spans all on:
228 ran outside graphs.
torchtitan.observability.profilerloads neither cupti norCuspy.
host runs ahead, a late kernel from another stream stays in its step,
close() files the rest;
evicted with new ones);
test_trainer.pyannotation-config case (kernel spans + Cuspy pystacks -> exec keying + py stacks).