Skip to main content

Numba-MPI logo Numba-MPI

Python 3 LLVM Linux OK macOS OK Windows OK Github Actions Status Maintenance License: GPL v3 PyPI version Anaconda-Server Badge AUR package DOI

Overview

Numba-MPI provides Python wrappers to the C MPI API callable from within Numba JIT-compiled code (@jit mode). For an outline of the project, rationale, architecture, and features, refer to: Numba-MPI paper in SoftwareX (open access) (please cite if Numba-MPI is used in your research).

Support is provided for a subset of MPI routines covering: size/rank, send/recv, sendrecv, allreduce, reduce, bcast, scatter/gather & allgather, barrier, wtime and basic asynchronous communication with isend/irecv (for contiguous arrays only); for request handling including wait/waitall/waitany and test/testall/testany.

The API uses NumPy and supports both numeric and character datatypes (e.g., broadcast). Initial JIT-compilable support for custom datatypes (i.e. structures defined with np.dtype) has been gradually introduced since v1.4, and as of now covers send, recv and sendrecv functions. Note that it relies on (intentionally) non-JIT-compilable type_create_struct, type_create_resized, type_commit and type_free (see example below). For custom datatypes, type checks are only performed when run without JIT compilation (e.g. by setting NUMBA_DISABLE_JIT=1). With JIT-compilation enabled, custom data structures are sent byte-by-byte without type checks, but in an alignment-aware manner.

Auto-generated docstring-based API docs are published on the web: https://numba-mpi.github.io/numba-mpi

Packages can be obtained from PyPI (pip install numba-mpi), Conda Forge (conda install conda-forge::numba-mpi), Arch Linux (yay -S python-numba-mpi) or by invoking pip install git+https://github.com/Numba-MPI/Numba-MPI.git.

Numba-MPI is a pure-Python package. The codebase includes a test suite used through the GitHub Actions workflows (thanks to mpi4py's setup-mpi!) for automated testing on: Intel Linux (MPICH, OpenMPI & Intel MPI), ARM Linux (MPICH & OpenMPI), Intel and ARM macOS (MPICH) and Windows (MS MPI).

Features that are not implemented yet include (help welcome!):

  • support for non-default communicators
  • support for MPI_IN_PLACE in [all]gather/scatter and allreduce
  • ...

Basic send/recv example

import numba, numba_mpi, numpy as np

@numba.jit()
def test_basic_send_recv():
    src = np.array([1., 2., 3., 4., 5.])
    dst_tst = np.empty_like(src)

    if numba_mpi.rank() == 0:
        numba_mpi.send(src, dest=1, tag=11)
    elif numba_mpi.rank() == 1:
        numba_mpi.recv(dst_tst, source=0, tag=11)

Asynchronous isend/irecv example

import numba, numba_mpi, numpy as np

@numba.njit
def test_async_isend_irecv():
    rank = numba_mpi.rank()
    size = numba_mpi.size()

    assert size == 4, "This example requires exactly 4 MPI processes."

    send_to = (rank + 1) % size
    recv_from = (rank - 1 + size) % size

    send_data = np.full(5, rank, dtype=np.int64)
    recv_data = np.empty_like(send_data)

    reqs = np.full(2, numba_mpi.REQUEST_NULL, dtype=numba_mpi.RequestType)

    status, send_req = numba_mpi.isend(send_data, dest=send_to, tag=0)
    assert status == numba_mpi.SUCCESS
    reqs[0:1] = send_req

    status, recv_req = numba_mpi.irecv(recv_data, source=recv_from, tag=0)
    assert status == numba_mpi.SUCCESS
    reqs[1:2] = recv_req

    while True:
        status, index = numba_mpi.waitany(reqs)
        assert status == numba_mpi.SUCCESS

        if index == numba_mpi.UNDEFINED:
            break
        if index == 0:
            print("Rank", rank, ": send completed.")
        elif index == 1:
            print("Rank", rank, ": received", recv_data)
            for i in range(recv_data.size):
                assert recv_data[i] == recv_from

    print("Rank", rank, ": all requests completed.")

Custom datatype handling example

import numba, numba_mpi, numpy as np

@numba.jit()
def number_crunching(p_send):
    if numba_mpi.rank() == 0:
        numba_mpi.send(p_send, dest=1, tag=11)

    if numba_mpi.rank() == 1:
        p_recv = np.zeros_like(p_send)
        numba_mpi.recv(p_recv, source=0, tag=11)
        print(p_recv)

def test_custom_dtype():
    point_dt = np.dtype(
        [
            ("xyz", np.float64, (3,)),
            ("id", np.intc),
        ],
        align=True,
    )

    mpi_dt_point = numba_mpi.type_create_struct(point_dt)
    numba_mpi.type_commit(mpi_dt_point)
    number_crunching(p_send = np.array( 
        [
            ((1.0, 2.0, 3.0), 99),
            ((5.0, 3.2, 9.0), 54)
        ],
        dtype=point_dt
    ))
    numba_mpi.type_free(mpi_dt_point)

Example comparing Numba-MPI vs. mpi4py performance

The example below compares Numba+mpi4py vs. Numba+Numba-MPI performance. The sample code estimates $\pi$ by numerical integration of $\int_0^1 (4/(1+x^2))dx=\pi$ dividing the workload into n_intervals handled by separate MPI processes and then obtaining a sum using allreduce (see, e.g., analogous Matlab docs example). The computation is carried out in a JIT-compiled function get_pi_part() and is repeated N_TIMES. The repetitions and the MPI-handled reduction are done outside or inside of the JIT-compiled block for mpi4py and Numba-MPI, respectively. Timing is repeated N_REPEAT times and the minimum time is reported. The generated plot shown below depicts the speedup obtained by replacing mpi4py with numba_mpi, plotted as a function of N_TIMES / n_intervals - the number of MPI calls per interval. The speedup, which stems from avoiding roundtrips between JIT-compiled and Python code is significant (150%-300%) in all cases. The more often communication is needed (smaller n_intervals), the larger the measured speedup. Note that nothing in the actual number crunching (within the get_pi_part() function) or in the employed communication logic (handled by the same MPI library) differs between the mpi4py or Numba-MPI solutions. These are the overhead of mpi4py higher-level abstractions and the overhead of repeatedly entering and leaving the JIT-compiled block if using mpi4py, which can be eliminated by using Numba-MPI, and which the measured differences in execution time stem from.

import timeit, mpi4py, numba, numba_mpi, numpy as np

N_TIMES = 10000
RTOL = 1e-3

@numba.jit
def get_pi_part(n_intervals=1000000, rank=0, size=1):
    h = 1 / n_intervals
    partial_sum = 0.0
    for i in range(rank + 1, n_intervals, size):
        x = h * (i - 0.5)
        partial_sum += 4 / (1 + x**2)
    return h * partial_sum

@numba.jit
def pi_numba_mpi(n_intervals):
    pi = np.array([0.])
    part = np.empty_like(pi)
    for _ in range(N_TIMES):
        part[0] = get_pi_part(n_intervals, numba_mpi.rank(), numba_mpi.size())
        numba_mpi.allreduce(part, pi, numba_mpi.Operator.SUM)
        assert abs(pi[0] - np.pi) / np.pi < RTOL

def pi_mpi4py(n_intervals):
    pi = np.array([0.])
    part = np.empty_like(pi)
    for _ in range(N_TIMES):
        part[0] = get_pi_part(n_intervals, mpi4py.MPI.COMM_WORLD.rank, mpi4py.MPI.COMM_WORLD.size)
        mpi4py.MPI.COMM_WORLD.Allreduce(part, (pi, mpi4py.MPI.DOUBLE), op=mpi4py.MPI.SUM)
        assert abs(pi[0] - np.pi) / np.pi < RTOL

plot_x = [x for x in range(1, 11)]
plot_y = {'numba_mpi': [], 'mpi4py': []}
for x in plot_x:
    for impl in plot_y:
        plot_y[impl].append(min(timeit.repeat(
            f"pi_{impl}(n_intervals={N_TIMES // x})",
            globals=locals(),
            number=1,
            repeat=10
        )))

if numba_mpi.rank() == 0:
    from matplotlib import pyplot
    pyplot.figure(figsize=(8.3, 3.5), tight_layout=True)
    pyplot.plot(plot_x, np.array(plot_y['mpi4py'])/np.array(plot_y['numba_mpi']), marker='o')
    pyplot.xlabel('number of MPI calls per interval')
    pyplot.ylabel('mpi4py/Numba-MPI wall-time ratio')
    pyplot.title(f'mpiexec -np {numba_mpi.size()}')
    pyplot.grid()
    pyplot.savefig('readme_plot.svg')

plot

MPI resources on the web

Acknowledgements

We thank all contributors and users who reported feedback to the project through GitHub issues.

Development of Numba-MPI has been supported by the Polish National Science Centre (grant no. 2020/39/D/ST10/01220), the Max Planck Society and the European Union (ERC, EmulSim, 101044662). We further acknowledge Poland’s high-performance computing infrastructure PLGrid (HPC Centers: ACK Cyfronet AGH) for providing computer facilities and support within computational grant no. PLG/2023/016369.

Metadata

Release files for numba-mpi 1.4.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for numba-mpi 1.4.2
File Size Uploaded Provenance Actions
numba_mpi-1.4.2.tar.gz 54.6 kB Without provenance Details for numba_mpi-1.4.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for numba-mpi 1.4.2
File Interpreter ABI Platform Actions
numba_mpi-1.4.2-py3-none-any.whl Python 3 none any Details for numba_mpi-1.4.2-py3-none-any.whl

Total release size: 90.1 kB

Release files / numba_mpi-1.4.2.tar.gz

Download URL numba_mpi-1.4.2.tar.gz
Size 54.6 kB
Tags Source
SHA-256 checksum
How to use checksums
51f4f1deebd2b9fd492725b770d9f23fb61e6a3339720e4cbf77124fdcb0e03e
BLAKE2b-256 checksum
How to use checksums
27f481703d8604da72b8cd57e3a3e849adb1025e21b4c381365c90b73742dbff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / numba_mpi-1.4.2-py3-none-any.whl

Download URL numba_mpi-1.4.2-py3-none-any.whl
Size 35.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
de90bb88dbc8d98222a16164d0eaf094dcfcadca04f77ba717c0d78c391136c3
BLAKE2b-256 checksum
How to use checksums
bedfed1a72763cb0c6de52c53c0d2313660e87865753273a652d2f24a8579135
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Security for numba-mpi 1.4.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.4.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page