Skip to content

Commit

Permalink
Update multiprocessing context to be Pool specific (pybamm-team#4001)
Browse files Browse the repository at this point in the history
* convert global start context to individual pool context

* Update context creation, add tests for coverage

---------

Co-authored-by: Valentin Sulzer <valentinsulzer@hotmail.com>
Co-authored-by: Eric G. Kratz <kratman@users.noreply.github.com>
  • Loading branch information
3 people authored and js1tr3 committed Aug 12, 2024
1 parent 296b990 commit 5ef9ea6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
13 changes: 8 additions & 5 deletions pybamm/solvers/base_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
import pybamm
from pybamm.expression_tree.binary_operators import _Heaviside

# Set context for parallel processing depending on the platform
if platform.system() == "Darwin" or platform.system() == "Linux":
mp.set_start_method("fork")


class BaseSolver:
"""Solve a discretised model.
Expand Down Expand Up @@ -70,6 +66,7 @@ def __init__(
self.algebraic_solver = False
self._on_extrapolation = "warn"
self.computed_var_fcns = {}
self._mp_context = self.get_platform_context(platform.system())

@property
def root_method(self):
Expand Down Expand Up @@ -917,7 +914,7 @@ def solve(
model_inputs_list,
)
else:
with mp.Pool(processes=nproc) as p:
with mp.get_context(self._mp_context).Pool(processes=nproc) as p:
new_solutions = p.starmap(
self._integrate,
zip(
Expand Down Expand Up @@ -1395,6 +1392,12 @@ def check_extrapolation(self, solution, events):
"outside these bounds."
)

def get_platform_context(self, system_type: str):
# Set context for parallel processing depending on the platform
if system_type.lower() in ["linux", "darwin"]:
return "fork"
return "spawn"

@staticmethod
def _set_up_model_inputs(model, inputs):
"""Set up input parameters"""
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/test_solvers/test_base_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,12 @@ def test_multiple_models_error(self):
with self.assertRaisesRegex(RuntimeError, "already been initialised"):
solver.solve(model2, t_eval=[0, 1])

def test_multiprocess_context(self):
solver = pybamm.BaseSolver()
assert solver.get_platform_context("Win") == "spawn"
assert solver.get_platform_context("Linux") == "fork"
assert solver.get_platform_context("Darwin") == "fork"

@unittest.skipIf(not pybamm.have_idaklu(), "idaklu solver is not installed")
def test_sensitivities(self):
def exact_diff_a(y, a, b):
Expand Down

0 comments on commit 5ef9ea6

Please sign in to comment.