Python tasks over many nodes with mpi4py.futures
A job array goes beyond one node with a job for each task. When your tasks are calls of a Python function, the whole computation can instead stay in one job and one script: a pool of workers, like the pool of processes on one node, but with its workers spread over every node of the job.
Why the pool on one node stops there
ProcessPoolExecutor starts its workers by forking or spawning processes, and a process can only start other processes on its own node. So asking Slurm for 2 nodes and running pi_futures.py gives you a pool on the first node, and a second node doing nothing, for which you are still charged.
What you need is something that can start processes on every node of the job, and send them work. That is what srun and MPI already do for MPI programs, as in the section on MPI, and mpi4py.futures builds a pool on top of them: MPIPoolExecutor has the same interface as ProcessPoolExecutor, with MPI ranks as its workers.
The same π, on MPI ranks
Here is Monte Carlo π that way:
#!/usr/bin/env python3
"""Monte Carlo π on MPI ranks, with mpi4py.futures:
srun python -m mpi4py.futures pi_mpi4py_futures.py
Rank 0 runs this script and hands out the tasks; every other rank is a worker.
"""
import socket
from collections import Counter
from mpi4py import MPI
from mpi4py.futures import MPIPoolExecutor
import pi
def count_hits(seed):
"""One task, and the node it ran on."""
return pi.count_hits(seed), socket.gethostname()
if __name__ == "__main__":
print(f"{MPI.COMM_WORLD.Get_size() - 1} workers")
with MPIPoolExecutor() as pool:
results = list(pool.map(count_hits, range(1, pi.TASKS + 1)))
for host, tasks in sorted(Counter(host for _, host in results).items()):
print(f"{host}: {tasks} tasks")
pi.report(sum(hits for hits, _ in results), pi.TASKS * pi.SAMPLES)It is pi_futures.py of the pool on one node, with MPIPoolExecutor in place of ProcessPoolExecutor, and no number of workers. Each task also returns the name of the node it ran on, so that the output shows where the work went.
It needs mpi4py, and an mpi4py that works across nodes is the subject of the page on conda and the vendor’s MPI. The examples on this page and on the page on hybrid MPI use its first route, conda-forge’s external MPICH bound to the vendor’s MPI at run time, with NumPy added:
name: pi-mpi
channels:
- conda-forge/label/mpi-external
- conda-forge
dependencies:
- python=3.13
- numpy
# mpi4py, built against an MPICH that the vendor's MPI stands in for at run time
- mpi4py
- mpich * external_*created as before, with mamba env create --channel-priority flexible -f environment-mpi.yml. Then the job, on a Cray system:
#!/bin/bash
#SBATCH --job-name=pi-mpi4py-futures
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=4
#SBATCH --cpus-per-task=1
#SBATCH --time=00:05:00
set -eo pipefail
# The vendor's MPI. On a Cray system, it comes with the programming environment.
module reset
module load PrgEnv-gnu
source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "${CONDA_ENV:-pi-mpi}"
# The vendor's libmpi.so.12, for mpi4py to find, since the environment has none.
export LD_LIBRARY_PATH="${MPICH_DIR}/lib-abi-mpich:${LD_LIBRARY_PATH:-}"
# Where pi.py is, for `import pi`.
export PYTHONPATH="$PWD/../pi"
# Every worker is a rank with one thread, on a core of its own.
source ../pi/num-threads.sh 1
# 8 ranks: rank 0 runs the script, and the other 7 are its workers.
srun --cpu-bind=cores python -m mpi4py.futures pi_mpi4py_futures.pyThe first half is the batch script of the conda page, loading the vendor’s MPI and pointing mpi4py at it. The last line is the new part: srun starts 8 ranks, 4 on each node, each running python -m mpi4py.futures pi_mpi4py_futures.py, and --cpu-bind=cores pins each rank to its own core.
-m mpi4py.futures is what turns 8 copies of the script into one pool. It runs before your script, and splits the ranks by their number. Rank 0 runs your script as usual, and when the script creates an MPIPoolExecutor, rank 0 is its controller, which hands out the tasks and collects the results. Every other rank never runs your script’s main part: it waits for tasks from rank 0, runs them, and sends back the results, until the pool is closed. So the output, from rank 0, starts with 7 workers, then one line per node with how many of the 64 tasks ran there, and ends with the same line as every other strategy:
pi = 3.141543 from 4294967296 samples
The tasks are handed out as the workers become free, so a worker that gets a quick task simply gets another one sooner, and the work balances itself even when the tasks take different times.
As on one node, the function the workers run has to be one they can find by name, defined at the top level of a module or of the script, and its arguments and results are pickled and sent over MPI. That is cheap for a seed and a count, and for anything that is small compared with how long the task takes.
How many ranks
Rank 0 is the controller, not a worker. So with N ranks you get N − 1 workers, and to get W workers, you ask for W + 1 ranks.
In the job above, 8 ranks on 8 cores give 7 workers, and the controller’s core spends the job mostly waiting. On a real job, with whole nodes, that is one core out of hundreds: ask for one rank per core, e.g. --nodes=4 --ntasks-per-node=144 --cpus-per-task=1 on nodes of 144 cores, which gives 575 workers.
If your tasks use threads themselves, give each rank as many cores as it has threads, as on the page on threads: e.g. --ntasks-per-node=36 --cpus-per-task=4 on the same nodes, num-threads.sh 4 in the job, and 143 workers with 4 threads each. Then the controller holds 4 cores to itself, which is the cost of keeping the numbers simple.
More workers than tasks is a waste: with 64 tasks, any worker beyond the 64th never gets one. On a real problem, you’d want many more tasks than workers, so that the ones that finish early pick up the remaining tasks.
Without -m mpi4py.futures
You may find examples that run the script with plain python pi_mpi4py_futures.py, or with mpiexec -n 1. Then MPIPoolExecutor starts its workers itself, as new MPI processes, with MPI’s dynamic process management (MPI_Comm_spawn). That needs the MPI library, and the batch system, to support starting processes after the job has started, which some vendor MPIs do not. So on a cluster, I’d always launch with srun ... python -m mpi4py.futures, where every rank is started by srun at the beginning, and no spawning is needed.1
When a task fails
It is the same as on one node: when a task raises an exception on a worker, MPIPoolExecutor raises it again on rank 0 when its result is retrieved, so go through the results, as list(pool.map(...)) does here, and the tasks not yet started are cancelled. Then the exception ends your script on rank 0, and under -m mpi4py.futures, an exception that nothing catches calls MPI.COMM_WORLD.Abort, which ends every rank, so a failed task does not leave the workers waiting until the job runs out of time.
Limitations
All the results come back to rank 0. For a count, that is nothing, but if each task returns a large array, they all travel over the network to one process, and have to fit in its memory together. Then it is better for each task to write its result to a file, and return only the file’s name.
It needs an mpi4py that works across nodes, with everything that the section on MPI is about. And it is one job: if it runs out of time, the tasks it did not finish are lost, unless each writes its result to a file as it goes, so that a rerun can skip them.
The next page spreads a pool over the nodes of a job through Python’s own multiprocessing, with DragonHPC.
Footnotes
mpi4py also has
MPICommExecutor, which turns the ranks of a program you launched with plainsrun python script.pyinto a pool, with rank 0 as the controller: inwith MPICommExecutor() as pool:,poolis the pool on rank 0, andNoneon every other rank. It is useful when you cannot change how the script is launched.↩︎