Skip to main content

Dask Parallelization with PBS and SLURM

Running FWI across HPC cluster nodes

DevitoHorizon uses a Scheduler abstraction over shot-level parallelism. The built-in DaskScheduler works with any Dask Client, including distributed clusters managed by PBS (Torque/PBS Pro) and SLURM.

How shot-level parallelism works

physics.objective() maps compute_shot_gradient() over a batch of shots. Each shot is an independent task: it loads a cropped model from disk, runs forward + adjoint simulation, and returns a gradient dictionary. Operators are pre-compiled and cached to disk by the main process before workers start, so workers only unpickle cached operators rather than recompiling them.

The serialized function closure sent to each worker is intentionally lean:

  • Model arrays are excluded — workers load the model from a shared path.
  • Wavelet store is excluded — the main process extracts each shot’s wavelet before dispatch and passes it explicitly.

This design minimises the data that must be serialized per task and works well with Dask scatter.

PBS (Torque / PBS Pro)

Note

These are the manual routes. For most runs the launcher command above is simpler and needs no scheduler setup.

Requirements

  • A shared filesystem (Lustre, GPFS, NFS) accessible from all nodes.
  • Dask distributed package (pip install dask distributed).
  • output_dir pointing to a path on the shared filesystem.

Beyond the launcher command above, there are two manual approaches:

  1. All-in-one Python script — uses dask-jobqueue to launch workers from Python.
  2. Batch script + JSON — the PBS script starts the Dask scheduler and workers, writes the scheduler address to a JSON file, and a separate Python script connects via that JSON.

Approach 1: all-in-one Python script

This approach uses dask-jobqueue (pip install dask-jobqueue) to manage the cluster from within your Python script.

from dask_jobqueue import PBSCluster
from dask.distributed import Client

from devitohorizon.data import Dataset
from devitohorizon.physics import DevitoPhysics
from devitohorizon.optimization import SPG
from devitohorizon.scheduler import DaskScheduler

# --- Cluster setup ---
cluster = PBSCluster(
    queue='gpu',
    cores=1,               # one Devito thread per worker
    memory='16GB',
    walltime='02:00:00',
    job_extra_directives=['-l select=1:ncpus=8:ngpus=1'],
    # Dask workers run on the shared filesystem
    local_directory='/scratch/myproject/dask-workers',
    log_directory='/scratch/myproject/dask-logs',
)
cluster.scale(jobs=8)      # 8 PBS jobs = 8 Devito workers

client = Client(cluster)
scheduler = DaskScheduler(client)

# --- FWI setup ---
# output_dir must be on the shared filesystem so workers can read
# cached operators and temporary model files.
physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    output_dir='/scratch/myproject/fwi_run',
    model='/scratch/myproject/model.zarr',
    wavelet={'type': 'ricker', 'f0': 8.0},
)

dataset = Dataset.from_zarr('/scratch/myproject/shots.zarr')
optimizer = SPG(maxiter=20)

model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=model0,
    bounds={'vp': (1.5, 5.5)},
    scheduler=scheduler,
)

client.close()
cluster.close()

Approach 2: batch script with scheduler JSON

In this approach, the PBS batch script starts a Dask scheduler and workers directly, writing the scheduler address to a JSON file. Your FWI Python script then connects to the running cluster via that file.

PBS batch script (submit_fwi.pbs)

#!/bin/bash
#PBS -N fwi_run
#PBS -q gpu
#PBS -l select=8:ncpus=8:ngpus=1
#PBS -l walltime=04:00:00
#PBS -j oe

# Shared filesystem paths
export PROJECT_DIR=/scratch/myproject
export SCHEDULER_FILE=${PROJECT_DIR}/scheduler.json

# Clean up any previous scheduler file
rm -f ${SCHEDULER_FILE}

# Start the Dask scheduler on the head node and write its
# address to a JSON file that workers and the client can use
dask scheduler \
    --scheduler-file ${SCHEDULER_FILE} &

# Wait for the scheduler to be ready
sleep 5

# Start one Dask worker per allocated node
for node in $(cat ${PBS_NODEFILE} | sort -u); do
    ssh ${node} \
        "dask worker \
            --scheduler-file ${SCHEDULER_FILE} \
            --nworkers 1 \
            --nthreads 8 \
            --memory-limit 16GB \
            --local-directory ${PROJECT_DIR}/dask-workers" &
done

# Wait for workers to register
sleep 10

# Run the FWI script — it connects via the JSON file
python ${PROJECT_DIR}/run_fwi.py \
    --scheduler-file ${SCHEDULER_FILE}

# Clean up
rm -f ${SCHEDULER_FILE}

FWI Python script (run_fwi.py)

import argparse

from dask.distributed import Client

from devitohorizon.data import Dataset
from devitohorizon.physics import DevitoPhysics
from devitohorizon.optimization import SPG
from devitohorizon.scheduler import DaskScheduler

parser = argparse.ArgumentParser()
parser.add_argument(
    '--scheduler-file', required=True,
    help='Path to Dask scheduler JSON file'
)
args = parser.parse_args()

# Connect to the already-running Dask cluster via the JSON
client = Client(scheduler_file=args.scheduler_file)
print(f"Connected to {client.scheduler_info()['address']}")
print(f"Workers: {len(client.scheduler_info()['workers'])}")

scheduler = DaskScheduler(client)

# --- FWI setup ---
physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    output_dir='/scratch/myproject/fwi_run',
    model='/scratch/myproject/model.zarr',
    wavelet={'type': 'ricker', 'f0': 8.0},
)

dataset = Dataset.from_zarr('/scratch/myproject/shots.zarr')
optimizer = SPG(maxiter=20)

model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=model0,
    bounds={'vp': (1.5, 5.5)},
    scheduler=scheduler,
)

client.close()

Submit with:

qsub submit_fwi.pbs

Shared filesystem layout

/scratch/myproject/
    fwi_run/
        .operator_cache/    # pre-compiled Devito operators (written once)
        _tmp_models/        # temporary model files per iteration (auto-cleaned)
    shots.zarr              # observed shot data
    model.zarr              # initial velocity model

Operators in .operator_cache/ are written by the main process during the first objective() call and reused by all workers on every subsequent call. Temporary models in _tmp_models/ are cleaned up automatically after each objective evaluation.

This layout is what a run uses when the nodes share a filesystem. A model given as a specification with storage credentials keeps both beside itself on that storage instead — <container>/.operator_cache/ and <container>/_horizon_staging/ — so a cloud cluster, whose nodes share no filesystem at all, needs no shared mount.

SLURM

Note

These are the manual routes. For most runs the launcher command above is simpler and needs no scheduler setup.

Requirements

Same as PBS: shared filesystem and dask distributed.

Approach 1: all-in-one Python script

Uses dask-jobqueue (pip install dask-jobqueue):

from dask_jobqueue import SLURMCluster
from dask.distributed import Client
from devitohorizon.scheduler import DaskScheduler

cluster = SLURMCluster(
    account='myallocation',
    partition='gpu',
    cores=1,
    memory='16GB',
    walltime='02:00:00',
    job_extra_directives=[
        '--gres=gpu:1',
        '--ntasks-per-node=1',
    ],
    local_directory='/scratch/myproject/dask-workers',
    log_directory='/scratch/myproject/dask-logs',
)
cluster.scale(jobs=16)

client = Client(cluster)
scheduler = DaskScheduler(client)

Everything else is identical to the PBS approach 1 above.

Approach 2: batch script with scheduler JSON

SLURM batch script (submit_fwi.sbatch)

#!/bin/bash
#SBATCH --job-name=fwi_run
#SBATCH --account=myallocation
#SBATCH --partition=gpu
#SBATCH --nodes=8
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=8
#SBATCH --gres=gpu:1
#SBATCH --time=04:00:00

# Shared filesystem paths
export PROJECT_DIR=/scratch/myproject
export SCHEDULER_FILE=${PROJECT_DIR}/scheduler.json

# Clean up any previous scheduler file
rm -f ${SCHEDULER_FILE}

# Start the Dask scheduler on the first node
dask scheduler \
    --scheduler-file ${SCHEDULER_FILE} &

# Wait for the scheduler to be ready
sleep 5

# Start one Dask worker on each allocated node
srun --ntasks-per-node=1 \
    dask worker \
        --scheduler-file ${SCHEDULER_FILE} \
        --nworkers 1 \
        --nthreads ${SLURM_CPUS_PER_TASK} \
        --memory-limit 16GB \
        --local-directory ${PROJECT_DIR}/dask-workers &

# Wait for workers to register
sleep 10

# Run the FWI script — it connects via the JSON file
python ${PROJECT_DIR}/run_fwi.py \
    --scheduler-file ${SCHEDULER_FILE}

# Clean up
rm -f ${SCHEDULER_FILE}

The run_fwi.py script is the same as in the PBS example above — it connects via Client(scheduler_file=...).

Submit with:

sbatch submit_fwi.sbatch

Adaptive scaling

dask-jobqueue supports adaptive scaling — the cluster grows or shrinks based on pending tasks:

cluster.adapt(minimum_jobs=2, maximum_jobs=32)

This is useful when shot batches vary in size across iterations.

Tips

Pre-build operators before the cluster is fully up

Call physics.prebuild_operators(model) explicitly before dispatching the first objective to ensure the cache is warm before workers start:

physics = DevitoPhysics(...)
physics.prebuild_operators(physics.model)  # compile once, all workers reuse

Tune nthreads per worker

Devito uses OpenMP for intra-node parallelism. Set OMP_NUM_THREADS to match the number of physical cores on each node:

cluster = SLURMCluster(
    env_extra=['export OMP_NUM_THREADS=8'],
    ...
)

Monitor with the Dask dashboard

print(client.dashboard_link)

Forward the dashboard port with SSH if running on a login node:

ssh -L 8787:compute-node:8787 login-node
Back to top