Skip to content
Back to skills

Running Cluster Experiments

ASecurity

Use when planning, budgeting, submitting or resuming a multi-job experiment campaign on a Slurm/HPC cluster — sizing walltime, shaping jobs and arrays, deciding what to submit first, or after a job hit its walltime, produced no results, silently ran the wrong configuration, or got the wrong number of GPUs.

  • 7 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added September 5, 2026
researchpythonrustgoshellbashnodeapi

Works with

  • cli
  • api

Security analysis

A100/100

Scanned November 29, 2026

npx -y skills add chgagne/claude-skills-research --skill running-cluster-experiments --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Running Cluster Experiments?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Running Cluster Experiments
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/chgagne-running-cluster-experiments/badge)](https://www.skillsdirectory.com/skills/chgagne-running-cluster-experiments)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: running-cluster-experiments
description: Use when planning, budgeting, submitting or resuming a multi-job experiment campaign on a Slurm/HPC cluster — sizing walltime, shaping jobs and arrays, deciding what to submit first, or after a job hit its walltime, produced no results, silently ran the wrong configuration, or got the wrong number of GPUs.
---

# Running Cluster Experiments

## Overview

This is the **methodology** of experiment campaigns on shared clusters. For the mechanics — MFA, account strings, gres names, quotas, partitions, rsync flags — **REQUIRED BACKGROUND: use `using-drac-clusters`.**

**Core principle: a scheduler will kill your job at an arbitrary point, and a cluster will hand you less than you asked for. Design for both, or your allocation buys nothing.** Every rule below is a consequence.

The expensive failures are never "the code crashed". They are: the job ran perfectly and wrote nothing; the job ran a different experiment than its name says; the allocation was spent before the first useful instruction.

## Never compute on a login node — use an interactive allocation

Login nodes: `squeue`, `ls`, `sacct`, `diskusage_report`, editing, `sbatch`, file transfer only. **Anything that loops over data, parses a large file, trains, plots, or runs for more than a few seconds: not fine** — including "just this once", and work already started. **Interactive compute is a normal allocation, not a special favour:**

```bash
salloc --account=<alloc> --cpus-per-task=4 --mem=16G --time=1:00:00   # shell on a compute node
srun --jobid=<id> --pty bash                                          # shell inside a running job
```

**Asking for less gets you compute faster than not asking at all.** If interactive scheduling is genuinely slow, the answer is `sbatch`, not the login node. Measured queue times: reference/cost-model.md.

## Build a cost model before you choose a walltime

**Measure per-unit cost at the real configuration, on the machine that will run it, then multiply.** Not at a smaller model, not at a shorter run, not on a different cluster, not from last quarter's estimate.

Budgets die three ways: extrapolating across scale, across units (measuring *a* unit instead of the *worst* one), and across machines. Incidents and numbers: reference/cost-model.md.

- **Measure on the cluster you will submit to.** A rate from another cluster is an estimate, not a calibration.
- **Two agreeing anchors are not a trend line.** Treat cross-machine transfer as unmeasured until measured.
- Hardest for **CPU-bound** work; GPU work transfers better, but its CPU-side client, data loading and startup do not.
- **Margin computed against an untrusted anchor is not margin.**
- **Time the MOST EXPENSIVE unit, not a convenient one.** If unknown, time one per stratum (dataset, model, problem size).
- **Then add margin for variance *within* a stratum**, which can rival the variance between strata.
- **Watch the trend, not the mean.** Per-unit cost often rises during a run; correct for it explicitly.
- **The underestimate grows with the extrapolation distance.** If cost depends on accumulated state, a short calibration is biased.
- **Set the walltime per stratum, not globally.** An array shares one `--time`: one array submission per stratum.
- **Record the measured rate next to the `--time` line**, with the configuration AND the unit it was measured on. "4.6 h/cell" is a trap; "4.6 h/cell on dataset X, 11 h on dataset Y" is a budget.
- Round `--time` *down* into a partition bucket (see `using-drac-clusters`), but never below the measured cost.

### Fixing a walltime after submission

`scontrol update JobId=<id> TimeLimit=<new>` on a PENDING job **is accepted but does not re-route its partition**: past the cap it waits forever as ordinary `(Priority)`. Cancel and resubmit instead. Check the caps first:

```bash
sinfo -h -o "%P %l" | sort -u
```

## One resource class per job

**Do not co-locate work with different resource profiles in one job.** Split by what each part needs. Splitting also buys **queue position**: short jobs start sooner, and a killed short job loses less.

- **Check that splitting is scientifically neutral first** — no shared state (RNG seeded per part, no carry-over between arms); if shared, say so and keep them together.
- **Splitting a job must also split its output path.** Concurrent writes to one file are a silent lost-update race; one output per part, merge at analysis.

The incident behind this rule: reference/incidents.md.

## Adapt or abort — decide by what changes

When the cluster hands you less than you asked for, **the choice is not about how much less you got. It is about whether the shortfall changes what you are measuring.**

- **Changes only cost** (time, batch size, parallel width, node count) → **adapt, and record the adaptation next to the result.**
- **Changes what is measured** (a capability the experiment's definition depends on is missing, ignored, or silently substituted) → **ABORT before the expensive resource is spent, and never run the reduced version under the original name.**

**When unsure, ask: if this run completes, will its output file still deserve the name I am about to give it?** If not, abort, however cheap the fix looks and however deep the queue is.

**Gate in this order — cheapest and most fatal first — all before any model load, server start, or data staging:**

| Gate | Check | Why it must abort |
|---|---|---|
| **Semantic capability** | The feature the experiment's *meaning* depends on is actually active (e.g. constrained decoding really enabled, not silently ignored) | Highest stakes: the arm runs, completes, and measures something else entirely under its own name |
| **Parallel width vs devices** | Devices *allocated* == width requested (`nvidia-smi -L \| wc -l` vs your tensor/data-parallel setting) | Asking for width 2 with 1 device wastes the whole job |
| **Devices on one node** | `--nodes=1` was actually emitted | A total device count can be satisfied *across* nodes; most intra-job parallelism cannot span them |
| **Environment** | Import every module the entry point needs (`python -c "import numpy, sklearn, mypkg"`) | ~1 s here vs discovering it after a multi-minute model load |
| **Inputs present** | Caches/datasets exist and are readable | Offline modes cannot create a missing cache; the job dies late |
| **Walltime cap** | Requested time ≤ this cluster's maximum | Unsubmittable on capped clusters; needs checkpointing instead |
| **Output collisions** | This task's output paths are unique | See "Derive identifiers" |

**Every wait-for-a-service loop needs a timeout, and the timeout is a gate.** An unbounded `wait until healthy` converts a bad node into a full-allocation loss. Incident: reference/incidents.md.

**A polling predicate that can match the poller itself never terminates.** `pgrep -f` matches full command lines, including the polling shell's own:

```sh
until ! pgrep -qf "myjob input.dat"; do sleep 5; done   # never exits:
                                                        # the loop matches itself
```

Poll on something that cannot describe the poller:

```sh
kill -0 "$PID" 2>/dev/null                 # a PID captured at launch
squeue -h -j "$JOBID" | grep -q .          # the scheduler's own record
test -e "$OUTDIR/DONE"                     # a sentinel the job writes
```

**Better still, do not poll for work whose completion is already reported to you** (notify-on-exit, `--dependency=afterok:$JOBID`). Reserve polling for state nothing reports; give the interval a reason.

**One failed task in an otherwise healthy array is usually the node, not your code.** Check `sacct -j <id> -X -o JobID,State,NodeList` and `scontrol show node <host> | grep -E 'State|Reason'`; resubmit that index alone.

- **Resolve all configuration before starting anything expensive.** A config error should surface in one second, not after a model load.
- **Gate on what your entry points actually use.** A gate that produces false aborts is worse than no gate.

## Results must survive a kill

**The flush unit must be strictly smaller than the smallest unit of work a walltime can kill.** Anything a job finished must be on disk before it starts the next thing.

- Flush after every unit, not every batch of units.
- **Re-check granularity whenever the job's shape changes.** "Per row" is a relationship between code and submission.
- Prefer append-only streams for large per-item output; whole-file rewrites do not survive a kill.
- Ask directly: *if this dies at 90%, what is on disk?* If "nothing", fix that before submitting.
- For resumable campaigns, have each chunk call the `dracmon-cell` hook (see `using-drac-clusters`) with one `DRACMON_CAMPAIGN` exported.

The incident behind this rule: reference/incidents.md.

## Stage the campaign

**Never submit the full array first.** Submit one cheap task that exercises the same machinery, and **write down the stage-2 trigger before stage 1 runs** — afterwards you will rationalise whatever you see.

A trigger is a checklist with exact commands and a stated failure interpretation:

> Submit the remaining N only if: all smoke tasks `COMPLETED`; the log shows the derived config line; **and** both output files exist, each with exactly one record and the expected fields. *If only one file exists, the identifier is not reaching the code and the real array would clobber itself — fix that first.*

Design the smoke to exercise **the property you are unsure about**, at minimum scale (a collision test needs *two* array tasks). **Staging pays even when the predicted risk does not materialise.**

### Stage 1 validates the pipeline. It is not a preview of the result.

Do not read a scientific direction off the staged unit. Not as a hint, not as "early evidence", not hedged. **The bias is structural, not merely small-n:** you stage on the cheapest unit, which is the least representative.

- Report stage 1 as **"the pipeline works"**, never as "early results suggest".
- Hedging does not license the inference; a hedged directional claim is still a directional claim.
- Describing a stage-1 number as a *finding* rather than a *check* is the tell.

Incidents behind both rules: reference/incidents.md.

## Derive identifiers, never hand-write them

**If N concurrent tasks each need a unique output path, compute it from the array index.** A hand-written tag typo silently destroys a result, undetectable because the file looks fine.

```bash
# Map SLURM_ARRAY_TASK_ID -> one cell + a unique tag; abort on out-of-range.
if ! ASSIGN="$(python3 grid_task.py --index "$SLURM_ARRAY_TASK_ID" --prefix "$PREFIX")"; then
  echo "ABORT: refused array index ${SLURM_ARRAY_TASK_ID}" >&2; exit 1
fi
eval "$ASSIGN"
echo "[grid] task ${SLURM_ARRAY_TASK_ID} -> ${TAG}"     # makes the mapping auditable in the log
```

- **Out-of-range must raise, never wrap** — modular arithmetic maps an oversized `--array` back onto cell 0's tag.
- **`eval "$(cmd)"` discards `cmd`'s exit status.** Capture and test it, or a refused index runs the *whole grid* under one tag.
- **Echo the resolved mapping**, so a log can be traced back to its task.
- Put the index arithmetic in a tested function, not inline in the batch script.

## Verify tracked state; do not trust your notes

**Status notes record what was *submitted*, and nobody goes back when it lands.** Re-verify against the cluster at the start of every session before acting on anything written down.

```bash
sacct -X -S <YYYY-MM-DD> -o JobID%16,JobName%20,State,Elapsed,ExitCode
sacct -j <arrayid> -X -n -o State | sort | uniq -c    # array state histogram
```

Then confirm the *artifacts*, not just the exit code: record count, expected fields, the metric you think you measured. `COMPLETED` means the script exited 0. Incident: reference/incidents.md.

## Common mistakes

| Mistake | Consequence |
|---|---|
| Anything CPU-heavy on a login node | Killed by staff; `salloc` was available in seconds |
| Budgeting walltime from a smaller model or shorter run | Off by 1-2 orders of magnitude; every task dies |
| Budgeting from a rate measured on a different cluster | Same code, same config, 2.6x slower on the new machine; CPU-bound work transfers worst |
| Treating two agreeing measurements as confirmation | Two similar machines agreeing predicts nothing about a third; it is one data point wearing two hats |
| Reading a scientific direction off the staged unit | You staged on the cheapest unit, which is the least representative one; the full campaign can and does reverse it |
| Calibrating on one unit when units differ in cost | The projection is right for that unit and 2-3x wrong for another; the slow ones die at ~75% and write nothing |
| Ignoring variance *within* a stratum | One seed finishes, its sibling times out on the same dataset |
| Raising the walltime globally to protect one slow stratum | Every task queues worse, possibly in a scarcer partition, for a minority's benefit |
| `scontrol update TimeLimit=` past the partition cap | Accepted, but the partition is not re-routed; the job waits forever as ordinary `(Priority)` |
| An unbounded wait-for-service loop | A node that hangs mid-init costs the whole allocation instead of minutes |
| A `pgrep -f` poll whose pattern appears in the poller's own command line | The predicate is always true; the loop outlives the job it watches, silently and at zero CPU |
| Timing only the first few units | Per-unit cost commonly rises; mean underestimates |
| One job holding accelerators for a CPU-only part | Pays GPU-hours for CPU arithmetic, and forces an unfittable walltime |
| Flush unit == job unit | A kill at 99% writes nothing, including finished sub-units |
| Assuming a flush granularity still holds after reshaping jobs | The code didn't change; the relationship did |
| Running on when a *meaning-changing* capability is missing | Completes, publishes, measures the wrong thing under the right name |
| Adapting to a smaller allocation without recording it | Result is real but unreproducible; later readers assume the original config |
| Splitting a job without splitting its output path | Sequential writes become concurrent ones; a lost-update race with a silent loser |
| Gates placed after the model load | Failure costs the allocation it was meant to protect |
| Guarding on imports the job never uses | Aborts jobs that would have succeeded |
| Submitting the full array first | The whole budget rides on untested machinery |
| Writing the stage-2 trigger after seeing stage 1 | You will rationalise whatever happened |
| A one-task smoke for a collision property | One task cannot collide; use two |
| Hand-writing N unique output tags | One typo silently destroys hours, undetectably |
| `eval "$(cmd)"` for derived config | Exit status discarded; a refusal becomes a silent no-op |
| Trusting a status file's job states | Rows are written at submit time and never revisited |
| Treating `COMPLETED` as "the result is right" | Exit 0 says nothing about what was measured |

## Red flags — stop and check

- About to run a loop, a parse, or a plot over ssh → that is a login node
- About to set `--time` from a number you did not measure at this configuration
- About to apply one unit's cost to unmeasured units → name the most expensive one, or measure per stratum
- About to carry a rate from another cluster or your laptop → an estimate, not a calibration
- Two measurements agree and you call it confirmation → they corroborate each other, not the machine you will use
- Writing a `wait until ready` loop with no timeout
- Writing a `pgrep -f`/`ps | grep` poll whose pattern matches the polling shell itself
- About to submit >2 tasks of untested machinery → smoke one first
- Cannot answer "if this dies at 90%, what is on disk?"
- About to hand-write a third unique output tag
- A required capability is missing and you consider continuing → **abort; a wrong result is worse than no result**
- Justifying staying on a login node with an unmeasured runtime → the estimate you are least entitled to trust
- About to describe a stage-1 number as a finding rather than a check → it is the cheapest unit
- Writing "early results suggest" about anything less than the full grid
- About to report progress from a status file you have not re-verified this session
- About to call a job successful because it exited 0

Measured (S1-S3, `_evals/process-skills/`): this ~220-line text against the earlier 418-line one, 21 decision scenarios x 6 runs: same decisions within the pre-registered margin (pooled pass 105 vs 111/126 over the three process skills), 11% cheaper. Cases moved to `reference/`.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in research →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.