/fold-cp:mem_profile [e2e | trunk] [N_token] [cp size]from fold-cp
Memory-profiles PyTorch CUDA workflows using the caching-allocator history, attributes top memory peaks to specific modules and lines of code, and emits a markdown report with clickable file:line links.
Ships in fold-cp. 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.
Finds the largest problem size a CP workflow can afford and which modules/lines hold the memory at each peak. Two pieces, both model-agnostic:
scripts/mem_profile.py;scripts/mem_profile_analysis.py.The skeletons are complete except for two model hooks (build_model /
run_forward) in the driver. The four load-bearing steps below are where people
get stuck; follow them in order.
/fold-cp:test;
docs/cp_infra.md for topology + world_size.nvidia-smi available; for CP, a multi-GPU node (square grid). Before claiming GPUs, probe
occupancy (nvidia-smi --query-compute-apps=pid,used_memory --format=csv) and HOLD if the
target devices are busy — never oversubscribe (one job per slot); the manage_gpu plugin
automates this claim/hygiene if installed.model.infer_protein(seq)) and how to
build/load + CP-wrap the model — the same wiring the nsys driver uses.PyTorch's CUDA caching allocator can log every block alloc/free with the Python+C++
stack that requested it. This is exactly what Boltz2's CUDAMemoryProfile
(pl.Callback) does; reproduce it without Lightning around one forward:
torch.cuda.memory._record_memory_history(max_entries=400_000) # start (ring buffer)
run_forward(model, args) # the REAL workflow
torch.cuda.synchronize(device)
torch.cuda.memory._dump_snapshot(path) # write the .pickle
torch.cuda.memory._record_memory_history(enabled=None) # stop + free buffer
What matters (these bite):
reset_peak_memory_stats, then start recording. The
first call allocates cuBLAS/cuDNN workspaces and grows the allocator pool;
without a warmup the snapshot is full of one-off allocations and the peak is
wrong. One warmup forward under torch.no_grad() is enough.max_entries is a ring buffer. A deep workflow (recycles × diffusion steps)
emits millions of events; if it's too small you silently lose the early
timeline. Start at 200_000–400_000 and bump if the analyzer's event count
looks truncated.max_memory_allocated. That gap is usually negligible (note it in the report);
if you need the timeline peak to match max_memory_allocated exactly, start
recording before model build (--record-from-start, larger pickle).torch.no_grad(). Otherwise saved-for-backward tensors
inflate the peak and mislead the attribution.max_memory_allocated / max_memory_reserved, reduced MAX across ranks); the
reserved−allocated gap is fragmentation. The .pickle opens at
https://pytorch.org/memory_viz for an interactive timeline + the flame graph
of stacks live at the peak — the analyzer in Step 3 automates the same
attribution headlessly.Use one process per CP rank with torchrun (not mp.spawn) — torchrun owns the
rendezvous and gives a clean process tree:
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
torchrun --standalone --nnodes=1 --nproc_per_node=<world> \
-m your.mem_profile --n-token <N> --cp0 <a> --cp1 <a>
RANK/LOCAL_RANK/WORLD_SIZE/MASTER_* from torchrun, sets
the device from LOCAL_RANK, inits the process group, builds + CP-wraps the
model, and dumps …_rank{0..world-1}.pickle. Fail fast if RANK is unset
(Rule 12) — no silent single-GPU fallback.expandable_segments:True is usually required at the ceiling — it fights the
fragmentation that makes reserved ≫ allocated and triggers cudaMalloc
retries / spurious OOMs.N_token upward (or bisect) with a short-step probe
until it OOMs, then take the full-default snapshot at the largest N that fits.
Memory typically scales O(samples·N²), so the affordable N drops fast.The driver skeleton (scripts/mem_profile.py) has the
torchrun harness, warmup, record/dump, and the per-rank MAX reduction wired up —
fill in build_model(device, args) (construct/load + .eval() + CP-wrap) and
run_forward(model, args) (one real, no_grad forward).
The snapshot is a pickle of {"device_traces": [...per device...], "segments": ...}.
Each device_traces[d] is a time-ordered list of allocator events; the ones
you need are action ∈ {"alloc", "free_requested", "free_completed"}, each with
size, addr, time_us, and frames — the captured stack innermost→outermost,
each frame {filename, line, name}. The analyzer is pure stdlib (no torch
import) so it runs anywhere the pickle lands, in four stages:
allocated total:
alloc adds size and records the live addr; the first free of a live
addr subtracts it. The running total is the allocated-bytes curve and its
max equals torch.cuda.max_memory_allocated. (Pick the busiest device trace.)--dedup-pct
(default 3%) of an already-selected peak so the N peaks are different
plateaus/phases, not adjacent samples of one peak. (A naive "top-N samples"
returns the same peak N times — the bug to avoid.)--project-root (your code, not torch/site-packages) as the blame site;
fall back to the deepest .py frame. Resolve the enclosing Class.method from
the source with ast (cache per file) so sites are readable. Aggregate bytes +
tensor count per (file, line).% of peak, tensor count, the Class.method label, and a
short call chain. Render each site as a clickable link — default
vscode://file{abs}:{line} (also cursor://…, GitHub blob/<sha>#Lline, or
file://) so the reader jumps straight to the line.CLI contract (keep these flags — they're what makes the report usable):
snapshot positional; --top-n 6, --top-contributors 15, --dedup-pct 3.0,
--min-sep-ms 0.0, --project-root <repo root> (frames under it are "project"),
--link-style vscode|cursor|github|file|none, --repo-url/--commit (for github
links; commit defaults to git rev-parse HEAD), --out. Defaults are
project-agnostic (--project-root = cwd, --repo-url = none).
python scripts/mem_profile_analysis.py <snapshot>_rank0.pickle \
--project-root <repo-root> --top-n 6 --link-style vscode
# writes MEM_PEAK_ANALYSIS_<snapshot>.md next to the pickle
Read the report top-down:
% of peak — name the module/line holding the most memory. A single
Class.method dominating (e.g. a confidence head or a diffusion pair-bias at
[samples, heads, N, N]) is the bottleneck to attack.max_memory_allocated (minus the baseline gap if you recorded around the
forward). A large reserved − allocated means fragmentation → confirm
expandable_segments:True and consider it part of the ceiling.MEM_PROFILE_SUMMARY.md: the max-affordable N table (N → peak →
OK/OOM), the dominant module per peak (with the clickable links), the
reserved/fragmentation note, and the concrete next optimization.timeout-wrap every run; set a process-group timeout; tee logs under /tmp/$USER/..pickles (tens of MB each × ranks) are regenerable —
gitignore them; commit the analyzer, the driver, and the markdown report.reset_peak_memory_stats before recording, or the peak is wrong.scripts/mem_profile.py filled in for the model + per-rank …_rank*.pickle
(gitignored), with peak_alloc/peak_reserved reported.MEM_PEAK_ANALYSIS_<snapshot>.md (peaks → contributors, clickable links) and a
MEM_PROFILE_SUMMARY.md (max-affordable N, the bottleneck module, the next
optimization).What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub nvidia-bionemo/boltz-cp --plugin fold-cp11 skills in this plugin
/benchmarkBenchmark a CP inference or training workflow to find the maximum token count that fits at a given CP size and to record end-to-end walltime. Sweeps input size (tokens N, atoms, MSA depth S) over real or synthesized data, ramps N until OOM to report the max, times fwd (inference) or fwd+bwd+step (training) with warmup and median-of-repeats, captures peak memory, and writes a results table to docs/cp_benchmark.md. Use once a CP workflow runs end-to-end, to quantify the memory headroom CP buys and the walltime cost.
/build_infraProbe and establish the distributed test infrastructure for CP development. Inventories local GPUs (count, model, memory, NVLink topology), checks the software stack (Python, PyTorch+CUDA, NCCL, torch.distributed), and runs shipped smoke tests for batch_isend_irecv P2P, all_gather, all_reduce, reduce_scatter, and a DTensor round-trip. Maps the GPU count to which CP topologies are testable (2D needs >=4 GPUs, 1D needs >=2 ideally 3, full integration wants 8). When no local GPUs are available, generates a SLURM submission template and guides the user to provide cluster access. Records docs/cp_infra.md. Use after learn_context, before shard_data_feats / dtensor_modules / test.
/cpize_model_workflowOrchestrate the END-TO-END integration of context parallelism into a custom co-folding / structure-prediction model: turn the whole effort into a prioritized, dependency-sorted worklist, then drive it phase by phase — map the model (learn_context), verify infra (build_infra), shard data features (shard_data_feats), port modules (dtensor_modules, fanned out via dispatch_work), prove correctness (test), wire the trainer/predictor (dist_lifecycle), and finally profile memory and compute (mem_profile, nsys_profile) and benchmark. Use as the front door when the user wants to "CP-ify my model" as a whole program of work — it prioritizes, sequences, and gates the long task list and delegates each task to the right fold-cp skill. Not for a single module (use dtensor_modules + test directly).
/dispatch_workOrchestrate a team of agents to integrate many CP modules and tests in parallel. Builds the work-list from the module map, derives a data-flow dependency graph, topologically sorts it into GPU-slot-bounded waves, and spawns a coder+reviewer pair per work item. Reviewers enforce serial-as-ground-truth, no-vacuous-tests, and the fold-cp hard rules; coupled up/down-stream items cross-review each other's input/output placement contracts before finalizing. Use when the scope is several CP modules and their tests at once — not for a single module (use dtensor_modules + test directly for that).
/dist_lifecycleStand up the distributed-model lifecycle for a CP training/inference run: device placement before DTensor wrapping, the all-trainable-params-are-DTensors invariant (with placeholder/freeze for unimplemented modules), checkpoint save (DTensor → plain) and load (realign via the live state_dict template + redistribute optimizer state to parameter placements), resume RNG seed offset, and DTensor-safe EMA. Use after dtensor_modules + build_infra, when wiring the ported CP modules into a real trainer/predictor (Lightning or custom) and you need checkpoints, resume, or EMA to work — the gap between "modules pass parity" and "training runs and resumes".
/dtensor_modulesImplement DTensor-based context-parallel model modules that mirror a serial reference. Maps each serial layer/module to its Boltz-CP counterpart with exact input/output shapes, placements, collectives, and backward memory budget; writes the CP implementation following the autograd.Function conventions (explicit collectives, no implicit DTensor ops, promote_types, explicit from_local shape/stride, attribute-name + registration-order mirroring); and verifies it against the serial forward+backward via the test skill. Use when porting a custom model's trunk / attention / triangle / OPM / diffusion / confidence / loss modules to CP.
Other plugins' skills for the same job