为什么 python MPI allreduce 返回一个输入列表?

Why is the python MPI allreduce returning an input list?

我有以下示例问题,使用 mpi4py 中的 allreduce 函数跨多个进程查找列表中每个元素的最小值。但是,结果列表不正确。 allreduce 的输出始终是输入列表之一。如何纠正?

输出

Rank 0: [2, 3, 6, 6, 10, 0, 9, 2, 4, 1]
Allreduce: [0, 0, 4, 4, 1, 0, 10, 10, 1, 5]
Rank 1: [4, 7, 8, 1, 3, 2, 1, 8, 2, 10]
Rank 2: [6, 2, 6, 3, 2, 3, 7, 6, 10, 4]
Rank 3: [7, 1, 0, 0, 3, 1, 6, 5, 9, 10]
Rank 4: [0, 0, 4, 4, 1, 0, 10, 10, 1, 5]
Rank 5: [1, 9, 3, 5, 9, 4, 9, 5, 4, 5]
Rank 6: [1, 4, 6, 10, 7, 2, 1, 2, 1, 3]
Rank 7: [8, 8, 8, 2, 7, 7, 9, 2, 1, 2]
Rank 8: [7, 2, 4, 10, 7, 7, 5, 2, 9, 1]
Rank 9: [3, 1, 1, 3, 5, 10, 7, 4, 2, 5]

代码

from mpi4py import MPI
import random
    
#MPI Parallelization
comm = MPI.COMM_WORLD # gets communication pool 
rank = comm.Get_rank()  # gets rank of current process 
num_ranks = comm.Get_size() # total number of processes
 
r = [random.randint(0,10) for i in range(0,10)]
    
print("Rank " + str(rank) + ": " + str(r))
  
comm.Barrier()
rr = comm.allreduce(r, op=MPI.MIN)
   
if rank == 0:
    print("Allreduce: " + str(rr))

一般来说,mpi4pynumpy 搭配效果最佳。

这是一个 allreduce 示例: (注意 numpy 你应该使用 Allreduce(...) 而不是 allreduce(...)

from mpi4py import MPI
import random
import numpy as np
    
#MPI Parallelization
comm = MPI.COMM_WORLD # gets communication pool 
rank = comm.Get_rank()  # gets rank of current process 
num_ranks = comm.Get_size() # total number of processes
 
r = np.random.randint(0, 100, 10)
rr = np.empty(10, dtype=int)
    
print("Rank " + str(rank) + ": " + str(r))
  
comm.Barrier()
comm.Allreduce([r, MPI.INT], [rr, MPI.INT], op=MPI.MIN)
   
if rank == 0:
    print("Allreduce: " + str(rr))

在你的情况下,我怀疑 MPI.MIN 应用于 python 列表的结果不是具有最少元素的列表,因此你将获得给定等级的完整缓冲区.