Learning Slurm on one machine: a four-node practice cluster in Docker

Updated 2026-10-24. The DDP batch script in section 6 now includes the two lines the repository’s copy has: the echo that prints the first line of the output shown, and the move of an earlier checkpoint, without which a second submission resumes from the finished checkpoint instead of starting over.

Most GPU training clusters are run by Slurm. If you have never used it, the first hours on a real cluster go to learning its commands, and on a rented cluster those hours are billed. None of that learning needs a GPU. This post builds a small Slurm cluster from Docker containers on one machine, so you can practise everything except the GPUs themselves.

By the end you will have:

  1. a cluster with one controller and four compute nodes, each claiming four (fake) GPUs;
  2. submitted, watched and cancelled jobs, and seen a time limit and a priority at work;
  3. run a PyTorch DDP job across two nodes, launched by Slurm;
  4. stopped a node in the middle of that job and watched Slurm put the job back in the queue and restart it from its last checkpoint.

What you need: Linux with Docker (I used Docker 29.1.3 on Ubuntu, 16 CPU threads, 62 GB of memory) and basic familiarity with Docker and PyTorch. The cluster runs on CPUs only, so it teaches how Slurm schedules and launches work; how fast GPUs talk to each other across nodes is a question for real hardware.

1. What a Slurm cluster is made of

A Slurm cluster is a handful of programs that talk to each other over the network. Four matter here:

program runs on what it does
slurmctld one controller machine the scheduler: keeps the queue, decides which job runs on which nodes
slurmd every compute node starts and stops the job’s processes on that node, reports back to the controller
slurmdbd one machine, with a database stores the history of every job, so you can ask afterwards what ran and how it ended
munged every machine proves to the others which user sent each request; every machine holds the same secret key

And six words you will meet in every command:

word meaning
node one machine that runs jobs
partition a named group of nodes with its own rules (time limit, priority); a queue, in effect
job one request: “give me these resources and run this”
job step one launch of processes inside a job; each srun starts one, and the batch script itself runs as one
task one process of a step; a step with four tasks on each of two nodes has eight processes
GRES “generic resource”: anything countable besides CPUs and memory, here GPUs

In the practice cluster each of these programs gets its own container:

slurmctld, slurmdbd with MariaDB and four compute containers c1 to c4 on one Docker network, the controller and compute nodes sharing one directory for logs and checkpoints

Seven containers in total: the controller, the accounting daemon, its MariaDB database, and four compute nodes c1 to c4. The four Slurm programs’ containers run munged (the database does not). A directory on the host is mounted as /shared in the controller and in the four compute nodes; it plays the part of the shared file system that a real cluster has, and it is where job output and checkpoints go.

2. Build the cluster

The files below are abridged to the lines that matter.

One image for every role

All Slurm containers use the same image. It is Ubuntu 24.04 with Slurm from the distribution’s packages (version 23.11.4), munge, and a CPU-only PyTorch for the training example:

1
2
3
4
5
6
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y --no-install-recommends \
slurm-wlm slurmdbd slurm-client munge mariadb-client python3 python3-venv
RUN python3 -m venv /opt/venv && /opt/venv/bin/pip install \
--index-url https://download.pytorch.org/whl/cpu torch
RUN userdel -r ubuntu; useradd -m -u 1000 -s /bin/bash lab # ubuntu:24.04 already uses uid 1000

The user lab submits the jobs. It has the same user id as my account on the host, so files that jobs write into /shared can be read and deleted from the host without sudo.

An environment variable ROLE tells each container which program to start. The start script does three things for every role: installs the shared munge key (the same secret file on every machine; without it the programs reject each other), copies the configuration into /etc/slurm, and starts the program for its role.

Describe the cluster: slurm.conf

slurm.conf is the one file that describes the whole cluster, and every machine reads the same copy. These are the lines that matter for a first cluster:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ClusterName=lab
SlurmctldHost=slurmctld # where the controller runs (a container name)
AccountingStorageType=accounting_storage/slurmdbd
AccountingStorageHost=slurmdbd # where the accounting daemon runs

# what a job may share: cores, memory and GPUs are handed out separately, not whole nodes
SelectType=select/cons_tres
SelectTypeParameters=CR_Core_Memory
DefMemPerCPU=1000 # memory a job gets per CPU if it does not ask (without it: the whole node)
GresTypes=gpu # this cluster has a countable resource called gpu

# how processes are tracked; cgroup-based choices do not work in an unprivileged container (section 9)
ProctrackType=proctrack/linuxproc
TaskPlugin=task/none

PriorityType=priority/multifactor # priority = weighted sum of factors (section 5); the default is first-come
PreemptType=preempt/partition_prio # a higher-tier partition may push out jobs (section 8)
SlurmdTimeout=30 # a node silent for 30 s counts as dead (default 300)
ReturnToService=2 # a dead node that registers again is put back in use automatically
JobRequeue=1 # batch jobs may be requeued after a node failure (section 7)
KillWait=10 # seconds between SIGTERM and SIGKILL when a job is ended

NodeName=c[1-4] CPUs=4 RealMemory=4000 Gres=gpu:4 State=UNKNOWN
PartitionName=main Nodes=c[1-4] Default=YES MaxTime=02:00:00 PriorityTier=1
PartitionName=low Nodes=c[1-4] MaxTime=02:00:00 PriorityTier=1 PreemptMode=REQUEUE
PartitionName=high Nodes=c[1-4] MaxTime=02:00:00 PriorityTier=2 PreemptMode=OFF

NodeName=c[1-4] declares four nodes at once; c[1-4] is Slurm’s shorthand for c1,c2,c3,c4, and you will see it in every command’s output. Each node claims 4 CPUs, 4000 MB of memory and 4 GPUs. Docker limits each compute container to 4 CPUs to match. The three partitions all contain the same four nodes; main is the default, and low and high are only used in the preemption example at the end.

DefMemPerCPU deserves a word. With CR_Core_Memory, memory is a resource that jobs reserve just like cores. A job that does not say how much it needs (--mem) gets the default, and if no default is set, it reserves the whole node’s memory. Then a one-CPU job blocks a four-CPU node by itself, which is easy to mistake for a shortage of CPUs or GPUs.

Fake GPUs: gres.conf

Gres=gpu:4 above says each node has four GPUs. A second file, gres.conf, tells slurmd which device files those GPUs are. The containers have no GPUs, so I point it at four device files that exist everywhere:

1
NodeName=c[1-4] Name=gpu File=/dev/null,/dev/zero,/dev/full,/dev/random

Slurm does not open them. It only counts them, schedules jobs against the count, and tells each job which of the four it was given. That is enough to practise asking for GPUs.

Compose file and first start

The compose file has one service per container. The parts worth seeing are a compute node and the shared directory:

1
2
3
4
5
6
7
8
9
c1:
build: . # the image from the Dockerfile above
image: slurm-lab:local
hostname: c1
environment: { ROLE: slurmd }
cpus: 4
volumes:
- ./config:/etc/slurm-lab:ro # slurm.conf, gres.conf, munge key
- ./data/shared:/shared # the "shared file system"

Two things must exist before the first start. The munge key is any 1024 random bytes, the same file for every container. The shared directory must belong to uid 1000, the user lab inside the containers, or jobs cannot write their output there (section 9):

1
2
$ dd if=/dev/urandom of=config/munge.key bs=1024 count=1 && chmod 600 config/munge.key
$ mkdir -p data/shared/logs data/shared/ckpt # owned by my user, uid 1000

Then start everything and ask the controller what it sees. sinfo lists partitions and the state of their nodes:

1
2
3
4
5
6
$ docker compose up -d --build
$ docker exec slurmctld sinfo
PARTITION AVAIL TIMELIMIT NODES STATE NODELIST
main* up 2:00:00 4 idle c[1-4]
low up 2:00:00 4 idle c[1-4]
high up 2:00:00 4 idle c[1-4]

Four idle nodes in each partition means every slurmd has registered with the controller and is waiting for work. The * after main marks the default partition. sinfo -N shows one line per node instead, with its CPUs, memory, GPUs and partition:

1
2
3
4
5
6
7
$ docker exec slurmctld sinfo -N -o "%N %c %m %G %t %P"
NODELIST CPUS MEMORY GRES STATE PARTITION
c1 4 4000 gpu:4 idle main*
c1 4 4000 gpu:4 idle low
c1 4 4000 gpu:4 idle high
c2 4 4000 gpu:4 idle main*
...

Each node appears once per partition it belongs to, so c1 is listed three times.

From here on, every command runs inside the controller container as user lab (docker exec -it -u lab -w /shared/logs slurmctld bash), the way you would log in to a cluster’s login node.

3. Your first jobs

There are two ways to run something:

  • srun runs a command on the cluster and waits for it, printing its output in your terminal. Used on its own, it first creates a job and waits in the queue like any other job; inside a batch script it starts processes on the nodes the job already has. Good for quick checks.
  • sbatch puts a script in the queue and returns at once with a job id. The script runs when resources free up, and its output goes to a file (slurm-<job id>.out in the directory you submitted from). This is how training jobs are run.

sbatch --wrap turns a one-line command into a script, which is handy for practice. Submit, look at the queue, cancel:

1
2
3
4
5
6
$ sbatch --parsable -t 5 --wrap 'hostname; sleep 60'     # --parsable prints only the job id
10
$ squeue
JOBID PARTITION NAME USER ST TIME NODES NODELIST(REASON)
10 main wrap lab R 0:03 1 c1
$ scancel 10

In squeue, ST is the state: R running, PD pending (waiting). For a running job the last column lists its nodes; for a pending job it gives the reason it is waiting, which section 4 uses. --wrap jobs are all named wrap.

sacct reads the job history from the database, so it also shows jobs that have finished:

1
2
3
4
$ sacct -j 10 -X --format=JobID,JobName,State,ExitCode,NodeList
JobID JobName State ExitCode NodeList
------------ ---------- ---------- -------- ---------------
10 wrap CANCELLED+ 0:0 c1

CANCELLED+ is CANCELLED by <user id>, cut to fit the column; a + at the end of any sacct field means it was cut. ExitCode 0:0 is the exit status, then the signal that ended the job.

Time limits are enforced. -t 5 above asked for five minutes. A job that runs past its limit is killed. Here a job that sleeps 90 seconds was given one minute:

1
2
3
4
5
$ sbatch --time=1 --wrap 'sleep 90'
$ sacct -j 11 -X --format=JobID,State,Elapsed,Timelimit
JobID State Elapsed Timelimit
------------ ---------- ---------- ----------
11 TIMEOUT 00:01:27 00:01:00

It ran 1 minute 27 seconds, not exactly one minute. The controller checks time limits about every 30 seconds, so a job can overrun by up to that much. It then sends the job SIGTERM, and SIGKILL KillWait seconds (10 here) later if the job is still alive; sleep exits at the first signal. On a real cluster the lesson is: ask for a little more time than you need, and save checkpoints, or a job that overruns loses its work.

4. Asking for GPUs

A job asks for GPUs with --gres=gpu:N, meaning N GPUs on each of its nodes. Slurm tells the job’s processes which GPUs they got through CUDA_VISIBLE_DEVICES, the variable PyTorch and every CUDA program read:

1
2
$ srun --gres=gpu:4 -N1 bash -c 'echo "$(hostname): CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"'
c1: CUDA_VISIBLE_DEVICES=0,1,2,3

Ask for more than any node has, and Slurm refuses immediately instead of queueing a job that can never run:

1
2
$ srun --gres=gpu:5 -N1 hostname
srun: error: Unable to allocate resources: Requested node configuration is not available

GPUs are not shared between jobs. Two jobs that each want 3 GPUs on node c1 (-w c1 pins a job to a node) cannot run there together, because 3 + 3 is more than 4, so the second one waits. Two jobs that each want 2 GPUs fit, and run side by side:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ sbatch --gres=gpu:3 -w c1 -t 2 --wrap 'sleep 30'
Submitted batch job 26
$ sbatch --gres=gpu:3 -w c1 -t 2 --wrap 'sleep 5'
Submitted batch job 27
$ squeue -o "%.8i %.8T %.6b %R"
JOBID STATE TRES_P NODELIST(REASON)
27 PENDING gres/g (Resources)
26 RUNNING gres/g c1
$ scancel 26 27
$ sbatch --gres=gpu:2 -w c1 -t 2 --wrap 'sleep 30'
Submitted batch job 28
$ sbatch --gres=gpu:2 -w c1 -t 2 --wrap 'sleep 30'
Submitted batch job 29
$ squeue -o "%.8i %.8T %.6b %R"
JOBID STATE TRES_P NODELIST(REASON)
28 RUNNING gres/g c1
29 RUNNING gres/g c1

(Resources) in the reason column means the job is waiting because the resources it asked for are in use; it starts when they are released. This test needs the DefMemPerCPU line from section 2: without it, the first job reserves all of c1’s memory, and the second job waits for memory, whatever it asks of the GPUs.

5. Who goes first: priority

When several jobs are waiting in the same partition, Slurm starts the one with the highest priority number first. (Two refinements: a partition with a higher PriorityTier goes before all others, and the backfill scheduler may start a smaller job early if that does not delay the job at the head of the line.) The number is a weighted sum of factors set in slurm.conf, such as how long the job has waited, how much the user has used recently, the job’s size and its partition. A user can lower their own job’s priority with --nice.

To see it, I filled the cluster with one job, then queued two more that each need all four nodes: first one with --nice=5000, then one without:

1
2
3
4
5
$ squeue -o "%.8i %.10j %.8T %.10Q %.6p %r" --sort=-p
JOBID NAME STATE PRIORITY PRIORI REASON
12 wrap RUNNING 11625 0.0000 None
14 nice0 PENDING 11625 0.0000 Resources
13 nice5000 PENDING 6625 0.0000 Priority

Job 14 was submitted later, but it is first in line: its priority is 11625 against 6625. The difference is exactly the 5000 that --nice subtracted. The reasons say it too: job 14 waits only for Resources, while job 13 waits for Priority, meaning a job ahead of it must start first. The PRIORI column is the same priority scaled to between 0 and 1, which rounds to zero at these values. sprio -l breaks each number into its factors, which is the place to look when you wonder why a job is not starting.

6. A two-node DDP job

This is the job the cluster was built for: PyTorch DistributedDataParallel (DDP) with four processes on each of two nodes, eight in total. On GPUs it would use the NCCL backend; here it uses gloo, PyTorch’s CPU backend. The way Slurm launches it is the same either way.

The batch script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#SBATCH --job-name=ddp-cpu
#SBATCH --nodes=2 # two machines
#SBATCH --ntasks-per-node=4 # four processes on each: 8 ranks in total
#SBATCH --cpus-per-task=1
#SBATCH --gres=gpu:4 # four GPUs per node (one per process on a GPU cluster)
#SBATCH --time=00:10:00
#SBATCH --output=/shared/logs/%x-%j.out # %x = job name, %j = job id

export MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1)
export MASTER_PORT=29500
echo "nodes: $SLURM_JOB_NODELIST master: $MASTER_ADDR tasks: $SLURM_NTASKS"
# start from step 0, not from the checkpoint an earlier submission left
[ -e /shared/ckpt/ddp-cpu.pt ] && mv /shared/ckpt/ddp-cpu.pt /shared/ckpt/ddp-cpu.pt.prev
srun /opt/venv/bin/python /home/lab/exercises/ddp_train.py --steps 200 --ckpt /shared/ckpt/ddp-cpu.pt

The scripts live in an exercises/ directory on the host that compose mounts at /home/lab/exercises in every Slurm container, so every node sees the same files. Save the batch script there as 02-ddp.sbatch and submit it from the controller with sbatch /home/lab/exercises/02-ddp.sbatch.

Line by line:

  • The #SBATCH lines are options to sbatch, written into the script so it is self-contained.
  • The script itself runs once, on the first node of the job. SLURM_JOB_NODELIST holds the job’s nodes in the short form (c[1-2]); scontrol show hostnames expands it to one name per line, and the first name becomes MASTER_ADDR, the address where all ranks meet to set up communication.
  • srun then starts the eight processes, four on each node. It is Slurm’s launcher, so there is no torchrun here.

Each process learns who it is from variables that srun sets: SLURM_PROCID is its rank (0 to 7), SLURM_NTASKS is the total (8). The training script turns them into what PyTorch expects:

1
2
3
rank = int(os.environ['SLURM_PROCID'])
world = int(os.environ['SLURM_NTASKS'])
dist.init_process_group('gloo', init_method='env://', rank=rank, world_size=world)

init_method='env://' reads MASTER_ADDR and MASTER_PORT from the environment, which every process inherited from the batch script. The model is a small two-layer network on random data. Every 20 steps, rank 0 saves a checkpoint: it writes a temporary file and then renames it, so a crash in the middle of a save never leaves a half-written checkpoint behind. If a checkpoint exists when the script starts, it resumes from it; section 7 needs that. The whole script, exercises/ddp_train.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Tiny DDP training on CPU with the gloo backend, launched by `srun` (one process per task).
Rank and world size come from Slurm's environment; MASTER_ADDR/MASTER_PORT from the sbatch script.
Saves a checkpoint every --ckpt-every steps (rank 0, atomic rename) and resumes from it if present, so a requeued
job continues where the last checkpoint left off (exercise 3)."""
import argparse, os, socket, time
import torch, torch.distributed as dist, torch.nn as nn

p = argparse.ArgumentParser()
p.add_argument('--steps', type=int, default=200)
p.add_argument('--ckpt', default='/shared/ckpt/ddp.pt')
p.add_argument('--ckpt-every', type=int, default=20)
p.add_argument('--step-seconds', type=float, default=0.0, help='sleep per step, to make a job last long enough to kill')
a = p.parse_args()

rank = int(os.environ['SLURM_PROCID']); world = int(os.environ['SLURM_NTASKS']); local = int(os.environ['SLURM_LOCALID'])
os.environ.setdefault('RANK', str(rank)); os.environ.setdefault('WORLD_SIZE', str(world))
dist.init_process_group('gloo', init_method='env://', rank=rank, world_size=world)
torch.manual_seed(0); torch.set_num_threads(1)
model = nn.Sequential(nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 1))
ddp = nn.parallel.DistributedDataParallel(model)
opt = torch.optim.SGD(ddp.parameters(), lr=0.05)
start = 0
if os.path.exists(a.ckpt):
ck = torch.load(a.ckpt, map_location='cpu')
ddp.module.load_state_dict(ck['model']); opt.load_state_dict(ck['opt']); start = ck['step']
if rank == 0: print(f'resumed from {a.ckpt} at step {start}', flush=True)
if rank == 0:
print(f'world {world} ranks; node {socket.gethostname()} rank {rank} local {local}; '
f'SLURM_JOB_ID {os.environ.get("SLURM_JOB_ID")} restart {os.environ.get("SLURM_RESTART_COUNT", "0")}; '
f'fake GPUs on this node: SLURM_GPUS_ON_NODE={os.environ.get("SLURM_GPUS_ON_NODE")}', flush=True)
g = torch.Generator().manual_seed(1000 + rank)
for step in range(start, a.steps):
x = torch.randn(64, 32, generator=g); y = (x.sum(1, keepdim=True) > 0).float()
loss = nn.functional.binary_cross_entropy_with_logits(ddp(x), y)
opt.zero_grad(); loss.backward(); opt.step()
if a.step_seconds: time.sleep(a.step_seconds)
if (step + 1) % a.ckpt_every == 0:
dist.barrier()
if rank == 0:
tmp = a.ckpt + '.tmp'
torch.save({'model': ddp.module.state_dict(), 'opt': opt.state_dict(), 'step': step + 1}, tmp)
os.replace(tmp, a.ckpt)
print(f'step {step + 1}/{a.steps} loss {loss.item():.4f} checkpoint saved', flush=True)
dist.barrier()
if rank == 0: print('done', flush=True)
dist.destroy_process_group()

The output file, with eight copies of a PyTorch warning about NumPy (which the image does not install) removed:

1
2
3
4
5
6
7
$ cat /shared/logs/ddp-cpu-19.out
nodes: c[1-2] master: c1 tasks: 8
world 8 ranks; node c1 rank 0 local 0; SLURM_JOB_ID 19 restart 0; fake GPUs on this node: SLURM_GPUS_ON_NODE=4
step 20/200 loss 0.6686 checkpoint saved
...
step 200/200 loss 0.2990 checkpoint saved
done

7. When a node goes away

On a real cluster, nodes fail. When a node under a running batch job dies, Slurm can put the job back in the queue by itself. Whether it may is set per job with --requeue (or --no-requeue), and the cluster-wide default is JobRequeue in slurm.conf (1 here, so --requeue only makes it explicit). This applies to node failure and preemption, not to a job whose own program exits with an error; that job simply ends FAILED. Whether the job then continues or starts over depends on your training script: it continues only if the script saved checkpoints somewhere that outlives the node, and reads them on start. The script from section 6 does both.

The drill: the same job, slowed down to half a second per step and 600 steps long, submitted with --requeue. Once it has saved its second checkpoint (step 40), a script on the host runs docker stop c2, the job’s second node. A few seconds after Slurm marks the node as dead, it runs docker start c2 again. This is what happened, in seconds from the moment the job was given its nodes:

docker stop at 24 s, c2 misses a ping at 48 s and is marked DOWN at 58 s, run 1 ends NODE_FAIL, the job waits 132 s in PENDING with Reason BeginTime, run 2 resumes at step 40 and completes at 478 s

Step by step:

  1. 24 s: c2 is stopped. The four processes on c1 notice at once: their connections to the processes on c2 close, and gloo stops them with Connection closed by peer ... typically caused by a remote worker crashing. In DDP every step needs every rank, so the job cannot go on without c2. But the job stays RUNNING: srun is still waiting for its four processes on c2, which it can no longer reach, and only Slurm’s node-failure handling will end them.
  2. 48 s and 58 s: the controller notices. The controller checks on its nodes regularly. Its check of c2 fails at 48 s, and at 58 s, 34 s after the stop, it declares c2 dead (SlurmdTimeout=30). In sinfo the node shows as allocated* in between (* means “not responding”) and then down*. The controller ends the job’s first run with the state NODE_FAIL and, because the job is requeueable, puts it back in the queue. srun prints srun: error: Node failure on c2.
  3. 61 s: c2 is back. The container restarts, its slurmd registers again, and the controller returns it to service on its own.
  4. 58 s to 190 s: the job waits. The job sits in the queue for 132 s with the reason BeginTime, although all four nodes are free. This is deliberate: when Slurm requeues a batch job it sets an earliest start time of now plus one credential lifetime plus one second (batch_requeue_fini). A credential is the signed permission a node needs to start the job’s processes; waiting one lifetime means the credential of the failed run has expired everywhere before the new run starts. The lifetime is 120 s by default (DEFAULT_EXPIRATION_WINDOW), so the job could start from 179 s, and the scheduler picked it up on its next pass, at 190 s. It can be shortened with AuthInfo=cred_expire=<seconds> in slurm.conf, down to 5 s (cred.c).
  5. 190 s to 478 s: the second run. The job starts again on c1 and c2. The training script finds the checkpoint and prints resumed from /shared/ckpt/ddp-requeue.pt at step 40; the job finishes at 478 s with state COMPLETED. Inside the second run, SLURM_RESTART_COUNT is 1, so a script can tell that it is a restart.

sacct -D (show every run of a job, not only the last) records both runs:

1
2
3
4
5
$ sacct -j 21 -D -X --format=JobID,State,Elapsed,NodeList,Start,End
JobID State Elapsed NodeList Start End
------------ ---------- ---------- --------------- ------------------- -------------------
21 NODE_FAIL 00:00:59 c[1-2] 2026-10-20T14:46:14 2026-10-20T14:47:13
21 COMPLETED 00:04:48 c[1-2] 2026-10-20T14:49:25 2026-10-20T14:54:13

What it cost: the steps since the last checkpoint, 34 s until Slurm declared the node dead, and the 132 s wait. Each has a setting: the checkpoint interval in your script, SlurmdTimeout, and the credential lifetime.

docker stop shuts a node down cleanly, which is why the surviving processes heard about it at once. A node that loses power or its network sends nothing, so the surviving processes get no closed connection to react to; that case is a different drill and is not covered here.

8. Preemption

A partition can be allowed to push out jobs from another. Here high has a higher PriorityTier than low, and low has PreemptMode=REQUEUE:

1
2
3
4
5
6
$ sbatch -p low  -N 4 --exclusive --requeue --wrap 'sleep 300'   # job 22 takes all four nodes
$ sbatch -p high -N 4 --exclusive --wrap 'sleep 20' # job 23
$ squeue -o "%.8i %.6j %.5P %.9T %.6p %R"
JOBID NAME PARTI STATE PRIORI NODELIST(REASON)
23 high high RUNNING 0.0000 c[1-4]
22 low low PENDING 0.0000 (BeginTime)

Job 22 was stopped and put back in the queue (scontrol show job 22 shows Restarts=1), and job 23 took its nodes. Job 22 then waits with reason BeginTime, under the same rule as in section 7.

9. Pitfalls when running Slurm 23.11 in containers

Each of these breaks the cluster or its jobs in a container, with a message that does not point at the cause.

  • GPUs declared without device files are dropped. A gres.conf line that gives only a count (Name=gpu Count=4) is ignored by Slurm 23.11 with the log message “Ignoring file-less GPU”, and the node is then rejected because it reports 0 of its 4 GPUs. The fix is the File= line in section 2.
  • slurmd needs a cgroup plugin it can load. Slurm 23.11 always loads one. The cgroup v2 plugin, cgroup/v2, needs dbus and a writable /sys/fs/cgroup, which an unprivileged container does not have, and the option to turn cgroups off only exists from Slurm 24.05. CgroupPlugin=cgroup/v1 in cgroup.conf loads without touching anything, as long as no other setting uses cgroups: Slurm’s default process tracking, proctrack/cgroup, would, so slurm.conf sets ProctrackType=proctrack/linuxproc and TaskPlugin=task/none. The price of those two: a job is not confined to the cores and memory it asked for, only scheduled as if it were.
  • The controller looks up node addresses once, at start. Docker’s DNS only knows containers that are running, so if the controller starts before c1 to c4, it never finds them. The controller’s start script waits until all four names resolve.
  • A job needs a writable directory to start in. By default a job writes its output to the directory it was submitted from. If the job’s user cannot write there, the job fails before it starts with exit code 53. Submit from a directory the job user owns, such as /shared/logs here.

10. Command summary

command what it does
sinfo, sinfo -N partitions and node states (idle, allocated, down; * = not responding)
srun <cmd> run a command now on allocated nodes, output to the terminal
sbatch script.sh queue a script; output to slurm-<id>.out
squeue the queue: running jobs and their nodes, waiting jobs and their reasons
scancel <id> cancel a job
sacct -j <id> -X a job’s history from the database (-D for every run of a requeued job)
sprio -l why a waiting job has the priority it has
scontrol show job <id> everything the controller knows about a job, including Restarts
scontrol show hostnames <list> expand c[1-2] into c1, c2

Reproduce

Every file in this post is in rockyshi-dev/slurm-docker-lab: the Dockerfile, the compose file, the four configuration files and the exercise scripts, with a driver script.

1
2
3
4
5
6
7
$ git clone https://github.com/rockyshi-dev/slurm-docker-lab && cd slurm-docker-lab
$ ./lab.sh up # munge key, build, start, wait for four idle nodes
$ ./lab.sh ex1 # sections 3-5: first jobs, GPUs, priority
$ ./lab.sh ex2 # section 6: two-node DDP
$ ./lab.sh ex3 # section 7: node failure drill
$ ./lab.sh ex4 # section 8: preemption
$ ./lab.sh down

Your job ids will differ from the ones shown: they count every job the cluster has run.