4

I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the Open MPI library (installed via homebrew) and pybind11.

The C++ class is as follows:

#include <pybind11/pybind11.h>
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <mpi.h>
// #define PyMPI_HAVE_MPI_Message 1
// #include <mpi4py/mpi4py.h>


namespace py = pybind11;

class SomeComputation
{
    float multiplier;
    std::vector<int> test;
    MPI_Comm comm_;

public:
    void Init()
    {
        int rank;
        MPI_Comm_rank(comm_, &rank);
        test.clear();
        test.resize(10, rank);
    }

    void set_comm(MPI_Comm comm){
        this->comm_ = comm;
    }

    SomeComputation(float multiplier_) : multiplier(multiplier_){}
    ~SomeComputation() { std::cout << "Destructor Called!\n"; }


    float compute(float input)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10));
        for (int i = 0; i != 10; ++i)
        {
            std::cout << test[i] << " ";
        }
        std::cout << std::endl;
        return multiplier * input;
    }
};

PYBIND11_MODULE(module_name, handle)
{
    py::class_<SomeComputation>(handle, "Cpp_computation")
        .def(py::init<float>()) // args of constructers are template args
        .def("set_comm", &SomeComputation::set_comm)  
        .def("compute", &SomeComputation::compute)
        .def("cpp_init", &SomeComputation::Init);
}

and here's the python interface spawning the same C++:

from build.module_name import * 
import time

from mpi4py import MPI


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


m = Cpp_computation(44.0) # send communicator to cpp
m.cpp_init()
i = 0
while i < 5:
    print(m.compute(i))
    time.sleep(1)
    i+=1

I've already tried "Sharing an MPI communicator using pybind11" but I'm stuck at a long unhelpful error (full message):

[...]
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22:   required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]'
/Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7:   required from here
/opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t'
 1372 |     : public integral_constant<bool, __is_base_of(_Base, _Derived)>
      |                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6:
/opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t'
  419 | typedef struct ompi_communicator_t *MPI_Comm;
      |                ^~~~~~~~~~~~~~~~~~~

[...]

/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22:   required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]'
/Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7:   required from here
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t'
   40 |         return {{&typeid(Ts)..., nullptr}};
      |                   ^~~~~~~~~~
In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6:
/opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t'
  419 | typedef struct ompi_communicator_t *MPI_Comm;
      |                ^~~~~~~~~~~~~~~~~~~

[...]

                 from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1:
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>'
   40 |         return {{&typeid(Ts)..., nullptr}};
      |                                          ^
      |                                          |
      |                                          <brace-enclosed initializer list>

[...]

In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1:
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]':
[..]
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22:   required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]'
/Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7:   required from here
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73:   in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()'
/Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function
  266 |         PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
      |                                       ^~~~~

The error points to .def("set_comm", &SomeComputation::set_comm)

What is the cause of these errors, and how should they be resolved?

UPDATE: Added answer below by using custom type caster as explained in this answer. But is it the only way to go about it?

Jarwin
  • 1,045
  • 1
  • 9
  • 30
  • From what I could decipher, MPI_comm has only been declared and not defined, so you should hold it by (`MPI_comm* comm_;`) and not directly by value. See https://stackoverflow.com/questions/8972588/is-the-pimpl-idiom-really-used-in-practice – unddoch Dec 25 '21 at 17:44
  • Of course, that might not be the real problem. Could you try and post the full main.cpp in this case? The error references line 79 but your code is shorter than this. – unddoch Dec 25 '21 at 17:45
  • Is is possible you haven't imported all the required headers from MPI? A couple of the errors are referencing a type that's incomplete, so it's possible you're missing an include that is required which would "complete" the type definition. – jlucier Dec 28 '21 at 15:55
  • All information should be added to the question (as explained in the [site guidelines](//stackoverflow.com/help/how-to-ask) and [sample code guidelines](//stackoverflow.com/help/mcve)), not just [linked to](//meta.stackoverflow.com/q/254428/90527). For one thing, external pages go away (there are plenty of questions on SO where the OP didn't expect this to happen, yet it did). In the case of a long error (such as C++ compilation output), the core error messages could be posted, with a link used for the full output. – outis Dec 29 '21 at 19:53
  • (If not sure how to edit down a long error message, assistance could be requested in chat, which requires only 20 rep, or a comment could be made to the same point.) – outis Dec 29 '21 at 20:00
  • @jlucier afaik, i included all the required headers for mpi, infact, if i remove the setter for mpi communicator, the compilation happens without any error. – Jarwin Dec 29 '21 at 21:36
  • @unddoch I had stripped down some comments before pasting the code, line 79 originally points to `set_comm` definition. (question updated) – Jarwin Dec 29 '21 at 21:42
  • @Jarwin: if Open MPI isn't a requirement, you might try [MPICH](https://www.mpich.org/); the sample compiled without the error when I built against it. – outis Dec 29 '21 at 22:47
  • `struct ompi_communicator_t` looks to be declared in "open-mpi/4.1.2/include/ompi/communicator/communicator.h". What happens if `#include ` is added to the C++ class definition file? – outis Dec 30 '21 at 00:07

2 Answers2

0

Using a void * as an argument compiled successfully for me. It's ABI-compatible with the pybind11 interfaces (an MPI_Comm is a pointer in any case). All I had to change was this:

void set_comm(void* comm){
  this->comm_ = (MPI_Comm)comm;
}

I also added MPI libraries and include folders to setup.py, as follows (replace folders as necessary with your MPI implementation):

ext_modules = [
    Pybind11Extension("module_name",
        ["src/main.cpp"],
        include_dirs=["/etc/alternatives/mpi-x86_64-linux-gnu"],
        library_dirs=["/usr/lib/x86_64-linux-gnu/openmpi/lib"],
        libraries=["mpi", "mpi_cxx"],
    ),
]
Tal Ben-Nun
  • 439
  • 3
  • 7
  • Ah, I see. However, I get an error message stating `MPI_Comm_rank` is undefined during runtime. `ImportError: build/mpi_lib.cpython-310-x86_64-linux-gnu.so: undefined symbol: MPI_Comm_rank` – Jarwin Dec 29 '21 at 21:34
  • Did you compile it with `mpicc`? I used the following command line: `CC=mpicxx CXX=mpicxx python setup.py develop` – Tal Ben-Nun Dec 30 '21 at 15:00
  • Despite compiling it with mpicc it crashes with the same error when called from python. Could you upload your CMake file? I am not sure about `setup.py` – Jarwin Jan 20 '22 at 10:18
  • I'm not using CMake, all the build instructions are in setup.py. I also managed to remove the requirement to compile with mpicxx by adding the libraries directly. See edited answer. I compiled this with `python setup.py develop`. Let me know if you need more components. Adding `mpi_cxx` to the libraries fixes the above ImportError. – Tal Ben-Nun Jan 24 '22 at 10:05
0

Based on this answer: https://stackoverflow.com/a/62449190/4593199

I was able to transfer MPI Communicator by creating custom MPI type caster.

#include <pybind11/pybind11.h>
#include <mpi.h>
#include <mpi4py/mpi4py.h>

namespace py = pybind11;

struct mpi4py_comm {
  mpi4py_comm() = default;
  mpi4py_comm(MPI_Comm value) : value(value) {}
  operator MPI_Comm () { return value; }

  MPI_Comm value;
};


namespace pybind11 { namespace detail {
  template <> struct type_caster<mpi4py_comm> {
    public:
      PYBIND11_TYPE_CASTER(mpi4py_comm, _("mpi4py_comm"));

      // Python -> C++
      bool load(handle src, bool) {
        PyObject *py_src = src.ptr();

        // Check that we have been passed an mpi4py communicator
        if (PyObject_TypeCheck(py_src, &PyMPIComm_Type)) {
          // Convert to regular MPI communicator
          value.value = *PyMPIComm_Get(py_src);
        } else {
          return false;
        }

        return !PyErr_Occurred();
      }

      // C++ -> Python
      static handle cast(mpi4py_comm src,
                         return_value_policy /* policy */,
                         handle /* parent */)
      {
        // Create an mpi4py handle
        return PyMPIComm_New(src.value);
      }
  };
}} // namespace pybind11::detail


// recieve a communicator and check if it equals MPI_COMM_WORLD
void print_comm(mpi4py_comm comm)
{
        int rank;
        std::vector<int> test; 
        MPI_Comm_rank(MPI_COMM_WORLD, &rank);

        test.clear();
        test.resize(10, rank); 

        for (int i = 0; i != 10; ++i) {
            std::cout << test[i] << " ";
        }
        std::cout << std::endl;
}


class SomeComputation
{
    float multiplier;
    std::vector<int> test;
    MPI_Comm comm_;

public:
    void Init()
    {
        int rank;
        MPI_Comm_rank(comm_, &rank);
        test.clear();
        test.resize(10, rank);
    }
    SomeComputation(float multiplier_) : multiplier(multiplier_){}
    ~SomeComputation() { std::cout << "Destructor Called!\n"; }

    void set_comm(mpi4py_comm comm){
        this->comm_ = comm;
    }

    float compute(float input)
    {
        // std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10));
        for (int i = 0; i != 10; ++i)
        {
            std::cout << test[i] << " ";
        }
        std::cout << std::endl;
        return multiplier * input;
    }
};


mpi4py_comm get_comm()
{
  return MPI_COMM_WORLD; // Just return MPI_COMM_WORLD for demonstration
}

PYBIND11_MODULE(native, m)
{
  // import the mpi4py API
  if (import_mpi4py() < 0) {
    throw std::runtime_error("Could not load mpi4py API.");
  }

  // register the test functions
  m.def("print_comm", &print_comm, "Do something with the mpi4py communicator.");
  m.def("get_comm", &get_comm, "Return some communicator.");


    py::class_<SomeComputation>(m, "Cpp_computation")
        .def(py::init<float>()) // args of constructers are template args
        .def("set_comm", &SomeComputation::set_comm)
        .def("compute", &SomeComputation::compute)
        .def("cpp_init", &SomeComputation::Init);
}

This compiled and ran successfully, however, is there a more elegant way to go about it?

Jarwin
  • 1,045
  • 1
  • 9
  • 30