I want to use mpi4py to parallize an optimization problem. To minimize my function I use the minimize routine from scipy
from scipy.optimize import minimize
def f(x, data) :
#returns f(x)
x = minimize(f, x0, args=(data))
Now if I want to parallelize my function using mpi4py. The implementatino of the minimization algorithm is sequential and can only run on one process so only my function is parallelized which is not a problem since the function call is to most time consuming step. But I can't figure out how to implement this problem, with parallel and sequential parts.
Here is my attempt:
from scipy.optimize import minimize
from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
N = 100 # for testing
step = N//size # say that N is divisible by size
def mpi_f(x, data) :
x0 = x[rank*step:(rank+1)*step]
res = f(x0, data)
res = comm.gather(res, root=0)
if rank == 0 :
return res
if rank == 0 :
x = np.zeros(N)
xs = minimize(mpi_f, x, args=(data))
This is obviously not working since mpi_f only runs on the process 0. So I am asking how should I proceed ?
Thanks.