【问题标题】:Unexpected output from mpi4py programmpi4py 程序的意外输出
【发布时间】:2015-09-20 16:00:19
【问题描述】:

我是使用 Python 的 MPI 新手,我在这里遇到了一些问题。这是我的代码:

from mpi4py import MPI

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

if rank == 0:
        a = 1 
        comm.bcast(a, root=0)
        s = comm.reduce(a, op=MPI.SUM)
        print 'From process 0, sum =', s
elif rank == 1:
        b = 2
        comm.bcast(b, root=1)  
        x = comm.reduce(b, op=MPI.SUM)
        print 'From process 1, sum =', x

我要打印:From process PROCESS_NUMBER, sum = 3

进程 0 打印正确,但进程 1 打印无。

我不明白为什么。谁能帮帮我?

【问题讨论】:

    标签: python mpi mpi4py


    【解决方案1】:

    comm.reduce(a, op=MPI.SUM) 对应于MPI_Reduce():总和仅在根进程上可用。

    如果您希望通信器的每个进程都可以使用总和,您可以使用comm.allreduce(a, op=MPI.SUM)。它对应于MPI_Allreduce()。请参阅this page 了解更多关于MPI_Reduce() 和MPI_Allreduce() 之间的区别。

    【讨论】:

      【解决方案2】:
      1. 任何集体操作(Bcast,Reduce)都应该被调用 进程,所以放在if rank == N里面是不正确的 声明。
      2. 在第二个 reduce 中,您必须指定 root=1。
      3. 广播中需要分配a = comm.bcast(a, root=0)

      更正的代码:

      from mpi4py import MPI
      
      comm = MPI.COMM_WORLD
      rank = comm.Get_rank()
      
      if rank == 0:
              a = 1
      else:
              a = None
      a = comm.bcast(a, root=0)
      s = comm.reduce(a, op=MPI.SUM)
      if rank == 0:
              print 'From process 0, sum =', s
      
      if rank == 1:
              b = 2
      else:
              b = None
      b = comm.bcast(b, root=1)
      x = comm.reduce(b, op=MPI.SUM, root=1)
      
      if rank == 1:
              print 'From process 1, sum =', x
      

      在 3 个进程上运行的结果:

      From process 0, sum = 3
      From process 1, sum = 6
      

      【讨论】:

      • 将集合放在条件中本质上并没有错:例如,您可以跳过除根以外的所有进程的reduce 调用的接收缓冲区。只要每个人都同意缓冲区的根和形状,有一些情况就可以了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多