I need to evaluate a Sympy lambda function in parallel using multiprocessing.Pool. It seems Sympy lambda function could not be pickled by default and therefore fails when used in Pool. Is there any solution to it?
A minimal example is as below.
from multiprocessing import Pool
# from pathos.multiprocessing import Pool
x = sympy.symbols('x')
expr = sympy.sympify('x*x')
jacobian_lambda = sympy.lambdify(x, sympy.Matrix([expr]).jacobian([x]))
pool = Pool()
res1 = pool.apply_async(jacobian_lambda, [1])
res2 = pool.apply_async(jacobian_lambda, [2])
print([res1.get(), res2.get()])
I expect to get
[[2], [4]]
which is the evaluation of the derivative of x^2 on 1 and 2.
I got the following error when I try to run the code above.
_pickle.PicklingError: Can't pickle <function <lambda> at 0x7efd90e32d08>: attribute lookup <lambda> on numpy failed
I am aware that Passing sympy lambda to multiprocessing.Pool.map might be a duplicate question, but there does not seem to be a solution without removing lambda function.
Passing sympy lambda to multiprocessing.Pool.map The accepted answer suggests defining a function at the top level, which doesn't seem to solve the problem. Another suggestion to use pathos.multiprocessing does not help in this case, either.
Thanks.