--- name: run-experiment description: Deploy and run ML experiments on local, remote, Vast.ai, or Modal serverless GPU. Use when user says "run experiment", "deploy to server", "跑实验", or needs to launch training jobs. argument-hint: "[experiment-description]" allowed-tools: Bash(*), Read, Grep, Glob, Edit, Write, Skill(serverless-modal) --- # Run Experiment Deploy and run ML experiment: $ARGUMENTS ## Workflow ### Step 1: Detect Environment Read the project's `CLAUDE.md` to determine the experiment environment: - **Local GPU** (`gpu: local`): Look for local CUDA/MPS setup info - **Remote server** (`gpu: remote`): Look for SSH alias, conda env, code directory - **Vast.ai** (`gpu: vast`): Check for `vast-instances.json` at project root — if a running instance exists, use it. Also check `CLAUDE.md` for a `## Vast.ai` section. - **Modal** (`gpu: modal`): Serverless GPU via Modal. No SSH, no Docker, auto scale-to-zero. Delegate to `/serverless-modal`. **Modal detection:** If `CLAUDE.md` has `gpu: modal` or a `## Modal` section, the entire deployment is handled by `/serverless-modal`. Jump to **Step 4: Deploy (Modal)** — Steps 2-3 are not needed (Modal handles code sync and GPU allocation automatically). **Environment contract** (`../shared-references/compute-env-contract.md`): read existing server notes or the provider's ledger before preparing the environment. Reuse the user's confirmed conda/venv and working command; a missing ARIS ledger does not require rebuilding. If no relevant validation exists, run one small, task-relevant smoke in that environment and record the command and actual output. Reuse prior validation when the environment and execution path have not changed. New or rebuilt environments need the spec, import/kernel checks and a fresh agent-follows-doc pass once setup is stable; substantive installation or invocation changes need the affected checks. Plain prose/log edits do not trigger a rebuild or fresh recheck. This execution evidence does not replace research acceptance. **Preparation failures:** carry the same failure, attempted fixes and remaining budget across child skills in the existing run notes/tracker. After two targeted repairs to the same environment problem make no new progress, stop repeating preparation and return the exact command/error to the main owner for takeover or an authorized alternative. Missing permissions, authentication, network access or a compatible driver are environment prerequisites, not reasons to rewrite the training script. Keep the original code-sanity retry budget and reviewer gates. **Vast.ai detection priority:** 1. If `CLAUDE.md` has `gpu: vast` or a `## Vast.ai` section: - If `vast-instances.json` exists and has a running instance → use that instance - If no running instance → call `/vast-gpu provision` which analyzes the task, presents cost-optimized GPU options, and rents the user's choice 2. If no server info is found in `CLAUDE.md`, ask the user. ### Step 2: Pre-flight Check Check GPU availability on the target machine: **Remote (SSH):** ```bash ssh nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader ``` **Remote (Vast.ai):** ```bash ssh -p root@ nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader ``` (Read `ssh_host` and `ssh_port` from `vast-instances.json`, or run `vastai ssh-url ` which returns `ssh://root@HOST:PORT`) **Local:** ```bash nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader # or for Mac MPS: python -c "import torch; print('MPS available:', torch.backends.mps.is_available())" ``` Free GPU = memory.used < 500 MiB. ### Step 3: Sync Code (Remote Only) Check the project's `CLAUDE.md` for a `code_sync` setting. If not specified, default to `rsync`. #### Option A: rsync (default) Prefer the project's existing deployment command or explicit file list. Otherwise, allow directory traversal and include the configuration/small resources read by the actual experiment command, alongside Python sources. For example: ```bash rsync -avz --prune-empty-dirs \ --exclude='.*' --exclude='__pycache__/' --exclude='/venv/' --exclude='/env/' \ --exclude='data/' --exclude='datasets/' --exclude='weights/' \ --exclude='checkpoints/' --exclude='outputs/' --exclude='wandb/' \ --include='*/' --include='*.py' \ --include='/configs/sanity.json' --include='/assets/vocab.json' \ --exclude='*' "/" ":/" ``` Replace the two explicit config/resource paths with those your command needs; add other required small files explicitly. Keep exclusions before directory/file includes, and add project-specific private paths there. Hidden agent/config files, data, weights and outputs stay out of this example. Use the project source root, not the user's home directory; do not replace these rules with an unfiltered copy. A successful sync exit is not a launch check: run the smallest actual experiment from the configured remote code directory and inspect its log and result file. #### Option B: git (when `code_sync: git` is set in CLAUDE.md) Push local changes to remote repo, then pull on the server: ```bash # 1. Push from local git add -A && git commit -m "sync: experiment deployment" && git push # 2. Pull on server ssh "cd && git pull" ``` Benefits: version-tracked, multi-server sync with one push, no rsync include/exclude rules needed. #### Option C: Vast.ai instance Sync code to the vast.ai instance (always rsync, code dir is `/workspace/project/`): ```bash rsync -avz -e "ssh -p " \ --include='*.py' --include='*.yaml' --include='*.yml' --include='*.json' \ --include='*.txt' --include='*.sh' --include='*/' \ --exclude='*.pt' --exclude='*.pth' --exclude='*.ckpt' \ --exclude='__pycache__' --exclude='.git' --exclude='data/' \ --exclude='wandb/' --exclude='outputs/' \ ./ root@:/workspace/project/ ``` Install dependencies per the env contract (ordered phases — pins first, one `pip install` per phase; see `../shared-references/compute-env-contract.md`): ```bash ssh -p root@ "pip install -q torch==" # phase 1: pins ssh -p root@ "pip install -q " # phase 2+ ``` Legacy fallback — `requirements.txt` only, no env spec: install as one phase, and treat any version fight as the signal to convert to ordered phases: ```bash scp -P requirements.txt root@:/workspace/ ssh -p root@ "pip install -q -r /workspace/requirements.txt" ``` ### Step 3.5: W&B Integration (when `wandb: true` in CLAUDE.md) **Skip this step entirely if `wandb` is not set or is `false` in CLAUDE.md.** Before deploying, ensure the experiment scripts have W&B logging: 1. **Check if wandb is already in the script** — look for `import wandb` or `wandb.init`. If present, skip to Step 4. 2. **If not present, add W&B logging** to the training script: ```python import wandb wandb.init(project=WANDB_PROJECT, name=EXP_NAME, config={...hyperparams...}) # Inside training loop: wandb.log({"train/loss": loss, "train/lr": lr, "step": step}) # After eval: wandb.log({"eval/loss": eval_loss, "eval/ppl": ppl, "eval/accuracy": acc}) # At end: wandb.finish() ``` 3. **Metrics to log** (add whichever apply to the experiment): - `train/loss` — training loss per step - `train/lr` — learning rate - `eval/loss`, `eval/ppl`, `eval/accuracy` — eval metrics per epoch - `gpu/memory_used` — GPU memory (via `torch.cuda.max_memory_allocated()`) - `speed/samples_per_sec` — throughput - Any custom metrics the experiment already computes 4. **Verify wandb login on the target machine:** ```bash ssh "wandb status" # should show logged in # If not logged in: ssh "wandb login " ``` > The W&B project name and API key come from `CLAUDE.md` (see example below). The experiment name is auto-generated from the script name + timestamp. ### Step 4: Deploy #### Remote (via SSH + screen) For each experiment, create a dedicated screen session with GPU binding: ```bash ssh "screen -dmS bash -c '\ eval \"\$(/conda shell.bash hook)\" && \ conda activate && \ CUDA_VISIBLE_DEVICES= python