/pytorch-opt-skills:pytorch-profilerfrom pytorch-opt-skills
Use torch.profiler to decide where to spend optimization effort in PyTorch training and to find what slowed a run down: GPU idle gaps, host-device syncs (.item(), cudaStreamSynchronize, pageable copies), DataLoader waits seen in a trace, kernel hotspots, launch-bound steps, exposed NCCL all-reduce, a late DDP rank, rare multi-second stalls, a regression between two versions. Use when setting up torch.profiler.profile, schedule (skip_first past torch.compile and autotune warmup), record_function or tensorboard_trace_handler; when reading a .pt.trace.json without chrome://tracing; when attributing GPU time under torch.compile; or when a fix that looked large in a trace didn't move throughput.
Ships in pytorch-opt-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Profile a few steady-state steps on one rank unless there are stalls or stragglers (§9). Decide first whether the GPU is busy or idle: busy means the kernels are the target, idle means finding what it waits for. Then rank the candidates by potential time savings. A trace diagnoses; an unprofiled A/B on the same node validates. A fix that removes idle time may only improve throughput by ~1% when the trace caught warmup, or when the idle wasn't what limited the step.
Run without the profiler and log each step's wall time. The step after which it stays within noise is skip_first,
and it is often dozens of steps. Early steps are slow, and misleading, because of:
max-autotune);aten::mm host ops while the GPU idles;cudaMalloc calls inside the window;A window of compile warmup can show several times the idle of a steady one, full of stalls that are gone a few dozen steps later.
TORCH_LOGS=recompiles logs each
recompile, so set skip_first past the last one.skip_first to avoid it, or to hold one on purpose.Run with MYPROJ_PROFILE=skip_first,active, e.g. MYPROJ_PROFILE=50,3: skip 50 steps, record 3 optimizer steps
and write the trace; a single-rank run then leaves the loop. warmup keeps its default of 1. Unset, the profiler
is a nullcontext and costs nothing; any other unparsable value raises. §9 cycles this schedule instead, to catch
a rare stall. Prefix the variable with your project's name, since a bare PROFILE can collide with other tools.
from __future__ import annotations
import contextlib
import os
import socket
import time
import warnings
from pathlib import Path
import torch.distributed as dist
from torch import nn
from torch.profiler import ProfilerActivity, profile, record_function, schedule
class StepProfiler:
def __init__(
self,
sched_skip_first: int, # steps before the window, past compile and autotune warmup
sched_warmup: int = 1, # steps traced but discarded before the window
sched_active: int = 3, # steps in the window; 0 disables the profiler on this rank
record_shapes: bool = False, # input shapes for §7; grows the trace and holds tensor refs, so off for an A/B
worker_name: str | None = None, # trace file prefix; None: {hostname}_{pid}, as the handler names it
out_dir: str | Path = "traces", # trace directory, fresh per run
) -> None:
self.trace_path: Path | None = None # set when the window is written; stays None on an unprofiled rank
self.out_dir = Path(out_dir)
self.worker_name = worker_name or f"{socket.gethostname()}_{os.getpid()}"
self._prof_ctx: profile | contextlib.nullcontext[None] = contextlib.nullcontext()
if sched_active <= 0: # off on this rank: the nullcontext stays and costs nothing
return
self.out_dir.mkdir(parents=True, exist_ok=True)
self._prof_ctx = profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
record_shapes=record_shapes,
# with_stack=True adds Python frames, but names the enclosing function, not the line, and grows the trace
# for memory, torch.cuda.memory._record_memory_history with snapshots beats profile_memory
schedule=schedule(
skip_first=sched_skip_first,
wait=0,
warmup=sched_warmup,
active=sched_active,
repeat=1, # one window; §9 cycles instead
),
on_trace_ready=self._write,
)
def __enter__(self) -> StepProfiler:
self._prof_ctx.__enter__()
return self
def __exit__(self, *args: object) -> None:
if isinstance(self._prof_ctx, profile) and not self.trace_path:
warnings.warn("profiler window didn't close: drop the last ProfilerStep")
self._prof_ctx.__exit__(*args) # an exit inside the window still writes the steps it caught
def _write(self, prof: profile) -> None: # tensorboard_trace_handler's naming, but it returns no path
self.trace_path = self.out_dir / f"{self.worker_name}.{time.time_ns()}.pt.trace.json" # .gz costs seconds
prof.export_chrome_trace(str(self.trace_path))
def step(self) -> None: # once per optimizer step, never per micro-batch
if isinstance(self._prof_ctx, profile):
self._prof_ctx.step() # the window's last step writes the trace, so trace_path is set once it closes
@record_function("clip_grad") # decorator form: labels every call
def clip_grad(model: nn.Module) -> None:
nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
if dist.is_initialized(): # true once init_process_group has run
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
rank = 0
world_size = 1
skip_first, active = (int(v) for v in os.environ.get("MYPROJ_PROFILE", "0,0").split(","))
prof = StepProfiler(skip_first, sched_active=active if rank == 0 else 0, worker_name=f"rank{rank}") # rank 0 only
with prof:
for batch in loader:
with record_function("forward"):
loss = model(batch)
with record_function("backward"):
loss.backward()
clip_grad(model)
with record_function("optimizer"):
optimizer.step()
optimizer.zero_grad(set_to_none=True)
prof.step() # under gradient accumulation, only on the micro-batch that ends a cycle
if prof.trace_path and world_size == 1:
break # with peers, one rank leaving here would deadlock them in the next collective
if prof.trace_path:
print(f"profiler trace: {prof.trace_path}")
record_function inside a compiled function never reaches the trace. Dynamo drops it by
default.torch._dynamo.config.capture_profiler_record_function = True (torch ≥ 2.11) puts the label into the graph, but
Inductor then removes it so that it can't block fusion. Only backends that skip Inductor, such as aot_eager,
keep it.__next__, Optimizer.step#..., collectives, and
Torch-Compiled Region: i/j around each compiled graph.trace_path is set. Multi-rank: cap at the launcher, since a rank that breaks deadlocks
its peers — and drop the window and the next step from throughput stats, since the stall shows in the peers'.optimizer.step() — Accelerate's wrapper calls
that every micro-batch. Use accelerator.sync_gradients, (i + 1) % accum == 0, or a framework's step-end hook.skip_first.
Drop its last ProfilerStep#, which spans post-loop code (a final eval or checkpoint), not a step.Read the trace as text first: that works where chrome://tracing is blocked, and an agent can do it with a short
stdlib script. The file is Chrome trace JSON, gzipped when it ends in .gz: {"traceEvents": [...]}.
name, cat, ph, ts and dur (both µs), pid, tid and args.ph == "X".ProfilerStep#N is not the training step: label each with record_function(f"train_step_{global_step}").| quantity | rule |
|---|---|
| window | cat == "user_annotation" and name starts with ProfilerStep#: from the first start to the last end |
| GPU work | cat in kernel, gpu_memcpy, gpu_memset, with dur > 0 |
| GPU work of the window | its launch is inside the window: the event with cat in cuda_runtime, cuda_driver and the same args.correlation |
| busy, idle | busy is the union of GPU intervals; idle is the gaps between them, from the first GPU start to the last end |
| compute-only busy | the same union without collective kernels, name matching (?i)[nr]ccl |
| exposed comm | busy − compute-only busy |
| idle waiting for data | idle overlapping user_annotation events named enumerate(DataLoader)#... |
| syncs | cat in cuda_runtime, cuda_driver, name matching the sync pattern below, and ts inside the window |
| a sync's cost | the gap that opened during the call: from the call's return to the next GPU start (0 if the GPU stayed busy) |
| call site | the shortest user_annotation and cpu_op on the same tid that contain the event |
| gap context | the cpu_op and user_annotation events covering most of the gap; none means an untraced stall (§6) |
| hotspots | dur summed per kernel name, with launch counts |
| per step | for each ProfilerStep#: kernel count, GPU time, and host label time |
Sync pattern: ^(cuda|hip)(Stream|Device|Event)Synchronize$.
Report:
Why the rules:
gpu_user_annotation is not work. These spans are labels projected onto the GPU timeline, and they cover idle
time. Counting them can turn a quarter-idle window into "nearly all busy". ProfilerStep#N has such a copy too,
which is why the window comes from the host user_annotation.cuLaunchKernel (cuda_driver); cuBLAS and
aten kernels through cudaLaunchKernel (cuda_runtime). Scanning only one makes real launches look like host
stalls.Per-op tables, using the documented calls:
print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=-1))
print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10))
A table has no timeline, so it can't show gaps, overlap or syncs. Host time on an op includes any blocking, and
grouping by input shape is empty unless the capture set record_shapes=True.
HTA (pip install HolisticTraceAnalysis) answers two questions the rules above can only infer. It reads a
directory of traces, gzipped or not:
from hta.trace_analysis import TraceAnalysis
analyzer = TraceAnalysis(trace_dir="traces")
idle = analyzer.get_idle_time_breakdown() # idle split into host_wait, kernel_wait and other wait
queue = analyzer.get_queue_length_summary() # launch queue depth; a minimum of 0 means the host ran dry
launches = analyzer.get_cuda_kernel_launch_stats() # launch delay, and kernels shorter than their own launch
host_wait against kernel_wait is §4's host-or-GPU question answered directly, where the gap-size split above
is a best guess.
ProfilerStep# window, so its idle share and the window's differ:
22.9% against 17.2% on one trace here. Never compare a percentage from one tool against one from the other.get_gpu_kernel_breakdown's mean/min/max/stddev columns are per rank, so a single-rank trace gives
min = max = sum and stddev = 0, which reads like a single call.By eye: ui.perfetto.dev opens .json.gz traces. It parses the trace in the browser, with a limit around 2 GB.
Use v57 or later, since earlier builds dropped PyTorch events that overlapped on one track. Check your site's policy
before opening traces from private code.
Start from the step's composition: compute-only busy, exposed communication, and idle. Then bound each candidate before working on it:
| the trace shows | it is | go to |
|---|---|---|
step spans, kernel counts or GPU time varying between steps; cudaMalloc or compile events | the wrong window | §1 |
| compute-only busy close to the whole window, few gaps | GPU-bound | §7 |
idle while the host waited in DataLoader __next__ | input-bound | the pytorch-dataloader skill |
| syncs with idle after them; gaps that start as a sync returns | sync drains | §5 |
| thousands of 10-100 µs gaps, host time far above GPU time, or a launch queue draining to 0 | the host can't keep up | §6 |
| long host ops launching nothing while the GPU idles | host work | §6 |
| a gap no host event covers, or one cheap op spanning tens of ms | an untraced host stall | §6 |
| exposed comm a large share of the window | communication-bound | §8 |
| one rank with the most data wait and the least collective time (all ranks traced) | a late rank | §9 |
| an all-reduce every micro-batch, or none in a multi-rank DDP window | no_sync not in effect, or no DDP wrapper | §8 |
The host runs ahead of the GPU, filling a queue. A sync blocks the host until the GPU catches up.
.item()
can be a slow kernel surfacing.cudaEventSynchronize calls itself.| code | in the trace |
|---|---|
.item(), float(t), .tolist(), print(t), if t: | aten::_local_scalar_dense → cudaStreamSynchronize |
.cpu(), .numpy() | aten::copy_ → Memcpy DtoH + cudaStreamSynchronize |
torch.tensor(x, device="cuda") | aten::copy_ → Memcpy HtoD (Pageable -> Device) + cudaStreamSynchronize |
.to(device) without non_blocking=True | aten::copy_ → Memcpy HtoD + cudaStreamSynchronize |
nonzero, boolean masks, masked_select, unique | cudaStreamSynchronize under the op |
torch.cuda.synchronize() | cudaDeviceSynchronize |
torch.cuda.set_sync_debug_mode("warn"), which warns with a traceback. It misses
torch.cuda.synchronize() and non-blocking copies from pageable memory..item() them at logging steps;torch.zeros((), device=...) or torch.full, never torch.tensor(value, device=...);pin_memory=True and non_blocking=True;host_wait, a launch queue draining
towards 0, or launch delays near 0 (§3). The causes are below.mode="reduce-overhead"), but only with fixed shapes;@torch.compiler.disable region pays launch overhead for every op inside it, so shrink it to the call that
needs it.py-spy dump --pid <pid> --native while it's stuck, gc.callbacks to time collections, and
faulthandler.dump_traceback_later(t, repeat=True) as a watchdog. gc.freeze() after setup takes long-lived
objects out of future collections.triton_poi_* is pointwise;triton_per_* is a persistent reduction;triton_red_* is a reduction;triton_tem_* is a template (GEMM or attention);record_shapes=True (§2).kernel_cutlass_kernel_flash_attn...), so test flash before
cutlass;max-autotune moves GEMMs from the vendor library into Triton templates.max-autotune alone has made an attention backward kernel
about twice as cheap, with no code change. See the pytorch-compile skill.numel × element size summed over inputs
and outputs, read from the launching cpu_op, since an Inductor kernel hides its inputs in one fused op.no_sync() isn't
taking effect: check that the object you call it on is the DDP wrapper. A model-unwrapping helper can return the
inner module, e.g. Accelerate's unwrap_model() with keep_torch_compile=True.NCCL_DEBUG=INFO; a line like GPU Direct RDMA Disabled means every byte is staged through host memory. NCCL_NET_GDR_LEVEL=SYS can enable it when the GPU
and NIC sit on different sockets.A slow step costs every rank, because the step waits for the slowest. A straggler and a rare stall are the same failure, and it reads backwards: the late rank spends the least time in collectives, because the others spin waiting for it, so its data wait or sync reads as all-reduce time on their traces, not as a wait. Three questions:
pytorch-dataloader skill), a sync (§5), or a gap no
host event covers (§6).The rolling capture varies §2's class. Add a stall_threshold_s argument in seconds; time each step in
step() into a collections.deque(maxlen=sched_active); pass repeat=0 to the schedule, which cycles windows
until the run ends instead of stopping after one; and hand on_trace_ready this in place of _write:
def _write_if_stalled(self, prof: profile) -> None:
if self.trace_path: # the write stalls its own step, which would otherwise trigger the next capture
return
if max(self.step_times_s) >= self.stall_threshold_s:
self._write(prof)
Run it on every rank, StepProfiler(50, sched_active=3, worker_name=f"rank{rank}") with a 5 s threshold.
trace_path is set once a stall is caught, so drop the early stop from the loop: a rolling run trains to the
end, and trace_path holds the trace.
skip_first and warmup aren't judged, so the compile step isn't flagged.ProfilerStep#N labels give the step.step_times_s in _write_if_stalled, which costs one sync per window.A regression between two versions:
API facts checked against the torch 2.15 docs and source, and HTA against the 0.5.0 docs (2026-11).
What SKILL.md sets; muted values are Claude Code's defaults
pytorch-opt-skills@mila-skills is listed by mila-iqia/skills — review the source before installing
npx claudepluginhub mila-iqia/skills --plugin pytorch-opt-skills5 skills in this plugin
/pytorch-compileDiagnose and fix torch.compile problems: graph breaks, recompilation, slow compile time, and compile-mode / runtime tradeoffs. Use when torch.compile is slow to compile, slower than eager, stalls for minutes on step 1 or on every new shape, or when you see graph break, "Recompiling function", guard failure, cache_size_limit / recompile_limit, dynamic shapes, mark_dynamic, tlparse, TORCH_TRACE, TORCH_LOGS=recompiles/graph_breaks, Dynamo, Inductor, Triton autotune, max-autotune, coordinate_descent_tuning, specialize_float, CUDA graphs / reduce-overhead, cudagraph_mark_step_begin, allow_in_graph, torch.compiler.disable, or "accessing tensor output of CUDAGraphs". Also for reusing compiled artifacts across jobs or nodes — megacache / Mega-Cache, save_cache_artifacts, load_cache_artifacts, cold vs warm compile, TORCHINDUCTOR_CACHE_DIR — for profiling a compiled model (kernels are fused and invisible to module hooks), for measurement hygiene when benchmarking compiled vs eager, and for the optimizer step outside the compiled model — fused=True, foreach, fused Adam / AdamW / SGD, compiling optimizer.step, LR scheduler recompiles./pytorch-dataloaderDiagnose and fix PyTorch input pipelines that starve the GPU: DataLoader wait, low or bursty GPU utilization, periodic or rare multi-second stalls, eval slower than train, slow time to first step, worker host-memory blowups. Use when tuning num_workers, prefetch_factor, pin_memory, non_blocking, persistent_workers or in_order; when next() wait may be a CUDA sync; when samples come from mmap, Arrow / HF datasets, LMDB, HDF5, .npy or shards on network storage (Lustre, BeeGFS, VAST/NFS; Mila and Alliance/DRAC clusters) or are staged to $SLURM_TMPDIR; when data outgrows page cache or local disk; for chunk shuffling or shuffle buffers; when scaling to more nodes or faster GPUs; or when one DDP rank waits on another's late batch.Other plugins' skills for the same job