gpt4 book ai didi

boost - Pybind11:可以使用 mpi4py 吗?

转载 作者:行者123 更新时间:2023-12-01 09:45:40 25 4
gpt4 key购买 nike

在 Pybind11 中是否可以在 Python 端使用 mpi4py,然后将通信器交给 C++ 端?

如果是这样,它将如何工作?

如果没有,是否可以使用Boost?如果是这样,它将如何完成?

我在网上搜索了几个小时,但没有找到任何东西。

最佳答案

这确实是可能的。正如 John Zwinck 在评论中指出的那样,MPI_COMM_WORLD将自动指向正确的通信器,因此无需将任何内容从 python 传递到 C++ 端。

例子

首先,我们有一个简单的 pybind11 模块,它确实公开了一个简单的打印一些 MPI 信息的函数(取自许多在线教程之一)。要编译模块,请参见此处 pybind11 cmake example .

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

void say_hi()
{
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
MPI_Get_processor_name(processor_name, &name_len);
printf("Hello world from processor %s, rank %d out of %d processors\n",
processor_name,
world_rank,
world_size);
}

PYBIND11_MODULE(mpi_lib, pybind_module)
{
constexpr auto MODULE_DESCRIPTION = "Just testing out mpi with python.";
pybind_module.doc() = MODULE_DESCRIPTION;

pybind_module.def("say_hi", &say_hi, "Each process is allowed to say hi");
}

接下来是python方面。这里我重用了这篇文章中的例子: Hiding MPI in Python并简单地放入 pybind11 库中。所以首先是调用 MPI python 脚本的 python 脚本:
import sys
import numpy as np

from mpi4py import MPI

def parallel_fun():
comm = MPI.COMM_SELF.Spawn(
sys.executable,
args = ['child.py'],
maxprocs=4)

N = np.array(0, dtype='i')

comm.Reduce(None, [N, MPI.INT], op=MPI.SUM, root=MPI.ROOT)

print(f'We got the magic number {N}')

和子进程文件。在这里,我们简单地调用库函数,它就可以工作了。
from mpi4py import MPI
import numpy as np

from mpi_lib import say_hi


comm = MPI.Comm.Get_parent()

N = np.array(comm.Get_rank(), dtype='i')

say_hi()

comm.Reduce([N, MPI.INT], None, op=MPI.SUM, root=0)

最终结果是:
from prog import parallel_fun
parallel_fun()
# Hello world from processor arch_zero, rank 1 out of 4 processors
# Hello world from processor arch_zero, rank 2 out of 4 processors
# Hello world from processor arch_zero, rank 0 out of 4 processors
# Hello world from processor arch_zero, rank 3 out of 4 processors
# We got the magic number 6

关于boost - Pybind11:可以使用 mpi4py 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49259704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com