mpi4py | comm.bcast 不起作用

Com*_*ner 2 python hpc cluster-computing mpi mpi4py

我正在编写一个简单的 python 脚本来测试 mpi4py。具体来说,我想从给定处理器(例如rank 0)广播标量和数组,以便所有其他处理器都可以在后续步骤中访问广播标量和数组的值。

这就是我到目前为止所做的:

from __future__ import division
from mpi4py import MPI
import numpy as np

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

if rank==0:
    scal = 55.0
    mat = np.array([[1,2,3],[4,5,6],[7,8,9]])

    arr = np.ones(5)
    result = 2*arr

    comm.bcast([ result , MPI.DOUBLE], root=0)
    comm.bcast( scal, root=0)
    comm.bcast([ mat , MPI.DOUBLE], root=0) 

for proc in range(1, 3):
    if (rank == proc):
        print "Rank: ", rank, ". Array is: ", result
        print "Rank: ", rank, ". Scalar is: ", scal
        print "Rank: ", rank, ". Matrix is: ", mat
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

NameError: name 'mat' is not defined
    print "Rank: ", rank, ". Matrix is: ", mat
Run Code Online (Sandbox Code Playgroud)

另外,在我的输出 (print "Rank: ", rank, ". Scalar is: ", scalprint "Rank: ", rank, ". Array is: ", arr) 中,我没有看到scal和的值array。我在这里缺少什么?我将非常感谢任何帮助。

jcg*_*ret 7

我在这里看到两个错误:

  • 您的变量scal和 numpy 数组matarrresults仅在等级 0 上定义。它们应该在所有 MPI 等级上定义。事实上,当数据在所有等级上广播时,必须分配变量和 Numpy 数组来存储接收到的结果。
  • bcast适用于 Python 对象,并经过腌制(例如序列化)以便发送。Bcast适用于 Numpy 数组。因此,根据您发送/接收的内容相应地使用不同的调用。而且,他们必须被召集到所有队伍中。

由于我使用的是 Python 3,因此我也更正了这些print调用。然而,由于print_functionfuture导入,您不应该注意到 Python 2 的任何问题

最后,我建议您查看此处的 MPI4Py 教程:http://mpi4py.scipy.org/docs/usrman/tutorial.html。我认为它们涵盖了您可以使用 MPI4Py 执行的大部分操作。

这是有效的:

from __future__ import division, print_function
from mpi4py import MPI
import numpy as np

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


scal = None
mat = np.empty([3,3], dtype='d')

arr = np.empty(5, dtype='d')
result = np.empty(5, dtype='d')


if rank==0:
    scal = 55.0
    mat[:] = np.array([[1,2,3],[4,5,6],[7,8,9]])

    arr = np.ones(5)
    result = 2*arr

comm.Bcast([ result , MPI.DOUBLE], root=0)
scal = comm.bcast(scal, root=0)
comm.Bcast([ mat , MPI.DOUBLE], root=0)

print("Rank: ", rank, ". Array is:\n", result)
print("Rank: ", rank, ". Scalar is:\n", scal)
print("Rank: ", rank, ". Matrix is:\n", mat)
Run Code Online (Sandbox Code Playgroud)