Python:mpi4py 的计算时间问题

计算科学 Python mpi
2021-12-08 13:18:50

我在 Python 中使用mpi4py并行处理 20 个最小化函数。20 个工作人员中的每一个都处理相同的算法,但具有不同的随机初始起始值。我不明白处理我的工作所花费的时间。我希望每个工作人员花费大致相同的时间来最小化该功能,但它从 300 秒到 2000 秒不等。现在我不确定为什么会这样。我想知道我是否正确指定了我的 MPI 工作,或者这恰好是因为它注定要发生。这是我的代码

from mpi4py import MPI
import os
import random
import nlopt

data = #load a dataset

#Set the range for each of the variables (parameters)
X1_ = arange(1.01,1.99,.01)
X2_ = arange(0.01, 0.9, 0.01)

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

# Draw random values for each of the parameters
X1 = random.choice(X1_)
X2 = random.choice(X2_)

#Set up the lower and upper bound for each variables:
X1min = 1.05
X1max = 1.99
X2min = .01
X2max = 0.9999999

def myfunc(x, grad):
    if grad.size > 0:
        grad = numgrad(myfunction, [x[0], x[1]],
                       step=1e-8) #numgrad is a function that computes the gradient but irrelevant with a derivative-free algo
    return myfunction([x[0], x[1]], data)

opt = nlopt.opt(nlopt.LN_NELDERMEAD, 2)
opt.set_lower_bounds([X1min, X2min])
opt.set_upper_bounds([X1max, X2max])
opt.set_min_objective(myfunc)
opt.set_xtol_rel(1e-8)
opt.maxeval = 10000
x = opt.optimize([X1, X2])
minf = opt.last_optimum_value()

我的 MPI 规范中是否缺少某些内容?

1个回答

乍一看,代码看起来不错——它按照你说的去做。

您发布的代码中几乎没有通信,因此您可以尝试隔离性能原因的一件事是在串行的 20 个起点中的每一个上运行 nlopt,一次一个。执行此操作时,请确保将随机数生成器的种子设置为固定值,以便始终获得相同的随机变量。

对它们进行计时将确认或反驳我怀疑的主要原因:Nelder-Mead 需要不同数量的迭代来收敛不同的起始值,从而导致您观察到的性能差异。