Skip to content
System Status: All systems are operational • Services are available and operational.
Click for detailed status

Resubmit Slurm jobs

Motivation

Imagine submitting 1'000 jobs. Most need only 1 GiB of memory, but a few require 10 GiB. If you cannot predict which jobs need more memory, you have two choices: request 10 GiB for every job and waste resources on most of them, or request 1 GiB and risk having some jobs fail.

This tutorial shows how to avoid that trade-off by automatically retrying jobs that run out of memory, using a larger memory allocation.

The problem

Typically simulations that can adjust their mesh/grid automatically show such memory behaviour. A good (a priori) mesh/grid usually allows most simulations of a parameter sweep to keep the mesh/grid as is. But some parameter configurations require the mesh/grid to be adjusted. This adjustment/remeshing/regridding causes the program to suddenly need a lot more memory. Because it is often unpredictable which parameter configurations will lead to a mesh/grid adjustment, it's hard to tailor a slim memory envelope.

For the sake of simplicity and without loss of generality, we assume our program usually requires 1 GiB of memory, but sometimes it needs 10 GiB. Requesting 10 GiB for every job wastes resources (9 GiB are reserved but unused), which brings down Slurm priority and increases queue waiting times. Requesting only 1 GiB, on the other hand, causes memory-intensive jobs to fail.

A solution is to automatically retry jobs that run out of memory with a larger memory allocation, as soon as they fail.

This tutorial demonstrates how to implement this using Slurm job arrays and job dependencies. Each array task is initially submitted with a 1 GiB memory allocation. When a task starts, it submits a lightweight monitoring job for itself. If the task runs out of memory, the monitoring job automatically resubmits it with a 10 GiB allocation.

The solution

The solution consists of three scripts:

  • job.sh: Submits a monitoring job for itself when it starts (on the initial run), then runs the actual simulation.
  • monitor.sh: Checks the final state of an array task and resubmits it if it ran out of memory.
  • submit.sh: Submits the initial job array.

The workflow is:

  1. Submit the entire job array with the initial CPU count and low --mem-per-cpu allocation, passing the paths to job.sh and monitor.sh along with the high-memory value.
  2. When each simulation task starts, job.sh submits a monitoring job for itself with --dependency="afternotok:<job_id>_<task_id>" and --kill-on-invalid-dep=yes, then launches the simulation.
  3. If a simulation task fails (non-zero exit code, OOM, etc.), its corresponding monitoring job becomes eligible to run. If the simulation task succeeds, the afternotok dependency can never be satisfied and --kill-on-invalid-dep=yes causes Slurm to cancel the monitoring job automatically without running it.
  4. The monitoring job checks the simulation task's final state using sacct.
  5. If the task terminated with OUT_OF_MEMORY, it is resubmitted with the same CPU count and the higher --mem-per-cpu allocation (and without passing a monitoring script, so the retry does not spawn another monitor).
  6. Otherwise, no further action is taken.

Because each monitoring job is only created when its simulation task starts and depends only on that task, failed tasks can be retried while other tasks in the original array are still running, successful tasks never consume resources for a monitoring job, and pending tasks do not clutter the queue with pending monitors.

The job script

Create job.sh containing the monitoring submission and the actual computation:

#!/bin/bash
#SBATCH --job-name=simulation
#SBATCH --output=logs/simulation_%A_%a.out
#SBATCH --error=logs/simulation_%A_%a.err

JOB_SCRIPT=${1:-}
MONITOR_SCRIPT=${2:-}
HIGH_MEM_PER_CPU=${3:-}

echo "Running task $SLURM_ARRAY_TASK_ID on $SLURM_CPUS_PER_TASK CPU(s)"

# Submit a monitoring job for this task if a monitor script was provided.
# On high-memory retries, these arguments are omitted so no second monitor is submitted.
if [[ -n "$JOB_SCRIPT" && -n "$MONITOR_SCRIPT" && -n "$HIGH_MEM_PER_CPU" ]]; then
    MONITOR_JOB_ID=$(sbatch --parsable \
        --chdir="$SLURM_SUBMIT_DIR" \
        --dependency="afternotok:${SLURM_ARRAY_JOB_ID}_${SLURM_ARRAY_TASK_ID}" \
        --kill-on-invalid-dep=yes \
        "$MONITOR_SCRIPT" \
        "$SLURM_ARRAY_JOB_ID" \
        "$SLURM_ARRAY_TASK_ID" \
        "$JOB_SCRIPT" \
        "$SLURM_CPUS_PER_TASK" \
        "$HIGH_MEM_PER_CPU")

    MONITOR_JOB_ID=${MONITOR_JOB_ID%%;*}
    echo "Submitted monitoring job: $MONITOR_JOB_ID"
fi

# Run the actual computation
# TODO: Replace "simulation" with your program.
srun ./simulation "$SLURM_ARRAY_TASK_ID"

Adjust ./simulation to your program and its needs.

Both --cpus-per-task and --mem-per-cpu are deliberately not specified in the script. They are supplied by submit.sh (and by monitor.sh on retry).

Note that JOB_SCRIPT is passed explicitly as an argument rather than using $0, because Slurm copies batch scripts to a temporary spool directory before executing them. Passing the original path ensures monitor.sh can resubmit the script after the initial job finishes.

The monitoring script

Create monitor.sh:

#!/bin/bash
#SBATCH --job-name=mem-monitor
#SBATCH --time=00:10:00
#SBATCH --cpus-per-task=1
#SBATCH --mem-per-cpu=256M
#SBATCH --output=logs/monitor_%j.out
#SBATCH --oversubscribe

ARRAY_JOB_ID=$1
TASK_ID=$2
JOB_SCRIPT=$3
CPUS_PER_TASK=$4
HIGH_MEM_PER_CPU=$5

JOB_ID="${ARRAY_JOB_ID}_${TASK_ID}"

echo "Monitoring array task $JOB_ID"

# Wait for the allocation to reach a terminal state in accounting.
STATE=""
for i in {1..60}; do
    STATE=$(sacct -X -n -P -j "$JOB_ID" \
        --format=State | head -n 1 | tr -d '[:space:]')

    if [[ -n "$STATE" && "$STATE" != "PENDING" && "$STATE" != "RUNNING" && "$STATE" != "COMPLETING" ]]; then
        break
    fi

    STATE=""
    sleep 5
done

if [[ -z "$STATE" ]]; then
    echo "ERROR: Could not retrieve final state for $JOB_ID"
    exit 1
fi

echo "Task $JOB_ID finished with state: $STATE"

# Retry only if the allocation or any of its job steps ran out of memory.
if sacct -n -P -j "$JOB_ID" --format=State | grep -q "OUT_OF_MEMORY"; then
    echo "Resubmitting task $TASK_ID with $CPUS_PER_TASK CPU(s) and $HIGH_MEM_PER_CPU per CPU."

    RETRY_JOB_ID=$(sbatch --parsable \
        --job-name=simulation-high-mem \
        --output="logs/simulation-high-mem_%A_%a.out" \
        --error="logs/simulation-high-mem_%A_%a.err" \
        --array="$TASK_ID" \
        --cpus-per-task="$CPUS_PER_TASK" \
        --mem-per-cpu="$HIGH_MEM_PER_CPU" \
        "$JOB_SCRIPT")

    RETRY_JOB_ID=${RETRY_JOB_ID%%;*}
    echo "Submitted retry: $RETRY_JOB_ID"
else
    echo "No retry necessary."
fi

The polling loop uses sacct -X to wait until the allocation itself reaches a terminal state. Once finished, the script checks all accounting records for $JOB_ID (without -X) so that out-of-memory kills occurring inside individual srun job steps are also caught. Because monitor.sh resubmits "$JOB_SCRIPT" without any extra arguments, the retried job skips submitting another monitor.

The submission script

Create submit.sh:

#!/bin/bash

# TODO: Configure this to the needs of your program
###################################################
FIRST=0
LAST=999

CPUS_PER_TASK=1

LOW_MEM_PER_CPU=1G
HIGH_MEM_PER_CPU=10G
###################################################

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)

JOB_SCRIPT="$SCRIPT_DIR/job.sh"
MONITOR_SCRIPT="$SCRIPT_DIR/monitor.sh"

# Create logs directory
mkdir -p "$SCRIPT_DIR/logs"

# Submit initial low-memory job array.
# Each task will submit its own monitoring job when it starts.
ARRAY_JOB_ID=$(sbatch --parsable \
    --chdir="$SCRIPT_DIR" \
    --array="$FIRST-$LAST" \
    --cpus-per-task="$CPUS_PER_TASK" \
    --mem-per-cpu="$LOW_MEM_PER_CPU" \
    "$JOB_SCRIPT" \
    "$JOB_SCRIPT" \
    "$MONITOR_SCRIPT" \
    "$HIGH_MEM_PER_CPU")

# Remove everything from the first semicolon (;) onwards
ARRAY_JOB_ID=${ARRAY_JOB_ID%%;*}

echo "Submitted initial job array: $ARRAY_JOB_ID"

Adjust FIRST and LAST to match the desired array indices. Adjust CPUS_PER_TASK, LOW_MEM_PER_CPU, and HIGH_MEM_PER_CPU to match your program's CPU and memory requirements. Remember that with --mem-per-cpu, the total memory allocated to each task is CPUS_PER_TASK × MEM_PER_CPU.

Submit the workflow

Make the scripts executable:

chmod +x job.sh monitor.sh submit.sh

Submit the workflow:

./submit.sh

This submits:

  • 1'000 initial tasks with CPUS_PER_TASK CPU cores and LOW_MEM_PER_CPU memory per CPU core each.
  • As each task starts running, it dynamically submits one monitoring job waiting for that task to fail. Because of --dependency="afternotok:<job_id>_<task_id>" and --kill-on-invalid-dep=yes, Slurm automatically cancels the monitoring job if the initial task succeeds, so successful jobs do not require running an additional job.

The monitoring jobs always run on a single CPU with only 256 MB of memory and up to 10 minutes of runtime. They do not consume compute resources while waiting for their dependencies.

Monitor the jobs

Check the jobs in the queue (this shows the initial tasks, active monitoring jobs, and any high-memory retries):

squeue -u "$USER"

Inspect the accounting information for the initial array:

sacct -j ARRAY_JOB_ID --format=JobID,State,ExitCode,AllocCPUS,ReqMem,MaxRSS

The output files are stored in the logs directory:

logs/
├── simulation_12345_0.out
├── simulation_12345_0.err
├── simulation_12345_1.out
├── simulation_12345_1.err
├── monitor_12346.out
├── simulation-high-mem_12347_1.out
├── simulation-high-mem_12347_1.err
└── ...

Testing the workflow

Before running this setup on a large production sweep, you can test the entire workflow end-to-end with a small 10-task array using a lightweight dummy simulation script. In this test, even-numbered tasks allocate a small amount of memory and succeed immediately, while odd-numbered tasks intentionally exceed the initial memory limit, trigger OUT_OF_MEMORY, and succeed on retry.

1. Create a test simulation script

Save the following Python script as simulation in the same directory as job.sh:

#!/usr/bin/env python3
import sys
import time

if len(sys.argv) < 2:
    print("Usage: ./simulation <task_id>", file=sys.stderr)
    sys.exit(1)

task_id = int(sys.argv[1])

# Even tasks: 200 MiB (succeeds on low-memory run)
# Odd tasks:  2048 MiB / 2 GiB (OOMs on 1 GiB run, succeeds on 4 GiB retry)
if task_id % 2 == 0:
    target_mib = 200
else:
    target_mib = 2048

print(f"Task {task_id}: allocating {target_mib} MiB of RAM...", flush=True)

# Write non-zero bytes so the OS commits physical pages (RSS) immediately
block = b"\x01" * (target_mib * 1024 * 1024)

# Hold the memory briefly so Slurm's accounting/OOM killer registers it
time.sleep(5)

print(f"Task {task_id}: finished successfully (allocated {len(block) // (1024 * 1024)} MiB).", flush=True)

2. Configure submit.sh for the test

Temporarily adjust the top variables in submit.sh to submit 10 tasks (0–9) with a 1 GiB initial limit and a 4 GiB retry limit (here using 2 CPUs per task):

FIRST=0
LAST=9

CPUS_PER_TASK=2
LOW_MEM_PER_CPU=512M   # 1 GiB total -> tasks 0,2,4,6,8 pass; 1,3,5,7,9 OOM
HIGH_MEM_PER_CPU=2G    # 4 GiB total -> retried odd tasks pass

3. Run and verify

Make simulation executable and submit the test workflow:

chmod +x simulation job.sh monitor.sh submit.sh
./submit.sh

What to expect:

  • Even tasks (0, 2, 4, 6, 8): Complete on the first run with state COMPLETED, writing to logs/simulation_<jobid>_<taskid>.out. Their monitoring jobs are automatically cancelled by Slurm (no monitor_*.out file is created).
  • Odd tasks (1, 3, 5, 7, 9): Terminate on the first run with state OUT_OF_MEMORY. Their monitoring jobs run, log Resubmitting task ... in logs/monitor_*.out, and submit simulation-high-mem retry jobs that finish with state COMPLETED and write to logs/simulation-high-mem_<retry_jobid>_<taskid>.out.

Important considerations

Only OUT_OF_MEMORY failures are retried

The monitoring script retries tasks only if Slurm reports OUT_OF_MEMORY for the allocation or any of its job steps.

Other failures, such as segmentation faults, invalid input, or timeouts, are not retried.

High-memory jobs are not retried again

This implementation has only two memory classes. Because monitor.sh resubmits job.sh without the monitoring arguments, a high-memory retry does not spawn another monitoring job and will not be resubmitted if it also runs out of memory.

Accounting delay

The monitoring job starts after the original task terminates with a non-OK state, but accounting information might not be finalized immediately. The script therefore polls sacct for up to 5 minutes (well within its 10-minute wall-time limit) until a terminal state is recorded.

If accounting information is still unavailable, the monitor exits with an error rather than silently assuming that the task succeeded.

Summary

This approach allows jobs to request only the memory they actually need in the common case, while automatically accommodating memory-intensive tasks.

The main advantages are:

  • No need to know the memory requirements of individual tasks beforehand.
  • No need to wait for the entire array to finish before retrying failed tasks.
  • Successful tasks do not run a monitoring job, since --dependency="afternotok:<job_id>_<task_id>" with --kill-on-invalid-dep=yes causes Slurm to cancel their monitors automatically.
  • No changes to the actual simulation program.
  • Original array task IDs and input mappings are preserved.
  • Only genuine out-of-memory failures are retried.

The approach can be extended with additional memory classes or more sophisticated retry policies if required.

Happy computing!