mpi4py(1)

MPI for Python

Section 1 python-mpi4py-doc bookworm source

Description

. .

.

\\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2]

. RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1

. RE

mpi4py - MPI for Python

Lisandro Dalcin

\%dalcinl@gmail.com

November 07, 2022

This document describes the MPI for Python package. MPI for Python provides Python bindings for the Message Passing Interface (MPI) standard, allowing Python applications to exploit multiple processors on workstations, clusters and supercomputers.

This package builds on the MPI specification and provides an object oriented interface resembling the MPI-2 C++ bindings. It supports point-to-point (sends, receives) and collective (broadcasts, scatters, gathers) communication of any picklable Python object, as well as efficient communication of Python objects exposing the Python buffer interface (e.g. NumPy arrays and builtin bytes/array/memoryview objects).

Over the last years, high performance computing has become an affordable resource to many more researchers in the scientific community than ever before. The conjunction of quality open source software and commodity hardware strongly influenced the now widespread popularity of \%Beowulf class clusters and cluster of workstations.

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 is used in today’s most demanding scientific and engineering application related to modeling, simulation, design, and signal processing. However, portable message-passing parallel programming used to be a nightmare in the past because of the many incompatible options developers were faced to. Fortunately, this situation definitely changed after the MPI Forum released its standard specification.

High performance computing is traditionally associated with software development using compiled languages. However, in typical applications programs, only a small part of the code is time-critical enough to require the efficiency of compiled languages. The rest of the code is generally related to 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 tasks.

For implementing general-purpose numerical computations, MATLAB [1] is the dominant interpreted programming language. In 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.

MATLAB is a registered trademark of The MathWorks, Inc.

\%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 allows users to 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].

\%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 is 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.

\%OOMPI

It has no relation with Python, but is an excellent object oriented approach to MPI.

It is 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.

MPI Forum. MPI: A Message Passing Interface Standard. International Journal of Supercomputer Applications, volume 8, number 3-4, pages 159-416, 1994.

MPI Forum. MPI: A Message Passing Interface Standard. High Performance Computing Applications, volume 12, number 1-2, pages 1-299, 1998.

William Gropp, Ewing Lusk, and Anthony Skjellum. Using MPI: portable parallel programming with the message-passing interface. MIT Press, 1994.

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.

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.

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.

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.

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.

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.

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 provide user-extensible facilities to serialize general Python objects using ASCII or binary formats. The marshal module provides facilities to serialize built-in Python objects using a binary format specific to Python, but independent of machine architecture issues.

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).

Although simple and general, the serialization approach (i.e., pickling and unpickling) previously discussed 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 (that 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.

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.

In MPI for Python, \%Comm is the base class of communicators. The \%Intracomm and \%Intercomm classes are sublcasses 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.

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 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.

New communicator instances can be obtained with the \%Comm.Clone, \%Comm.Dup and \%Comm.Split methods, as well 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 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.

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.

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.

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.

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 come in two parts: posting functions, which begin the requested operation; and test-for-completion functions, which allow to discover whether the requested operation has completed.

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.

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 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.

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 reducion 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.

Several MPI implementations, including Open MPI and MVAPICH, support passing GPU pointers to MPI calls to avoid explict 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:

mpi4py is built against a GPU-aware MPI library.

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.

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.

This MPI-2 extension can be really useful, especially for sequential applications built on top of parallel modules, or parallel applications with a client/server model. The MPI-2 process model provides a mechanism to create new processes and establish communication between them and the existing MPI application. It also provides mechanisms to establish communication between two existing MPI applications, even when one did not start the other.

In MPI for Python, new independent process groups can be created by calling the \%Intracomm.Spawn method within an intracommunicator. This call returns a new intercommunicator (i.e., an \%Intercomm instance) at the parent process group. The child process group can retrieve the matching intercommunicator by calling the \%Comm.Get_parent class method. At each side, the new intercommunicator can be used to perform point to point and collective communications between the parent and child groups of processes.

Alternatively, disjoint groups of processes can establish communication using a client/server approach. Any server application must first call the \%Open_port function to open a port and the \%Publish_name function to publish a provided service, and next call the \%Intracomm.Accept method. Any client applications can first find 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 methods return an \%Intercomm instance. When connection between client/server processes is no longer needed, all of them must cooperatively call the \%Comm.Disconnect method. Additionally, server applications should release resources by calling the \%Unpublish_name and \%Close_port functions.

One-sided communications (also called Remote Memory Access, RMA) supplements the traditional two-sided, send/receive based MPI communication model with a one-sided, put/get based interface. One-sided communication that can take advantage of the capabilities of highly specialized network hardware. Additionally, this extension lowers latency and software overhead in applications written using a shared-memory-like paradigm.

The MPI specification revolves around the use of objects called windows; they intuitively specify regions of a process’s memory that have been made available for remote read and write operations. The published memory blocks can be accessed through three functions for put (remote send), get (remote write), and accumulate (remote update or reduction) data items. A much larger number of functions support different synchronization styles; the semantics of these synchronization operations are 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, the \%Win.Free method should be called.

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 target process cooperates by calling the \%Win.Post and \%Win.Wait methods. There is also a collective variant provided by the \%Win.Fence method. Passive target synchronization is 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.

The POSIX standard provides a model of a widely portable file system. However, the optimization needed for parallel input/output cannot be achieved with this generic interface. In order to ensure efficiency and scalability, the underlying parallel input/output system must provide a high-level interface supporting partitioning of file data among processes and a collective interface supporting complete transfers of global data structures between process memories and files. Additionally, further efficiencies can be gained via support for asynchronous input/output, strided accesses to data, and control over physical file layout on storage devices. This scenario motivated the inclusion in the MPI-2 standard of a custom interface in order to support more elaborated parallel input/output operations.

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

The common patterns for accessing a shared file (broadcast, scatter, gather, reduction) is 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), and synchronism (blocking, nonblocking, and split collective with begin/end phases).