Skip to content
Projects

Run directories

Download notebookView on GitHubRun when the site was built.

A parameter scan is a set of directories, one per run, that all ask for the same resources and run the same commands. RunSet submits such a set as one SLURM job array, remembers in each directory which task of which job it was given to, and tells where every run stands. Calling submit() again only sends what is neither finished nor in the queue, so the runs that failed or ran out of time go back with the call that started the set.

Demo mode — if sbatch is not on your PATH (when the docs are built, or on a laptop), the cell below replaces the SLURM commands by a small stand-in that “runs” every submitted task at once and lets one of them fail the first time. On a cluster the stand-in is skipped and the jobs are real.

# -- Demo mode ----------------------------------------------------------------
# Stands in for sbatch, sacct, squeue and scancel when there is no SLURM.
# Remove this cell on a cluster.
import re
import shutil
from pathlib import Path
from unittest.mock import MagicMock, patch
from slurm_script_generator.squeue import _expand_task_spec
if shutil.which("sbatch"):
print("SLURM detected: the jobs below are real.")
else:
_states = {} # (job, task) -> state
_jobs = [4241]
def _answer(stdout="", returncode=0):
result = MagicMock()
result.stdout, result.stderr, result.returncode = stdout, "", returncode
return result
def _fake_slurm(cmd, **kwargs):
if cmd[0] == "sbatch":
text = Path(cmd[1]).read_text()
_jobs.append(_jobs[-1] + 1)
listed = text.split("RUN_DIRECTORIES=(")[1].split(")")[0].split()
spec = re.search(r"--array=(\S+)", text).group(1)
for task in _expand_task_spec(spec):
# the first job "loses" its second task; everything else finishes
failed = len(_jobs) == 2 and task == 2
_states[(_jobs[-1], task)] = "TIMEOUT" if failed else "COMPLETED"
if not failed:
Path(listed[task - 1].strip("'"), "result.txt").write_text("42\n")
return _answer(f"Submitted batch job {_jobs[-1]}\n")
if cmd[0] == "sacct":
return _answer(
"".join(f"{j}_{t}|{s}\n" for (j, t), s in sorted(_states.items()))
)
return _answer(returncode=1) # squeue: nothing is queued any more
patch("subprocess.run", side_effect=_fake_slurm).start()
patch("shutil.which", side_effect=lambda name: f"/usr/bin/{name}").start()
print("No SLURM here: using the stand-in.")
No SLURM here: using the stand-in.

Four run directories, each with its own input file. In a real scan these are written by whatever sets up the cases.

import tempfile
scan = Path(tempfile.mkdtemp()) / "scan"
directories = []
for pressure in (0.1, 0.3, 1.0, 3.0):
directory = scan / f"p_{pressure:g}"
directory.mkdir(parents=True)
(directory / "input.txt").write_text(f"pressure = {pressure}\n")
directories.append(directory)
[d.name for d in directories]
['p_0.1', 'p_0.3', 'p_1', 'p_3']

RunSet takes the directories, a SlurmScript with the resources and the commands of one run, and a function that says whether a run is done. The commands are executed inside the run directory. The order of the directories fixes the task ID of each, counted from 1.

from slurm_script_generator import RunSet, SlurmScript
script = SlurmScript(
nodes=1,
ntasks_per_node=16,
time="02:00:00",
custom_commands=["srun ./solver input.txt > result.txt"],
)
def is_finished(directory):
return (directory / "result.txt").exists()
runs = RunSet(directories, script, name="scan", is_finished=is_finished)
print(runs)
task run state job
1 p_0.1 new -
2 p_0.3 new -
3 p_1 new -
4 p_3 new -
4 runs: 4 new

Without is_finished a run counts as finished when SLURM reports its task as COMPLETED, which needs accounting (sacct) on the cluster.

array_script() shows what will be submitted: the script of the set with --array, a job name and an output file, and in front of the commands the list of all run directories and a cd into the one of the task. throttle limits how many tasks run at the same time.

print(runs.array_script(throttle=2).generate_script())
#!/bin/bash
########################################################
# Pragmas for Job Config #
#SBATCH --job-name=scan # name of job
# #
# Pragmas for Time And Priority #
#SBATCH --time=02:00:00 # time limit
# #
# Pragmas for Io And Directory #
#SBATCH --output=/tmp/tmp3ax41ilh/scan/scan-%A_%a.out # File to redirect output (%%x=jobname, %%j=jobid)
# #
# Pragmas for Dependencies And Arrays #
#SBATCH --array=1-4%2 # submit a job array
# #
# Pragmas for Core Node And Task Allocation #
#SBATCH --nodes=1 # number of nodes on which to run
#SBATCH --ntasks-per-node=16 # number of tasks to invoke on each node
########################################################
RUN_DIRECTORIES=(
/tmp/tmp3ax41ilh/scan/p_0.1
/tmp/tmp3ax41ilh/scan/p_0.3
/tmp/tmp3ax41ilh/scan/p_1
/tmp/tmp3ax41ilh/scan/p_3
)
cd "${RUN_DIRECTORIES[$((SLURM_ARRAY_TASK_ID - 1))]}" || exit 1
exec > "slurm-${SLURM_ARRAY_JOB_ID}_${SLURM_ARRAY_TASK_ID}.out" 2>&1
srun ./solver input.txt > result.txt

The list of directories is part of the script, and SLURM copies the script when the job is submitted. A task that starts hours later still finds its directory, whatever has happened to the set in the meantime.

submit() writes the script to scan/scan.sh, calls sbatch once and puts a small file slurm_run.json with the job and task ID into every run directory it submitted.

job_id = runs.submit(throttle=2)
job_id
4242
print((directories[0] / "slurm_run.json").read_text())
{"job_id": 4242, "task": 1, "submitted": "2026-11-29T10:16:16"}

print(runs) asks SLURM once for all tasks (one sacct and one squeue call) and combines the answer with is_finished. status() gives the same as a list of Run objects, counts() as a dictionary.

print(runs)
task run state job
1 p_0.1 finished 4242_1
2 p_0.3 TIMEOUT 4242_2
3 p_1 finished 4242_3
4 p_3 finished 4242_4
4 runs: 1 TIMEOUT, 3 finished
[(run.directory.name, run.state, run.needs_submit) for run in runs.status()]
[('p_0.1', 'finished', False),
('p_0.3', 'TIMEOUT', True),
('p_1', 'finished', False),
('p_3', 'finished', False)]

A run shows finished, new (never submitted), the SLURM state of its task (PENDING, RUNNING, FAILED, TIMEOUT, …), ended (it left the queue and there is no accounting to say how) or unknown (SLURM cannot be asked from here).

One task ran out of time. The same call sends that one back, and only that one: the array is now --array=2.

runs.submit(throttle=2)
print(runs)
task run state job
1 p_0.1 finished 4242_1
2 p_0.3 finished 4243_2
3 p_1 finished 4242_3
4 p_3 finished 4242_4
4 runs: 4 finished
runs.submit() is None # nothing left to do
True
  • submit(retry=False) only sends runs that were never submitted.
  • submit(force=True) also sends finished runs again; runs that are pending or running are never submitted twice.
  • cancel() cancels the tasks of the set that are still in the queue.

An array has one resource request and one time limit. If some runs of a campaign are much longer than others, make one RunSet per group, each with its own script, so that the short ones do not wait behind a request they do not need. The states of the tasks of any array are also available directly:

from slurm_script_generator import task_states
task_states(job_id)
{4242: {1: 'COMPLETED', 2: 'TIMEOUT', 3: 'COMPLETED', 4: 'COMPLETED'}}