| name | experiment-queue |
| description | SSH job queue for multi-seed / multi-config ML experiments with OOM-aware retry, stale-screen cleanup, wave-transition race prevention, and phase-dependency enforcement. Use when user says "batch experiments", "้ๅๅฎ้ช", "run grid", "multi-seed sweep", "auto-chain experiments", or when `/run-experiment` is insufficient for โฅ10 jobs that need orchestration. `/auto-experiment` Phase 4 auto-routes here when a milestone declares โฅ10 jobs or has `depends_on`. |
| argument-hint | ["manifest-or-grid-spec"] |
| allowed-tools | Bash(*), Read, Grep, Glob, Edit, Write, Agent, Skill(run-experiment), Skill(monitor-experiment) |
Experiment Queue
Orchestrate large batches of ML experiments on SSH remote GPU servers with proper state tracking, OOM retry, stale-screen cleanup, wave transitions, and phase-dependency enforcement.
When to Use This Skill
Use when /run-experiment is insufficient:
- โฅ10 jobs that need batching across GPUs
- Multi-seed sweeps (e.g., 21 seeds ร 12 cells)
- Wave transitions (run wave 1, wait, run wave 2, wait, run wave 3...)
- Teacher+student chains (train teacher, then distill; auto-trigger student after teacher done)
- OOM-prone configs where you need to retry with different GPU or wait
- Mixed seed grids where failed cells need re-running
Do NOT use for:
- Single ad-hoc experiment (use
/run-experiment)
- Modal / Vast.ai deployments (those have their own orchestration)
- Experiments that need manual inspection between runs
Why This Exists
The major wall-clock sinks in multi-seed grid experiments are:
- Stale screens โ python finishes, wandb uploads, screen hangs, next wave blocked
- OOM on shared GPU โ previous job's memory not yet released
- Wave race โ new wave launches before previous wave fully settles
- Missing checkpoints โ student launches before teacher saved
- Parser duplication โ rewriting multi-seed analysis python every batch
All of these are pure engineering friction that can be orchestrated. /run-experiment + /monitor-experiment cover ad-hoc single runs but lack OOM retry, displacement-aware GPU gating, wave settlement, and crash-safe state โ at โฅ10 concurrent jobs these gaps start firing.
Core Concepts
Job Manifest
A manifest lists jobs with explicit state:
project: my_grid_experiment
cwd: /home/user/your_project
conda: my_env
ssh: gpu-server
default_cmd: >
python run_distill.py --backbone softmax --lam 0.5
--K 500 --L 96 --W 16 --n_steps 30000 --batch_size 128 --lr 1e-4
preconditions:
- type: checkpoint_exists
path: checkpoints/transformer/teacher_L96_K500_N{N}.pt
gpus: [0, 1, 2, 3, 4, 5, 6, 7]
max_parallel: 8
gpu_free_threshold_mib: 500
oom_retry:
delay: 120
max_attempts: 3
jobs:
- id: s200_N64_n50K
args: {seed: 200, n_hidden: 64, n_train_subset: 50000, subset_seed: 2024}
- id: s200_N128_n50K
args: {seed: 200, n_hidden: 128, n_train_subset: 50000, subset_seed: 2024}
Job State Machine
pending โ running โ completed
โ failed_oom โ pending (after delay) [retry up to N]
โ failed_other โ stuck (needs manual inspection)
stale_screen_detected โ cleaned โ pending
Wave Orchestration
A "wave" is a batch of jobs that fit available GPUs. Next wave only starts when:
- All current-wave python processes have exited
- No stale screens remain for current-wave tags
- GPU memory has dropped below threshold (โค500 MiB)
- Precondition checks pass for next-wave jobs
Coordination with cost.json and queue_state.json
MECHANIST has two parallel state files at different granularities:
| File | Granularity | Writer | Consumers |
|---|
runs/<run-id>/cost.json | Per-run (1 file per logical experiment run) | /run-experiment Step 5.5 (initial stub) + /monitor-experiment Step 3.6 (finalize) | /auto-experiment Phase 5, /auto-iteration-loop Phase C, /auto-verify budget tracking |
$REMOTE_RUN_DIR/queue_state.json | Per-batch (1 file per /experiment-queue invocation, covering all jobs in the batch) | bundled queue_manager.py copied from this skill's scripts/ directory โ updated every poll cycle | This skill's monitoring (Step 4), Phase-4 batch-level diagnostics in /auto-experiment |
They are complementary, not redundant: queue_state.json is the source of truth for "which jobs in this batch are still running / OOM-retrying / stuck"; cost.json is the source of truth for "how many GPU-hours did this individual run consume." When /experiment-queue finishes a job (state machine transitions running โ completed), its expected_output is verified โ at that point the caller of /experiment-queue (typically /auto-experiment Phase 4) should invoke /monitor-experiment on each completed job to finalize that run's cost.json. Do not duplicate cost accounting inside queue_state.json โ keep the two files at their respective granularities.
Workflow
Step 1: Parse Manifest / Build from Grid
Input can be:
- YAML manifest (explicit job list, recommended for complex cases)
- Grid spec (Cartesian product of param values, e.g.,
N=[64,128,256] ร n=[50K,150K,500K,652K])
- Natural language description (Claude parses into manifest)
Bind the run identifiers once so every later step (manifest save, scp, launch, monitor, resume) refers to the same paths. Set these as local shell variables before generating the manifest:
PROJECT_DIR="${PROJECT_DIR:?set PROJECT_DIR to the local project root}"
RUN_TS=$(date -u +%Y%m%dT%H%M%SZ)
LOCAL_RUN_DIR="$PROJECT_DIR/experiment_queue/$RUN_TS"
mkdir -p "$LOCAL_RUN_DIR"
Save the built manifest to $LOCAL_RUN_DIR/manifest.json for reproducibility.
When invoked from /auto-experiment Phase 4 (auto-routed), the caller forwards the milestone's run list plus a derived phases: block (one phase per milestone, with depends_on: populated from EXPERIMENT_PLAN.md's declared dependencies); this skill does not re-parse the plan.
Step 2: Pre-flight
- Check SSH connection works
- Check conda env exists on remote
- Check
cwd exists on remote
- Check all preconditions (checkpoints, input files)
- Check GPU availability (at least
max_parallel free GPUs)
If any precondition fails, show user which jobs are blocked and why.
Step 3: Launch Scheduler
The scheduler implementation lives in this skill's scripts/queue_manager.py. Three preliminaries before launch.
3a. Resolve the local helper directory. The two helpers (queue_manager.py, build_manifest.py) sit under scripts/ next to this SKILL.md:
QUEUE_TOOLS="${CLAUDE_SKILL_DIR}/scripts"
[ -f "$QUEUE_TOOLS/queue_manager.py" ] || { echo "ERROR: experiment_queue helpers not found under \$CLAUDE_SKILL_DIR/scripts" >&2; exit 1; }
Do not resolve these helpers from the user's current project directory; pluginized skills should use their own bundled scripts.
3b. Compute remote paths. Use both a remote-relative form (for scp destinations โ modern scp runs in SFTP mode and does NOT reliably expand $HOME in destination paths) and a $HOME-prefixed form (for ssh ... command strings, where remote bash WILL expand $HOME):
REMOTE_RUN_REL=".mechanist_queue/runs/$RUN_TS"
REMOTE_RUN_DIR="\$HOME/$REMOTE_RUN_REL"
3c. Bootstrap the remote run directory and copy helpers + manifest. Per-invocation and idempotent. Use a unique run directory rather than /tmp so concurrent queues do not collide and so resume-after-crash is reproducible.
ssh <server> "mkdir -p \"$REMOTE_RUN_DIR/logs\" \"\$HOME/.mechanist_queue\""
scp "$QUEUE_TOOLS/queue_manager.py" "$QUEUE_TOOLS/build_manifest.py" <server>:.mechanist_queue/
scp "$LOCAL_RUN_DIR/manifest.json" <server>:"$REMOTE_RUN_REL/manifest.json"
3d. Launch the scheduler as a detached nohup process on the SSH host:
ssh <server> "nohup python3 \"\$HOME/.mechanist_queue/queue_manager.py\" \\
--manifest \"$REMOTE_RUN_DIR/manifest.json\" \\
--state \"$REMOTE_RUN_DIR/queue_state.json\" \\
--log-dir \"$REMOTE_RUN_DIR/logs\" \\
> \"$REMOTE_RUN_DIR/queue_mgr.log\" 2>&1 &"
Notes for callers:
-
--log-dir is what queue_manager.py actually consumes (per-job log files for OOM detection). Do NOT pass --log <path> โ that flag is declared but unused, and a single combined log breaks the per-job stale-screen / OOM heuristics.
-
Persist RUN_TS / REMOTE_RUN_REL / REMOTE_RUN_DIR to disk so monitoring and resume can reload them without regenerating:
{
printf 'PROJECT_DIR=%q\n' "$PROJECT_DIR"
printf 'RUN_TS=%q\n' "$RUN_TS"
printf 'LOCAL_RUN_DIR=%q\n' "$LOCAL_RUN_DIR"
printf 'REMOTE_RUN_REL=%q\n' "$REMOTE_RUN_REL"
printf 'REMOTE_RUN_DIR=%q\n' "$REMOTE_RUN_DIR"
} > "$LOCAL_RUN_DIR/run_meta.txt"
%q shell-escapes the values so the file is safely sourceable later. Note that REMOTE_RUN_DIR keeps a literal $HOME (do not expand it locally), which is the right form for re-use inside ssh "..." strings later.
3e. Resume an existing queue (only when the user asks). A fresh RUN_TS per invocation is correct for new queues. To resume a crashed queue, do NOT regenerate RUN_TS โ reload the recorded values and re-run only the launch command (Step 3d), not the bootstrap (Step 3c):
LOCAL_RUN_DIR="/abs/path/to/project/experiment_queue/<existing-run-ts>"
. "$LOCAL_RUN_DIR/run_meta.txt"
The scheduler:
- Reads manifest
- Loops: for each pending job, assign to free GPU, launch via
screen
- Polls job status (every 60s)
- Detects stale screens (python exited but screen detached โ kill)
- Detects OOM (CUDA OOM in log โ mark failed_oom โ retry after delay)
- Detects completion (expected output JSON/file exists) โ mark completed
- Launches next wave when current wave settles
- Writes state to
queue_state.json continuously
Step 4: Monitoring
User can check state anytime, using $REMOTE_RUN_DIR from Step 3b (or reload from $LOCAL_RUN_DIR/run_meta.txt for an older run):
ssh <server> "cat \"$REMOTE_RUN_DIR/queue_state.json\"" \
| jq '.jobs | group_by(.status) | map({(.[0].status): length}) | add'
Note: /monitor-experiment is focused on per-run screen sessions, result JSONs, W&B, and the cost.json finalization (Step 3.6 there). For batch-level queue-state monitoring, use the literal jq command above against the recorded REMOTE_RUN_DIR. The two views are complementary โ see the "Coordination with cost.json and queue_state.json" section above.
Step 5: Post-completion
When all jobs in manifest.json are completed or stuck:
- The remote scheduler (
queue_manager.py) exits cleanly with All jobs done to its own stdout (captured in $REMOTE_RUN_DIR/queue_mgr.log). It does NOT write the local summary.
- The local skill agent then aggregates state into
$LOCAL_RUN_DIR/summary.md (read $REMOTE_RUN_DIR/queue_state.json, group by status, optionally pull per-job logs).
- The local skill agent invokes
/monitor-experiment on each completed job to finalize its runs/<job-id>/cost.json (so downstream consumers can read GPU-hours from the canonical place).
- Local skill agent invokes
/analyze-results if analyze_on_complete: true.
Grid Spec Syntax
Instead of writing 24 job entries manually:
grid:
N: [64, 128, 256]
n: [50000, 150000, 500000, 652000]
seed: [42, 200, 201]
template:
id: "s${seed}_N${N}_n${n}"
args: {seed: ${seed}, n_hidden: ${N}, n_train_subset: ${n}}
Expands to 36 jobs automatically.
Wave Chaining
For sequential phases (teacher โ student):
phases:
- name: train_teachers
grid:
N: [384, 512]
template:
cmd: python run_train.py --direction c --backbone softmax --n_hidden ${N} ...
output_check: checkpoints/transformer/teacher_L96_K500_N${N}.pt
- name: distill_students
depends_on: train_teachers
grid:
N: [384, 512]
seed: [42, 200, 201]
template:
cmd: python run_distill.py --n_hidden ${N} --seed ${seed} ...
output_check: figures/distill_sw_N${N}_*_seed${seed}.json
Scheduler enforces depends_on: distill_students jobs stay pending until all
train_teachers jobs are completed.
OOM Handling
Detect OOM from stdout:
torch\.OutOfMemoryError: CUDA out of memory
On detection:
- Mark job
failed_oom
- Kill screen
- Wait
oom_retry.delay seconds
- Check if current GPU is free; if not, try another free GPU
- Requeue as
pending
- Max
oom_retry.max_attempts before marking stuck
Stale Screen Detection
Every 60s, for each running screen:
- Check screen exists (
screen -ls)
- Check python PID still running (
ps -p)
- If screen exists but python exited:
- If expected output file exists โ mark
completed, kill stale screen
- If no output file โ mark
failed_other, kill screen
Resume-on-restart
If scheduler crashes / is killed:
- Read
queue_state.json
- For each
running job: check screen; if still alive, keep; if not, re-evaluate state
- For each
pending: continue normally
- Idempotent: safe to restart scheduler without losing state
Output: Summary Report
# Experiment Queue Summary
**Project**: my_grid_experiment
**Started**: 2026-05-18 11:36:29
**Completed**: 2026-05-18 18:02:14
**Total wall-clock**: 6h 25m
**Jobs**: 40 completed, 2 OOM-retried then completed, 0 stuck
## Phases
| Phase | Jobs | Success | OOM retries | Duration |
| --- | --- | --- | --- | --- |
| train_teachers | 2 | 2 | 0 | 58m |
| distill_students | 24 | 24 | 2 | 4h 02m |
| multi_seed_validation | 16 | 16 | 0 | 1h 25m |
## Results Files
- 42 JSON files in `figures/distill_sw_*.json`
- 42 cost manifests in `runs/<job-id>/cost.json` (finalized via `/monitor-experiment` Step 3.6)
## Next Steps
- Run `/analyze-results` on output JSONs
- Caller (`/auto-experiment` Phase 5) aggregates per-run cost manifests into the milestone summary
Comparison with /run-experiment
| Feature | /run-experiment | experiment-queue |
|---|
| Single-shot experiment | โ
| โ
(overkill) |
| Multi-GPU parallel | Basic | Proper scheduling |
| Wave transitions | Manual | Automatic |
| OOM retry | Manual | Automatic |
| Stale screen cleanup | Manual | Automatic |
| Teacherโstudent chain | Manual | Built-in |
| State persistence | cost.json per-run only | queue_state.json per-batch + per-run cost.json |
| Resume on crash | Per-run only (no batch state) | Yes, batch-level |
| Grid expansion | Manual | Declarative |
Rule: Use /run-experiment for โค5 jobs. Use experiment-queue for โฅ10 jobs or any milestone with depends_on. /auto-experiment Phase 4 auto-routes based on this rule โ see its "Phase 4: Deploy Full Experiments" section.
Key Rules
- Never overlap screens on the same GPU โ always wait for
memory.used < 500 MiB before launching new job
- Always write state to disk โ every state change flushed to
queue_state.json atomically (write tmp + rename)
- Idempotent scheduler โ safe to restart; picks up from state file
- Expected-output-based completion โ don't trust screen state alone; verify output file exists
- Bounded retry โ max N OOM retries, then mark
stuck and alert
- Dependencies enforced at launch โ never launch student before teacher checkpoint exists
cost.json finalization is the caller's job โ this skill writes batch state; per-run cost manifests are finalized by /monitor-experiment Step 3.6, invoked by the caller after batch completion
Known Failure Modes
- SSH connection drop during scheduling: scheduler keeps running on remote (nohup), just reconnect and check
- GPU reservation by another user: scheduler waits, does not pre-empt
- Disk full on remote: scheduler detects write failure, marks all pending
stuck, alerts
Example Session
User: "่ท T5+T6 ๅ
จ้จๅฎ้ช๏ผT5 = Nโ{80,192} ร n 4 values ร seed {200,201}, T6 = Nโ{384,512} ร n 4 values ร seed {42,200,201}; T6 ้่ฆๅ
train teacher"
Claude invokes /experiment-queue:
- Parses description into 2-phase manifest
- Phase 1: T5 (16 jobs, no teacher dependency) + T6 teacher training (2 jobs)
- Phase 2: T6 distillation (24 jobs, depends on teachers)
- Deploys scheduler via nohup
- Reports: "Scheduler PID 93534, total 42 jobs, estimated 6-7h wall-clock"
Then user can check anytime or wait for summary report.
See Also
/run-experiment โ single experiment deployment; writes per-run cost.json stub
/monitor-experiment โ per-run progress check + finalizes cost.json
/auto-experiment Phase 4 โ auto-routes to this skill when a milestone declares โฅ10 jobs or has depends_on
skills/experiment-queue/scripts/queue_manager.py (bundled) โ the scheduler implementation; resolved at runtime via $CLAUDE_SKILL_DIR/scripts
skills/experiment-queue/scripts/build_manifest.py (bundled) โ build manifest from grid spec; same resolution
Rationale / Source
Adapted from an upstream experiment-queue skill (originally identified via a 2026-04-16 post-mortem of a 1.5-day multi-seed paper experiment session). The wall-clock sinks identified there โ stale screens, OOM, wave transitions, manual parser โ all apply identically to MECHANIST's experiment stage when run sizes exceed /run-experiment's single-shot scope. The Python helpers (queue_manager.py, build_manifest.py) are a direct port with environment-variable renames and cost.json coordination added.