Skip to content

General

Slurm from Scratch

Guide · SLURM, Clusters · updated on 16/10/2026

Author: Ángel Fernández Caravaca
Date: October 17, 2026

Slurm (Simple Linux Utility for Resource Management) is an open source workload scheduling and management system (job scheduler) designed for high-performance computing (HPC) clusters and supercomputers. Slurm does three jobs at once: it shares out the cluster's resources (manager), decides in which order the queue is served (scheduler) and starts the processes on the nodes (launcher). Two daemons do this: slurmctld (the controller) manages the resources and the queue, and slurmd (one per node) starts the processes.

Core Concepts

Below are some of Slurm's core concepts that are worth knowing before working with this manager. They are terms you will see in the Slurm documentation, in community guides, and even your favourite AI model will use them:

  • Node: a machine in the cluster, with its CPU, its RAM and sometimes GPUs.

  • Partition: a group of nodes with its own rules. The cluster has two partitions, general (photon[2-10,13-16]) and cosmological (photon11).

  • Job: a reservation of cluster resources together with a sequence of instructions to be run. It is assigned a SLURM_JOB_ID.

  • Job Step: one of the instructions to be run inside the job, that is, using the reserved resources. "Every time we run srun something, Slurm runs that something with the Job's resources".

  • Tasks: how many times the same Job Step is launched. For example: --ntasks=3 \(\equiv\) run this instruction 3 times. It is assigned a SLURM_PROCID. If the program is not parallelised with MPI (a library that lets tasks send messages to each other), they are identical copies; if it is, the copies share out the work.

  • Array: a set of independent jobs launched with the same script and the same resource request, but with a different index that lets you vary the code's parameters. As a result, unlike tasks, each element of the array is an independent job with its own reservation, it can land on a different node, and it can even start and/or fail separately. It is associated with a SLURM_ARRAY_TASK_ID.

  • Queue: the mechanism by which Slurm stores and organises users' jobs when there are no free resources right away, ordering them by priority.

To try to set up an analogy that clarifies these concepts, picture a huge restaurant with several kitchens. The customers, us, don't go in to cook; we hand an order to a head waiter (Slurm), who decides which kitchen and which cooks prepare it, and when. So:

Slurm term Restaurant analogy What it really is
Node A complete kitchen A physical computer in the cluster, with its CPU, its RAM and sometimes GPUs
Partition An area of the restaurant by speciality A group of nodes with common rules (maximum time, who can use it...)
Job A whole order What you ask Slurm for: "reserve these resources and run this"
Job step Each dish in the order Each program launched inside a job with srun
Task A cook working on the order One of the processes set up for a job step
Array The same sandwich but with different sauces A program tried out with different configurations
Queue The order board List of the jobs submitted by each user

It is important to take these concepts on board before working with the cluster, since the result of our jobs depends on how we specify the order for our dish. This becomes clear when we look at:

How does Slurm decide who runs what and when?

  1. You submit a job with the resources you need (CPUs, memory, time, partition).
  2. Slurm puts it in the queue: your job enters with the PENDING state (we will talk about states later on).
  3. It computes a priority. Factors such as how long it has been waiting, how much of the cluster you have used recently (the fair share: whoever has used little goes ahead of whoever has used a lot), the size of the job and the partition all play a part.
  4. It looks for a slot. It checks whether there are free nodes that meet what you asked for, and if there are, your job moves to RUNNING. At this stage, Slurm's gap-filling feature, also known as Backfill, is worth highlighting: if a large job is waiting for many nodes to free up, Slurm can slip in small, short jobs as long as they don't delay the large one.
  5. When it finishes (or runs out of time), the resources are freed and the cycle continues.

Warning

Slurm doesn't guess how much you need; it trusts what you ask for: if you ask for less than you need, your job may die; if you ask for more, you wait longer and block resources for everyone else.

It also assumes your code is correct, and it saves the outputs exactly as you specify. This must be kept in mind because, if you are not careful, the outputs of one job can overwrite those of another.

Running Jobs

Until now, each node in the cluster belonged to a professor, so that only that professor and their associates could use those nodes. This changes radically with the introduction of a queue manager: now all the nodes belong to everyone, since Slurm takes care of sharing out the cluster's resources as fairly as possible.

This section details the different routes and commands you will use when launching jobs through this queue manager.

Incognito vs Slurm

  • Incognito: on this route, the queue manager is unaware that you are running code. As a result, resources are not shared fairly, since Slurm has no control over your runs.

    When is this way of working justified? Solely and exclusively for visualising data/results and/or minor calculations.

    Reason: the cluster has no graphical interface, so figures can't be displayed while code is running. They have to be saved in our directories, or Jupyter Notebooks have to be used to render them in place. Although you should use Slurm commands even for this kind of task (and they will be provided), I understand that it can sometimes be tedious for what is actually going to be done. That is why this route is allowed under these conditions.

Danger

As the cluster administrator, I have ways of detecting misuse and applying penalties when running jobs.

  • Slurm: on this route, the queue manager knows that you are running code. As a result, resources are shared fairly, since Slurm has control over your runs. The rest of the section focuses on the commands associated with this route.

Interactive (srun) vs Batch (sbatch)

These are the two commands used to send your jobs through Slurm. We have:

srun (interactive) sbatch (batch)
How it works Runs the command now, live, in your terminal You submit a script and get your terminal back instantly
If you close the terminal The job dies The job carries on
Output Straight to your screen To a file (.out)
Ideal for Quick tests, debugging, shell sessions Real, long, reproducible jobs
If there are no resources Your terminal stays blocked waiting The job waits in the queue and you carry on with your own things

Continuing with the restaurant analogy, srun is ordering at the bar and standing there until you are served, whereas sbatch is leaving your order and sitting down at the table, or even going home and being told when it is ready. I think these examples make it clear why each one is ideal for what has been indicated.

With this intuition in place, let's look in more depth at how each one is used:

  • srun: runs a command in the foreground, tied to your terminal: it waits there in the queue until resources are available and, if you close it, the job dies. It is suitable for short tests or individual tasks that can comfortably be launched by hand.

    Examples:

    In this first example we see how to run terminal commands through Slurm:

    afdezcaravaca@photon2:~$ srun hostname 
    photon13
    

    Likewise, we can run our scripts. Suppose we have a file hola_mundo.py whose content is:

    hola_mundo.py
    import socket
    print(f'Hello world from {socket.gethostname()}')
    

    It is run with:

    (ml_3.12) afdezcaravaca@photon2:~/desktop/slurm_from_scratch$ srun python hola_mundo.py
    Hello world from photon13
    

Note

When I talked about running incognito, I said "you should use Slurm commands even for this kind of task". I was referring to srun. For example, with python:

srun python plot_resultados.py # It must save the plots in our directories
  • sbatch: submits a script and gives you the terminal back instantly. It is the route for long or reproducible jobs, because the job carries on even if you close the session and the resources are written down in the script itself (.sh).

    Example:

    For this example I have created a file called ejemplo_sbatch.sh whose content is:

    ejemplo_sbatch.sh
    1
    2
    3
    4
    #!/bin/bash
    
    srun hostname
    srun python hola_mundo.py
    

    Then we would have to run:

    (ml_3.12) afdezcaravaca@photon2:~/desktop/slurm_from_scratch$ sbatch ejemplo_sbatch.sh # (1)!
    Submitted batch job 4707
    
    1. When it finishes, it creates a slurm-4707.out file in our directory.

    Here we clearly see the difference between srun and sbatch: whereas the former returns the output to the same terminal, the latter submits a job and generates a slurm-4707.out file with the outputs of each job step:

    slurm-4707.out
    photon13                   # Output of srun hostname
    Hello world from photon13  # Output of srun python ~/desktop/slurm_from_scratch/hola_mundo.py
    

Notice that, in these examples, we haven't requested any resources: in that case Slurm uses the cluster's default values. In the next section we will see how to request them.

Run instructions:

It is well known that terminal commands accept flags to control their behaviour (ls vs ls -l). The srun and sbatch commands are no exception: their flags let you control the resources associated with the job, the job's name, where the .out files are created, etc.

With sbatch, these flags can also be written inside the script itself, on lines starting with #SBATCH at the top of the file. These are the SBATCH directives, and they make it easy to configure the experiment as well as recording the resources of each run in writing, which helps reproducibility. In this section we will look at the options available.

Note

The SBATCH directives are the same for srun and sbatch (except --array, which only exists in sbatch), and the only thing that changes is how they are invoked. On the other hand, although the following table shows the sbatch directives as #SBATCH, bear in mind that they can also be invoked in their flag form. The reason is purely didactic and has to do with the fact that they are usually used inside a .sh script.

Directive in srun Directive in sbatch What it does Example in srun Example in sbatch
--job-name #SBATCH --job-name Readable name for the job. Helps to identify it in the queue srun --job-name=prueba hostname #SBATCH --job-name=prueba
--partition #SBATCH --partition Which partition it runs on. If you leave it out, the default one is used srun --partition=general hostname #SBATCH --partition=general
--ntasks #SBATCH --ntasks How many tasks (processes) you want. srun --ntasks=3 hostname #SBATCH --ntasks=3
--cpus-per-task #SBATCH --cpus-per-task How many cores are allocated to each task srun --cpus-per-task=4 python script.py #SBATCH --cpus-per-task=4
--mem #SBATCH --mem RAM per node (8G = 8 GB; with no suffix, megabytes) srun --mem=8G python script.py #SBATCH --mem=8G
--mem-per-cpu #SBATCH --mem-per-cpu RAM per core. Not used together with --mem srun --mem-per-cpu=2G python script.py #SBATCH --mem-per-cpu=2G
--time #SBATCH --time Maximum run time (HH:MM:SS or D-HH:MM:SS). If exceeded, Slurm kills the job srun --time=00:10:00 python script.py #SBATCH --time=01:00:00
--output #SBATCH --output File where whatever the program prints goes. %j is replaced by the JobID. In sbatch, if omitted, slurm-<JOBID>.out is created srun --output=salida.out hostname #SBATCH --output=salida_%j.out
--error #SBATCH --error Separate file for errors. If omitted, they go to the same file as --output srun --error=errores.err python script.py #SBATCH --error=errores_%j.err
--nodes #SBATCH --nodes Number of nodes to reserve. Only makes sense if the program really splits work between nodes srun --nodes=2 --ntasks=4 hostname #SBATCH --nodes=2
--gpus #SBATCH --gpus Number of GPUs for the job. Variants: --gpus-per-node, --gpus-per-task srun --gpus=1 python entrena.py #SBATCH --gpus=1
--gres #SBATCH --gres Classic way to request generic resources, usually GPUs, per node (--gres=gpu:1) srun --gres=gpu:1 python entrena.py #SBATCH --gres=gpu:1
Not available #SBATCH --array Launches an array of jobs, each with its own $SLURM_ARRAY_TASK_ID. Only exists in sbatch Not available #SBATCH --array=1-10
--dependency #SBATCH --dependency Doesn't start until another job meets a condition (afterok:101 = when 101 finishes successfully) srun --dependency=afterok:101 hostname #SBATCH --dependency=afterok:101
--chdir #SBATCH --chdir Working directory where the job runs srun --chdir=/ruta/proyecto python script.py #SBATCH --chdir=/ruta/proyecto

Warning

If you look at the Slurm documentation you will find plenty of directives I haven't included here. I considered these to be the ones you will use most, but if anyone thinks I should add another one, let me know.

Danger

On this cluster, each physical core provides 2 threads and Slurm counts each thread as a CPU (for example, photon5 has 4 sockets × 24 cores × 2 threads = 192 CPUs). These are hardware threads, and they must not be confused with the software threads used by a multithreaded program (such as NumPy), which are the ones spread across the reserved CPUs. Also, Slurm allocates whole cores: on each node, a job's number of CPUs is rounded up to the next even number. If we request 1 CPU, we are allocated 2 and both count as used, and if we request 3, we are allocated 4. With several nodes, the rounding applies on each one: requesting 1 CPU on each of 2 nodes means 4 CPUs allocated, not 2.

You can check this with sacct -j <JobID> --format=JobID,ReqCPUS,AllocCPUS, comparing what was requested (ReqCPUS) with what was allocated (AllocCPUS).

CONCLUSION: request CPUs in multiples of 2 on each node, so as not to waste a thread no other job can use.

Below I will discuss a few examples, all working on a .sh file so you can see the anatomy of a script:

Example 1: Code without parallelisation
In this example we use the previous code, the difference being that we include the SBATCH directives.

With this script we launch 1 Job called hola_mundo into the queue of the general partition (photon[2-10,13-16]). The job consists of 1 job step: srun python hola_mundo.py.

This job step consists of 1 task (--ntasks=1), which is assigned a single CPU (--cpus-per-task=1). Since Slurm reserves CPUs rounding up to the next even number, this script actually reserves 2 CPUs. From this we deduce that everything will fit on a single node, on which 1GB of RAM is reserved for the whole job.

On the other hand, once the job's state changes to RUNNING, it has a time limit of 5 minutes to finish. The terminal output, including errors (we haven't specified --error), will be saved in a file hola_mundo_<JobID>.out.

The two echo lines are not job steps: they run directly in the script, they are not launched with srun. Their output ends up in the same .out, so the file will contain, in this order: the start date, the Python greeting (which includes the node name) and the end date.

ejemplo1.sh
#!/bin/bash
#SBATCH --job-name=hola_mundo
#SBATCH --partition=general
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=1
#SBATCH --mem=1G
#SBATCH --time=00:05:00
#SBATCH --output=hola_mundo_%j.out

echo "Start: $(date)"
srun python hola_mundo.py
echo "End: $(date)"

To launch it, submit it with sbatch from the directory where the script and hola_mundo.py are, since python will look for the file in the directory the job is launched from:

$ sbatch ejemplo1.sh

Example 2: Multithreaded code
Here we are going to run the program matrices.py, which multiplies two \(6000 \times 6000\) matrices with NumPy. This code will let us see how multithreaded parallelisation works, that is, a single process that splits the computation across several threads, each running on a different CPU of the same machine.

Warning

As I said before, Slurm is not responsible for your code, in this case for multithreaded parallelisation. It is simply a work dispatcher. Our code must be adapted for parallelisation.

The python script:

matrices.py
import os
import socket
import time
import numpy as np

# Show the requested resources (optional)
n_cpus = os.environ.get("SLURM_CPUS_PER_TASK", "1")
n_hilos = os.environ.get("OMP_NUM_THREADS", "not set")
print(f"Node: {socket.gethostname()}")
print(f"CPUs reserved per task: {n_cpus}")
print(f"Threads configured (OMP_NUM_THREADS): {n_hilos}")
# Define the matrices:
N = 6000
a,b = np.random.rand(N,N), np.random.rand(N,N)
# Start timing:
inicio = time.perf_counter()
c = a @ b # The linear algebra library NumPy uses splits the computation across threads
fin = time.perf_counter()
print(f"Elapsed time: {fin - inicio:.6f}s")

With this script we launch 1 Job called matrices into the queue of the general partition (photon[2-10,13-16]). The job consists of 1 job step (srun python matrices.py).

This job step consists of 1 task (--ntasks=1) which is assigned 4 CPUs. Since the matrices.py code is adapted to use multithreaded parallelisation, it will use as many threads as OMP_NUM_THREADS says, which the script sets equal to the number of reserved CPUs (4).

Since a task is a single process, its 4 CPUs must be on the same node, on which 4GB of RAM is reserved for the whole job.

On the other hand, once the job's state changes to RUNNING, it has a time limit of 10 minutes to finish. The terminal output will be saved in a file matrices_<JobID>.out, while errors will be saved in a file matrices_<JobID>.err.

ejemplo2.sh
#!/bin/bash
#SBATCH --job-name=matrices
#SBATCH --partition=general
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=4
#SBATCH --mem=4G
#SBATCH --time=00:10:00
#SBATCH --output=matrices_%j.out
#SBATCH --error=matrices_%j.err

# Tell NumPy how many threads it may use: as many as the CPUs we have reserved
export OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK

echo "Start: $(date)"
srun python matrices.py
echo "End: $(date)"

To launch it, submit it with sbatch from the directory where the script and matrices.py are:

$ sbatch ejemplo2.sh

Note

Try changing the value of --cpus-per-task and compare the time reported in the .out files. That way you can check the benefits of multithreaded parallelisation. The time won't drop exactly in proportion (with 4 CPUs it won't be 4 times faster, among other things because 4 CPUs are equivalent to 2 physical cores), and NumPy must be installed in the environment you use.

Note

If we had added the srun hostname job step, of the 4 CPUs reserved in that step, 3 CPUs would have sat idle, because that command isn't parallelised into threads. Here it would hardly matter, since it lasts milliseconds, but with a long step that doesn't use threads resources would indeed be wasted.

Example 3: Multiprocess code
Next we are going to see how to work with a script that benefits from multiprocess computation: launching several independent copies of the same code, where each copy takes care of a different part of the work. This is very useful for speeding up the execution of a piece of code, since it lets you split it into different tasks that run simultaneously and independently.

In this example we are going to compute the sum of the first 100,000,000 natural numbers. This work can be split among several tasks that each compute, independently, a partial sum, to be combined afterwards to obtain the total. This split is achieved by using each task's identifier (SLURM_PROCID). The code of suma_parcial.py is:

suma_parcial.py
import os
import socket
# Find out which task I am:
rank = int(os.environ["SLURM_PROCID"])
# Find out how many tasks there are:
size = int(os.environ["SLURM_NTASKS"])  
# Numbers to add up
N = 100_000_000
# Add up my share (one in every "size" numbers):
suma_parcial = sum(range(rank + 1, N + 1, size))
# Save my partial sum to a file named after my identifier
with open(f"parcial_{rank}.txt", "w") as f:
    f.write(str(suma_parcial))
print(f"Task {rank} of {size} on {socket.gethostname()}: partial sum = {suma_parcial}")

The code that combines the results into a single output is combinar.py:

combinar.py
import glob
# Numbers to add up:
N = 100_000_000
# List of all the files, in order:
ficheros = sorted(glob.glob("parcial_*.txt"))
# Add up the contents of all of them:
total = sum(int(open(f).read()) for f in ficheros)
# Prints:
print(f"Files combined: {len(ficheros)}")
print(f"Total sum = {total}")
print(f"Expected result = {N * (N + 1) // 2}")

To run this, we have the script ejemplo3.sh. With it we launch 1 Job called suma_tasks into the queue of the general partition (photon[2-10,13-16]). The job consists of 2 job steps run sequentially: first srun python suma_parcial.py and then srun --ntasks=1 python combinar.py.

Each job step launches a different number of tasks:

  • suma_parcial.py: step 0 launches 20 tasks at once. Each task adds up one in every 20 numbers (5,000,000 in total) and saves its result in a file parcial_<SLURM_PROCID>.txt.
  • combinar.py: step 1 launches a single task, which runs once the previous 20 have finished and gathers the results.

Here we must bear in mind that each task is assigned 1 CPU, so in total 20 CPUs are reserved (the ones the largest step needs). Since the smallest machine in the cluster has 80 CPUs, this whole job will normally fit on a single machine, on which a total of 1GB of RAM is reserved for the whole job.

On the other hand, once the job's state changes to RUNNING, it has a time limit of 10 minutes to finish. The terminal output, including errors (we haven't specified --error), will be saved in a file suma_tasks_<JobID>.out.

ejemplo3.sh
#!/bin/bash
#SBATCH --job-name=suma_tasks
#SBATCH --partition=general
#SBATCH --ntasks=20
#SBATCH --cpus-per-task=1
#SBATCH --mem=1G
#SBATCH --time=00:10:00
#SBATCH --output=suma_tasks_%j.out

# Remove results from previous runs
rm -f parcial_*.txt

echo "Start: $(date)"
echo " "
echo "---- Outputs of suma_parcial.py ----"
srun python suma_parcial.py                # step 0: 20 tasks at once, each adds up its share
echo " "
echo "---- Outputs of combinar.py ----"
srun --ntasks=1 python combinar.py         # step 1: 1 task gathers the results
echo " "
echo "End: $(date)"
To launch it, submit it with sbatch from the directory where the scripts are:

$ sbatch ejemplo3.sh

Example 4: Job arrays

Next we are going to see how to launch many independent runs of the same script with a single command, each with its own resource reservation. This is the typical case in which we want to repeat the same calculation while changing a few parameters: trying out several configurations, repeating an experiment with different random seeds, processing a different data file in each run...

For this we use an array. Unlike what we saw in Example 3, where 1 job launched several tasks collaborating on the same calculation, here each element of the array is an independent job, with its own resource reservation, which can land on a different node and start or fail separately. The only thing that distinguishes them is their index, which Slurm gives us in the SLURM_ARRAY_TASK_ID variable.

In this example we are going to estimate the value of \(\pi\) with the Monte Carlo method, launching 5 independent simulations. Each element of the array uses its index as the random seed, so each one gets a slightly different value. The code of pi_montecarlo.py is:

pi_montecarlo.py
import os
import random
import socket
# Get the job's index:
indice = int(os.environ["SLURM_ARRAY_TASK_ID"])
# Set the seed:
random.seed(indice)
# Number of points to throw:
PUNTOS = 5_000_000
dentro = 0
for _ in range(PUNTOS):
    # Generate a random point:
    x, y = random.random(), random.random()
    # Check whether it falls inside the circle:
    if x * x + y * y <= 1:
        dentro += 1
# Estimate of pi:
pi_estimado = 4 * dentro / PUNTOS
print(f"Array element {indice} on {socket.gethostname()}: pi ~ {pi_estimado:.5f} (seed {indice})")

To try different seeds with a single command, we use ejemplo4.sh. In this case we launch 5 jobs (--array=1-5) called montecarlo into the queue of the general partition. Each job consists of a single job step (srun python pi_montecarlo.py).

Each job step launches a single task, since the code of pi_montecarlo.py is sequential, that is, it isn't parallelised by threads or by processes. This task only requests 1 CPU, but from what we have seen, 2 CPUs are actually reserved. This fits on a single node, on which 500MB of RAM is reserved.

Once a job's state changes to RUNNING, it has a time limit of 5 minutes to finish. The terminal output, including errors (we haven't specified --error), will be saved in one file per element, montecarlo_<arrayID>_<index>.out.

Each job generates its own files and can start, fail or finish at different times. If all 5 run at once, a total of 10 CPUs (2 per job) and 2.5GB of RAM are reserved, but Slurm treats them separately: if the cluster is busy at that moment, some elements may start before others while the rest stay in the queue (PENDING).

ejemplo4.sh
#!/bin/bash
#SBATCH --job-name=montecarlo
#SBATCH --partition=general
#SBATCH --array=1-5
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=1
#SBATCH --mem=500M
#SBATCH --time=00:05:00
#SBATCH --output=montecarlo_%A_%a.out

echo "Start: $(date)"
srun python pi_montecarlo.py
echo "End: $(date)"

To launch it, submit it with sbatch from the directory where the scripts are:

$ sbatch ejemplo4.sh

Example 5: Several nodes
So far all our jobs have fitted on a single machine. Next we are going to see how to split the same job across several nodes. This is necessary when the work needs more CPUs or more memory than a single node offers, since a process (a task) can't be split across machines, but a job with several tasks can.

For this we reuse the calculation from Example 3: the sum of the first 100,000,000 natural numbers, with the same suma_parcial.py and combinar.py code. There is no need to modify them, because each task still uses its identifier (SLURM_PROCID) to know which part is its own, whichever node it is on. What changes is the Slurm script:

ejemplo5.sh
#!/bin/bash
#SBATCH --job-name=suma_nodos
#SBATCH --partition=general
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=2
#SBATCH --cpus-per-task=1
#SBATCH --mem=1G
#SBATCH --time=00:10:00
#SBATCH --output=suma_nodos_%j.out

# Remove results from previous runs
rm -f parcial_*.txt

echo "Start: $(date)"
echo "Allocated nodes: $SLURM_JOB_NODELIST"
srun python suma_parcial.py                          # step 0: 4 tasks, spread across the 2 nodes
srun --nodes=1 --ntasks=1 python combinar.py         # step 1: 1 task gathers the results
echo "End: $(date)"

With the ejemplo5.sh script we launch 1 Job called suma_nodos into the queue of the general partition. The job consists of 2 job steps run sequentially: first srun python suma_parcial.py and then srun --nodes=1 --ntasks=1 python combinar.py.

What is new is how the resources are requested. With --nodes=2 we reserve 2 nodes, and with --ntasks-per-node=2 we specify that 2 tasks are launched on each node. So step 0 launches 4 tasks at once, 2 on each node, and step 1 launches a single task, which runs once the previous ones have finished. Each task is assigned 1 CPU (--cpus-per-task=1), so in total 4 CPUs are reserved (2 and 2).

As for memory, remember that --mem is reserved per node. With 2 nodes, --mem=1G means 1GB on each, 2GB in total. Until now, using a single node, "per node" and "in total" were the same, but not here.

On the other hand, once the job's state changes to RUNNING, it has a time limit of 10 minutes to finish. The terminal output, including errors (we haven't specified --error), will be saved in a file suma_nodos_<JobID>.out. In it we will see which nodes Slurm has allocated to us ($SLURM_JOB_NODELIST) and, in each task's output, the name of the node where it ran (socket.gethostname()), so we can check that there are two different nodes.

To launch it, submit it with sbatch from the directory where the scripts are:

$ sbatch ejemplo5.sh

Warning

For this example to work, the directory the job is launched from must be shared by both nodes. This is solved by the shared file system the cluster has in place. The tasks on both nodes save their parcial_<SLURM_PROCID>.txt files there, and combinar.py needs to see all of them. If the directory were local to one node, step 1 wouldn't find the other node's files.

Summary of the examples

Example Key directives Jobs Steps per job Tasks per step CPUs reserved Nodes RAM
1. Not parallelised --ntasks=1 --cpus-per-task=1 1 1 1 1 requested (2 allocated) 1 1GB
2. Multithreaded --ntasks=1 --cpus-per-task=4 1 1 1 4 1 4GB
3. Multiprocess --ntasks=20 --cpus-per-task=1 1 2 20 and 1 20 1 (normally) 1GB
4. Array --array=1-5 --ntasks=1 --cpus-per-task=1 5 1 1 1 requested per job (2 allocated; 10 if they coincide) 1 per job 500MB per job (2.5GB if they coincide)
5. Several nodes --nodes=2 --ntasks-per-node=2 --cpus-per-task=1 1 2 4 and 1 4 2 1GB per node (2GB in total)

Some conclusions:

  • SBATCH directives always at the top: all #SBATCH lines must come before the first command in the script. Once Slurm sees a line that isn't a comment, it stops reading directives.

  • Job steps run sequentially: job steps run one after another, that is, the next one doesn't start until the previous one finishes. Each one uses, in turn, the resources reserved by the job.

    The tasks within a job step run simultaneously, and each one needs its own CPU from the reservation.

    As a result, if 4 CPUs are reserved in total (--ntasks=4 --cpus-per-task=1):

    • Each job step can launch up to 4 tasks at once, one per CPU.
    • If a job step asked for more tasks than reserved CPUs, srun would give an error.
  • CPUs requested: the number of CPUs you reserve depends on how you configure the SBATCH directives. The most general expression for a job is:

    \[ \text{CPUs per job} = \text{ntasks} \times \text{cpus-per-task} \]

    where \(\text{ntasks} = \text{nodes} \times \text{ntasks-per-node}\) if --ntasks-per-node is used.

    If we launch an array, each element is an independent job. If they all run at once:

    \[ \text{Total CPUs} = \text{CPUs per job} \times \text{array size} \]

    Remember that the CPUs actually allocated may be more, because of the rounding to whole cores.

  • RAM requested: the memory you reserve depends on the directive you use:

    • With --mem (the one we used in the examples), it is requested per node:

      \[ \text{RAM per job} = \text{mem} \times \text{nodes} \]
    • With --mem-per-cpu, it is requested per CPU:

      \[ \text{RAM per job} = \text{mem-per-cpu} \times \text{CPUs per job} \]

    The two can't be used at the same time. With a single node, --mem is directly the job's total RAM.

    If we launch an array, each element is an independent job with its own reservation. If they all run at once:

    \[ \text{Total RAM} = \text{RAM per job} \times \text{array size} \]

    Remember that, with --mem-per-cpu, memory is counted over the CPUs actually allocated, which may be more because of the rounding to whole cores.

  • GPUs requested: the count depends on the directive you use:

    Directive What it requests GPUs per job
    --gpus=N N GPUs for the whole job \(N\)
    --gpus-per-node=N N GPUs on each node \(N \times \text{nodes}\)
    --gpus-per-task=N N GPUs for each task \(N \times \text{ntasks}\)
    --gres=gpu:N N GPUs on each node (classic form) \(N \times \text{nodes}\)

    If we launch an array, each element is an independent job. If they all run at once:

    \[ \text{Total GPUs} = \text{GPUs per job} \times \text{array size} \]

    Unlike CPUs, GPUs are allocated whole, with no rounding.

  • Decision table: an intuition for how to choose our SBATCH directives:

    My program is... I request...
    A normal Python script (a single thread) --ntasks=1 --cpus-per-task=1
    A multithreaded program (NumPy, PyTorch with several threads, OpenMP) --ntasks=1 --cpus-per-task=8 (for example)
    An MPI program (several processes that communicate) --ntasks=16 --cpus-per-task=1 (for example)
    I want to launch 100 independent runs --array=1-100
    My program splits work between processes and needs more CPUs than a node has --nodes=2 --ntasks-per-node=2 (for example)
  • SLURM environment variables: these are variables SLURM generates so you can use them.

Variable Content
$SLURM_JOB_ID The job's number
$SLURM_JOB_NAME The job's name
$SLURM_JOB_NODELIST List of allocated nodes
$SLURMD_NODENAME Name of the node where this part runs
$SLURM_NTASKS Number of tasks requested
$SLURM_CPUS_PER_TASK CPUs per task

Now that we know how to submit jobs, we will focus on checking how the cluster is doing and, more importantly, what state our jobs are in.

Analysing states

The commands we will use most are sinfo and squeue. With them, we answer: "how is the cluster doing?" (sinfo) and "what is happening with the jobs?" (squeue).

sinfo: checking the state of nodes and partitions

This command lets us find out the state of the cluster's nodes, each one associated with a partition. It is run in the terminal with:

sinfo

The expected result is:

1
2
3
PARTITION    AVAIL  TIMELIMIT  NODES  STATE NODELIST
general*        up   infinite     13   idle photon[2-10,13-16]
cosmological    up   infinite      1   idle photon11

This table gives the meaning of each field:

Column Meaning
PARTITION Name of the partition. The * marks the default one
AVAIL up = accepts jobs; down = closed
TIMELIMIT Maximum time per job (1-00:00:00 = 1 day). On our cluster the time is infinite.
NODES How many nodes are in that state
STATE State of the nodes (see table below)
NODELIST Which nodes they are

Warning

Both of the cluster's partitions have an infinite time limit, so it is your responsibility to check the state of your runs.

DON'T LET A PROCESS BECOME A ZOMBIE!

  • Most common node states:
State Meaning
idle Completely free
mix Partially busy (some CPUs still free)
alloc Completely busy
drain / drng Taken out for maintenance: doesn't accept new jobs
down Down or unreachable
  • Useful variants:
1
2
3
sinfo -Nl          # One line per node, in detail (CPUs, memory, state)
sinfo -p general         # Only the "general" partition
sinfo -R             # Show the REASON why nodes are down/drained

squeue: checking the job queue

This command lets us view the job queue for the whole cluster. It is run from the terminal with:

squeue

Example output:

1
2
3
4
JOBID    PARTITION       NAME     USER  ST       TIME  NODES NODELIST(REASON)
  101      general    analisis    maria  R   01:23:10      1   photon2
  102      general  simulacion    juan  PD       0:00      2  (Resources)
  103 cosmological     entrena    maria PD       0:00      1  (Priority)
This table gives the meaning of each field:

Column Meaning
JOBID Job identifier (you'll need it to cancel!)
NAME Job name
USER Who submitted it
ST Abbreviated state (R = running, PD = pending)
TIME How long it has been running
NODES How many nodes (machines) the job occupies or has requested. In the example, job 102 requests 2 nodes and the others 1
NODELIST(REASON) If it is running: on which node. If it is waiting: why it is waiting
  • Job states: the ST column in squeue shows the abbreviated state, and sacct shows it with the full name.
State ST Meaning
PENDING PD In the queue, waiting for resources (the reason appears in NODELIST(REASON))
RUNNING R Running right now (a node appears in NODELIST(REASON))
COMPLETING CG Finishing: resources are being released
COMPLETED CD Finished successfully
FAILED F Finished with an error (non-zero exit code)
CANCELLED CA Was cancelled, by the user or by an administrator
TIMEOUT TO Exceeded the requested --time and Slurm killed it
OUT_OF_MEMORY OOM Used more RAM than reserved and Slurm killed it
NODE_FAIL NF The node it was running on failed
SUSPENDED S Temporarily paused

Note

squeue only shows pending or running jobs. Those that have already finished (COMPLETED, FAILED, CANCELLED, TIMEOUT...) disappear from the queue after a few minutes, and to look them up afterwards you use sacct -j <JobID>.

  • Most common reasons for waiting: these are some of the different labels that can appear in the NODELIST(REASON) column.
Reason What it means What to do?
Priority There are higher-priority jobs ahead Wait; it's normal
Resources It's your turn, but there aren't enough free resources yet Wait, or request fewer resources
Dependency Waiting for another job to finish (--dependency) Check that the job it depends on finished successfully
QOSMaxJobsPerUserLimit You already have the maximum number of jobs allowed running Wait for some to finish
BeginTime It was scheduled to start later Nothing, it's expected
PartitionTimeLimit You are requesting more time than the partition allows Reduce --time or change partition
ReqNodeNotAvail The nodes it needs aren't available (down, drained or reserved) Check sinfo -R, or wait
JobHeldUser / JobHeldAdmin The job is held, by the user or by an administrator Release it with scontrol release <JobID>, or talk to the administrator
PartitionDown The partition is closed (AVAIL = down) Wait for it to reopen

To see the full reason for a specific job:

scontrol show job <JobID>    # Look for the "Reason=" line
squeue --start               # Estimate of when pending jobs will start
  • Useful variants:
1
2
3
4
5
squeue -u $USER              # Only MY jobs 
squeue -j 101                # Only job 101
squeue -u $USER -t PENDING   # Only my jobs that are waiting
squeue --start               # Estimate of when pending jobs will start
watch -n 2 squeue -u $USER   # Refreshes every 2 seconds (Ctrl+C to exit)

sacct: looking up jobs that have already finished

squeue only shows what is pending or running, so to see how a job ended (and how much it used) you use sacct. For example, for the job from Example 5 (number 6313):

sacct -j 6313 --format=JobID,ReqCPUS,AllocCPUS
1
2
3
4
5
6
JobID         ReqCPUS  AllocCPUS 
------------ -------- ---------- 
6313                4          4 
6313.batch          2          2 
6313.0              4          4 
6313.1              1          1

Each row is a part of the job:

JobID What it is
6313 The whole job
6313.batch The .sh script itself (the echo, rm... lines)
6313.0 Job step 0: srun python suma_parcial.py
6313.1 Job step 1: srun --nodes=1 --ntasks=1 python combinar.py

The columns most often used with --format:

Column What it shows
State Final state (COMPLETED, FAILED, TIMEOUT...)
ExitCode The program's exit code (0 = no errors)
Elapsed Real time it took
ReqCPUS / AllocCPUS CPUs requested versus CPUs allocated
ReqMem Memory requested
MaxRSS Maximum memory it actually used
NodeList Nodes where it ran

A useful combination for reviewing a job at a glance:

sacct -j <JobID> --format=JobID,JobName,State,ExitCode,Elapsed,ReqCPUS,AllocCPUS,MaxRSS

Tip

sacct is for fine-tuning what you request: compare Elapsed with the --time you requested and MaxRSS with the --mem. If you asked for much more than you used, next time you can ask for less and it will start sooner.