[docs]classMPIService:""" Interface for MPI Communication context. This class will also emulate MPI Communication context in single node context. """def__init__(self,comm=None):self._mpi=MPIModule("mpi4py.MPI")self._comm=commorself._mpi.COMM_WORLD
[docs]@contextlib.contextmanagerdeftry_all(self,default_exception=None):""" Create a context manager that checks if any exception is raised by any processes within the context, and make all other processes raise an exception in that case :param Exception default_exception: Exception instance to raise for all processes that did not raise during the context. :return: context manager """exc_instance=Nonedefault_exception=default_exceptionorRuntimeError("An error occurred on a different rank")try:yieldexceptExceptionase:exc_instance=eexceptions=self.allgather(exc_instance)ifany(exceptions):raise(exceptions[self.get_rank()]ifexceptions[self.get_rank()]elsedefault_exception)
[docs]@contextlib.contextmanagerdeftry_main(self):""" Create a context manager that checks if any exception is raised by the main process within the context, and make all other processes raise this exception in that case Warning: All processes will still enter the context, but only main exception will be raised. :return: context manager """exc_instance=Nonetry:# All processes have to enter the context# contextlib will throw an error if one does not yieldyieldexceptExceptionase:exc_instance=eexception=self.bcast(exc_instance)ifexceptionisnotNone:raiseexception
[docs]classMPIModule(MockModule):""" Module provider of the MPI interface. """@property@functools.cachedefCOMM_WORLD(self):if(any("mpi"inkey.lower()forkeyinos.environ)and"BSB_IGNORE_PARALLEL"notinos.environ):raiseDependencyError("MPI runtime detected without parallel support."+" Please install with `pip install bsb[parallel]`."+" Set `BSB_IGNORE_PARALLEL` to ignore this error.")returnNone