【问题标题】:python MPI for dictionary iteration用于字典迭代的python MPI
【发布时间】:2021-08-25 02:14:46
【问题描述】:

我想使用 MPI (mpi4.py)(消息传递接口)拆分字典的迭代。

例如,

from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

tmp_list = []
for key, value in some_dict.items():
    tmp_values = some_function(key,value)
    tmp_list.append(tmp_values)

有一些简单的代码。 我如何为迭代编写 MPI 代码。

【问题讨论】:

  • 首字母缩略词“MPI”超载。你将不得不更详细地了解你想要什么。
  • 另外,不要使用dict作为名字,它是内置函数。
  • 你是什么意思split the iteration of dictionary using MPI。您是否希望将数据分散到各个核心然后进行迭代

标签: python dictionary mpi


【解决方案1】:

您首先需要将 dict 转换为列表,然后将列表划分为您将使用的多个进程。这是必要的,以便comm.scatter 可以跨所有进程发送部分数据。然后可以使用comm.gather

收集最终结果

脚本.py

#!/usr/bin/python

from mpi4py import MPI

comm = MPI.COMM_WORLD
size = comm.Get_size() # get number of processes
rank = comm.Get_rank() # get the current rank of process

def some_fun(x,y): # some random function
    return x+y

def chunkIt(seq, num): #function to chunk list into {size} parts for scatter to work
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

some_dict = {i: i**2 for i in range(100)} # some random data to work on

if rank == 0:
    data = chunkIt(list(some_dict.items()), size) # convert dict into list first and then divide the data into {size} parts
    # print(f"rank: {rank} / data: {data}")
else:
    data = None
    
data = comm.scatter(data, root=0) # scatter the data accross given processes
print(f"rank: {rank} / data: {data}\n")

sub_dict = dict(data) # convert the list into dict

tmp_list = [] #local to each process
for key, value in sub_dict.items():
    tmp_values = some_fun(key, value)
    tmp_list.append(tmp_values)
  
tmp_list = comm.gather(tmp_list, root=0) # gathering data from all procs to root proc
if rank == 0:
    print(f"length of tmp_list on rank: {rank} is: {len(tmp_list)}")
    print(f"tmp_list: {tmp_list}") #tmp_list is list ot lists. make sure to convert it into required ds 
else:
    assert tmp_list is None

使用chmod使其可执行

chmod +x script.py

然后运行

mpiexec -n 4 script.py

-n 是要运行的进程数

注意:我使用的是 ubuntu 16.04 和 python 3.7.10 和 mpi4py==3.0.3

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2014-01-21
    相关资源
    最近更新 更多