** kwargs不在mpi4py MPIPoolExecutor中工作

问题描述 投票:1回答:1

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中的注释掉部分时,代码按预期运行。

python-3.x kwargs mpi4py
1个回答
0
投票

我不认为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协议的列表。

© www.soinside.com 2019 - 2024. All rights reserved.