/fold-cp:test [path to source file under test] [unit|layer|module|workflow] [1d|2d|both]from fold-cp
Writes multi-rank pytest parity tests proving a distributed PyTorch implementation matches its serial reference, plus property/invariant tests for cases without a serial oracle. Covers unit through workflow levels with anti-vacuous enforcement.
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.
Most CP correctness is parity: given identical inputs and weights, the distributed forward+backward must numerically match the serial reference, which is the only value oracle (Rule 13) — Steps 1–7 below. But some correctness properties have no serial value oracle and need a different, property / invariant test (see §Property tests) — most notably anything random (RNG / noise), where no distributed RNG reproduces an all-gathered single-device draw, so only the entropy structure is checkable. Either way: a test that can pass with a broken implementation is worse than no test — follow the anti-vacuous rules without exception. The worker skeleton, comparison matrix, and helper inventory are in reference.md.
docs/cp_infra.md gives the launch recipe + world_size (run build_infra if
not).| Level | What it pins | Compare |
|---|---|---|
| unit | one op / autograd.Function | op output + grad vs serial op |
| layer | one layer in isolation | layer fwd+bwd vs serial layer |
| module | module with real feature inputs (from the shared synthetic DataModule — Step 2.2) | module fwd+bwd vs serial module |
| workflow | end-to-end inference or train step | outputs / loss / weight deltas vs serial |
Test path mirrors the source path:
tests/distributed/<path>/test_dtensor_<file>.py for DTensor tests,
test_<file>.py otherwise. Write the parity test for a new operator before
anything downstream depends on it.
Prefer real inference/training features if the user can provide them — ask for a path and the feature format.
Otherwise synthesize through ONE shared synthetic Dataset + DataLoader + DataModule —
not per-test data-gen, and not loose one-off helper functions. Build a single synthetic
data stack in the project's distributed/testing/ subpackage (mirror src/boltz/testing/utils.py
and src/boltz/distributed/testing/):
Dataset whose __getitem__ yields a synthesized input_feature_dict matching §3's
contract (names, shapes, dtypes, axis semantics, masks), with a feature_subset knob;DataLoader (bs=1 + the production collate);DataModule that REUSES the production CP distributor (distribute_input_feature_dict
/ the data module's distributor) — never a re-implementation — to emit, for the requested
subset, both the serial (full) and CP (DTensor) views. Every feature is emitted at the
data-feature sharding requirements (the §3 placements / the §4.5 data-feature→consumer
contract), which the reused distributor satisfies by construction — a synthetic
dataset/dataloader/featurizer must never hand-roll placements that violate that contract.Every test — data, module, and workflow — draws its inputs from this one DataModule and SUBSETS the feature set its target consumes. The common synth + distribution + divisibility-padding + atom-index-remap code then lives in exactly one place; tests never duplicate it. Two payoffs:
torch.randint/randn.randn only for genuine intermediate activations that are not featurizer
outputs (an upstream single/pair representation, a diffusion noise level).Use the same inputs and weights on the serial and CP sides — load one state_dict into both,
and draw features from the DataModule with one deterministic seed so both sides see identical
inputs. Convert the module to the test dtype (fp64) before load_state_dict to avoid an fp32
round-trip (fold-cp test discipline).
Before any multi-GPU run, verify the fwd+bwd decomposition on a 1×1 mesh (single rank / single process, where every collective degenerates to a no-op), in fp64, CP == serial. This isolates math / placement-seam / op-order bugs from collective bugs, needs no GPUs or multi-rank launch, and runs in seconds; a 2-rank gloo run is a cheap second step. Modules that pass this 1×1 pre-check hit multi-GPU parity on the first try — treat it as routine, not optional. Only then build the multi-rank worker:
spawn_multiprocessing(worker, world_size, *args) (Boltz testing
utils) or mp.spawn.DeviceMesh for the topology.tests/distributed/test_dtensor_stop_and_go.py.try/finally to destroy_process_group() and free the GPU on exit;
do not try/except to swallow a rank's error and continue — the throwing rank skips its
remaining collectives and deadlocks the others (broadcast an ok/error sentinel instead — Rule 20).seed_by_rank(rank) for per-rank inputs that must differ; use a contained
torch.Generator rather than global manual_seed.| Comparison | Use |
|---|---|
| DTensor vs serial reference | full_tensor() to reassemble, then assert_close |
| DTensor vs DTensor (same placements) | to_local() on both — no communication |
| Gradients (replicated params) | grad.full_tensor() — Partial(Sum) needs the reduce; to_local() is only this rank's contribution |
Run serial fwd+bwd on full tensors; run CP fwd+bwd on sharded DTensors; compare.
grad_output for backward — never .sum().backward()
(uniform grads mask sign/permutation bugs).cp_size > 1): local.shape[sharded_dim] < global.shape[sharded_dim]
— skip for cp=1 (a valid debugging mesh where local == global).assert_all_identical).0 == 0 passes).param.grad.full_tensor() vs serial. A replicated
param whose grad is a per-rank partial (missing all-reduce) passes forward + input-grad
parity but is wrong; only the param-grad check catches it.assert_close default tolerances. If it only passes after loosening
atol, that is a bug signal — derive the tolerance from the error budget, do not
tune it (Rule 15).cp, a padded
axis, a single-element shard).One test function parametrized over a tuple of mesh configs (do not copy-paste per
size). Prefer CUDA parametrizations; keep at most one CPU param (e.g. non-power-of-two
cp) for CI path coverage.
timeout 120 python -m pytest <test path> -x -q |& tee /tmp/$USER/<name>.log
Make the log self-verifying (Rule 22). Print the evidence on success, not only on
failure: the measured max abs/rel difference and the tolerance, the mesh / world_size, and a
one-line confirmation of each non-vacuous check (sharding-active, replicated-identical, grads
non-zero, per-param-grad). An orchestrator or reviewer then verifies the gate by reading this
log instead of re-running the GPU test (Rule 22) — a silent assert_close that prints nothing on
green forces a needless re-run. Emit the numbers.
Inspect the log even on green (catch silent skips / warnings). When a test fails, assume the implementation is wrong (Rule 14) — diagnose the CP code; do not weaken the test.
Some correctness properties are not numerical equality to the serial reference — the serial run is not a value oracle for them. The oracle is a structural invariant the distributed run must satisfy. Write a property test when:
Canonical example — test_rng_entropy (tests/distributed/test_dtensor_predict.py):
asserts every per-rank RNG draw obeys single-device RNG entropy equivalence (the
fold-cp RNG rule) — sharded-axis draws carry independent entropy (the cp0 diffusion noise
must not tile), replicate-axis draws are identical (via broadcast) — without comparing
to any serial value. Mechanism (skeleton in reference.md):
spawn_multiprocessing;random / numpy / torch RNG entry points to fingerprint every
drawn sample per rank, and save the per-rank fingerprints to the test context (one JSON
per rank);Anti-vacuous rules for property tests (these replace parity's grad_output/fp64/tolerance):
git stash the fix) and confirm it FAILS, then restore.
For test_rng_entropy, the pre-fix shared seed fails on the tiled coordinate noise.>= N ranks drew
sizable samples (numel above a threshold so scalar/degenerate draws don't make it vacuous),
never zero.timeout-wrap, per-collective PG timeout, tee logs, CUDA-preferred.autograd.Function, parametrized over (activation dtype × aux/
mask dtype × autocast on/off) — end-to-end parity is vacuous against a cast inserted and
reverted inside one Function (Rule 19). Make intermediate dtypes observable with a forward-
pre-hook profiler (post-hooks miss the recompute pass under use_reentrant=False).ptxas -v,
assert 0 bytes spill). Triton kernels are often fp32-only (raise on fp64), so do the fp64
CP-vs-serial parity via the REFERENCE path on both sides, and gate the kernel separately
(compiles + matches its own fp32 reference + 0 spill). To force the reference path, override the
has-kernel flag in every module that imported it into its own namespace (grep the flag name) —
setting it only on the defining module is insufficient; run eager + kernel in one process.setUp (use fork_rng/local no_grad); an OOM
poisons the shared CUDA context and cascades (must-fix); classify a failing dist test in a
fresh process; log grad_norm in on_after_backward (it is 0 before backward)./fold-cp:dist_lifecycle for the resume test.)TODO/FIXME after a feature lands: grep the distributed tree + tests for
markers referencing the new capability and resolve stale ones (remove if done, or convert
to a concrete follow-up) so they don't rot.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
distributed-testing, parity-testing, pytest, pytorch, cp-testing
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