【问题标题】:Setting random seed in python disturbs multiprocessing在 python 中设置随机种子会干扰多处理
【发布时间】:2018-06-04 07:36:21
【问题描述】:

我观察到在 python 中使用多处理之前设置随机种子会导致奇怪的行为。

在 python 3.5.2 中,仅使用 2 或 3 个内核,使用的 CPU 百分比很低。 在 python 2.7.13 中,所有请求的内核都以 100% 使用,但代码似乎永远不会完成。当我删除随机种子的初始化时,并行化工作正常。

即使在并行化函数中没有明确使用 random,也会发生这种情况。我现在假设种子是在进程之间共享的,这会阻止多处理的顺利运行,但是有人可以提供正确的答案吗?


我已经在 Linux 上运行了代码,这里是一个最小的代码示例:

from multiprocessing import Pool
import numpy as np
import random

random.seed = 2018

NB_CPUS = 4

def test(x):
    return x**2

pool = Pool(NB_CPUS)
args = [np.random.rand() for _ in range(100000)]

results = pool.map(test, args)

pool.terminate()
results[-5:]

【问题讨论】:

    标签: python python-3.x random python-2.x python-multiprocessing


    【解决方案1】:

    答案有点晚了,但是您将random.seed function 设置为int 会破坏一切。你应该这样做:

    random.seed(2018)
    

    回溯的最后几行提供了应该使这一点显而易见的上下文:

      File "/usr/lib64/python2.7/multiprocessing/process.py", line 130, in start
        self._popen = Popen(self)
      File "/usr/lib64/python2.7/multiprocessing/forking.py", line 125, in __init__
        random.seed()
    TypeError: 'int' object is not callable
    

    这会导致Pool 继续尝试创建新的工作进程,但因为每次无法取得进展时都会发生这种情况。

    这背后是multiprocessing 知道它应该在分叉时重新播种随机模块,以便子进程不共享相同的 RNG 状态。为此,它会尝试调用 random.seed 函数,但您已将其设置为不可调用的 int --- 因此出现错误!

    与此相关的另一个问题是multiprocessing 不知道重新播种 NumPy RNG,所以下面的代码:

    from multiprocessing import Pool
    import numpy as np
    
    def test(i):
        print(i, np.random.rand())
    
    with Pool(4) as pool:
        pool.map(test, range(4))
    

    将导致每个工作人员打印相同的值。 This issue 已经有一段时间了,但仍然开放。您可以通过使用工作人员 initializer 来解决此问题,例如:

    def initfn():
        np.random.seed()
    
    with Pool(4, initializer=initfn) as pool:
        pool.map(test, range(4))
    

    现在将导致上述test 函数打印不同的值。请注意,如果您不进行任何其他工作级别初始化,您甚至可以使用 Pool(4, initializer=np.random.seed)

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2014-09-20
      • 2011-06-14
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      相关资源
      最近更新 更多