mpi4py文档声称你可以通过MPIPoolExecutor传递** kwargs,但我无法让它工作。我执行以下代码:
import time
import socket
import numpy as np
from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
def print_val(x, kwargsstr):
time.sleep(1)
msg = "x value: " + str(x) + \
", socket: " + str(socket.gethostname()) + \
", rank: " + str(MPI.COMM_WORLD.Get_rank()) + \
", time: " + str(np.round(time.time(), 1)) + \
", kwargs string: " + kwargsstr
print(msg)
return x
def main():
kwarg = 'test'
kwargs = {'kwargsstr':kwarg}
with MPIPoolExecutor() as executor:
x_v = []
# for res in executor.map(print_val,
# range(9), 9*[kwarg]):
for res in executor.map(print_val,
range(9), **kwargs):
x_v += [res]
print(x_v)
if __name__ == '__main__':
"""
run on command line with 1 scheduler and 2 workers:
$ mpiexec -n 1 -usize 3 -machinefile hostfile.txt python mpi4py_kwargs.py
"""
main()
通过这个命令:
$ mpiexec -n 1 -usize 3 -machinefile hostfile.txt python mpi4py_kwargs.py
并收到此错误消息:
TypeError: print_val() missing 1 required positional argument: 'kwargsstr'
请注意,当切换main中的注释掉部分时,代码按预期运行。
我不认为map
支持kwargs。我们来看看source code
map
确实在其签名中采用kwargs
:
def map(self, fn, *iterables, **kwargs):
这就是文档中关于kwargs
论点的内容:
Keyword Args:
unordered: If ``True``, yield results out-of-order, as completed.
关键字参数(不包括unordered
)是否会传递给callables并不明显。我们继续。使用以下方式完成实施:
iterable = getattr(itertools, 'izip', zip)(*iterables)
return self.starmap(fn, iterable, **kwargs)
因此,kwargs
被转发到starmap
:
def starmap(self, fn, iterable, timeout=None, chunksize=1, **kwargs):
使用相同的文档
Keyword Args:
unordered: If ``True``, yield results out-of-order, as completed.
实现如下:
unordered = kwargs.pop('unordered', False)
if chunksize < 1:
raise ValueError("chunksize must be >= 1.")
if chunksize == 1:
return _starmap_helper(self.submit, fn, iterable,
timeout, unordered)
else:
return _starmap_chunks(self.submit, fn, iterable,
timeout, unordered, chunksize)
显然,一旦kwargs
被检索,unordered
就不再使用了。因此,map
不认为kwargs
是可驯服的kwargs。
正如我的评论中所指出的,对于这个特定的例子,你可以提供参数作为非关键字参数,但也可以提供位置参数:
for res in executor.map(print_val, range(9), [kwarg] * 9):
因为map
的第二个论点被记录为:
iterables: Iterables yielding positional arguments to be passed to
the callable.
对于刚接触python的人:
>>> kwarg = 'test'
>>> [kwarg] * 9
['test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']
其中[kwarg] * 9
是实现iterables协议的列表。