map_parallel¶
A drop-in replacement of map and itertools.starmap, but in parallel, with
backends to choose from: processes, threads, subinterpreters, dask and MPI.
from map_parallel import map_parallel, starmap_parallel
def f(x, y):
return x**y
if __name__ == "__main__":
# list(map(f, [1, 2, 3], [2, 2, 2])), on a pool of processes
map_parallel(f, [1, 2, 3], [2, 2, 2]) # [1, 4, 9]
# list(itertools.starmap(f, [(1, 2), (2, 2), (3, 2)])), on 4 threads
starmap_parallel(f, [(1, 2), (2, 2), (3, 2)], mode="multithreading", processes=4) # [1, 4, 9]
The same code runs on any backend: change mode, and nothing else.
Installation¶
pip install map-parallel
# with the optional backends
pip install "map-parallel[dask]"
pip install "map-parallel[mpi]" # needs an MPI implementation, see mpi4py's documentation
# or
conda install -c conda-forge map_parallel
map_parallel itself is pure Python with no dependencies, supports Python 3.11 and later, and is tested on free-threaded builds of Python (3.13t on).
Backends¶
|
runs on |
suits |
|---|---|---|
|
CPU-bound pure Python, with a GIL |
|
|
I/O-bound work; work that releases the GIL; anything, on free-threaded Python |
|
|
|
CPU-bound pure Python, in one process |
|
dask.distributed: the active |
a cluster you already have |
|
HPC, with dynamic load balancing |
|
|
mpi4py, one equal block of work per rank |
HPC, where |
|
|
debugging |
Choosing a backend explains which to use when, and why.
Both functions take the same keyword arguments:
processes: the number of workers, orNonefor the backend’s default;1runs serially.chunksize: the number of calls sent to a worker at a time. Raise it when each call is quick, to cut the overhead per call.return_results:Falseto discard the results, e.g. whenfwrites its output to files.
An exception raised by f propagates to the caller, whatever the backend, and
whether or not the results are returned. For mpi_simple, it is raised on every
rank, so that no rank waits forever for the one that failed.
Except for multithreading and serial, f, its arguments and its results go
to other processes or interpreters, so they must be picklable: define f at
the top level of a module, and guard the script’s entry point with
if __name__ == "__main__":.
The MPI modes run under mpiexec:
mpiexec -n 4 python -m mpi4py.futures script.py # mode="mpi"
mpiexec -n 4 python script.py # mode="mpi_simple": every rank runs the script
Documentation¶
Citation¶
If map_parallel contributes to your research, please cite it through its Zenodo record, whose DOI resolves to the latest version.