/fold-cp:dist_lifecycle [wrap | checkpoint | resume | ema | optimizer]from fold-cp
Sets up distributed model lifecycle for CP training: device placement, DTensor parameter validation, checkpoint save/load, resume, and EMA under DTensor.
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.
None: SKILL.md is the whole skill.
Porting modules (dtensor_modules) proves the math; this skill makes the trainer
work: device placement, parameter typing, checkpoint I/O, resume, and EMA under
DTensor. These steps are where a parity-passing model still fails to train or resume.
Reference files (all under $BOLTZ_CP_REPO/src/boltz/distributed):
lightning_strategy.py, train.py, predict.py, model/optim/ema.py, manager.py.
dtensor_modules + test).docs/cp_infra.md (topology, world_size, launch recipe) and
docs/current_code_structure.md (framework: Lightning / DeepSpeed / custom).Move the serial module to its CUDA device before wrapping/distributing it. A CPU
module wrapped against a CUDA mesh is a device mismatch. Order: build serial → .to(device)
→ DTensor-wrap (train.py:_create_distributed_model). Fail fast if torch.distributed
is not initialized — no silent single-GPU fallback (Rule 12).
Gradient redistribution (on_after_backward → param.grad.redistribute(...)) only fires
on DTensor parameters; a plain-tensor trainable parameter silently bypasses it and
diverges across ranks. So:
__init__: every requires_grad parameter is a DTensor (else raise).state_dict stays key-compatible with the serial checkpoint), requires_grad_(False),
and raise NotImplementedError on forward. This keeps checkpoints portable and lets
training proceed without the unimplemented submodule (boltz2.py _PlaceholderModule).state_dict keys line up.Convert every DTensor in the payload to a plain (full) tensor before writing
(lightning_strategy.py). Save an identical plain checkpoint (portable across
topologies / loadable by the serial model). Do not use a callable map_location
with DTensor checkpoints.
state_dict() as the template — from_local/distribute_tensor each loaded tensor
to the placement the live parameter expects.optimizer.step() — plain-tensor optimizer state from the checkpoint mixed with
DTensor parameters errors (or silently mis-updates) on step.strict=False plus an explicit architecture check
(e.g. assert v2 flags / module presence) — strict=False silently tolerates a
confidence-module or V1/V2 mismatch that then crashes or mis-loads.from_local (with explicit shape/stride/placements) over distribute_tensor
on every same-process load/restore path, and keep map_location a string device — a
callable map_location strips the DTensor type.load_from_checkpoint, re-inject any ctor args passed to
save_hyperparameters(ignore=[...]) (validators, callbacks, non-serializable objects):
they come back None, so restore them from the live module/config before use.Offset the seed by global rank, and on resume additionally by epoch +
global_step, so ranks don't replay identical data/noise and a resume doesn't repeat
the pre-resume stream (train.py). This is the entropy side of the single-device RNG
rule; replicate-axis consistency is still by broadcast, and control-flow scalars
(recycling/sampling counts) are broadcast across the flat CP group. (See RULES.md
"single-device RNG entropy equivalence" + Rule 18.)
EMA updates parameters with in-place .data arithmetic, which bypasses DTensor
dispatch — so EMA only works correctly when the parameters are Replicate on every
mesh axis; Shard/Partial placements give silently wrong EMA updates. When swapping
EMA weights in/out, back up each tensor's device_mesh + placements and rewrap, rather
than round-tripping through CPU (which strips the DTensor type) — see model/optim/ema.py.
Guard the EMA update with torch.inference_mode(False) (an EMA step inside an inference-mode
context errors on the in-place write), keep a CPU backup of the shadow weights for
checkpointing, and on fine-tune resume backfill any missing EMA keys from the live
parameters so a newly-added module doesn't crash the EMA load.
Hand to /fold-cp:test: train N steps → checkpoint → resume → train M more, and assert
(a) the resumed run's weights/optimizer state match a non-interrupted run (within the
fp budget), (b) intermediate checkpoints differ from the final, (c) the saved checkpoint
contains plain tensors (no DTensors), (d) it loads into the serial model, and (e) when
you change the checkpoint/serialization layout, a checkpoint written by the prior format
still loads (backward-compat) — cover both save and load paths. Mirror
tests/distributed/test_dtensor_stop_and_go.py (monkeypatch the distributed cleanup to a
no-op for in-process port reuse).
from_local(local.detach(), …), adding a structurally-zero term, or letting the framework's
grad-accumulation divide such a tensor creates a fresh DTensor from _local_tensor with
requires_grad=False — backward then no-ops and weights never move, with no error. Keep
the loss on the autograd graph (no detach/native re-dispatch on the differentiable path,
Rule 6); if you must accumulate manually, pin grad-accumulation to 1 and verify grad_norm > 0.weights_only=True. Lightning/torch
checkpoints carry non-tensor objects by design; forcing weights_only=True breaks the load —
it is accepted risk, not a vulnerability to patch.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).
/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.
/learn_contextExplore a custom co-folding / structure-prediction model to understand its inference and training workflows, entry points, training framework (PyTorch Lightning vs DeepSpeed), data-feature format, and featurization pipeline — then map those components onto the existing Boltz-CP context-parallel reference so downstream CP integration reuses what already exists. Produces docs/current_code_structure.md. Use FIRST, before any other fold-cp skill, or whenever that doc is missing/stale. Runs interactively (Q&A with the user) or autonomously on request.
Other plugins' skills for the same job