/fold-cp:nsys_profile [e2e | trunk] [N_token] [cp size]from fold-cp
Profiles context-parallel (CP) inference/training workflows using NVIDIA Nsight Systems, with CUDA/NVTX tracing and custom module annotations for timeline readability.
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.
Profiles where a CP workflow spends GPU time and communication, with the module hierarchy named (trunk / TriMul / Pairformer / diffusion / confidence) so the timeline is readable. The five 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; multi-GPU node (CP 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.nsys usually ships inside the cuda-toolkit / nsight-systems conda package,
and Nsight Compute installs bundle a matching nsys:
which nsys; find "$CONDA_PREFIX" -name nsys -type f 2>/dev/null # env-local
find ~/miniconda3 ~/anaconda3 -name nsys -type f 2>/dev/null | head # any env
nsys --version # and the bundled one's --version
Pick a version new enough for the GPU arch — a stale /usr/bin/nsys (e.g.
2022.x) will not recognize Blackwell (sm_120); prefer the conda 2024.5+/2025.x
binary. If none exists: conda install -c nvidia nsight-systems (or
cuda-nsight-systems) into the env, or pip install nvidia-nsight-systems.
Record the absolute path you use.
Two regimes:
current_code_structure.md §3) — correct shapes/dtypes/axis
semantics, valid masks, consistent atom_to_token. Initialize weights with
Glorot-uniform × small gain (e.g. 0.1) so deep stacks stay numerically tame
(also what /fold-cp:test parity uses). Good for the CP-relevant subset (e.g.
the trunk) where you control the inputs.from_pretrained(<local_dir>, load_esmc=False) to skip the frozen LM) and
drive the real inference entry point (e.g. model.infer_protein(seq) /
processor.fold) with a random sequence so featurization is real and valid.
Pick N_token so the full default workflow fits — the diffusion pair-bias
[samples, heads, N, N] and a deep trunk OOM at large N; a realistic length
(256–1024) runs the default sampler, large N is for the trunk-only sweep.Trace the real inference call to enumerate every stage (front-end → recycling
trunk → heads → diffusion → confidence) and which parts are CP-distributed vs
serial. Then wrap one process per CP rank with torchrun (don't use
mp.spawn for the profiled run — one launcher, clean process tree for nsys):
# module run under torchrun: torchrun sets RANK/LOCAL_RANK/WORLD_SIZE/MASTER_*
def run(args):
rank = int(os.environ["RANK"])
torch.manual_seed(args.seed) # identical RNG on every rank
init_distributed(...) # DistributedManager / init_process_group (ENV reads torchrun env)
model = build_or_load(...).to(device).eval()
wrap_model_with_cp(...) # CP-distribute trunks (transparent: full-tensor in/out)
with torch.no_grad():
run_e2e_forward(model, inputs) # the REAL workflow
Rules that matter (fold-cp Rule 7): seed all ranks identically and broadcast control-flow counts (recycles, sampling steps) so every rank issues the same collectives in the same order — divergent control flow deadlocks NCCL. The launcher and CP-wrap live on your side, not in the upstream model.
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
nsys profile -o profiling/results/inference/<name> --export sqlite \
--trace cuda,nvtx,osrt --force-overwrite true --cuda-memory-usage true \
--pytorch=autograd-shapes-nvtx \
--python-functions-trace=<custom.json> \ # Step 5; gives module names
--cudabacktrace=all --python-backtrace=cuda \
torchrun --standalone --nnodes=1 --nproc_per_node=<cp> \
-m <your.profile_module> --n-token <N> --cp0 <a> --cp1 <a>
nsys stats --report cuda_gpu_kern_sum --report nvtx_gpu_proj_sum <name>.nsys-rep
Know what each does and its caveats (these bite):
--trace cuda,nvtx,osrt — kernels + NVTX domains + OS runtime. nsys traces
torchrun and its spawned ranks (one report, all ranks).--pytorch=autograd-nvtx | autograd-shapes-nvtx — wraps the run in
emit_nvtx(). Annotates autograd ops only → a no-op for the parts under
torch.no_grad(), EXCEPT custom autograd.Functions (e.g. a distributed
TriMul) still get ranges (with shapes under -shapes-). functions-trace-shapes
is not a valid token; combine autograd-shapes-nvtx with functions-trace.--python-functions-trace=<json> — Python-function tracing (needs pip install nvtx); works under no_grad. This is the one that names modules (Step 5).--cudabacktrace=all / --python-backtrace=cuda — CPU/Python backtraces for
CUDA calls. Require CPU sampling; in restricted containers nsys warns "CPU
IP/backtrace sampling not supported, disabling" and they are inert (need
perf_event_paranoid ≤ 2 / privileges)..nsys-rep/.sqlite are regenerable — gitignore them.--pytorch=functions-trace uses the shipped pytorch.json, which annotates only
torch.* (generic Module.__call__, Linear.forward, …) — it will not
name your model's classes (TriMul / Pairformer / trunk / diffusion). To get those
without any in-model NVTX, pass a custom JSON that lists your module forwards,
same schema as the shipped file:
[ { "domain": "MyModel", "module": "pkg.path.to.module",
"functions": ["TriangleMultiplicativeBlockDistributed.forward",
"FoldingTrunkDistributed.forward", "DiffusionModule.forward"] } ]
Build it (merging the torch.* entries so you keep F.linear etc.) with
scripts/make_pytorch_functions_trace.py
— it imports each module, validates Class.method exists, and appends. Notes:
module is the import path where the class is defined and importable;
functions are ClassName.method (forward, or any method like sample).projects.x.y...), install that namespace alias before importing so the class
objects resolve (and isinstance identity holds).--python-functions-trace=<merged.json> (not --pytorch=functions-trace)
and keep --pytorch=autograd-shapes-nvtx for the autograd-Function shapes.nsys stats --report cuda_gpu_kern_sum --format table <rep> # kernels by GPU time
nsys stats --report nvtx_gpu_proj_sum --format table <rep> # module/op ranges (GPU-projected)
Look for: ncclDevKernel_SendRecv (Cannon-ring p2p) vs cutlass …gemm (local
matmul) — comm vs compute; AllGather (full-tensor gather at CP boundaries); the
per-module ranges (*.forward) to attribute time to trunk vs diffusion vs
confidence. Cross-check the interconnect (nvidia-smi topo -m): a no-NVLink
(PCIe) box makes the ring dominate; NVLink shifts it toward compute-bound.
timeout-wrap every run; set a process-group timeout; tee logs under /tmp/$USER/.expandable_segments:True
fights fragmentation.profiling/results/.../<name>.{nsys-rep,sqlite} (gitignored) + the custom
functions-trace JSON committed.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