/pytorch-skills:analyze-memory-snapshotfrom pytorch-skills
Analyzes PyTorch CUDA memory snapshots to diagnose GPU memory usage, OOMs, fragmentation, leaks, and retained tensors. Supports diffing two snapshots to find growing allocation sites.
Ships in pytorch-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.
Analyze PyTorch CUDA memory snapshots by inspecting allocator state and event history. Always prefer evidence from the snapshot over generic memory advice.
Get the snapshot path if the user did not provide one. Accept .pickle,
.pkl, .json, or a directory containing rank-local snapshots. If the user
only has a screenshot from memory_viz, ask for the underlying snapshot file.
Load the snapshot locally. PyTorch _dump_snapshot() files are pickles, so
only unpickle files the user provided or that already live in the workspace.
JSON snapshots can be loaded directly.
If available, run this skill's helper for a first-pass summary:
python scripts/analyze_snapshot.py /path/to/snapshot.pickle
If there are multiple ranks, run it per rank and compare peaks, active bytes, inactive bytes, OOM events, and top stack traces.
If the user has (or can capture) two snapshots from different points in the same run, diff them — this converts leak hunting from interpretation into a lookup of which allocation sites grew:
python scripts/analyze_snapshot.py step100.pickle --diff step200.pickle
For very large snapshots (hundreds of MB of trace history), the helper caps
trace analysis at --max-trace-events (default 1M) and reports how many old
events it dropped, so it stays usable without loading everything into your
analysis.
Read the raw snapshot when the helper output is insufficient. Inspect:
segments: allocator segments returned by cudaMallocblocks: live, awaiting-free, and inactive pieces inside each segmentdevice_traces: chronological allocation events when memory history was
enabledframes: stack traces for allocation sitesReport the memory picture in terms of allocator semantics:
total_sizeactive_allocatedactive_awaiting_free, often stream-relatedinactive blocks that PyTorch can reuserequested_size versus block sizeWhere memory is going
Group live active_allocated blocks by the most useful user frame. Report the
largest stack traces first, with bytes, percent of live memory, block count, and
representative file/function/line. Separate parameters, optimizer state,
activations, temporary buffers, communication buffers, and user containers when
the stack names make that clear.
Always attribute memory to the user's model code, not allocator or framework
internals. Snapshot stacks are dominated by frames inside
torch/nn/modules/*, torch/autograd/*, and torch/optim/*; skip past those
to the first frame in the user's own files and name the module or line that
owns the memory (for example "38% of live memory is activations of
model.decoder.layers[*].mlp, allocated at modeling.py:214"). Only fall
back to torch-internal frames when no user frame exists in the stack.
When memory is deallocated
Use device_traces to distinguish free_requested from free_completed.
Pending or delayed frees can mean tensors are still needed by another stream or
that work has not reached the free point yet. In multi-step traces, compare
repeated allocation sites with their matching free events: allocation sites that
appear every step without corresponding frees are stronger retention evidence
than one-time model or optimizer allocations. If traces include OOM events,
report the failed allocation size, device_free, OOM stack frame, and which live
allocation sites were holding memory immediately before the OOM.
Leak and retention patterns
Look for active bytes that grow across steps, repeated active allocations from
the same stack that are not freed, or a sawtooth where many tensors accumulate
and are released together. The strongest evidence is a two-snapshot diff
(--diff in the helper): an allocation site whose live bytes and block count
both grow between snapshots taken k steps apart is leaking or retaining.
Recognize these named patterns by their snapshot signature and give the matching fix:
loss.detach() (or .item()) before appending, or find
the retain_graph=True that keeps graphs alive.torch/optim/*-attributed
allocations appearing once at the first optimizer.step() and then stable.
This is expected retention, not a leak — say so explicitly; the fix for OOM
here is a smaller model/batch, a lower-memory optimizer, or sharding, not
leak hunting.device_traces).
Recommend activation checkpointing (torch.utils.checkpoint) and quantify
the tradeoff from the snapshot: the activation bytes that would be freed
versus recompute cost.from torch.utils.viz._cycles import warn_tensor_cycles and call
warn_tensor_cycles() during initialization to find object cycles that keep
CUDA tensors alive.Fragmentation and allocator behavior
Do not equate nvidia-smi usage with live tensors. PyTorch uses a caching CUDA
allocator, so reserved memory can be much larger than allocated tensor memory.
Large inactive blocks are reusable by PyTorch; empty_cache() may return fully
inactive segments to CUDA, but it does not free memory still occupied by live
tensors.
The most common confusing case is OOM with plenty reserved: the failed request size exceeds the largest single contiguous inactive block even though total inactive memory is larger. Diagnose it from the snapshot: compare the OOM's requested size against the largest inactive block (the helper reports "largest single reusable inactive block"), and check whether inactive memory is split across many segments. When that pattern holds, recommend, in order:
PYTORCH_ALLOC_CONF=expandable_segments:True — lets segments grow instead
of allocating new fixed-size ones; usually the highest-impact fix for
fragmentation OOMs.PYTORCH_ALLOC_CONF=max_split_size_mb:<N> — stops the allocator from
splitting blocks above N MiB, reducing hard-to-reuse fragments; suggest N
near the failing request size.State explicitly when fragmentation is not the problem — if live tensor memory alone approaches device capacity, allocator tuning will not help and the fix is model-level (batch size, checkpointing, sharding, precision).
Non-PyTorch memory
The snapshot only sees CUDA memory managed by the PyTorch allocator. NCCL,
custom CUDA extensions, cuDNN/cuBLAS workspaces, or direct CUDA allocations may
not appear. If device memory outside the snapshot is suspected, compare
torch.cuda.device_memory_used(device) or nvidia-smi with the snapshot's
reserved bytes.
Give the minimal capture pattern:
import torch
torch.cuda.memory._record_memory_history(max_entries=100000)
try:
run_your_code()
torch.cuda.memory._dump_snapshot("memory_snapshot.pickle")
finally:
torch.cuda.memory._record_memory_history(enabled=None)
Use a higher max_entries for long jobs, but warn that trace history has memory
overhead.
For OOM debugging, register an OOM observer so the snapshot is dumped automatically at the moment of failure — the user should not have to reproduce the crash twice:
import torch
def dump_on_oom(device, alloc, device_alloc, device_free):
torch.cuda.memory._dump_snapshot(f"oom_snapshot_dev{device}.pickle")
torch.cuda.memory._record_memory_history(max_entries=100000)
torch._C._cuda_attach_out_of_memory_observer(dump_on_oom)
For suspected leaks across training steps, capture a pair of snapshots —
one early (after the first optimizer step, so optimizer state is already
allocated) and one many steps later — then diff them with
analyze_snapshot.py earlier.pickle --diff later.pickle. Dumping at the same
point in the step (for example right after optimizer.step()) keeps the diff
free of within-step noise.
Start with the main finding in one sentence. Then provide:
Be explicit about uncertainty. If the snapshot lacks history, say which deallocation and peak questions cannot be answered from that artifact.
evals/checkers.py (opens in a new tab)evals/eval.yaml (opens in a new tab)evals/fixtures/leak_diff/snapshot_step_005.json (opens in a new tab)evals/fixtures/leak_diff/snapshot_step_050.json (opens in a new tab)evals/fixtures/oom_snapshot/oom_snapshot.json (opens in a new tab)evals/fixtures/summarize_fixture_snapshot/sample_snapshot.json (opens in a new tab)scripts/analyze_snapshot.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub meta-pytorch/skills --plugin pytorch-skills5 skills in this plugin
/abi-stableMigrate C++/CUDA PyTorch extension code to use the PyTorch stable ABI. Use when the user wants to make their project ABI stable, migrate to stable ABI, or use torch::stable APIs./agents-are-comingA dummy skill that announces the arrival of agents. Use when the user asks about agents, the agent revolution, or wants to hype up agents./debug-graph-breaksDebug and fix torch.compile graph breaks to prioritize and eliminate graph-breaks, and optionally achieve fullgraph compilation/profile-modelAnalyze PyTorch profiler traces (.json/.json.gz). Use when the user wants to diagnose GPU performance issues, find slow kernels, identify idle time, analyze communication overhead, or debug training bottlenecks.Other plugins' skills for the same job