Skip to content

Slurm Job Submissions

This page provides examples of different types of Slurm jobs and advice on writing job scripts.


Getting Started

If you have not already, please read the HPC Cluster page, which provides an introduction to submitting Slurm jobs. After reading that page, continue reading the sections below.

Slurm Options

There are many options that can be passed to srun and sbatch to change how Slurm jobs behave. Commonly used options that were not mentioned in the Interactive Jobs section on the HPC Cluster page are listed below:

-o
Specifies the file name that job output will be written to. If you do not use the -e option, errors will also be written to this file.
-e
The file name that job errors will be written to.
-a
Specifies an array of jobs that run using the same job script. See the Job Arrays section below for more information.
--ntasks-per-node
The number of tasks that should run on each node in the job. See the Tasks section below for more information.
-b
Specifies an amount of time to wait before scheduling the job. This can be useful if you want to submit a job now, but wait until later in the day for it to start running.
--gpus
Specifies the number of GPUs you would like access to in your job. See the GPU Jobs section below for more information.
-x
Lists nodes to exclude from your job. If your job is failing on a particular node, this option can prevent it from running there. Please report nodes that are causing issues to the ARC team.
--threads-per-core
The number of threads to allocate per CPU core requested with the -c option. To allocate physical cores to job tasks instead of logical cores, set this option to two.
--mail-user
An email address to send notifications about the state of your job.
--mail-type
A list of job events to send email notifications for. Valid event types include BEGIN, END, FAIL, REQUEUE, and ALL.

For more information on the options listed here and a full list of all the available options, see the official srun and sbatch documentation pages. You can also read the documentation on these commands from your terminal by running man srun and man sbatch.

Environment Variables

Some information about each job is made available to its job script using environment variables. Commonly used environment variables provided by Slurm are listed below:

SLURM_JOB_NAME
The name of the current Slurm job.
SLURM_JOB_ID
The ID of the current Slurm job.
SLURM_JOB_NODELIST
A list of nodes allocated for the current job.
SLURM_JOB_NUM_NODES
The number of nodes allocated for the current job.
SLURMD_NODENAME
The hostname of the current compute node.
SLURM_NTASKS
The total number of tasks in the job.
SLURM_PROCID
The ID of the current job task. This starts at zero and ends at (SLURM_NTASKS - 1).

These variables are only defined for jobs in job arrays. For more information on job arrays see the Job Arrays section below.

SLURM_ARRAY_JOB_ID
The ID of the current job array.
SLURM_ARRAY_TASK_COUNT
The total number of sub-jobs within the job array.
SLURM_ARRAY_TASK_ID
The ID of the current sub-job within the job array.

Tasks vs Cores

The difference between job tasks (specified with -n) and cores per task (specified with -c) can be confusing. This section describes the difference between the two and gives examples of when you might use one over the other.

Tasks

Each task is an instance of your application that the scheduler will run. To run multiple tasks in parallel, you need to use srun. The example below shows how you would run one task on each node in a two-node job:

#!/bin/bash
#SBATCH -N 2
#SBATCH -n 2
#SBATCH --ntasks-per-node=1

srun /bin/bash -c 'echo "Hello world from task $((SLURM_PROCID + 1)) of $SLURM_NTASKS on $SLURMD_NODENAME!"'

The output should look something like this:

Hello world from task 1 of 2 on cmri-n02!
Hello world from task 2 of 2 on cmri-n03!

There is one new option in this example, --ntasks-per-node. This option is required to ensure that each of the two tasks run on separate nodes. Without it, the scheduler may run both tasks on a single node.

By using srun to run the bash script in this example, we are telling the scheduler to run one instance of it per requested task, and to run those tasks in parallel across the requested nodes. The bash script that srun runs (starting with /bin/bash -c) uses environment variables set by Slurm (SLURM_PROCID, SLURM_NTASKS, and SLURMD_NODENAME) to print the active task number, total number of tasks, and node name.

In contrast to tasks, cores (specified with -c) are the number of CPU cores allocated to each task.

Cores

The number of cores allocated to each task is specified with the -c option. By default, each task can only use one CPU core. If the application you are running as a task is multithreaded, or uses forks to create subprocesses, you should request cores equal to the number of threads or subprocesses it uses.

For example, if your application uses 16 threads for processing, you would add the option #SBATCH -c 16 to your job script.

Job Arrays

Job arrays are a convenient way to run multiple copies of a job with different input files and options. The example below shows how you might run multiple copies of an R program using a job array:

#!/bin/bash
#SBATCH -J job_array_example
#SBATCH -N 1
#SBATCH -n 4
#SBATCH -c 1
#SBATCH -a 0-10%3
#SBATCH -o console-output.txt

module load R

min_time=$((SLURM_ARRAY_TASK_ID * 2))
max_time=$((min_time + 1))

for i in `seq 1 4`; do
        srun -n 1 R --no-restore --no-save --no-echo --args "${min_time}" "${max_time}" "${i}" < r-dataset-example.R
done

The -a 0-10%3 option defines the job array. It instructs the scheduler to create an array with 11 jobs indexed 0 through 10. The %3 at the end indicates that only three of the jobs in the array should run at once. In the body of the job script SLURM_ARRAY_TASK_ID is used to check the index of the current job in the array and supply different arguments to an example R program based on the index.

Each job runs four tasks using srun inside a for loop. It is important to pass the -n 1 option to srun here, otherwise the srun command will inherit the -n 4 SBATCH parameter above and run four copies of the example program for each set of inputs.

The source code for the r-dataset-example.R program used in this example is available in the R Example section below.

GPU Jobs

GPUs can be generically be requested in a Slurm job using the --gpus option. Be sure to specify the gpu partition as well with the -p option - requesting GPUs in the other partitions will result in an error:

[cmri-vm-login]$ srun --gpus=1 -p short --pty /bin/bash
srun: error: Unable to allocate resources: Requested node configuration is not available
[cmri-vm-login]$ srun --gpus=1 -p gpu --pty /bin/bash
[cmri-gpu01]$ nvidia-smi -L
GPU 0: Tesla T4 (UUID: GPU-fbd9531c-198a-15b2-246e-005471967712)

There are currently four GPU nodes in the cluster; two with two GPUs each and two with four GPUs each. See the Hardware section on the HPC Cluster page for more information. Multiple versions of CUDA, as well as the cuDNN and NCCL development libraries are available as modules.

To specify the type of GPU you want to use (either t4 or h200), you will need to use the --gres flag instead.

[cmri-vm-login ~]$ srun --gres=gpu:h200:1 -p gpu --pty /bin/bash
[cmri-gpu04 ~]$ nvidia-smi -L
GPU 0: NVIDIA H200 NVL (UUID: GPU-8f01c6ed-dd22-822f-7424-0d37f0ffdedf)

In the above example, "gpu" specifies the gres resource, "h200" specifies the GPU type and "1" requests one GPU.

Similarly, to request this type of GPU in a SBATCH job you would add something like this:

#!/bin/bash
#SBATCH --nodes=1 -p gpu
#SBATCH --gres=gpu:h200:1

echo "Hello"
nvidia-smi

MPI Jobs

OpenMPI modules with support for the Slurm scheduler are available on the cluster. srun is recommended for running MPI processes instead of mpirun:

#!/bin/bash
#SBATCH -N 2
#SBATCH -n 32
#SBATCH --ntasks-per-node=16
#SBATCH -J mpi_test

module load openmpi/4.1.4_gcc-12.2.0

rm -f ./mpi-hello-world
mpicc ./mpi.c -o mpi-hello-world

srun ./mpi-hello-world

This job runs 32 tasks (equivalent to 32 MPI ranks) across two nodes, 16 tasks per node. The job output should looks similar to this:

Hello world from processor cmri-n02, rank 0 out of 32 processors
Hello world from processor cmri-n02, rank 1 out of 32 processors
...
Hello world from processor cmri-n03, rank 30 out of 32 processors
Hello world from processor cmri-n03, rank 31 out of 32 processors

The source code for the mpi.c program used in this example is available in the MPI Example section below.

Job Efficiency

The seff command can be used to check the efficiency of completed jobs. This is useful for verifying that you requested the right amount of resources for a job. To use seff, you need to know the ID of the job you would like to check. Example seff output is shown below:

[cmri-vm-login]$ seff <job_id>
...
State: COMPLETED (exit code 0)
Nodes: 1
Cores per node: 16
CPU Utilized: 08:56:42
CPU Efficiency: 2.15% of 17-07:53:36 core-walltime
Job Wall-clock time: 1-01:59:36
Memory Utilized: 25.21 GB
Memory Efficiency: 41.63% of 60.55 GB

Examples

The sections below contain example job submission scripts, as well the source code for example programs referenced above.

Python Multiprocessing

The example python job script below requests two nodes, two tasks (one on each node), and two cores for each task. It then creates one process for each core (two per task), and prints information about the process and task ranks:

#!/usr/bin/env python3
#SBATCH -N 2
#SBATCH -n 2
#SBATCH --ntasks-per-node=1
#SBATCH -c 2

import multiprocessing as mp
import subprocess as sp
import argparse
import os

PROC_COUNT=2

parser=argparse.ArgumentParser( \
           description='Example Python multiprocessing job with Slurm')
parser.add_argument('--srun', action='store_true', default=False, \
           help='Run the script using srun.')
parser.add_argument('--path', type=str, default='', \
           help='Path to this script. Required to submit as a batch job.')

def proc_info(PROC_COUNT, index):
    print('Hello world from process ' + str(index) \
           + ' of ' + str(PROC_COUNT) \
           + ' in task ' + str(int(os.environ['SLURM_PROCID']) + 1) \
           + ' of ' + os.environ['SLURM_NTASKS'] \
           + ' on ' + os.environ['SLURMD_NODENAME'])

if __name__ == '__main__':
    args = parser.parse_args()
    if args.srun == True:
        mp.set_start_method('fork')
        for index in range(PROC_COUNT):
            q = mp.Queue()
            p = mp.Process(target=proc_info, args=(PROC_COUNT, \
                                                   index + 1,))
            p.start()
    elif args.path != '':
        sp.run('srun ' + args.path + ' --srun', shell=True)
    else:
        parser.error("--srun or --path must be specified")

This could be useful as a starting point for a python job script that runs processes across multiple nodes. If you save the example script above in a file named mp_test.py, you can use this command to submit it to the scheduler:

sbatch ./mp_test.py --path $(pwd)/mp_test.py

The job output should look similar to this:

Hello world from process 1 of 2 in task 1 of 2 on cmri-n02
Hello world from process 2 of 2 in task 1 of 2 on cmri-n02
Hello world from process 1 of 2 in task 2 of 2 on cmri-n03
Hello world from process 2 of 2 in task 2 of 2 on cmri-n03

MPI Example

The source code for the mpi.c example program used in the MPI Jobs section is given below. This example code was copied from the MPI Tutorial website.

#include <mpi.h>
#include <stdio.h>

int main(int argc, char** argv) {
    MPI_Init(NULL, NULL);

    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    char processor_name[MPI_MAX_PROCESSOR_NAME];
    int name_len;
    MPI_Get_processor_name(processor_name, &name_len);

    printf("Hello world from processor %s, rank %d out of %d processors\n",
           processor_name, world_rank, world_size);

    MPI_Finalize();
}

R Example

The source code for the r-dataset-example.R program used in the Job Arrays section is give below. This example calculates the mean weight of a group of chickens that ate a specific diet over a given time period, then writes the data to a file in csv format. The dataset used is provided by the R dataset package.

data(ChickWeight)

args = commandArgs(trailingOnly = TRUE)
min_time = as.integer(args[1])
max_time = as.integer(args[2])
diet = as.integer(args[3])

cw_subset = subset(ChickWeight,
                   Time >= min_time &
                     Time <= max_time & Diet == diet,
                   select = weight)

data = matrix(c(min_time,
                max_time,
                diet,
                mean(cw_subset$weight)),
              nrow = 1)

write.table(
  data,
  file = "output.csv",
  append = TRUE,
  col.names = FALSE,
  row.names = FALSE,
  sep = ",",
  dec = ".",
  eol = ",\n"
)