繁体   English   中英

mpi4py | comm.bcast不起作用

[英]mpi4py | comm.bcast does not work

我正在研究一个简单的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

但是,出现以下错误:

NameError: name 'mat' is not defined
    print "Rank: ", rank, ". Matrix is: ", mat

另外,在我的输出中( print "Rank: ", rank, ". Scalar is: ", scalprint "Rank: ", rank, ". Array is: ", arr ),我看不到scalarray 我在这里想念什么? 我将非常感谢您的帮助。

我在这里看到两个错误:

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

在使用Python 3时,我还更正了print调用。 但是,由于将来会print_function导入,因此您应该不会注意到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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM