/pytorch-opt-skills:pytorch-compilefrom pytorch-opt-skills
Diagnose 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.
Trending skills
7-day visitors to each skill page
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.
Read when SKILL.md points to them; scripts run unread.
A router. Identify which of four problems you have, run one command, open one
reference. Depth lives in references/; this file only gets you there.
Hard rule: never change a compile knob without a before/after measurement. Compile effects are large, run-to-run variance is larger, and most of the interesting quantities are not in any obvious log. See measurement.md.
Almost every torch.compile question is unanswerable without these, and almost nobody has them on.
TORCH_LOGS="graph_breaks,recompiles" python train.py 2> run.err # near-free
TORCHDYNAMO_VERBOSE=1 TORCH_LOGS="graph_breaks,recompiles" ... # + tracebacks
TORCH_TRACE=/abs/dir python train.py # ~10 s overhead
2> run.err or 2>&1.TORCH_LOGS as an empty string. Present-but-empty has crashed
import torch on some builds. Set it or unset it.os.environ.get("TORCH_LOGS") at startup.torch._dynamo.explain(fn)(*args) and
torch._dynamo.utils.counters.| you observe | signal that identifies it | first command | go to |
|---|---|---|---|
| compiled is slower than eager, or the profile shows many small compiled regions | Graph break in user code at lines; explain() reports >1 graph | python3 scripts/log_triage.py run.err | graph-breaks.md |
| a multi-second stall recurs whenever input shapes change | Recompiling function ... triggered by the following guard failure(s) | python3 scripts/log_triage.py run.err --recompiles | recompiles.md |
| one huge stall on step 1 (or the first step of each shape), then fast | no recompile lines after the first; step-1 wall time ≫ steady state | python3 scripts/trace_summary.py $TORCH_TRACE | compile-time.md |
| steady state itself is slow, crashes, or memory grew | no compile-log activity at the slow steps | profile and attribute by correlation id | mode-selection.md + tooling.md |
Four notes that decide most ambiguous cases:
TORCH_LOGS=recompiles alone shows zero graph breaks even when there are dozens.A break splits one compiled region into two with eager Python between. The cost is fragmentation — lost fusion across the boundary, and one recompile set per fragment per shape.
TORCH_LOGS="graph_breaks" ... 2> run.err && python3 scripts/log_triage.py run.err
grep -c 'Graph break in user code at' run.err
Reason strings you will actually see, each mapping to a fix pattern:
torch.* op returned non-Tensor bool → GB-1 · Dynamic shape operator
(aten.nonzero.default) → GB-2 · Data-dependent branching → GB-3 ·
call_id with args (NestedUserFunctionVariable(),) → GB-4 ·
Attempted to inline function marked as skipped → GB-5 (usually correct as-is) ·
assert_size_stride on an extern op → GB-7.
Break count is a bad target. A break at a boundary where the code was already running eagerly costs approximately nothing — measured, removing the trace attempt made throughput slightly better. Rank breaks by what they fragment: one inside the repeated block is worth ten at an already-eager library boundary. Details in graph-breaks.md.
A recompile is a guard failure. Ask three questions in order:
The guard text is the answer. Never infer the cause from the symptom — the decoder table in recompiles.md maps each guard form to its fix (RC-1 content-dependent widths · RC-2 rank flips · RC-3 lazily grown buffers · RC-4 Python ints · RC-5 reduce the shape stream).
Two things that surprise people: under the default dynamic=None a fragmented
model produces one burst of recompiles at the first shape transition and then
nothing; and each new concrete shape still pays a smaller one-time cost with no
log line at all — that is Inductor kernel warmup, not a guard failure, so do not
chase it.
TORCH_TRACE=/abs/dir python train.py
python3 scripts/trace_summary.py /abs/dir
Compile time can go into Dynamo tracing, AOT joint-graph tracing, Inductor
lowering, code generation, Triton kernel compilation, or autotune search. Read the
phase table, then read async_compile.wait as a share of code_gen — that
one ratio decides whether config levers can help at all:
ir_count / graph_op_count
(a 70× blowup is not unusual) and at restart_reasons.triton_kernel_compile_times_us — on one workload a single kernel was 94.8% of
all Triton compilation — and take that work out of the graph (CT-1/CT-2).The phase table is an attribution, not a partition: phases overlap, do not sum to wall time, and one can exceed total wall time because it is clocked in autotune workers. compile-time.md.
Module hooks do not work here. They cover only ~11% of kernel time, because
compiled regions do not nest under Python module scopes. Attributing from
nn.Module: <Class>_N rows will mislead you.
Attribute by correlation id instead: each GPU kernel event's
args.correlation maps back to its host-side launch. Then read the generated
name — triton_poi_fused_* (pointwise), triton_per_fused_* (persistent
reduction), triton_tem_fused_* (template) — whose suffix lists the fused aten
ops and is your map back to source. Full procedure in
tooling.md §4.
Before hand-optimizing a kernel, A/B the compile mode. On one workload
default → max-autotune-no-cudagraphs made an attention backward 2.13× cheaper
with no code change at all. mode-selection.md.
The optimizer step is outside the compiled model. Adam, AdamW and SGD
default to foreach; their faster fused kernel is opt-in:
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, fused=True)
For optimizers without a fused kernel, compile the step
(@torch.compile(fullgraph=False) def step(): opt.step()). Under an LR scheduler,
make lr a tensor and update it in place (fill_), or it recompiles on every
change. Don't compile a fused step.
Confirm which path ran by profiling a few steps and reading the ops under the optimizer step:
_fused_<optimizer> op per parameter group. A lone
_foreach_add_ (the step counter) can appear here too; it does not mean foreach._foreach_* math ops.Then A/B optimizer.step() wall time (CUDA events, median; kernel time misses
launch gaps). Confirm on full step time; it is usually a small share, so measure
before tuning.
TORCH_LOGS writes to stderr.Recompiling function lines proves nothing unless the variable was
provably set in that process.dynamic=, not
the compile mode; recompile cost scales with the mode (measured 4–6.5× for
max-autotune).async_compile.wait is ~90% of code_gen, stop turning knobs.async_compile.wait already dominates
— the work is already parallel; the lever is generating less code.model.compile(...) (in place) over model = torch.compile(model)
to avoid _orig_mod: prefixed state_dict keys, and unwrap helpers that
rewrite it on the live model (under DDP, silently disabling no_sync). Under
DDP, call it on the DDP object. It returns None; model.forward(x) and
deepcopy/pickled copies run eager.| lever | measured effect | cost | reach for it when |
|---|---|---|---|
| A/B the compile mode | 2.13× on one attention backward; 21.5% end-to-end | 4–6.5× recompile cost | always first — no code change |
specialize_float=True (CT-3) | −18% to −34% compile, −2% to −4% step time | recompile if the float's value varies | restart_reasons is non-empty |
coordinate_descent_tuning=False (CT-4) | −24% to −54% compile, incl. warm runs | +0.8% step time, +0.6 GiB peak | *coordinate_descent_tuning dominates the phase table |
| Compile preprocessing separately (CT-2) | −82% compile and faster runtime | a small refactor | one Triton kernel dominates compile |
| Reduce the shape stream (RC-5) | removes recompiles; flattens memory | padding waste | many distinct shapes |
| Regional compilation (CT-5) | recompiles 6→1 per shape, compile ~2× faster | −13 to −17% throughput, forever | compile time is the binding constraint |
Every row was measured on one workload at one problem size. Levers do not
transfer: specialize_float was worth −34% at one size and exactly zero at a
larger one. Re-measure on yours.
log_triage.py and trace_summary.py are stdlib only, no install step; the other
two import torch and run inside your training process.
python3 scripts/log_triage.py run.err # breaks by reason, recompiles by guard,
# limit hits, burst timing, a verdict
python3 scripts/trace_summary.py /trace/dir # phase table, IR blowup, guards, restarts,
# top Triton kernels, a verdict
python3 scripts/compile_watch.py --selftest # imports torch; also a known-good fixture
compile_watch.py also exposes CompileWatch() for in-process per-step
compile-phase deltas — cumulative totals stop being informative by the sixth
distinct shape.
megacache.py is a library, not a command: copy it into your trainer to share
compiled artifacts across jobs and nodes. See
compile-time.md §7 for the keying rules and the traps.
Confirm the path under test actually ran · read knobs from the resolved config
· know your noise floor (matched baselines differed 10.8%) · prefer medians and
kernel time to means · exclude compiling steps by shape first-appearance, not a
fixed warmup · compare total across all compiling steps, never step 1 alone ·
grep -c before and after, expecting the targeted lines gone and no others.
Full versions with the incident behind each: measurement.md.
| open | when |
|---|---|
| graph-breaks.md | finding, counting, and deciding whether to fix breaks |
| recompiles.md | you have guard text, or shapes vary |
| compile-time.md | one compile is enormous, or you want to reuse compiles across jobs |
| mode-selection.md | choosing a mode, CUDA-graph errors, config levers |
| measurement.md | before trusting any number |
| fix-patterns.md | the before/after catalogue, cited by ID everywhere |
| tooling.md | env vars, API index, tlparse, profiling a compiled model |
Quantitative deltas throughout come from measurements on a single transformer training workload. Treat them as orders of magnitude and re-measure on yours. The mechanisms are general; the numbers are not.
references/compile-time.md (opens in a new tab)references/fix-patterns.md (opens in a new tab)references/graph-breaks.md (opens in a new tab)references/measurement.md (opens in a new tab)references/mode-selection.md (opens in a new tab)references/recompiles.md (opens in a new tab)references/tooling.md (opens in a new tab)scripts/compile_watch.py (opens in a new tab)scripts/log_triage.py (opens in a new tab)scripts/megacache.py (opens in a new tab)scripts/trace_summary.py (opens in a new tab)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-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./pytorch-ddpTune PyTorch data-parallel training (DistributedDataParallel, and FSDP / HSDP), single- or multi-node, with two calibration jobs and a set of formulas instead of a knob sweep: decide whether communication is the bottleneck at all, then pick the strategy, visible GPUs/NICs, gradient accumulation and micro-batch size, bucket_cap_mb or FSDP unit size and resharding, comm hooks or reduce dtype (bf16/fp16/noop/PowerSGD), gradient_as_bucket_view, batched_grad_copy, static_graph and NCCL settings from measurements. Use when multi-GPU or multi-node scaling efficiency is below what you expect, when choosing DDP or FSDP knobs on a new project or cluster, when gradient accumulation looks like it all-reduces every micro-batch (no_sync not working), when torch.compile + DDP/FSDP misbehaves, when NCCL bandwidth, NVLink or GPUDirect RDMA is suspect, when one slow rank stalls the job, or when deciding if a model has outgrown DDP (FSDP/HSDP/ZeRO)./pytorch-profilerUse 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./pytorch-tweaksOne-line PyTorch settings that speed up training or inference or cut GPU memory, each a flag, env var or context manager: TF32, autocast, cudnn.benchmark, PYTORCH_ALLOC_CONF allocator options, inference_mode, fill_uninitialized_memory. Use when reviewing a script for cheap wins or when one of these settings comes up.Other plugins' skills for the same job