如何在 Python 中使用 MPI 在不同内核上实现简单的并行计算

How to implement simple parallel computation on different cores using MPI in Python

我想并行执行一个简单的计算任务。假设我有两个数组,每个数组包含 2 个组件,我想将这些数组的组件一个一个地求和并将它们存储在一个新数组中。组件有 4 种组合 (2x2)。一个简单的代码可以串行编写 ,它只使用 1 个核心 并且求和操作在该核心上实现了 4 次。这是代码:

a = [1 , 5]
b = [10 , 20]

d = []

for i in range(2):
    for j in range(2):

        c = a[i] + b[j]
        d.append(c)

print (d)

现在我想并行使用 MPI 到 运行 上面的代码 在我的 PC 上使用 4 个不同的内核让它更快。话虽如此,我希望 每个组合都在分配的核心 上实现(例如,在 4 个不同的核心上进行 4 次求和操作)。以下是我如何导入 MPI:

from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
rank_process = mpi_comm.rank

我从来没有使用过并行计算,所以它看起来有点令人困惑。我想知道是否有人可以帮助我解决这个问题。提前感谢您的宝贵时间。

您可以使用 Create_cart 将 MPI 进程分配给矩阵的各个部分,以便为它们指定索引 ij,就像在您的系列示例中一样。这是解决方案,

from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
rank = mpi_comm.rank
root = 0

#Define data
a = [1 , 5]
b = [10 , 20]
d = []

#Print serial solution
if rank == 0:
    for i in range(2):
        for j in range(2):
            c = a[i] + b[j]
            d.append(c) 

    print("Serial soln = ", d)

#Split domain into 2 by 2 comm and run an element on each process
cart_comm = mpi_comm.Create_cart([2, 2])
i, j = cart_comm.Get_coords(rank)
d = a[i] + b[j]

#Print solns on each process, note this will be jumbled
# as all print as soon as they get here
print("Parallel soln = ", d)

# Better to gather and print on root
ds = mpi_comm.gather(d, root=root)
if rank == root:
    print("Parallel soln gathered = ", ds)

你在哪里得到类似的东西,

('Serial soln = ', [11, 21, 15, 25])
('Parallel ('Parallel soln = '('Parallel soln = 'soln = ', 11)
, 21)
('Parallel soln = ', 15)
, 25)
('Parallel soln gathered = ', [11, 21, 15, 25])

并行输出混乱的地方。注意你需要 运行 和 mpiexec 如下,

mpiexec -n 4 python script_name.py

其中 script_name.py 是您的脚本名称。

我不确定这是您如何使用 MPI 的一个很好的例子。总体上阅读 MPI 并查看一些典型示例是值得的。特别要注意的是,由于每个进程都独立于自己的数据,因此您应该处理可以将其拆分为多个部分的问题。在您的示例中,所有列表 ab 都是在每个进程上单独定义的,每个进程只使用其中的一小部分。每个进程之间的唯一区别是等级(0 到 3)和后来来自 create_cart 的二维笛卡尔索引,这决定了它们使用 "global" 数组的哪一部分。

一个更好的解决方案,更接近您在实践中使用它的方式可能是将大型矩阵的各个部分分散到多个进程,使用矩阵的那部分做一些工作并收集回解决方案以获得完整的解决方案矩阵(同样,请参阅涵盖此类内容的示例)。