MPI4PY(1)

๐Ÿ“ฆ
version 3.1.5 ยท 3 versions
, in ubuntu noble

๐Ÿ’– MPI4PY ๐Ÿ’– โ€” MPI for Python

okay so you opened manual page MPI4PY(1) (that's section 1 of the manual, bestie, the "user commands" shelf) and the whole thing is titled MPI for Python. Buckle up, this one's a whole journey and it's genuinely iconic. ๐Ÿฆ‹


โœจ NAME โœจ

mpi4py โ€” MPI for Python ๐Ÿ’…

  • Author โ€” Lisandro Dalcin
  • Contact โ€” dalcinl@gmail.com
  • Date โ€” April 01, 2024

๐ŸŽ€ Abstract

So this document is describing the MPI for Python package. What it does is give you Python bindings for the Message Passing Interface (MPI) standard โ€” which basically means your Python apps get to flex on multiple processors on workstations, clusters, and supercomputers. ๐Ÿ”ฅ

It's built on top of the MPI specification, and it gives you an object oriented interface that looks a lot like the MPI-2 C++ bindings. It supports:

  • point-to-point communication (sends, receives) and collective communication (broadcasts, scatters, gathers) of any picklable Python object ๐Ÿ“ฆ
  • and efficient communication of Python objects that expose the Python buffer interface โ€” think NumPy arrays, plus builtin bytes / array / memoryview objects. slay. โœจ

๐ŸŒˆ INTRODUCTION ๐ŸŒˆ

Over the last years, high performance computing has become an affordable resource to many more researchers in the scientific community than ever before. The combo of quality open source software + commodity hardware strongly influenced how popular Beowulf class clusters and cluster of workstations are now. no cap.

Among many parallel computational models, message-passing has proven to be an effective one. This paradigm is specially suited for (but not limited to) distributed memory architectures, and it's used in today's most demanding scientific and engineering applications related to modeling, simulation, design, and signal processing. However โ€” and this is the ๐Ÿ˜ญ part โ€” portable message-passing parallel programming used to be a nightmare in the past because of all the incompatible options developers were faced with. Fortunately, that situation definitely changed after the MPI Forum released its standard specification.

High performance computing is traditionally associated with software development using compiled languages. But here's the tea: in typical applications programs, only a small part of the code is time-critical enough to actually need the efficiency of compiled languages. The rest of the code is generally about memory management, error handling, input/output, and user interaction โ€” and those are usually the most error prone and time-consuming lines of code to write and debug in the whole development process. Interpreted high-level languages can be really advantageous for this kind of task.

For implementing general-purpose numerical computations, MATLAB [1] is the dominant interpreted programming language. On the open source side, Octave and Scilab are well known, freely distributed software packages providing compatibility with the MATLAB language. In this work, we present MPI for Python, a new package enabling applications to exploit multiple processors using standard MPI "look and feel" in Python scripts. ๐Ÿ

[1] MATLAB is a registered trademark of The MathWorks, Inc.

๐Ÿงš What is MPI?

MPI, [mpi-using] [mpi-ref], the Message Passing Interface, is a standardized and portable message-passing system designed to function on a wide variety of parallel computers. The standard defines the syntax and semantics of library routines and lets users write portable programs in the main scientific programming languages (Fortran, C, or C++).

Since its release, the MPI specification [mpi-std1] [mpi-std2] has become the leading standard for message-passing libraries for parallel computers. Implementations are available from vendors of high-performance computers and from well known open source projects like MPICH [mpi-mpich] and Open MPI [mpi-openmpi]. ๐Ÿ‘‘

๐Ÿ What is Python?

Python is a modern, easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming with dynamic typing and dynamic binding. It supports modules and packages, which encourages program modularity and code reuse. Python's elegant syntax, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed. It's easily extended with new functions and data types implemented in C or C++. Python is also suitable as an extension language for customizable applications. ๐Ÿ’œ

Python is an ideal candidate for writing the higher-level parts of large-scale scientific applications [Hinsen97] and driving simulations in parallel architectures [Beazley97] like clusters of PC's or SMP's. Python codes are quickly developed, easily maintained, and can achieve a high degree of integration with other libraries written in compiled languages.

As this work started and evolved, some ideas were borrowed from well known MPI and Python related open source projects from the Internet. shoutout to the OGs ๐Ÿซถ

  • OOMPI
    • It has no relation with Python, but is an excellent object oriented approach to MPI.
    • It's a C++ class library specification layered on top of the C bindings that encapsulates MPI into a functional class hierarchy.
    • It provides a flexible and intuitive interface by adding some abstractions, like Ports and Messages, which enrich and simplify the syntax.
  • Pypar
    • Its interface is rather minimal. There is no support for communicators or process topologies.
    • It does not require the Python interpreter to be modified or recompiled, but does not permit interactive parallel runs.
    • General (picklable) Python objects of any type can be communicated. There is good support for numeric arrays, practically full MPI bandwidth can be achieved.
  • pyMPI
    • It rebuilds the Python interpreter providing a built-in module for message passing. It does permit interactive parallel runs, which are useful for learning and debugging.
    • It provides an interface suitable for basic parallel programing. There is not full support for defining new communicators or process topologies.
    • General (picklable) Python objects can be messaged between processors. There is not support for numeric arrays.
  • Scientific Python
    • It provides a collection of Python modules that are useful for scientific computing.
    • There is an interface to MPI and BSP (Bulk Synchronous Parallel programming).
    • The interface is simple but incomplete and does not resemble the MPI specification. There is support for numeric arrays.

Additionally, we would like to mention some available tools for scientific computing and software development with Python. โœจ

  • NumPy is a package that provides array manipulation and computational capabilities similar to those found in IDL, MATLAB, or Octave. Using NumPy, it is possible to write many efficient numerical data processing applications directly in Python without using any C, C++ or Fortran code.
  • SciPy is an open source library of scientific tools for Python, gathering a variety of high level science and engineering modules together as a single package. It includes modules for graphics and plotting, optimization, integration, special functions, signal and image processing, genetic algorithms, ODE solvers, and others.
  • Cython is a language that makes writing C extensions for the Python language as easy as Python itself. The Cython language is very close to the Python language, but Cython additionally supports calling C functions and declaring C types on variables and class attributes. This allows the compiler to generate very efficient C code from Cython code. This makes Cython the ideal language for wrapping for external C libraries, and for fast C modules that speed up the execution of Python code.
  • SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages like Perl, Tcl/Tk, Ruby and Python. Issuing header files to SWIG is the simplest approach to interfacing C/C++ libraries from a Python module.

๐Ÿ“š the citation wall (do not skip, it's giving academia ๐Ÿ’€)

  • [mpi-std1] โ€” MPI Forum. MPI: A Message Passing Interface Standard. International Journal of Supercomputer Applications, volume 8, number 3-4, pages 159-416, 1994.
  • [mpi-std2] โ€” MPI Forum. MPI: A Message Passing Interface Standard. High Performance Computing Applications, volume 12, number 1-2, pages 1-299, 1998.
  • [mpi-using] โ€” William Gropp, Ewing Lusk, and Anthony Skjellum. Using MPI: portable parallel programming with the message-passing interface. MIT Press, 1994.
  • [mpi-ref] โ€” Mark Snir, Steve Otto, Steven Huss-Lederman, David Walker, and Jack Dongarra. MPI - The Complete Reference, volume 1, The MPI Core. MIT Press, 2nd. edition, 1998.
  • [mpi-mpich] โ€” W. Gropp, E. Lusk, N. Doss, and A. Skjellum. A high-performance, portable implementation of the MPI message passing interface standard. Parallel Computing, 22(6):789-828, September 1996.
  • [mpi-openmpi] โ€” Edgar Gabriel, Graham E. Fagg, George Bosilca, Thara Angskun, Jack J. Dongarra, Jeffrey M. Squyres, Vishal Sahay, Prabhanjan Kambadur, Brian Barrett, Andrew Lumsdaine, Ralph H. Castain, David J. Daniel, Richard L. Graham, and Timothy S. Woodall. Open MPI: Goals, Concept, and Design of a Next Generation MPI Implementation. In Proceedings, 11th European PVM/MPI Users' Group Meeting, Budapest, Hungary, September 2004.
  • [Hinsen97] โ€” Konrad Hinsen. The Molecular Modelling Toolkit: a case study of a large scientific application in Python. In Proceedings of the 6th International Python Conference, pages 29-35, San Jose, Ca., October 1997.
  • [Beazley97] โ€” David M. Beazley and Peter S. Lomdahl. Feeding a large-scale physics application to Python. In Proceedings of the 6th International Python Conference, pages 21-29, San Jose, Ca., October 1997.

๐Ÿ‘‘ OVERVIEW ๐Ÿ‘‘

MPI for Python provides an object oriented approach to message passing which grounds on the standard MPI-2 C++ bindings. The interface was designed with focus in translating MPI syntax and semantics of standard MPI-2 bindings for C++ to Python. Any user of the standard C/C++ MPI bindings should be able to use this module without need of learning a new interface. fr fr, it's giving "you already know this". ๐Ÿ’…

๐Ÿฆ‹ Communicating Python Objects and Array Data

The Python standard library supports different mechanisms for data persistence. Many of them rely on disk storage, but pickling and marshaling can also work with memory buffers.

The pickle modules are out here giving you user-extensible facilities to serialize general Python objects using ASCII or binary formats. And the marshal module? It's serving facilities to serialize built-in Python objects using a binary format specific to Python, but independent of machine architecture issues. slay. โœจ

MPI for Python can communicate any built-in or user-defined Python object taking advantage of the features provided by the pickle module. These facilities will be routinely used to build binary representations of objects to communicate (at sending processes), and restoring them back (at receiving processes). it's giving encode/decode but make it โœจdistributedโœจ.


ngl bestie, the serialization approach we just talked about (pickling and unpickling) is simple and general, yes, but it imposes important overheads in memory as well as processor usage โ€” especially in the scenario of objects with large memory footprints being communicated. ๐Ÿ’€ Pickling general Python objects, ranging from primitive or container built-in types to user-defined classes, necessarily requires computer resources. Processing is also needed for dispatching the appropriate serialization method (which depends on the type of the object) and doing the actual packing. Additional memory is always needed, and if its total amount is not known a priori, many reallocations can occur. Indeed, in the case of large numeric arrays, this is certainly unacceptable and precludes communication of objects occupying half or more of the available memory resources. not the vibe. ๐Ÿ™ˆ

MPI for Python supports direct communication of any object exporting the single-segment buffer interface. This interface is a standard Python mechanism provided by some types (e.g., strings and numeric arrays), allowing access in the C side to a contiguous memory buffer (i.e., address and length) containing the relevant data. This feature, in conjunction with the capability of constructing user-defined MPI datatypes describing complicated memory layouts, enables the implementation of many algorithms involving multidimensional numeric arrays (e.g., image processing, fast Fourier transforms, finite difference schemes on structured Cartesian grids) directly in Python, with negligible overhead, and almost as fast as compiled Fortran, C, or C++ codes. main character energy fr fr. ๐Ÿ‘‘


๐Ÿ’… Communicators ๐Ÿ’…

In MPI for Python, Comm is the base class of communicators. The Intracomm and Intercomm classes are subclasses of the Comm class. The Comm.Is_inter method (and Comm.Is_intra, provided for convenience but not part of the MPI specification) is defined for communicator objects and can be used to determine the particular communicator class. iykyk. ๐ŸŽ€

The two predefined intracommunicator instances are available: COMM_SELF and COMM_WORLD. From them, new communicators can be created as needed. โœจ

The number of processes in a communicator and the calling process rank can be respectively obtained with methods Comm.Get_size and Comm.Get_rank. The associated process group can be retrieved from a communicator by calling the Comm.Get_group method, which returns an instance of the Group class. Set operations with Group objects like Group.Union, Group.Intersection and Group.Difference are fully supported, as well as the creation of new communicators from these groups using Comm.Create and Comm.Create_group. obsessed. ๐Ÿซถ

New communicator instances can be obtained with the Comm.Clone, Comm.Dup and Comm.Split methods, as well as methods Intracomm.Create_intercomm and Intercomm.Merge. ๐ŸŒธ

Virtual topologies (Cartcomm, Graphcomm and Distgraphcomm classes, which are specializations of the Intracomm class) are fully supported. New instances can be obtained from intracommunicator instances with factory methods Intracomm.Create_cart and Intracomm.Create_graph. ๐Ÿ’–


๐Ÿฆ‹ Point-to-Point Communications ๐Ÿฆ‹

Point to point communication is a fundamental capability of message passing systems. This mechanism enables the transmission of data between a pair of processes, one side sending, the other receiving. literally just two besties passing notes. ๐Ÿ“ฉ

MPI provides a set of send and receive functions allowing the communication of typed data with an associated tag. The type information enables the conversion of data representation from one architecture to another in the case of heterogeneous computing environments; additionally, it allows the representation of non-contiguous data layouts and user-defined datatypes, thus avoiding the overhead of (otherwise unavoidable) packing/unpacking operations. The tag information allows selectivity of messages at the receiving end. โœจ


๐Ÿ’Œ Blocking Communications ๐Ÿ’Œ

MPI provides basic send and receive functions that are blocking. These functions block the caller until the data buffers involved in the communication can be safely reused by the application program. so like, it's gonna sit there and wait for you. patience is a virtue bestie. โณ

In MPI for Python, the Comm.Send, Comm.Recv and Comm.Sendrecv methods of communicator objects provide support for blocking point-to-point communications within Intracomm and Intercomm instances. These methods can communicate memory buffers. The variants Comm.send, Comm.recv and Comm.sendrecv can communicate general Python objects. ๐Ÿ’…


๐Ÿงš Nonblocking Communications ๐Ÿงš

On many systems, performance can be significantly increased by overlapping communication and computation. This is particularly true on systems where communication can be executed autonomously by an intelligent, dedicated communication controller. ๐Ÿ”ฅ

MPI provides nonblocking send and receive functions. They allow the possible overlap of communication and computation. Non-blocking communication always comes in two parts: posting functions, which begin the requested operation; and test-for-completion functions, which allow you to discover whether the requested operation has completed. it's giving "start it and check on it later". ๐ŸŒˆ

In MPI for Python, the Comm.Isend and Comm.Irecv methods initiate send and receive operations, respectively. These methods return a Request instance, uniquely identifying the started operation. Its completion can be managed using the Request.Test, Request.Wait and Request.Cancel methods.

โš ๏ธ The management of Request objects and associated memory buffers involved in communication requires a careful, rather low-level coordination. Users must ensure that objects exposing their memory buffers are not accessed at the Python level while they are involved in nonblocking message-passing operations. do NOT touch them while they're busy bestie, fr fr. ๐Ÿ˜ญ

โญ Persistent Communications โญ

Often a communication with the same argument list is repeatedly executed within an inner loop. In such cases, communication can be further optimized by using persistent communication, a particular case of nonblocking communication allowing the reduction of the overhead between processes and communication controllers. Furthermore, this kind of optimization can also alleviate the extra call overheads associated to interpreted, dynamic languages like Python. ๐ŸŒธ

In MPI for Python, the Comm.Send_init and Comm.Recv_init methods create persistent requests for a send and receive operation, respectively. These methods return an instance of the Prequest class, a subclass of the Request class. The actual communication can be effectively started using the Prequest.Start method, and its completion can be managed as previously described. ๐Ÿซถ


๐Ÿ‘‘ Collective Communications ๐Ÿ‘‘

Collective communications allow the transmittal of data between multiple processes of a group simultaneously. The syntax and semantics of collective functions is consistent with point-to-point communication. Collective functions communicate typed data, but messages are not paired with an associated tag; selectivity of messages is implied in the calling order. Additionally, collective functions come in blocking versions only. periodt. ๐Ÿ’…

The more commonly used collective communication operations are the following.

  • Barrier synchronization across all group members.
  • Global communication functions
    • Broadcast data from one member to all members of a group.
    • Gather data from all members to one member of a group.
    • Scatter data from one member to all members of a group.
  • Global reduction operations such as sum, maximum, minimum, etc.

In MPI for Python, the Comm.Bcast, Comm.Scatter, Comm.Gather, Comm.Allgather, Comm.Alltoall methods provide support for collective communications of memory buffers. The lower-case variants Comm.bcast, Comm.scatter, Comm.gather, Comm.allgather and Comm.alltoall can communicate general Python objects. The vector variants (which can communicate different amounts of data to each process) Comm.Scatterv, Comm.Gatherv, Comm.Allgatherv, Comm.Alltoallv and Comm.Alltoallw are also supported, they can only communicate objects exposing memory buffers. ๐ŸŽ€

Global reduction operations on memory buffers are accessible through the Comm.Reduce, Comm.Reduce_scatter, Comm.Allreduce, Intracomm.Scan and Intracomm.Exscan methods. The lower-case variants Comm.reduce, Comm.allreduce, Intracomm.scan and Intracomm.exscan can communicate general Python objects; however, the actual required reduction computations are performed sequentially at some process. All the predefined (i.e., SUM, PROD, MAX, etc.) reduction operations can be applied. โœจ


๐Ÿš€ Support for GPU-aware MPI ๐Ÿš€

Several MPI implementations, including Open MPI and MVAPICH, support passing GPU pointers to MPI calls to avoid explicit data movement between the host and the device. On the Python side, GPU arrays have been implemented by many libraries that need GPU computation, such as CuPy, Numba, PyTorch, and PyArrow. In order to increase library interoperability, two kinds of zero-copy data exchange protocols are defined and agreed upon: DLPack and CUDA Array Interface. For example, a CuPy array can be passed to a Numba CUDA-jit kernel. ๐Ÿ”ฅ

MPI for Python provides an experimental support for GPU-aware MPI. This feature requires:

  1. mpi4py is built against a GPU-aware MPI library.
  2. The Python GPU arrays are compliant with either of the protocols.

See the Tutorial section for further information. We note that

  • Whether or not a MPI call can work for GPU arrays depends on the underlying MPI implementation, not on mpi4py.
  • This support is currently experimental and subject to change in the future. ๐Ÿ’€

๐ŸŒˆ Dynamic Process Management ๐ŸŒˆ

In the context of the MPI-1 specification, a parallel application is static; that is, no processes can be added to or deleted from a running application after it has been started. Fortunately, this limitation was addressed in MPI-2. The new specification added a process management model providing a basic interface between an application and external resources and process managers. glow up fr fr. ๐Ÿ’–

Like, this MPI-2 extension is genuinely iconic, no cap โ€” it's lowkey perfect for sequential apps built on top of parallel modules, or for parallel apps rocking a client/server model. The MPI-2 process model hands you a mechanism to spin up new processes and get them talking to the MPI application that already exists. It also gives you mechanisms to connect two MPI applications that already exist, even when one of them didn't start the other. Fr fr, it's giving matchmaker energy. ๐Ÿ’–

So in MPI for Python, you can create new independent process groups by calling the Intracomm.Spawn method inside an intracommunicator. That call hands back a brand-new intercommunicator (so, an Intercomm instance) over at the parent process group. Meanwhile the child process group can grab the matching intercommunicator by calling the Comm.Get_parent class method. And then, on each side, that shiny new intercommunicator is your bestie for doing point to point and collective communications between the parent and child groups. Slay. โœจ

Or โ€” plot twist โ€” disjoint groups of processes can link up using a client/server approach. Any server application has to first call the Open_port function to open a port, and the Publish_name function to publish a provided service, and then call the Intracomm.Accept method. Any client application can first hunt down a published service by calling the Lookup_name function, which returns the port where a server can be contacted, and next call the Intracomm.Connect method. Both Intracomm.Accept and Intracomm.Connect hand you back an Intercomm instance. When the client/server processes don't need the connection anymore, all of them have to cooperatively call the Comm.Disconnect method. And heads up: server applications should also free up resources by calling the Unpublish_name and Close_port functions. ๐Ÿซถ


๐Ÿฆ‹ One-Sided Communications ๐Ÿฆ‹

One-sided communications (they also call it Remote Memory Access, or RMA) is the glow-up on the classic two-sided, send/receive based MPI communication model โ€” it swaps in a one-sided, put/get based interface. One-sided communication can take advantage of the capabilities of highly specialized network hardware. On top of that, this extension lowers latency and software overhead in applications written using a shared-memory-like paradigm. It's giving efficiency, periodt. ๐Ÿ”ฅ

The MPI specification revolves around objects called windows; intuitively, they specify regions of a process's memory that have been made available for remote read and write operations. You can access those published memory blocks through three functions: for put (remote send), get (remote write), and accumulate (remote update or reduction) of data items. And a much larger number of functions support different synchronization styles โ€” the semantics of these synchronization operations are, ngl, fairly complex. ๐Ÿ’€

In MPI for Python, one-sided operations are available by using instances of the Win class. New window objects are created by calling the Win.Create method at all processes within a communicator and specifying a memory buffer. When a window instance is no longer needed, you should call the Win.Free method.

The three one-sided MPI operations for remote write, read and reduction are available through calling the methods Win.Put, Win.Get, and Win.Accumulate respectively within a Win instance. These methods need an integer rank identifying the target process and an integer offset relative the base address of the remote memory block being accessed.

The one-sided operations read, write, and reduction are implicitly nonblocking, and must be synchronized by using two primary modes:

  • Active target synchronization โ€” requires the origin process to call the Win.Start and Win.Complete methods at the origin process, and the target process cooperates by calling the Win.Post and Win.Wait methods. There's also a collective variant provided by the Win.Fence method.
  • Passive target synchronization โ€” way more lenient: only the origin process calls the Win.Lock and Win.Unlock methods.

Locks are used to protect remote accesses to the locked remote window, and to protect local load/store accesses to a locked local window. ๐Ÿ”’


๐Ÿ“ Parallel Input/Output ๐Ÿ“

The POSIX standard gives you a model of a widely portable file system. But โ€” and this is the whole tea โ€” the optimization you need for parallel input/output cannot be achieved with that generic interface. To make sure you get efficiency and scalability, the underlying parallel input/output system has to provide a high-level interface supporting partitioning of file data among processes, plus a collective interface supporting complete transfers of global data structures between process memories and files. And you can squeeze out even more efficiency via support for asynchronous input/output, strided accesses to data, and control over physical file layout on storage devices. This whole scenario is exactly what motivated the inclusion of a custom interface in the MPI-2 standard, so we could support more elaborated parallel input/output operations. ๐Ÿ’…

The MPI specification for parallel input/output revolves around the use of objects called files. As defined by MPI, files are not just contiguous byte streams. Instead, they're regarded as ordered collections of typed data items. MPI supports sequential or random access to any integral set of these items. And on top of that, files are opened collectively by a group of processes.

The common patterns for accessing a shared file (broadcast, scatter, gather, reduction) are expressed by using user-defined datatypes. Compared to the communication patterns of point-to-point and collective communications, this approach has the advantage of added flexibility and expressiveness. Data access operations (read and write) are defined for different kinds of:

  • positioning โ€” using explicit offsets, individual file pointers, and shared file pointers
  • coordination โ€” non-collective and collective
  • synchronism โ€” blocking, nonblocking, and split collective with begin/end phases

In MPI for Python, all MPI input/output operations are performed through instances of the File class. You get file handles by calling the File.Open method at all processes within a communicator and providing a file name and the intended access mode. After use, they must be closed by calling the File.Close method. Files can even be deleted by calling the method File.Delete. ๐Ÿ—‘๏ธ

After creation, files are typically associated with a per-process view. The view defines the current set of data visible and accessible from an open file as an ordered set of elementary datatypes. You can set and query this data layout with the File.Set_view and File.Get_view methods respectively. โœจ

Actual input/output operations are achieved by many methods combining read and write calls with different behavior regarding positioning, coordination, and synchronism. Summing up: MPI for Python provides the thirty (30) methods defined in MPI-2 for reading from or writing to files using explicit offsets or file pointers (individual or shared), in blocking or nonblocking and collective or noncollective versions. Thirty! Obsessed. ๐Ÿ‘‘


๐ŸŒˆ Environmental Management ๐ŸŒˆ

๐Ÿ’œ Initialization and Exit ๐Ÿ’œ

Module functions Init or Init_thread and Finalize provide MPI initialization and finalization respectively. Module functions Is_initialized and Is_finalized provide the respective tests for initialization and finalization.

NOTE: MPI_Init() or MPI_Init_thread() is actually called when you import the MPI module from the mpi4py package, but only if MPI is not already initialized. In such case, calling Init or Init_thread from Python is expected to generate an MPI error, and in turn an exception will be raised. ๐Ÿ˜ญ
NOTE: MPI_Finalize() is registered (by using Python C/API function Py_AtExit()) for being automatically called when Python processes exit, but only if mpi4py actually initialized MPI. Therefore, there is no need to call Finalize from Python to ensure MPI finalization. She handles it herself, bestie. ๐Ÿ’…

โญ Implementation Information โญ

  • The MPI version number can be retrieved from module function Get_version. It returns a two-integer tuple (version, subversion).
  • The Get_processor_name function can be used to access the processor name.
  • The values of predefined attributes attached to the world communicator can be obtained by calling the Comm.Get_attr method within the COMM_WORLD instance.

โฐ Timers โฐ

MPI timer functionalities are available through the Wtime and Wtick functions. Tick tock, bb. ๐Ÿ•ฐ๏ธ

๐Ÿ›‘ Error Handling ๐Ÿ›‘

In order facilitate handle sharing with other Python modules interfacing MPI-based parallel libraries, the predefined MPI error handlers ERRORS_RETURN and ERRORS_ARE_FATAL can be assigned to and retrieved from communicators using methods Comm.Set_errhandler and Comm.Get_errhandler, and similarly for windows and files.

When the predefined error handler ERRORS_RETURN is set, errors returned from MPI calls within Python code will raise an instance of the exception class Exception, which is a subclass of the standard Python exception RuntimeError.

NOTE: After import, mpi4py overrides the default MPI rules governing inheritance of error handlers. The ERRORS_RETURN error handler is set in the predefined COMM_SELF and COMM_WORLD communicators, as well as any new Comm, Win, or File instance created through mpi4py. If you ever pass such handles to C/C++/Fortran library code, it is recommended to set the ERRORS_ARE_FATAL error handler on them to ensure MPI errors do not pass silently. ๐Ÿ™ˆ
WARNING: Importing with from mpi4py.MPI import * will cause a name clashing with the standard Python Exception base class. Not the vibe. ๐Ÿ’€

๐ŸŽ€ TUTORIAL ๐ŸŽ€

WARNING: Under construction. Contributions very welcome! ๐Ÿซถ
TIP: Rolf Rabenseifner at HLRS developed a comprehensive MPI-3.1/4.0 course with slides and a large set of exercises including solutions. This material is available online for self-study. The slides and exercises show the C, Fortran, and Python (mpi4py) interfaces. For performance reasons, most Python exercises use NumPy arrays and communication routines involving buffer-like objects. ๐Ÿ“š
TIP: Victor Eijkhout at TACC authored the book Parallel Programming for Science and Engineering. This book is available online in PDF and HTML formats. The book covers parallel programming with MPI and OpenMP in C/C++ and Fortran, and MPI in Python using mpi4py. ๐Ÿ“–

MPI for Python supports convenient, pickle-based communication of generic Python object as well as fast, near C-speed, direct array data communication of buffer-provider objects (e.g., NumPy arrays). Both vibes. ๐Ÿฆ‹

  • Communication of generic Python objects You have to use methods with all-lowercase names, like Comm.send, Comm.recv, Comm.bcast, Comm.scatter, Comm.gather . An object to be sent is passed as a parameter to the communication call, and the received object is simply the return value.

The Comm.isend and Comm.irecv methods hand you back Request instances, bestie โ€” and you finish those off with the Request.test and Request.wait methods. That's the whole vibe. ๐ŸŽ€

The Comm.recv and Comm.irecv methods can also be handed a buffer object that you can reuse over and over again to receive messages, which means no internal memory allocation happening every single time. But heads up: that buffer has to be big enough to hold whatever got transmitted, so literally any buffer you pass to Comm.recv or Comm.irecv must be at least as long as the pickled data that was sent to the receiver. No shortcuts, no tiny buffers, no exceptions. ๐Ÿ’…

Collective calls like Comm.scatter, Comm.gather, Comm.allgather, Comm.alltoall want a single value or a sequence of Comm.size elements over at the root or at all processes. What do they give back? A single value, a list of Comm.size elements, or None. That's it. ๐Ÿฆ‹

NOTE: MPI for Python uses the highest protocol version available in the Python runtime (see the HIGHEST_PROTOCOL constant in the pickle module). The default protocol can be changed at import time by setting the MPI4PY_PICKLE_PROTOCOL environment variable, or at runtime by assigning a different value to the PROTOCOL attribute of the pickle object within the MPI module.

  • Communication of buffer-like objects ๐Ÿ’–

Okay so for these you HAVE to use method names that start with an upper-case letter, like Comm.Send, Comm.Recv, Comm.Bcast, Comm.Scatter, Comm.Gather. Capitalization is not optional, it's the whole point. ๐Ÿ‘‘

In general, buffer arguments to these calls have to be explicitly specified using a 2/3-list/tuple like [data, MPI.DOUBLE], or [data, count, MPI.DOUBLE] โ€” and just so you know, that first one uses the byte-size of data and the extent of the MPI datatype to define count.

For vector collective communication operations like Comm.Scatterv and Comm.Gatherv, buffer arguments get specified as [data, count, displ, datatype], where count and displ are sequences of integral values. โœจ

Automatic MPI datatype discovery for NumPy/GPU arrays and PEP-3118 buffers is supported, but limited to basic C types (all C/C99-native signed/unsigned integral types and single/double precision real/complex floating types) and to whether matching datatypes actually exist in the underlying MPI implementation. When it does work, you can just pass the buffer-provider object directly as a buffer argument and the count and MPI datatype get inferred for you. The way that justโ€ฆ works. ๐Ÿซถ

If mpi4py is built against a GPU-aware MPI implementation, GPU arrays can be passed to upper-case methods as long as they have either the __dlpack__ and __dlpack_device__ methods or the __cuda_array_interface__ attribute, compliant with the respective standard specifications. Also, only C-contiguous or Fortran-contiguous GPU arrays are supported. And this part is important: GPU buffers must be fully ready before any MPI routines operate on them, otherwise you get race conditions. Use the synchronization API of your array library to make sure. mpi4py does not have access to any GPU-specific functionality and thus cannot perform this operation automatically for users. It's giving "you have to do it yourself, bestie". ๐Ÿ˜ญ

๐Ÿƒโœจ Running Python scripts with MPI โœจ๐Ÿƒ

Most MPI programs can be run with the command mpiexec. In practice, running Python programs looks like:

$ mpiexec -n 4 python script.py

โ€ฆwhich runs the program with 4 processors. Four of them. Slay. ๐Ÿ’…

๐Ÿ’Œ Point-to-Point Communication ๐Ÿ’Œ

  • Python objects (pickle under the hood): ๐Ÿฅ’
from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
    data = {'a': 7, 'b': 3.14}
    comm.send(data, dest=1, tag=11)
elif rank == 1:
    data = comm.recv(source=0, tag=11)
  • Python objects with non-blocking communication: ๐Ÿฆ‹
from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
    data = {'a': 7, 'b': 3.14}
    req = comm.isend(data, dest=1, tag=11)
    req.wait()
elif rank == 1:
    req = comm.irecv(source=0, tag=11)
    data = req.wait()
  • NumPy arrays (the fast way!): ๐Ÿ”ฅ
from mpi4py import MPI
import numpy

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

# passing MPI datatypes explicitly
if rank == 0:
    data = numpy.arange(1000, dtype='i')
    comm.Send([data, MPI.INT], dest=1, tag=77)
elif rank == 1:
    data = numpy.empty(1000, dtype='i')
    comm.Recv([data, MPI.INT], source=0, tag=77)

# automatic MPI datatype discovery
if rank == 0:
    data = numpy.arange(100, dtype=numpy.float64)
    comm.Send(data, dest=1, tag=13)
elif rank == 1:
    data = numpy.empty(100, dtype=numpy.float64)
    comm.Recv(data, source=0, tag=13)

๐ŸŒˆ Collective Communication ๐ŸŒˆ

  • Broadcasting a Python dictionary: ๐Ÿ“ข
from mpi4py import MPI

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
    data = {'key1' : [7, 2.72, 2+3j],
            'key2' : ( 'abc', 'xyz')}
else:
    data = None
data = comm.bcast(data, root=0)
  • Scattering Python objects: ๐Ÿ“
from mpi4py import MPI

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

if rank == 0:
    data = [(i+1)**2 for i in range(size)]
else:
    data = None
data = comm.scatter(data, root=0)
assert data == (rank+1)**2
  • Gathering Python objects: ๐ŸŽ€
from mpi4py import MPI

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

data = (rank+1)**2
data = comm.gather(data, root=0)
if rank == 0:
    for i in range(size):
        assert data[i] == (i+1)**2
else:
    assert data is None
  • Broadcasting a NumPy array: โญ
from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

if rank == 0:
    data = np.arange(100, dtype='i')
else:
    data = np.empty(100, dtype='i')
comm.Bcast(data, root=0)
for i in range(100):
    assert data[i] == i
  • Scattering NumPy arrays: โœจ
from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

sendbuf = None
if rank == 0:
    sendbuf = np.empty([size, 100], dtype='i')
    sendbuf.T[:,:] = range(size)
recvbuf = np.empty(100, dtype='i')
comm.Scatter(sendbuf, recvbuf, root=0)
assert np.allclose(recvbuf, rank)
  • Gathering NumPy arrays: ๐Ÿ’œ
from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

sendbuf = np.zeros(100, dtype='i') + rank
recvbuf = None
if rank == 0:
    recvbuf = np.empty([size, 100], dtype='i')
comm.Gather(sendbuf, recvbuf, root=0)
if rank == 0:
    for i in range(size):
        assert np.allclose(recvbuf[i,:], i)
  • Parallel matrix-vector product: ๐Ÿงฎ
from mpi4py import MPI
import numpy

def matvec(comm, A, x):
    m = A.shape[0] # local rows
    p = comm.Get_size()
    xg = numpy.zeros(m*p, dtype='d')
    comm.Allgather([x,  MPI.DOUBLE],
                   [xg, MPI.DOUBLE])
    y = numpy.dot(A, xg)
    return y

๐Ÿ’พ MPI-IO ๐Ÿ’พ

  • Collective I/O with NumPy arrays: ๐Ÿ—‚๏ธ
from mpi4py import MPI
import numpy as np

amode = MPI.MODE_WRONLY|MPI.MODE_CREATE
comm = MPI.COMM_WORLD
fh = MPI.File.Open(comm, "./datafile.contig", amode)

buffer = np.empty(10, dtype=np.int)
buffer[:] = comm.Get_rank()

offset = comm.Get_rank()*buffer.nbytes
fh.Write_at_all(offset, buffer)

fh.Close()
  • Non-contiguous Collective I/O with NumPy arrays and datatypes: ๐ŸŒ€
from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

amode = MPI.MODE_WRONLY|MPI.MODE_CREATE
fh = MPI.File.Open(comm, "./datafile.noncontig", amode)

item_count = 10

buffer = np.empty(item_count, dtype='i')
buffer[:] = rank

filetype = MPI.INT.Create_vector(item_count, 1, size)
filetype.Commit()

displacement = MPI.INT.Get_size()*rank
fh.Set_view(displacement, filetype=filetype)

fh.Write_all(buffer)
filetype.Free()
fh.Close()

๐Ÿงš Dynamic Process Management ๐Ÿงš

  • Compute Pi - Master (or parent, or client) side: ๐Ÿ‘‘
#!/usr/bin/env python
from mpi4py import MPI
import numpy
import sys

comm = MPI.COMM_SELF.Spawn(sys.executable,
                           args=['cpi.py'],
                           maxprocs=5)

N = numpy.array(100, 'i')
comm.Bcast([N, MPI.INT], root=MPI.ROOT)
PI = numpy.array(0.0, 'd')
comm.Reduce(None, [PI, MPI.DOUBLE],
            op=MPI.SUM, root=MPI.ROOT)
print(PI)

comm.Disconnect()
  • Compute Pi - Worker (or child, or server) side: ๐Ÿฃ
#!/usr/bin/env python
from mpi4py import MPI
import numpy

comm = MPI.Comm.Get_parent()
size = comm.Get_size()
rank = comm.Get_rank()

N = numpy.array(0, dtype='i')
comm.Bcast([N, MPI.INT], root=0)
h = 1.0 / N; s = 0.0
for i in range(rank, N, size):
    x = h * (i + 0.5)
    s += 4.0 / (1.0 + x**2)
PI = numpy.array(s * h, dtype='d')
comm.Reduce([PI, MPI.DOUBLE], None,
            op=MPI.SUM, root=0)

comm.Disconnect()

๐ŸŽฎ CUDA-aware MPI + Python GPU arrays ๐ŸŽฎ

  • Reduce-to-all CuPy arrays: ๐Ÿ”ฅ
from mpi4py import MPI
import cupy as cp

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

sendbuf = cp.arange(10, dtype='i')
recvbuf = cp.empty_like(sendbuf)
assert hasattr(sendbuf, '__cuda_array_interface__')
assert hasattr(recvbuf, '__cuda_array_interface__')
cp.cuda.get_current_stream().synchronize()
comm.Allreduce(sendbuf, recvbuf)

assert cp.allclose(recvbuf, sendbuf*size)

๐Ÿ‘‘ One-Sided Communications ๐Ÿ‘‘

  • Read from (write to) the entire RMA window: ๐ŸŒธ
import numpy as np
from mpi4py import MPI
from mpi4py.util import dtlib

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

datatype = MPI.FLOAT
np_dtype = dtlib.to_numpy_dtype(datatype)
itemsize = datatype.Get_size()
N = 10
win_size = N * itemsize if rank == 0 else 0
win = MPI.Win.Allocate(win_size, comm=comm)

buf = np.empty(N, dtype=np_dtype)
if rank == 0:
    buf.fill(42)
    win.Lock(rank=0)
    win.Put(buf, target_rank=0)
    win.Unlock(rank=0)
    comm.Barrier()
else:
    comm.Barrier()
    win.Lock(rank=0)
    win.Get(buf, target_rank=0)
    win.Unlock(rank=0)
    assert np.all(buf == 42)
  • Accessing a part of the RMA window using the target argument, which is defined as (offset, count, datatype):
import numpy as np
from mpi4py import MPI
from mpi4py.util import dtlib

comm = MPI.COMM_WORLD
rank = comm.Get_rank()

datatype = MPI.FLOAT
np_dtype = dtlib.to_numpy_dtype(datatype)
itemsize = datatype.Get_size()

N = comm.Get_size() + 1
win_size = N * itemsize if rank == 0 else 0
win = MPI.Win.Allocate(
    size=win_size,
    disp_unit=itemsize,
    comm=comm,
)
if rank == 0:
    mem = np.frombuffer(win, dtype=np_dtype)
    mem[:] = np.arange(len(mem), dtype=np_dtype)
comm.Barrier()

buf = np.zeros(3, dtype=np_dtype)
target = (rank, 2, datatype)
win.Lock(rank=0)
win.Get(buf, target_rank=0, target=target)
win.Unlock(rank=0)
assert np.all(buf == [rank, rank+1, 0])

๐Ÿงš Wrapping with SWIG ๐Ÿงš

  • C source, bestie:
/* file: helloworld.c */
void sayhello(MPI_Comm comm)
{
  int size, rank;
  MPI_Comm_size(comm, &size);
  MPI_Comm_rank(comm, &rank);
  printf("Hello, World! "
         "I am process %d of %d.\n",
         rank, size);
}
  • SWIG interface file:
// file: helloworld.i
%module helloworld
%{
#include <mpi.h>
#include "helloworld.c"
}%

%include mpi4py/mpi4py.i
%mpi4py_typemap(Comm, MPI_Comm);
void sayhello(MPI_Comm comm);
  • Try it in the Python prompt and watch it eat, fr fr:
>>> from mpi4py import MPI
>>> import helloworld
>>> helloworld.sayhello(MPI.COMM_WORLD)
Hello, World! I am process 0 of 1.

๐Ÿฆ‹ Wrapping with F2Py ๐Ÿฆ‹

  • Fortran 90 source:
! file: helloworld.f90
subroutine sayhello(comm)
  use mpi
  implicit none
  integer :: comm, rank, size, ierr
  call MPI_Comm_size(comm, size, ierr)
  call MPI_Comm_rank(comm, rank, ierr)
  print *, 'Hello, World! I am process ',rank,' of ',size,'.'
end subroutine sayhello
  • Compiling example using f2py:
$ f2py -c --f90exec=mpif90 helloworld.f90 -m helloworld
  • Try it in the Python prompt:
>>> from mpi4py import MPI
>>> import helloworld
>>> fcomm = MPI.COMM_WORLD.py2f()
>>> helloworld.sayhello(fcomm)
Hello, World! I am process 0 of 1.

๐ŸŒˆ MPI4PY ๐ŸŒˆ

๐Ÿ’– Runtime configuration options ๐Ÿ’–

mpi4py.rc

Okay so this object has attributes exposing runtime configuration options that become effective at import time of the MPI module. Slay.

โœจ Attributes Summary โœจ

  • initialize โ€” Automatic MPI initialization at import
  • threads โ€” Request initialization with thread support
  • thread_level โ€” Level of thread support to request
  • finalize โ€” Automatic MPI finalization at exit
  • fast_reduce โ€” Use tree-based reductions for objects
  • recv_mprobe โ€” Use matched probes to receive objects
  • errors โ€” Error handling policy

๐ŸŽ€ Attributes Documentation ๐ŸŽ€

  • mpi4py.rc.initialize โ€” Automatic MPI initialization at import.
    • Type: bool
    • Default: True
    • SEE ALSO: MPI4PY_RC_INITIALIZE
  • mpi4py.rc.threads โ€” Request initialization with thread support.
    • Type: bool
    • Default: True
    • SEE ALSO: MPI4PY_RC_THREADS
  • mpi4py.rc.thread_level โ€” Level of thread support to request.
    • Type: str
    • Default: "multiple"
    • Choices: "multiple", "serialized", "funneled", "single"
    • SEE ALSO: MPI4PY_RC_THREAD_LEVEL
  • mpi4py.rc.finalize โ€” Automatic MPI finalization at exit.
    • Type: None or bool
    • Default: None
    • SEE ALSO: MPI4PY_RC_FINALIZE
  • mpi4py.rc.fast_reduce โ€” Use tree-based reductions for objects.
    • Type: bool
    • Default: True
    • SEE ALSO: MPI4PY_RC_FAST_REDUCE
  • mpi4py.rc.recv_mprobe โ€” Use matched probes to receive objects.
    • Type: bool
    • Default: True
    • SEE ALSO: MPI4PY_RC_RECV_MPROBE
  • mpi4py.rc.errors โ€” Error handling policy.
    • Type: str
    • Default: "exception"
    • Choices: "exception", "default", "fatal"
    • SEE ALSO: MPI4PY_RC_ERRORS

๐ŸŒธ Example ๐ŸŒธ

MPI for Python features automatic initialization and finalization of the MPI execution environment. By using the mpi4py.rc object, MPI initialization and finalization can be handled programatically, and honestly? iconic:

import mpi4py
mpi4py.rc.initialize = False  # do not initialize MPI automatically
mpi4py.rc.finalize = False    # do not finalize MPI automatically

from mpi4py import MPI # import the 'MPI' module

MPI.Init()      # manual initialization of the MPI environment
...             # your finest code here ...
MPI.Finalize()  # manual finalization of the MPI environment

๐Ÿ’… Environment variables ๐Ÿ’…

The following environment variables override the corresponding attributes of the mpi4py.rc and MPI.pickle objects at import time of the MPI module. iykyk.

NOTE: For variables of boolean type, accepted values are 0 and 1 (interpreted as False and True, respectively), and strings specifying a YAML boolean value (case-insensitive).
  • MPI4PY_RC_INITIALIZE
    • Type: bool
    • Default: True
    • Whether to automatically initialize MPI at import time of the mpi4py.MPI module.
    • SEE ALSO: mpi4py.rc.initialize
    • New in version 3.1.0.
  • MPI4PY_RC_FINALIZE
    • Type: None | bool
    • Default: None
    • Choices: None, True, False
    • Whether to automatically finalize MPI at exit time of the Python process.
    • SEE ALSO: mpi4py.rc.finalize
    • New in version 3.1.0.
  • MPI4PY_RC_THREADS
    • Type: bool
    • Default: True
    • Whether to initialize MPI with thread support.
    • SEE ALSO: mpi4py.rc.threads
    • New in version 3.1.0.
  • MPI4PY_RC_THREAD_LEVEL
    • Default: "multiple"
    • Choices: "single", "funneled", "serialized", "multiple"
    • The level of required thread support.
    • SEE ALSO: mpi4py.rc.thread_level
    • New in version 3.1.0.
  • MPI4PY_RC_FAST_REDUCE
    • Type: bool
    • Default: True
    • Whether to use tree-based reductions for objects.
    • SEE ALSO: mpi4py.rc.fast_reduce
    • New in version 3.1.0.
  • MPI4PY_RC_RECV_MPROBE
    • Type: bool
    • Default: True
    • Whether to use matched probes to receive objects.
    • SEE ALSO: mpi4py.rc.recv_mprobe
  • MPI4PY_RC_ERRORS
    • Default: "exception"
    • Choices: "exception", "default", "fatal"
    • Controls default MPI error handling policy.
    • SEE ALSO: mpi4py.rc.errors
    • New in version 3.1.0.
  • MPI4PY_PICKLE_PROTOCOL
    • Type: int
    • Default: pickle.HIGHEST_PROTOCOL
    • Controls the default pickle protocol to use when communicating Python objects.
    • SEE ALSO: PROTOCOL attribute of the MPI.pickle object within the MPI module.
    • New in version 3.1.0.
  • MPI4PY_PICKLE_THRESHOLD
    • Type: int
    • Default: 262144
    • Controls the default buffer size threshold for switching from in-band to out-of-band buffer handling when using pickle protocol version 5 or higher.
    • SEE ALSO: Module mpi4py.util.pkl5.
    • New in version 3.1.2.

โญ Miscellaneous functions โญ

  • mpi4py.profile()
  • mpi4py.get_config()
  • mpi4py.get_include()

okay bestie we are now officially inside the MPI4PY.MPI zone โœจ โ€” this is where all the actual objects and functions live, and there are so many of them, so buckle up. They come in two big flavours: Classes (the things you make instances of, the little guys) and Functions (the standalone calls, the free agents). Both are sorted into cute little themed clusters and honestly? the organization ate ๐Ÿ’…


๐ŸŒธ Classes ๐ŸŒธ

๐ŸŽ€ Ancillary ๐ŸŽ€

the support squad. the backstage crew. you don't always see them but nothing works without them ๐Ÿ’–

  • Datatype โ€” the type-description baddie, tells MPI what shape your data is
  • Status โ€” the receipt you get back from a communication call, holds the deets about what actually went down
  • Request โ€” the lil ticket for a nonblocking operation, your "hey did that finish yet" token
  • Prequest โ€” a persistent request, the version that sticks around so you can reuse it
  • Grequest โ€” a generalized request, the flexible one that lets you build custom completion rules
  • Op โ€” the operation object, for when you're doing reductions and need to say how to combine things
  • Group โ€” an ordered set of processes, the guest list ๐Ÿ“
  • Info โ€” a bag of key/value hints you hand to stuff that accepts hints

๐Ÿ’ซ Communication ๐Ÿ’ซ

the main character energy section, lowkey. this is where the actual talking happens ๐Ÿ“ฃ

  • Comm โ€” the base communicator, the abstract parent of everything chatty
  • Intracomm โ€” a communicator within one group of processes, the classic one
  • Topocomm โ€” a communicator with a topology, so you can do the fancy neighbor stuff
  • Cartcomm โ€” Cartesian topology, think grids and tori, very coordinates-core
  • Graphcomm โ€” general graph topology, arbitrary connection vibes
  • Distgraphcomm โ€” distributed graph topology, the graph version that scales across nodes
  • Intercomm โ€” a communicator that spans between two groups, the bridge situation ๐ŸŒ‰
  • Message โ€” a matched send/receive pair, the actual envelope of data that moved

๐Ÿ‘‘ One-sided operations ๐Ÿ‘‘

just one icon in here and she's running the whole room

  • Win โ€” the window object for RMA (remote memory access), where other processes can peek at your memory. iconic, honestly.

๐ŸŒˆ Input/Output ๐ŸŒˆ

  • File โ€” the object for parallel file I/O, because sometimes you gotta write to disk with your whole squad at once

๐Ÿฆ‹ Error handling ๐Ÿฆ‹

when things go sideways, these catch you ๐Ÿ˜ญ

  • Errhandler โ€” the handler object, decides what happens when an error pops off
  • Exception โ€” the exception type that actually gets raised into your Python code

๐Ÿงš Auxiliary ๐Ÿงš

the misc drawer, the junk drawer, the "we didn't know where else to put it" drawer (affectionate)

  • Pickle โ€” the pickling support, for serializing your Python objects across the wire
  • memory โ€” the memory module, for buffer-related things

โœจ Functions โœจ

๐Ÿ”ฅ Version inquiry ๐Ÿ”ฅ

just wanna know what you're working with? valid. here's the tea โ˜•

  • Get_version โ€” returns the version of the MPI standard that's in play
  • Get_library_version โ€” returns a string describing the actual MPI library implementation

โญ Initialization and finalization โญ

the opening and closing credits of your MPI program. you literally cannot skip these ๐ŸŽฌ

  • Init โ€” boots up MPI. call it first, bestie.
  • Init_thread โ€” same idea but you also request a specific threading level, for when you're feeling multithreaded
  • Finalize โ€” shuts MPI down. call it last. ๐Ÿซถ
  • Is_initialized โ€” checks whether Init has happened yet, returns a bool
  • Is_finalized โ€” checks whether Finalize has happened yet, returns a bool
  • Query_thread โ€” asks what threading level you actually got (spoiler: it might not be the one you asked for ๐Ÿ™ˆ)
  • Is_thread_main โ€” checks whether the calling thread is the one that called Init/Init_thread

๐Ÿ’œ Memory allocation ๐Ÿ’œ

  • Alloc_mem โ€” allocates memory that's suitable for MPI to use directly
  • Free_mem โ€” frees memory that Alloc_mem handed you. don't skip this, no cap.

๐ŸŒธ Address manipulation ๐ŸŒธ

for when you need to do math on memory addresses, which is a whole vibe

  • Get_address โ€” gives you the address of a memory location as an integer
  • Aint_add โ€” adds an integer offset to an address
  • Aint_diff โ€” subtracts one address from another, gives you the difference

๐ŸŽ€ Timer ๐ŸŽ€

for all your "how long did that take" needs โฑ๏ธ

  • Wtick โ€” returns the resolution of Wtime, i.e. how fine-grained the clock is
  • Wtime โ€” returns the current wall-clock time as a float

๐ŸŒˆ Error handling ๐ŸŒˆ

  • Get_error_class โ€” turns an error code into its error class
  • Get_error_string โ€” turns an error code into a human-readable string
  • Add_error_class โ€” registers a brand new error class
  • Add_error_code โ€” registers a new error code inside a given error class
  • Add_error_string โ€” attaches a string message to an error code

๐Ÿฆ‹ Dynamic process management ๐Ÿฆ‹

okay so if you're looking at the module map, this whole lil branch is Dynamic process management and she's very much "I introduce people to each other" energy. the whole squad:

  • Open_port โ€” โœจ her.
  • Close_port โ€” and this one when you're done with her. ๐Ÿ’…
  • Publish_name โ€” a name, out there in the world. ๐ŸŽ€
  • Unpublish_name โ€” taking that name back, no cap.
  • Lookup_name โ€” and finding one when you need it. ๐Ÿ”

โœจ Miscellanea โœจ

this is the junk drawer of the module, the misc shelf, and honestly she ate. everything that didn't fit anywhere else lives here:

  • Attach_buffer
  • Detach_buffer
  • Compute_dims
  • Compute_dims โ€” wait no, one time only bestie, sorry, she's just that iconic. ๐Ÿ˜ญ
  • Get_processor_name
  • Register_datarep
  • Pcontrol

(fr fr, every single one of those is in the map โ€” go look.)


๐ŸŽ€ Utilities ๐ŸŽ€

the utilities branch is lowkey a solo act. one baddie carrying the entire section:

  • get_vendor โ€” ๐ŸŒˆ just her. main character behaviour, we love to see it.

๐Ÿ‘‘ Attributes ๐Ÿ‘‘

okay bestie. sit down. hydrate. this next column on the map is Attributes and it is long. we are not skipping a single one, we are not summarising, we are reading the whole thing top to bottom, periodt. ๐Ÿ’€

  • UNDEFINED
  • ANY_SOURCE
  • ANY_TAG
  • PROC_NULL
  • ROOT
  • BOTTOM
  • IN_PLACE
  • KEYVAL_INVALID
  • TAG_UB
  • HOST
  • IO
  • WTIME_IS_GLOBAL
  • UNIVERSE_SIZE
  • APPNUM
  • LASTUSEDCODE
  • WIN_BASE
  • WIN_SIZE
  • WIN_DISP_UNIT
  • WIN_CREATE_FLAVOR
  • WIN_FLAVOR
  • WIN_MODEL
  • SUCCESS
  • ERR_LASTCODE
  • ERR_COMM
  • ERR_GROUP
  • ERR_TYPE
  • ERR_REQUEST
  • ERR_OP
  • ERR_BUFFER
  • ERR_COUNT
  • ERR_TAG
  • ERR_RANK
  • ERR_ROOT
  • ERR_TRUNCATE
  • ERR_IN_STATUS
  • ERR_PENDING
  • ERR_TOPOLOGY
  • ERR_DIMS
  • ERR_ARG
  • ERR_OTHER
  • ERR_UNKNOWN
  • ERR_INTERN
  • ERR_INFO
  • ERR_FILE
  • ERR_WIN
  • ERR_KEYVAL
  • ERR_INFO_KEY
  • ERR_INFO_VALUE
  • ERR_INFO_NOKEY
  • ERR_ACCESS
  • ERR_AMODE
  • ERR_BAD_FILE
  • ERR_FILE_EXISTS
  • ERR_FILE_IN_USE

and yeah, that's the whole column. every single name, exactly as the map has it, in exactly that order. ๐Ÿ’– we did not cut a single one, because cutting is not what we do here. ๐Ÿซถ

still more map to walk through, so don't go anywhere bestie โ€” ๐ŸŒธ

okay bestie, next batch of constants, and this run is LONG โ€” buckle up, we're going down the list ๐Ÿ’…


  • ERR_NO_SPACE โ€” out of space, no room at the inn, the name literally says it ๐Ÿ’€
  • ERR_NO_SUCH_FILE โ€” no such file, fr fr, she's not there
  • ERR_IO โ€” the classic I/O error, the "something happened with input/output" girlie
  • ERR_READ_ONLY โ€” read only bestie, don't even try to write ๐Ÿšซ
  • ERR_CONVERSION โ€” something didn't convert, and it's giving conversion error
  • ERR_DUP_DATAREP โ€” duplicate datarep, twice the datarep, twice the drama
  • ERR_UNSUPPORTED_DATAREP โ€” that datarep? not supported. sorry babe ๐ŸŽ€
  • ERR_UNSUPPORTED_OPERATION โ€” operation not supported, no notes, it just isn't
  • ERR_NAME โ€” a name error, iconic in its simplicity โœจ
  • ERR_NO_MEM โ€” no memory, she's exhausted, we've all been there ๐Ÿ˜ญ
  • ERR_NOT_SAME โ€” not the same!! they're not the same!!! ๐Ÿฆ‹
  • ERR_PORT โ€” port error, the port said no
  • ERR_QUOTA โ€” you hit the quota, that's it, that's the limit
  • ERR_SERVICE โ€” service error, the service is going through something
  • ERR_SPAWN โ€” spawn error, the spawn did not go as planned ๐Ÿ‘‘
  • ERR_BASE โ€” base error, and we respect that
  • ERR_SIZE โ€” size error, the size is wrong, don't ask
  • ERR_DISP โ€” displacement error, she's displaced ๐ŸŒธ
  • ERR_ASSERT โ€” assertion error, the assert asserted ๐Ÿ’…
  • ERR_LOCKTYPE โ€” lock type error, the lock type is not locking
  • ERR_RMA_CONFLICT โ€” RMA conflict, two girlies wanted the same thing ๐Ÿ’ฅ
  • ERR_RMA_SYNC โ€” RMA sync error, the sync did not sync
  • ERR_RMA_RANGE โ€” RMA range error, out of range, beyond the vibes
  • ERR_RMA_ATTACH โ€” RMA attach error, the attach did not attach
  • ERR_RMA_SHARED โ€” RMA shared error, sharing was attempted, sharing failed
  • ERR_RMA_FLAVOR โ€” RMA flavor error, wrong flavor, tragic ๐Ÿ“

  • ORDER_C โ€” order: C, for the C-coded girlies โœจ
  • ORDER_F โ€” order: F, short and mysterious
  • ORDER_FORTRAN โ€” order: Fortran, the full government name ๐Ÿ’–

  • TYPECLASS_INTEGER โ€” typeclass: integer, whole numbers only, no decimals allowed ๐ŸŽ€
  • TYPECLASS_REAL โ€” typeclass: real, floats have entered the chat
  • TYPECLASS_COMPLEX โ€” typeclass: complex, she's got layers ๐Ÿ’œ

  • DISTRIBUTE_NONE โ€” distribute: none, no distributing today
  • DISTRIBUTE_BLOCK โ€” distribute: block, chunky style ๐Ÿงฑ
  • DISTRIBUTE_CYCLIC โ€” distribute: cyclic, round and round we go ๐ŸŒ€
  • DISTRIBUTE_DFLT_DARG โ€” the default distribute argument, the DFLT DARG herself ๐Ÿ‘‘

  • COMBINER_NAMED โ€” combiner: named, she has a name and she's using it
  • COMBINER_DUP โ€” combiner: dup, duplicated, copy that
  • COMBINER_CONTIGUOUS โ€” combiner: contiguous, all together now ๐Ÿซถ
  • COMBINER_VECTOR โ€” combiner: vector, one-dimensional core
  • COMBINER_HVECTOR โ€” combiner: hvector, vector but with the h, iykyk
  • COMBINER_INDEXED โ€” combiner: indexed, working off an index
  • COMBINER_HINDEXED โ€” combiner: hindexed, the indexed one's sibling ๐ŸŒˆ
  • COMBINER_INDEXED_BLOCK โ€” combiner: indexed block, indexed AND blocky
  • COMBINER_HINDEXED_BLOCK โ€” combiner: hindexed block, the h returns
  • COMBINER_STRUCT โ€” combiner: struct, she's a whole structure ๐Ÿ’…
  • COMBINER_SUBARRAY โ€” combiner: subarray, a slice of the action
  • COMBINER_DARRAY โ€” combiner: darray, the distributed one, main character energy ๐Ÿ‘‘
  • COMBINER_RESIZED โ€” combiner: resized, she's been resized and she's thriving
  • COMBINER_F90_REAL โ€” combiner: F90 real, Fortran 90 real, very specific, very slay โญ
  • COMBINER_F90_COMPLEX โ€” combiner: F90 complex, complex but make it F90
  • COMBINER_F90_INTEGER โ€” combiner: F90 integer, integers, Fortran 90 edition

  • IDENT โ€” ident, they're identical, twins fr fr ๐Ÿ’–
  • CONGRUENT โ€” congruent, matching in all the right ways
  • SIMILAR โ€” similar, not the same but adjacent ๐Ÿฆ‹
  • UNEQUAL โ€” unequal, they're not matching, and that's okay

  • CART โ€” cart, as in Cartesian, as in grid girlie ๐ŸŽ€
  • GRAPH โ€” graph, she's a graph, she has edges and everything
  • DIST_GRAPH โ€” dist_graph, the distributed graph, she's everywhere
  • UNWEIGHTED โ€” unweighted, no weights, weightless, floating ๐ŸŒธ
  • WEIGHTS_EMPTY โ€” weights empty, there are no weights, the weights are gone ๐Ÿ’€

  • COMM_TYPE_SHARED โ€” comm type: shared, sharing is caring ๐Ÿซถ
  • BSEND_OVERHEAD โ€” the bsend overhead, she's the extra bit you have to account for
  • WIN_FLAVOR_CREATE โ€” win flavor: create, window flavor number one โœจ
  • WIN_FLAVOR_ALLOCATE โ€” win flavor: allocate, window flavor number two
  • WIN_FLAVOR_DYNAMIC โ€” win flavor: dynamic, window flavor number three, she moves ๐ŸŒ€
  • WIN_FLAVOR_SHARED โ€” win flavor: shared, window flavor number four
  • WIN_SEPARATE โ€” win: separate, they're apart, respectfully
  • WIN_UNIFIED โ€” win: unified, they're together, beautifully ๐Ÿ’œ
  • MODE_NOCHECK โ€” mode: nocheck, no checks happening here, and we move ๐Ÿ’…

okay bestie we are still in the constants and we are not stopping ๐Ÿ’… same section, same list, no new heading, we're just carrying on like a group chat that refuses to die. here's the next stretch, every single name, exactly as written, no skips and no merges ๐Ÿซถ


first up, the little MODE_ quartet that all scream NO in the name:

  • MODE_NOSTORE
  • MODE_NOPUT
  • MODE_NOPRECEDE
  • MODE_NOSUCCEED

four of them, all present, all accounted for ๐Ÿ™ˆ


then the lock girlies, and there are exactly two of them:

  • LOCK_EXCLUSIVE
  • LOCK_SHARED

the names are literally giving the whole vibe, iykyk ๐Ÿ‘‘


then a whole parade of MODE_ names โ€” bestie they just keep coming, one after the other, no breaks:

  • MODE_RDONLY
  • MODE_WRONLY
  • MODE_RDWR
  • MODE_CREATE
  • MODE_EXCL
  • MODE_DELETE_ON_CLOSE
  • MODE_UNIQUE_OPEN
  • MODE_SEQUENTIAL
  • MODE_APPEND

nine of them. count them. i did. ๐Ÿ’–


next, the seek squad:

  • SEEK_SET
  • SEEK_CUR
  • SEEK_END

and two more that showed up right behind them:

  • DISPLACEMENT_CURRENT
  • DISP_CUR

yes, DISPLACEMENT_CURRENT gets a whole long name and DISP_CUR gets the lil nickname version. both iconic, both on the list ๐ŸŒธ


then the THREAD_ four, all in a row like they're waiting for the bus:

  • THREAD_SINGLE
  • THREAD_FUNNELED
  • THREAD_SERIALIZED
  • THREAD_MULTIPLE

and then these two, just vibing on their own:

  • VERSION
  • SUBVERSION

okay now the MAX_ clique, and there are eight of them:

  • MAX_PROCESSOR_NAME
  • MAX_ERROR_STRING
  • MAX_PORT_NAME
  • MAX_INFO_KEY
  • MAX_INFO_VAL
  • MAX_OBJECT_NAME
  • MAX_DATAREP_STRING
  • MAX_LIBRARY_VERSION_STRING

eight. all caps. all MAX_. all here ๐Ÿ’…


then four more that are just doing their own thing:

  • DATATYPE_NULL
  • UB
  • LB
  • PACKED

short names, big energy, ngl โœจ


and now bestie. the datatype roster. this is the long one. deep breath. we're going in order, every single one:

  • BYTE
  • AINT
  • OFFSET
  • COUNT
  • CHAR
  • WCHAR
  • SIGNED_CHAR
  • SHORT
  • INT
  • LONG
  • LONG_LONG
  • UNSIGNED_CHAR
  • UNSIGNED_SHORT
  • UNSIGNED
  • UNSIGNED_LONG
  • UNSIGNED_LONG_LONG
  • FLOAT
  • DOUBLE
  • LONG_DOUBLE
  • C_BOOL
  • INT8_T
  • INT16_T
  • INT32_T
  • INT64_T
  • UINT8_T
  • UINT16_T
  • UINT32_T
  • UINT64_T
  • C_COMPLEX
  • C_FLOAT_COMPLEX
  • C_DOUBLE_COMPLEX
  • C_LONG_DOUBLE_COMPLEX
  • CXX_BOOL
  • CXX_FLOAT_COMPLEX

look at that. INT8_T through UINT64_T, the whole C_ complex family, CXX_BOOL and CXX_FLOAT_COMPLEX holding up the end. that's 34 names, and i did not skip a single one, no cap ๐ŸŽ€


note to self and to you bestie: these are names, that's the whole entry, the page doesn't hand out a lil description for each one here โ€” so i'm not gonna invent one. if it's on the list, it's on the list. periodt ๐Ÿ’œ

and we're still going, so don't close the tab, don't scroll away, there's more list where this came from ๐Ÿฆ‹


okay bestie so this next chunk is literally just the constant roster โ€” the names that live in the module, no long descriptions attached, no lore, just the full list. And we are not skipping a single one, because every one of these is a real thing you can type and it will work. ๐Ÿซถ

here's the first wave: the CXX_-flavoured complex crew, and then the _INT pair squad โ€” yes they really are called TWOINT, that's not a typo, that's iconic behaviour:

  • CXX_DOUBLE_COMPLEX
  • CXX_LONG_DOUBLE_COMPLEX
  • SHORT_INT
  • INT_INT
  • TWOINT
  • LONG_INT
  • FLOAT_INT
  • DOUBLE_INT
  • LONG_DOUBLE_INT

and now the Fortran vibes โœจ โ€” the plain old classics, then the numbered ones where the digits are telling you exactly how many bytes are in the building, iykyk:

  • CHARACTER
  • LOGICAL
  • INTEGER
  • REAL
  • DOUBLE_PRECISION
  • COMPLEX
  • DOUBLE_COMPLEX
  • LOGICAL1
  • LOGICAL2
  • LOGICAL4
  • LOGICAL8
  • INTEGER1
  • INTEGER2
  • INTEGER4
  • INTEGER8
  • INTEGER16
  • REAL2
  • REAL4
  • REAL8
  • REAL16
  • COMPLEX4
  • COMPLEX8
  • COMPLEX16
  • COMPLEX32

next up, the signed / unsigned / sized corner ๐ŸŒˆ โ€” BOOL is right there being all simple about it, and the SINT*_T ones are giving very "I come from <stdint.h>" energy:

  • UNSIGNED_INT
  • SIGNED_SHORT
  • SIGNED_INT
  • SIGNED_LONG
  • SIGNED_LONG_LONG
  • BOOL
  • SINT8_T
  • SINT16_T
  • SINT32_T
  • SINT64_T

and the F_ family ๐Ÿ’š โ€” yes there's an F_BOOL, yes it's cute, moving on:

  • F_BOOL
  • F_INT
  • F_FLOAT
  • F_DOUBLE
  • F_COMPLEX
  • F_FLOAT_COMPLEX
  • F_DOUBLE_COMPLEX

okay now we're out of datatype town and into the utility constants, which are honestly the most useful little gremlins in the whole list โ€” the <something>_NULL ones are your "nothing here yet, bestie" placeholders, and MESSAGE_NO_PROC is the one that's like "nobody's home, don't wait up" ๐Ÿ ๐Ÿ’€:

  • REQUEST_NULL
  • MESSAGE_NULL
  • MESSAGE_NO_PROC
  • OP_NULL

then the reduction operations</> ๐Ÿ”ฅ โ€” the ones you actually hand to a collective when you want it to crunch numbers across everybody. MAX, MIN, SUM, PROD are the main characters, the L* ones are the logical crew, the B* ones are the bitwise crew (the first letter is doing all the work, no cap), and MAXLOC / MINLOC come with location info too:

  • MAX
  • MIN
  • SUM
  • PROD
  • LAND
  • BAND
  • LOR
  • BOR
  • LXOR
  • BXOR
  • MAXLOC
  • MINLOC
  • REPLACE
  • NO_OP

and finally, the handle-type constants ๐ŸŽ€ โ€” the group ones, the info ones, and the error handler one:

  • GROUP_NULL
  • GROUP_EMPTY
  • INFO_NULL
  • INFO_ENV
  • ERRHANDLER_NULL
lowkey the pattern is: _NULL = "this handle points at nothing yet", and GROUP_EMPTY is the one that's a real, valid, deliberately-empty group rather than an absent one. big difference, bestie ๐Ÿ’…

and yeah, ERRHANDLER_NULL closed out that batch โ€” but keep scrolling, we are so not done here. ๐Ÿฆ‹

๐Ÿ’– ERRORS_RETURN


๐Ÿ’– ERRORS_ARE_FATAL


๐Ÿ’– COMM_NULL


๐Ÿ’– COMM_SELF


๐Ÿ’– COMM_WORLD


๐Ÿ’– WIN_NULL


๐Ÿ’– FILE_NULL


๐Ÿ’– pickle


๐ŸŒˆ MPI4PY.FUTURES ๐ŸŒˆ

โœจ New in version 3.0.0. โœจ

okay bestie, this package? It provides a high-level interface for asynchronously executing callables on a pool of worker processes, and it uses MPI for all the inter-process communication. it's giving "let the workers do the homework while you vibe." ๐Ÿซถ


๐Ÿฆ‹ concurrent.futures

The mpi4py.futures package is based on concurrent.futures from the Python standard library. More precisely, mpi4py.futures provides the MPIPoolExecutor class as a concrete implementation of the abstract class Executor. The submit() interface schedules a callable to be executed asynchronously and returns a Future object representing the execution of the callable. Future instances can be queried for the call result or exception. Sets of Future instances can be passed to the wait() and as_completed() functions. ๐Ÿ’…

NOTE: The concurrent.futures package was introduced in Python 3.2. A backport targeting Python 2.7 is available on PyPI. The mpi4py.futures package uses concurrent.futures if available, either from the Python 3 standard library or the Python 2.7 backport if installed. Otherwise, mpi4py.futures uses a bundled copy of core functionality backported from Python 3.5 to work with Python 2.7.

SEE ALSO:

  • Module concurrent.futures โ€” Documentation of the concurrent.futures standard module.

๐Ÿ‘‘ MPIPoolExecutor

The MPIPoolExecutor class uses a pool of MPI processes to execute calls asynchronously. By performing computations in separate processes, it allows to side-step the global interpreter lock, but also means that only picklable objects can be executed and returned. The __main__ module must be importable by worker processes, thus MPIPoolExecutor instances may not work in the interactive interpreter. ๐Ÿšซ๐Ÿ

MPIPoolExecutor takes advantage of the dynamic process management features introduced in the MPI-2 standard. In particular, the MPI.Intracomm.Spawn method of MPI.COMM_SELF is used in the master (or parent) process to spawn new worker (or child) processes running a Python interpreter. The master process uses a separate thread (one for each MPIPoolExecutor instance) to communicate back and forth with the workers. The worker processes serve the execution of tasks in the main (and only) thread until they are signaled for completion. ๐Ÿ”ฅ

NOTE: The worker processes must import the main script in order to unpickle any callable defined in the __main__ module and submitted from the master process. Furthermore, the callables may need access to other global variables. At the worker processes, mpi4py.futures executes the main script code (using the runpy module) under the __worker__ namespace to define the __main__ module. The __main__ and __worker__ modules are added to sys.modules (both at the master and worker processes) to ensure proper pickling and unpickling. ๐Ÿงš
WARNING: During the initial import phase at the workers, the main script cannot create and use new MPIPoolExecutor instances. Otherwise, each worker would attempt to spawn a new pool of workers, leading to infinite recursion. mpi4py.futures detects such recursive attempts to spawn new workers and aborts the MPI execution environment. As the main script code is run under the __worker__ namespace, the easiest way to avoid spawn recursion is using the idiom if __name__ == '__main__': ... in the main script. ๐Ÿ’€

๐ŸŒŸ class mpi4py.futures.MPIPoolExecutor(max_workers=None, initializer=None, initargs=(), **kwargs)

An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, its value is determined from the MPI4PY_FUTURES_MAX_WORKERS environment variable if set, or the MPI universe size if set, otherwise a single worker process is spawned. If max_workers is lower than or equal to 0, then a ValueError will be raised. ๐Ÿ˜ค

initializer is an optional callable that is called at the start of each worker process before executing any tasks; initargs is a tuple of arguments passed to the initializer. If initializer raises an exception, all pending tasks and any attempt to submit new tasks to the pool will raise a BrokenExecutor exception. ๐Ÿ˜ญ

Other parameters:

  • python_exe โ€” Path to the Python interpreter executable used to spawn worker processes, otherwise sys.executable is used.
  • python_args โ€” list or iterable with additional command line flags to pass to the Python executable. Command line flags determined from inspection of sys.flags, sys.warnoptions and sys._xoptions in are passed unconditionally.
  • mpi_info โ€” dict or iterable yielding (key, value) pairs. These (key, value) pairs are passed (through an MPI.Info object) to the MPI.Intracomm.Spawn call used to spawn worker processes. This mechanism allows telling the MPI runtime system where and how to start the processes. Check the documentation of the backend MPI implementation about the set of keys it interprets and the corresponding format for values.
  • globals โ€” dict or iterable yielding (name, value) pairs to initialize the main module namespace in worker processes.
  • main โ€” If set to False, do not import the __main__ module in worker processes. Setting main to False prevents worker processes from accessing definitions in the parent __main__ namespace.
  • path โ€” list or iterable with paths to append to sys.path in worker processes to extend the module search path.
  • wdir โ€” Path to set the current working directory in worker processes using os.chdir(). The initial working directory is set by the MPI implementation. Quality MPI implementations should honor a wdir info key passed through mpi_info, although such feature is not mandatory.
  • env โ€” dict or iterable yielding (name, value) pairs with environment variables to update os.environ in worker processes. The initial environment is set by the MPI implementation. MPI implementations may allow setting the initial environment through mpi_info, however such feature is not required nor recommended by the MPI standard.

๐ŸŽ€ submit(func, *args, **kwargs)

Schedule the callable, func, to be executed as func(*args, **kwargs) and returns a Future object representing the execution of the callable. it's literally "here's a job, ping me when it's done." ๐Ÿ’…

executor = MPIPoolExecutor(max_workers=1)
future = executor.submit(pow, 321, 1234)
print(future.result())

๐ŸŽ€ map(func, *iterables, timeout=None, chunksize=1, **kwargs)

Equivalent to map(func, *iterables) except func is executed asynchronously and several calls to func may be made concurrently, out-of-order, in separate processes. The returned iterator raises a TimeoutError if __next__() is called and the result isn't available after timeout seconds from the original call to map(). timeout can be an int or a float. If timeout is not specified or None, there is no limit to the wait time. If a call raises an exception, then that exception will be raised when its value is retrieved from the iterator. This method chops iterables into a number of chunks which it submits to the pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer. For very long iterables, using a large value for chunksize can significantly improve performance compared to the default size of one. By default, the returned iterator yields results in-order, waiting for successive tasks to complete. This behavior can be changed by passing the keyword argument unordered as True, then the result iterator will yield a result as soon as any of the tasks complete. โญ

executor = MPIPoolExecutor(max_workers=3)
for result in executor.map(pow, [2]*32, range(32)):
    print(result)

๐ŸŽ€ starmap(func, iterable, timeout=None, chunksize=1, **kwargs)

Equivalent to itertools.starmap(func, iterable). Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been "pre-zipped"). map(func, *iterable) is equivalent to starmap(func, zip(*iterable)). ๐Ÿฆ‹

executor = MPIPoolExecutor(max_workers=3)
iterable = ((2, n) for n in range(32))
for result in executor.starmap(pow, iterable):
    print(result)
  • shutdown(wait=True, cancel_futures=False) โ€” okay bestie, this one is the peace-out button ๐Ÿ’…. It signals the executor that it should free up any resources it's using once the currently pending futures are done executing. And heads up โ€” any call to submit() or map() made after shutdown() will raise a RuntimeError. No take-backs.

If wait is True, this method won't return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False, it returns immediately and the resources get freed whenever all pending futures are done executing. But here's the plot twist โ€” regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing. Periodt.

If cancel_futures is True, this method cancels all pending futures that the executor has not started running. Any futures that are completed or running won't be cancelled, regardless of the value of cancel_futures. The rules are the rules, sorry ๐Ÿ˜ญ.

And lowkey the best part: you can avoid calling this method explicitly at all if you use the with statement, which will shutdown the executor instance for you (waiting as if shutdown() were called with wait set to True). Obsessed with the convenience.

import time
with MPIPoolExecutor(max_workers=1) as executor:
    future = executor.submit(time.sleep, 2)
assert future.done()
  • bootup(wait=True) โ€” this is the pre-game stretch โœจ. It signals the executor that it should allocate eagerly any required resources (in particular, the MPI worker processes). If wait is True, then bootup() won't return until the executor resources are ready to process submissions. That said, resources are automatically allocated on the first call to submit(), so calling bootup() explicitly is seldom needed. It's giving optional side quest ๐Ÿซถ.
  • MPI4PY_FUTURES_MAX_WORKERS โ€” if the max_workers parameter to MPIPoolExecutor is None or just not given, this environment variable provides the fallback value for the maximum number of MPI worker processes to spawn. Backup dancer energy, but make it environment.
NOTE: since the master process uses a separate thread to perform MPI communication with the workers, the backend MPI implementation should provide support for MPI.THREAD_MULTIPLE. However ๐Ÿ˜ญ, some popular MPI implementations do not support concurrent MPI calls from multiple threads yet. Additionally, users may decide to initialize MPI with a lower level of thread support. So: if the level of thread support in the backend MPI is less than MPI.THREAD_MULTIPLE, mpi4py.futures will use a global lock to serialize MPI calls. And if the level of thread support is less than MPI.THREAD_SERIALIZED, mpi4py.futures will emit a RuntimeWarning. Noted, bestie ๐Ÿ“.
WARNING: ๐Ÿ’€ if the level of thread support in the backend MPI is less than MPI.THREAD_SERIALIZED (i.e, it is either MPI.THREAD_SINGLE or MPI.THREAD_FUNNELED), then in theory mpi4py.futures cannot be used. But rather than raising an exception, mpi4py.futures emits a warning and takes a "cross-fingers" attitude ๐Ÿคž and continues execution in the hope that serializing MPI calls with a global lock will actually work. It's giving "trust me bro, it'll be fine".

MPICommExecutor

So, legacy MPI-1 implementations (plus some vendor MPI-2 implementations) just do not support the dynamic process management features that the MPI-2 standard introduced. And on top of that, job schedulers and batch systems at supercomputing facilities may pose additional complications for applications using the MPI_Comm_spawn() routine. Ugh, the struggle ๐ŸŒง๏ธ.

With all of these issues in mind, mpi4py.futures supports an additional, more traditional, SPMD-like usage pattern that requires MPI-1 calls only. Python applications get started the usual way โ€” e.g. using the mpiexec command โ€” and the Python code should make a collective call to the MPICommExecutor context manager to partition the set of MPI processes within a MPI communicator into one master process and many worker processes. The master process gets access to an MPIPoolExecutor instance so it can submit tasks. Meanwhile the worker processes follow a different execution path and team up to execute the tasks submitted from the master. Iconic division of labour ๐Ÿ‘‘.

Besides alleviating the lack of dynamic process management features in legacy MPI-1 or partial MPI-2 implementations, the MPICommExecutor context manager may be useful in classic MPI-based Python applications that are willing to take advantage of the simple, task-based, master/worker approach available in the mpi4py.futures package. Cute!

  • class mpi4py.futures.MPICommExecutor(comm=None, root=0) โ€” the context manager for MPIPoolExecutor. It splits a MPI (intra)communicator comm (which defaults to MPI.COMM_WORLD if it's not provided or is None) into two disjoint sets: a single master process (with rank root in comm) and the remaining worker processes ๐Ÿฆ‹. These sets then get connected through an intercommunicator. The target of the with statement gets assigned either an MPIPoolExecutor instance (over at the master) or None (over at the workers).
from mpi4py import MPI
from mpi4py.futures import MPICommExecutor

with MPICommExecutor(MPI.COMM_WORLD, root=0) as executor:
    if executor is not None:
       future = executor.submit(abs, -42)
       assert future.result() == 42
       answer = set(executor.map(abs, [-42, 42]))
       assert answer == {42}
WARNING: if MPICommExecutor is passed a communicator of size one (e.g., MPI.COMM_SELF), then the executor instance assigned to the target of the with statement will execute all submitted tasks in a single worker thread โ€” which does ensure that task execution still progresses asynchronously. But ๐Ÿ˜ญ the GIL will prevent the main and worker threads from running concurrently on multicore processors. And on top of that, the thread context switching may harm the performance of CPU-bound tasks noticeably. In the case of I/O-bound tasks the GIL is not usually an issue, however โ€” but since a single worker thread is used, it progresses one task at a time. We advise against using MPICommExecutor with communicators of size one, and suggest refactoring your code to use instead a ThreadPoolExecutor. Do it for me bestie ๐Ÿซถ.

Command line

Recalling the issues related to the lack of support for dynamic process management features in MPI implementations, mpi4py.futures supports an alternative usage pattern where Python code (either from scripts, modules, or zip files) is run under command line control of the mpi4py.futures package by passing -m mpi4py.futures to the python executable. The mpi4py.futures invocation should be passed a pyfile path to a script (or a zipfile/directory containing a __main__.py file). Additionally, mpi4py.futures accepts -m mod to execute a module named mod, -c cmd to execute a command string cmd, or even - to read commands from standard input (sys.stdin). Summarizing, mpi4py.futures can be invoked in the following ways:

  • $ mpiexec -n numprocs python -m mpi4py.futures pyfile [arg] ...
  • $ mpiexec -n numprocs python -m mpi4py.futures -m mod [arg] ...
  • $ mpiexec -n numprocs python -m mpi4py.futures -c cmd [arg] ...
  • $ mpiexec -n numprocs python -m mpi4py.futures - [arg] ...

Before it starts the main script execution, mpi4py.futures splits MPI.COMM_WORLD into one master (the process with rank 0 in MPI.COMM_WORLD) and numprocs - 1 workers, and connects them through an MPI intercommunicator. After that, the master process proceeds with the execution of the user script code, which eventually creates MPIPoolExecutor instances to submit tasks. Meanwhile the worker processes follow a different execution path to serve the master ๐Ÿ’…. Upon successful termination of the main script at the master, the entire MPI execution environment exits gracefully. But in the case of any unhandled exception in the main script, the master process calls MPI.COMM_WORLD.Abort(1) to prevent deadlocks and force termination of the entire MPI execution environment. Dramatic, but necessary ๐Ÿ”ฅ.

WARNING: running scripts under command line control of mpi4py.futures is quite similar to executing a single-process application that spawns additional workers as required. However, there is a very important difference users should be aware of: all the MPIPoolExecutor instances created at the master will share the pool of workers. Tasks submitted at the master from many different executors will be scheduled for execution in random order as soon as a worker is idle. And any executor can easily starve all the workers (e.g., by calling MPIPoolExecutor.map() with long iterables ๐Ÿ˜ณ). If that ever happens, submissions from other executors will not be serviced until free workers are available. Plan accordingly!

SEE ALSO

  • Command line โ€” Documentation on Python command line interface.

Examples

The following julia.py script computes the Julia set and dumps an image to disk in binary PGM format โœจ. The code starts by importing MPIPoolExecutor from the mpi4py.futures package. Next, some global constants and functions implement the computation of the Julia set. The computations are protected with the standard if __name__ == '__main__':... idiom. The image is computed by whole scanlines, submitting all these tasks at once using the map method. The result iterator yields scanlines in-order as the tasks complete. Finally, each scanline is dumped to disk. Slay ๐Ÿ’œ.

julia.py

from mpi4py.futures import MPIPoolExecutor

x0, x1, w = -2.0, +2.0, 640*2
y0, y1, h = -1.5, +1.5, 480*2
dx = (x1 - x0) / w
dy = (y1 - y0) / h

c = complex(0, 0.65)

def julia(x, y):
    z = complex(x, y)
    n = 255
    while abs(z) < 3 and n > 1:
        z = z**2 + c
        n -= 1
    return n

def julia_line(k):
    line = bytearray(w)
    y = y1 - k * dy
    for j in range(w):
        x = x0 + j * dx
        line[j] = julia(x, y)
    return line

if __name__ == '__main__':

    with MPIPoolExecutor() as executor:
        image = executor.map(julia_line, range(h))
        with open('julia.pgm', 'wb') as f:
            f.write(b'P5 %d %d %d\n' % (w, h, 255))
            for line in image:
                f.write(line)

Okay so the recommended way to run your script is with mpiexec, and you tell it to launch one MPI process (that's your master) plus โ€” optional but like, strongly recommended โ€” the MPI universe size you want, which decides how many extra dynamically spawned processes (the workers) show up. That universe size comes from a batch system, or you set it yourself with command-line args to mpiexec or with environment variables. Below there's examples for MPICH and Open MPI [1]. In literally all of these, the mpiexec command launches a single master process that runs the Python interpreter and executes your main script. When it's needed, mpi4py.futures spawns the pool of 16 worker processes. The master submits tasks to the workers and waits for the results. The workers get incoming tasks, execute them, and send the results back to the master. ๐Ÿ’ซ

With the MPICH implementation (or its derivatives built on the Hydra process manager), you set the MPI universe size with the -usize argument to mpiexec:

$ mpiexec -n 1 -usize 17 python julia.py

or, alternative route, by setting the MPIEXEC_UNIVERSE_SIZE environment variable:

$ MPIEXEC_UNIVERSE_SIZE=17 mpiexec -n 1 python julia.py

In Open MPI, the MPI universe size is set with the -host argument to mpiexec:

$ mpiexec -n 1 -host <hostname>:17 python julia.py

Another way to say how many workers you want is the mpi4py.futures-specific environment variable MPI4PY_FUTURES_MAX_WORKERS:

$ MPI4PY_FUTURES_MAX_WORKERS=16 mpiexec -n 1 python julia.py
Heads up bestie: in that case the MPI universe size is ignored. ๐Ÿ˜Œ

Or, alternatively, you can run the script the more traditional way, meaning all the MPI processes get started at once. Your script runs under the command-line control of mpi4py.futures by passing the -m flag to the python executable:

$ mpiexec -n 17 python -m mpi4py.futures julia.py

Like we said before, those 17 processes get partitioned into one master and 16 workers. The master process executes the main script while the workers execute the tasks the master submitted. ๐Ÿซถ

[1] When you're using an MPI implementation that isn't MPICH or Open MPI, pls check the docs of that implementation and/or your batch system to find the ways to specify the MPI universe size you want.

GIL ๐ŸŒˆ

See global interpreter lock.


๐Ÿงฐ MPI4PY.UTIL

New in version 3.1.0.

The mpi4py.util package collects miscellaneous utilities sitting right in the intersection of Python and MPI. It's giving toolbox energy. ๐ŸŽ€

mpi4py.util.pkl5

New in version 3.1.0.

pickle protocol 5 (see PEP 574) introduced support for out-of-band buffers, which allows for way more efficient handling of certain object types that have large memory footprints.

MPI for Python uses the traditional in-band handling of buffers. That approach is appropriate for communicating non-buffer Python objects, or buffer-like objects with small memory footprints. For point-to-point communication, in-band buffer handling lets you communicate a pickled stream with a single MPI message, at the cost of extra CPU and memory overhead in the pickling and unpickling steps.

The mpi4py.util.pkl5 module gives you communicator wrapper classes that reimplement pickle-based point-to-point communication methods using pickle protocol 5. Handling out-of-band buffers necessarily involves multiple MPI messages, so that raises latency and hurts performance when the data is small. But when the data is large, the zero-copy savings of out-of-band buffer handling more than offset the extra latency costs. ๐Ÿ”ฅ On top of that, these wrapper methods overcome the infamous 2 GiB message count limit (MPI-1 to MPI-3). Not me being excited about beating a size limit, but likeโ€ฆ ๐Ÿ’…

NOTE: Support for pickle protocol 5 has been in the pickle module of the Python standard library since Python 3.8. Earlier Python 3 releases can use the pickle5 backport, which lives on PyPI and installs with: console python -m pip install pickle5

class mpi4py.util.pkl5.Request(*args, **kwargs)

Custom request class for nonblocking communications.

NOTE: Request is not a subclass of mpi4py.MPI.Request
  • Free()
  • cancel()
  • get_status()
  • test()
  • wait()
  • testall()
    • Classmethod
  • waitall()
    • Classmethod

class mpi4py.util.pkl5.Message(*args, **kwargs)

Custom message class for matching probes.

NOTE: Message is not a subclass of mpi4py.MPI.Message
  • recv()
  • irecv()
  • probe()
    • Classmethod
  • iprobe()
    • Classmethod

class mpi4py.util.pkl5.Comm(*args, **kwargs)

Base communicator wrapper class.

  • send()
  • bsend()
  • ssend()
  • isend()
  • ibsend()
  • issend()
  • recv()
  • irecv()
WARNING: This method cannot be supported reliably and raises RuntimeError. ๐Ÿ˜ญ
  • sendrecv()
  • mprobe()
  • improbe()
  • bcast()

class mpi4py.util.pkl5.Intracomm(*args, **kwargs)

Intracommunicator wrapper class.

class mpi4py.util.pkl5.Intercomm(*args, **kwargs)

Intercommunicator wrapper class.

Examples โœจ

test-pkl5-1.py

import numpy as np
from mpi4py import MPI
from mpi4py.util import pkl5

comm = pkl5.Intracomm(MPI.COMM_WORLD)  # comm wrapper
size = comm.Get_size()
rank = comm.Get_rank()
dst = (rank + 1) % size
src = (rank - 1) % size

sobj = np.full(1024**3, rank, dtype='i4')  # > 4 GiB
sreq = comm.isend(sobj, dst, tag=42)
robj = comm.recv (None, src, tag=42)
sreq.Free()

assert np.min(robj) == src
assert np.max(robj) == src

test-pkl5-2.py

import numpy as np
from mpi4py import MPI
from mpi4py.util import pkl5

comm = pkl5.Intracomm(MPI.COMM_WORLD)  # comm wrapper
size = comm.Get_size()
rank = comm.Get_rank()
dst = (rank + 1) % size
src = (rank - 1) % size

sobj = np.full(1024**3, rank, dtype='i4')  # > 4 GiB
sreq = comm.isend(sobj, dst, tag=42)

status = MPI.Status()
rmsg = comm.mprobe(status=status)
assert status.Get_source() == src
assert status.Get_tag() == 42
rreq = rmsg.irecv()
robj = rreq.wait()

sreq.Free()
assert np.max(robj) == src
assert np.min(robj) == src

mpi4py.util.dtlib

New in version 3.1.0.

The mpi4py.util.dtlib module provides converter routines between NumPy and MPI datatypes. Little translation service between the two worlds, iconic. ๐Ÿฆ‹

mpi4py.util.dtlib.from_numpy_dtype()

  • Parameters
    • dtype โ€” NumPy dtype-like object.

mpi4py.util.dtlib.to_numpy_dtype()

  • Parameters
    • datatype โ€” MPI datatype.

๐ŸŒˆ MPI4PY.RUN ๐ŸŒˆ

New in version 3.0.0. โœจ

okay bestie so when you import mpi4py, here's the whole vibe: it goes ahead and initializes the MPI execution environment by calling MPI_Init_thread(), and it also installs an exit hook that automatically calls MPI_Finalize() right before the Python process terminates. ๐ŸŽ€ On top of that, mpi4py is like "not me accepting the default error handler" and overrides ERRORS_ARE_FATAL in favor of ERRORS_RETURN, which is what lets it translate MPI errors into Python exceptions. ๐Ÿ’…

These departures from standard MPI behavior may be controversial, but honestly? They're quite convenient inside the highly dynamic Python programming environment. Third-party code using mpi4py can literally just do from mpi4py import MPI and perform MPI calls without all that tedious initialization/finalization handling. ๐Ÿ™ˆ And MPI errors, once translated automatically to Python exceptions, can be dealt with using the common tryโ€ฆexceptโ€ฆfinally clauses โ€” and any unhandled MPI exceptions will print a traceback, which helps you locate problems in your source code. ๐Ÿฆ‹

But here's the plot twist ๐Ÿ˜ญ โ€” unfortunately, the interplay of automatic MPI finalization and unhandled exceptions may lead to deadlocks. And in unattended runs, these deadlocks will drain the battery of your laptop, or burn precious allocation hours in your supercomputing facility. ๐Ÿ’€

Consider the following snippet of Python code. Assume this code is stored in a standard Python script file and run with mpiexec in two or more processes.

from mpi4py import MPI
assert MPI.COMM_WORLD.Get_size() > 1
rank = MPI.COMM_WORLD.Get_rank()
if rank == 0:
    1/0
    MPI.COMM_WORLD.send(None, dest=1, tag=42)
elif rank == 1:
    MPI.COMM_WORLD.recv(source=0, tag=42)

So process 0 raises a ZeroDivisionError exception before performing a send call to process 1. And since the exception is not handled, the Python interpreter running in process 0 will proceed to exit with non-zero status. But wait โ€” because mpi4py installed a finalizer hook to call MPI_Finalize() before exit, process 0 will block waiting for other processes to also enter the MPI_Finalize() call. Meanwhile, process 1 will block waiting for a message to arrive from process 0, thus never reaching MPI_Finalize(). And boom โ€” the whole MPI execution environment is irremediably in a deadlock state. ๐Ÿ˜ญ๐Ÿ˜ญ

To alleviate this issue, mpi4py offers a simple, alternative command line execution mechanism based on using the -m flag and implemented with the runpy module. โœจ To use this feature, Python code should be run passing -m mpi4py in the command line invoking the Python interpreter. And in case of unhandled exceptions, the finalizer hook will call MPI_Abort() on the MPI_COMM_WORLD communicator, thus effectively aborting the MPI execution environment. ๐Ÿ‘‘

WARNING: ๐Ÿšจ When a process is forced to abort, resources (e.g. open files) are not cleaned-up and any registered finalizers (either with the atexit module, the Python C/API function Py_AtExit(), or even the C standard library function atexit()) will not be executed. Thus, aborting execution is an extremely impolite way of ensuring process termination. However, MPI provides no other mechanism to recover from a deadlock state. ๐Ÿ’…

๐ŸŽ€ Interface options ๐ŸŽ€

The use of -m mpi4py to execute Python code on the command line resembles that of the Python interpreter. iykyk ๐Ÿ’–

  • mpiexec -n numprocs python -m mpi4py pyfile [arg] ...
  • mpiexec -n numprocs python -m mpi4py -m mod [arg] ...
  • mpiexec -n numprocs python -m mpi4py -c cmd [arg] ...
  • mpiexec -n numprocs python -m mpi4py - [arg] ...
  • <pyfile> โ€” Execute the Python code contained in pyfile, which must be a filesystem path referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file. ๐Ÿ—‚๏ธ
  • -m <mod> โ€” Search sys.path for the named module mod and execute its contents. ๐Ÿ”
  • -c <cmd> โ€” Execute the Python code in the cmd string command. โŒจ๏ธ
  • - โ€” Read commands from standard input (sys.stdin). ๐ŸŒธ

SEE ALSO:

  • Command line โ€” Documentation on Python command line interface. ๐Ÿ

โญ REFERENCE โญ

                                 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”
                                 โ”‚ mpi4py.MPI โ”‚   โ”‚
                                 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜

๐Ÿ’œ mpi4py.MPI ๐Ÿ’œ

mpi4py.MPI


๐ŸŒŸ CITATION ๐ŸŒŸ

If MPI for Python has been significant to a project that leads to an academic publication, please acknowledge that fact by citing the project. ๐Ÿซถ

๐Ÿ› ๏ธ INSTALLATION ๐Ÿ› ๏ธ

okay bestie, this is the part where we actually get mpi4py onto your machine. buckle up ๐Ÿ’–


๐ŸŒธ Requirements ๐ŸŒธ

to build MPI for Python you gotta have this stuff properly installed first, no skipping:

  • A working MPI implementation, and like, preferably one that supports MPI-3 and was built with shared/dynamic libraries. that's the vibe we want โœจ
NOTE: if you wanna build some MPI implementation straight from sources, go peek at the instructions at Building MPI from sources down in the appendix. i gotchu ๐Ÿซถ
  • Python 2.7, 3.5 or above. that's the floor, queen ๐Ÿ‘‘
NOTE: some MPI-1 implementations do require the actual command line arguments to be passed in MPI_Init(). if that's your situation, you're gonna need a rebuilt, MPI-enabled, Python interpreter executable. MPI for Python has some support to save you from that whole ordeal โ€” check the instructions at MPI-enabled Python interpreter in the appendix. it's giving helpful fr fr ๐Ÿ’…

๐ŸŽ€ Using pip ๐ŸŽ€

if you already have a working MPI (whether you installed it from sources or grabbed a pre-built package from your fave GNU/Linux distribution) and the mpicc compiler wrapper is on your search path, then bestie you can just use pip:

$ python -m pip install mpi4py
NOTE: if the mpicc compiler wrapper is not on your search path (or it's got a different name, rude of it), you can use env to pass the environment variable MPICC with the full path to the MPI compiler wrapper executable:
$ env MPICC=/path/to/mpicc python -m pip install mpi4py
WARNING: pip keeps previously built wheel files in its cache for future reuse. so if you wanna reinstall the mpi4py package using a different or updated MPI implementation, you have to either first remove the cached wheel file with:
$ python -m pip cache remove mpi4py
or ask pip to just disable the cache entirely:
$ python -m pip install --no-cache-dir mpi4py

not me warning you twice, it's for your own good ๐Ÿ˜ญ


๐Ÿฆ‹ Using distutils ๐Ÿฆ‹

the MPI for Python package is available for download at the project website, generously hosted by GitHub. you can use curl or wget to get a release tarball, whichever one is your main character energy:

  • Using curl:
$ curl -O https://github.com/mpi4py/mpi4py/releases/download/X.Y.Z/mpi4py-X.Y.Z.tar.gz
  • Using wget:
$ wget https://github.com/mpi4py/mpi4py/releases/download/X.Y.Z/mpi4py-X.Y.Z.tar.gz

after unpacking the release tarball:

$ tar -zxf mpi4py-X.Y.Z.tar.gz
$ cd mpi4py-X.Y.Z

the package is ready for building. periodt โœจ

MPI for Python uses a standard distutils-based build system. however, some distutils commands (like build) have extra options, and they're kinda iconic:

  • --mpicc= โ€” lets you specify a special location or name for the mpicc compiler wrapper.
  • --mpi= โ€” lets you pass a section with MPI configuration within a special configuration file.
  • --configure โ€” runs exhaustive tests for checking about missing MPI types, constants, and functions. you should pass this option in order to build MPI for Python against old MPI-1 or MPI-2 implementations, possibly providing a subset of MPI-3. (yes, it's thorough, it ate ๐Ÿ’…)

if you use an MPI implementation that provides a mpicc compiler wrapper (e.g., MPICH, Open MPI), it will be used for compilation and linking. this is the preferred and easiest way of building MPI for Python, no cap.

if mpicc is located somewhere in your search path, simply run the build command:

$ python setup.py build

if mpicc is not in your search path, or the compiler wrapper has a different name, you can run the build command specifying its location:

$ python setup.py build --mpicc=/where/you/have/mpicc

alternatively, you can provide all the relevant info about your MPI implementation by editing the file called mpi.cfg. you can use the default section [mpi] or add a new, custom section, for example [other_mpi] โ€” see the examples provided in the mpi.cfg file as a starting point to write your own section:

[mpi]

include_dirs         = /usr/local/mpi/include
libraries            = mpi
library_dirs         = /usr/local/mpi/lib
runtime_library_dirs = /usr/local/mpi/lib

[other_mpi]

include_dirs         = /opt/mpi/include ...
libraries            = mpi ...
library_dirs         = /opt/mpi/lib ...
runtime_library_dirs = /op/mpi/lib ...

...

and then run the build command, perhaps specifying your custom configuration section:

$ python setup.py build --mpi=other_mpi

after building, the package is ready for install. we love a smooth workflow ๐ŸŒˆ

if you have root privileges (either by logging in as the root user or by using sudo) and you wanna install MPI for Python in your system for all users, just do:

$ python setup.py install

the previous steps will install the mpi4py package at the standard location prefix/lib/pythonX.X/site-packages.

if you do not have root privileges, or you just wanna install MPI for Python for your private use, just do:

$ python setup.py install --user

your lil private corner of the filesystem, so valid ๐Ÿ’œ


๐Ÿงš Testing ๐Ÿงš

to quickly test the installation:

$ mpiexec -n 5 python -m mpi4py.bench helloworld
Hello, World! I am process 0 of 5 on localhost.
Hello, World! I am process 1 of 5 on localhost.
Hello, World! I am process 2 of 5 on localhost.
Hello, World! I am process 3 of 5 on localhost.
Hello, World! I am process 4 of 5 on localhost.

look at all five of them saying hello, they're so cute ๐Ÿ˜ญ๐Ÿ’–

if you installed from source, issuing at the command line:

$ mpiexec -n 5 python demo/helloworld.py

or (in the case of ancient MPI-1 implementations):

$ mpirun -np 5 python `pwd`/demo/helloworld.py

will launch a five-process run of the Python interpreter and run the test script demo/helloworld.py from the source distribution.

you can also run all the unittest scripts:

$ mpiexec -n 5 python test/runtests.py

or, if you have the nose unit testing framework installed:

$ mpiexec -n 5 nosetests -w test

or, if you have the py.test unit testing framework installed:

$ mpiexec -n 5 py.test test/

pick your fighter, they all slay ๐Ÿซถ


๐Ÿ“Ž APPENDIX ๐Ÿ“Ž

๐Ÿ‘‘ MPI-enabled Python interpreter ๐Ÿ‘‘

WARNING: these days it is no longer required to use the MPI-enabled Python interpreter in most cases, and, therefore, it is not built by default anymore because it is too difficult to reliably build a Python interpreter across different distributions. if you know that you still really need it, see below on how to use the build_exe and install_exe commands.

some MPI-1 implementations (notably, MPICH 1) do require the actual command line arguments to be passed at the time MPI_Init() is called. in this case, you'll need to use a re-built, MPI-enabled, Python interpreter binary executable. a basic implementation (targeting Python 2.X) of what is required is shown below:

#include <Python.h>
#include <mpi.h>

int main(int argc, char *argv[])
{
   int status, flag;
   MPI_Init(&argc, &argv);
   status = Py_Main(argc, argv);
   MPI_Finalized(&flag);
   if (!flag) MPI_Finalize();
   return status;
}

the source code above is straightforward; compiling it should also be. however, the linking step is more tricky: special flags have to be passed to the linker depending on your platform. in order to alleviate you from such low-level details, MPI for Python provides some pure-distutils based support to build and install an MPI-enabled Python interpreter executable:

$ cd mpi4py-X.X.X
$ python setup.py build_exe [--mpi=<name>|--mpicc=/path/to/mpicc]
$ [sudo] python setup.py install_exe [--install-dir=$HOME/bin]

after the above steps you should have the MPI-enabled interpreter installed as prefix/bin/pythonX.X-mpi (or $HOME/bin/pythonX.X-mpi). assuming that prefix/bin (or $HOME/bin) is listed on your PATH, you should be able to enter your MPI-enabled Python interactively, for example:

$ python2.7-mpi
Python 2.7.8 (default, Nov 10 2014, 08:19:18)
[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'/usr/bin/python2.7-mpi'
>>>

interactive and MPI-enabled?? it's giving main character energy fr ๐Ÿ”ฅ


๐Ÿ“ Building MPI from sources ๐Ÿ“

in the list below you have some executive instructions for building some of the open-source MPI implementations out there with support for shared/dynamic libraries on POSIX environments.

  • MPICH
$ tar -zxf mpich-X.X.X.tar.gz
$ cd mpich-X.X.X
$ ./configure --enable-shared --prefix=/usr/local/mpich
$ make
$ make install
  • Open MPI
$ tar -zxf openmpi-X.X.X tar.gz
$ cd openmpi-X.X.X
$ ./configure --prefix=/usr/local/openmpi
$ make all
$ make install
  • MPICH 1
$ tar -zxf mpich-X.X.X.tar.gz
$ cd mpich-X.X.X
$ ./configure --enable-sharedlib --prefix=/usr/local/mpich1
$ make
$ make install

perhaps you will need to set the LD_LIBRARY_PATH environment variable (using export, setenv or whatever applies to your system) pointing to the directory containing the MPI libraries. in case of getting runtime linking errors when running MPI programs, the following lines can be added to the user login shell script (.profile, .bashrc, etc.).

  • MPICH
MPI_DIR=/usr/local/mpich
export LD_LIBRARY_PATH=$MPI_DIR/lib:$LD_LIBRARY_PATH
  • Open MPI
MPI_DIR=/usr/local/openmpi
export LD_LIBRARY_PATH=$MPI_DIR/lib:$LD_LIBRARY_PATH
  • MPICH 1
MPI_DIR=/usr/local/mpich1
export LD_LIBRARY_PATH=$MPI_DIR/lib/shared:$LD_LIBRARY_PATH:
export MPICH_USE_SHLIB=yes
WARNING: MPICH 1 support for dynamic libraries is not completely transparent. users should set the environment variable MPICH_USE_SHLIB to yes in order to avoid link problems when using the mpicc compiler wrapper. don't skip this one bestie, it will bite you ๐Ÿ’€

โœ๏ธ AUTHOR โœ๏ธ

Lisandro Dalcin

2024, Lisandro Dalcin


and that's the whole page, bestie!! ๐ŸŽ€ the source is MPI4PY(1), version 3.1, dated April 01, 2024 โ€” so if you're reading this, you're fully caught up on the manual. go forth and build, test, and absolutely slay with your MPI implementation. i'm so proud of you, no cap ๐Ÿ’–โœจ๐Ÿฆ‹๐Ÿ‘‘๐Ÿซถ๐Ÿ’…

๐Ÿ“ฆ where this page comes from