Coverage for ase/parallel.py: 60.31%
257 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import atexit
2import functools
3import os
4import pickle
5import sys
6import time
7import warnings
8from abc import abstractmethod
9from typing import Protocol
11import numpy as np
14def paropen(name, mode='r', buffering=-1, encoding=None, comm=None):
15 """MPI-safe version of open function.
17 In read mode, the file is opened on all nodes. In write and
18 append mode, the file is opened on the master only, and /dev/null
19 is opened on all other nodes.
20 """
21 if comm is None:
22 comm = world
23 if comm.rank > 0 and mode[0] != 'r':
24 name = os.devnull
25 return open(name, mode, buffering, encoding)
28def parprint(*args, comm=None, **kwargs):
29 """MPI-safe print - prints only from master."""
30 if comm is None:
31 comm = world
32 if comm.rank == 0:
33 print(*args, **kwargs)
36class MPICommunicator(Protocol):
37 """Limited interface to MPI communicator for ASE."""
39 rank: int
40 """Rank of this process on the communicator."""
41 size: int
42 """Number of processes on this communicator."""
44 @property
45 def backend(self) -> str:
46 """A string identifier for this Python MPI interface.
48 The purpose of this string is to be able to check that the
49 correct MPI implementation is in use.
51 Each implementing subclass of this protocol should normally
52 try to pick a string that will be distinct from those of other
53 implementations, whereas wrappers should normally return the
54 backend of the wrapped communicator.
56 ASE already provides the implementations 'serial' and 'ase-mpi4py'.
57 """
58 raise NotImplementedError
60 @abstractmethod
61 def sum(self, a: np.ndarray, root: int = -1) -> None:
62 """In-place sum over ranks.
64 The sum is computed only on the rank specified by root,
65 or all ranks if root is -1."""
66 raise NotImplementedError
68 @abstractmethod
69 def sum_scalar(self, a, root: int = -1):
70 """Return the sum over ranks of a scalar.
72 See sum() for rules about root."""
73 raise NotImplementedError
75 # Input could be any kind of scalar, and we presumably want to
76 # return the same kind of scalar. But actually, probably a
77 # python scalar becomes a numpy scalar in our various
78 # implementations.
80 def product(self, a: np.ndarray, root: int = -1) -> None:
81 """In-place product over ranks.
83 See sum() for rules about root."""
84 # This should be abstract, but due to an oversight,
85 # MPI4Py does not have it. So now it is effectively optional.
86 raise NotImplementedError
88 @abstractmethod
89 def broadcast(self, a: np.ndarray, root: int) -> None:
90 """Broadcast array from root across all ranks."""
91 raise NotImplementedError
93 @abstractmethod
94 def barrier(self) -> None:
95 """Wait until all ranks reach barrier."""
96 raise NotImplementedError
98 @abstractmethod
99 def abort(self, code: int) -> None:
100 """Abort runtime with given error code."""
101 raise NotImplementedError
103 # The mpi4py communicator actually defines .split() as well, but
104 # probably we don't want to advertise that.
107class DummyMPI(MPICommunicator):
108 rank = 0
109 size = 1
110 backend = 'serial'
112 def _returnval(self, a, root=-1):
113 # MPI interface works either on numbers, in which case a number is
114 # returned, or on arrays, in-place.
115 if np.isscalar(a):
116 return a
117 if hasattr(a, '__array__'):
118 a = a.__array__()
119 assert isinstance(a, np.ndarray)
120 return None
122 def sum(self, a, root=-1):
123 if np.isscalar(a):
124 warnings.warn(
125 'Please use sum_scalar(...) for scalar arguments', FutureWarning
126 )
127 return self._returnval(a)
129 def sum_scalar(self, a, root=-1):
130 return a
132 def product(self, a, root=-1):
133 return self._returnval(a)
135 def broadcast(self, a, root):
136 assert root == 0
137 return self._returnval(a)
139 def barrier(self):
140 pass
142 def abort(self, code: int):
143 # Note: in practice we do not register an abort() call in serial.
144 raise SystemExit(code)
147class MPI:
148 """Wrapper for MPI world object.
150 Decides at runtime (after all imports) which one to use:
152 * MPI4Py
153 * GPAW
154 * Asap
155 * a dummy implementation for serial runs
157 """
159 def __init__(self):
160 self.comm = None
162 def __getattr__(self, name):
163 # Pickling of objects that carry instances of MPI class
164 # (e.g. NEB) raises RecursionError since it tries to access
165 # the optional __setstate__ method (which we do not implement)
166 # when unpickling. The two lines below prevent the
167 # RecursionError. This also affects modules that use pickling
168 # e.g. multiprocessing. For more details see:
169 # https://gitlab.com/ase/ase/-/merge_requests/2695
170 if name == '__setstate__':
171 raise AttributeError(name)
173 if self.comm is None:
174 self.comm = _get_comm()
176 gpaw_asap_specific_attrs = {
177 'scatter',
178 'min',
179 'min_scalar',
180 'max',
181 'max_scalar',
182 'send',
183 'gather',
184 'all_gather',
185 'alltoallv',
186 'new_communicator',
187 'test',
188 'testall',
189 'wait',
190 'waitall',
191 'get_members',
192 'compare',
193 'translate_ranks',
194 'get_c_object',
195 }
197 if name in gpaw_asap_specific_attrs:
198 warnings.warn(
199 'In the future, unless ASE_PARALLEL_WORLD_HOOK is specified, '
200 'ase.parallel.world will provide only the '
201 'ase.parallel.MPICommunicator interface, '
202 f'and this does not include a {name!r} attribute.',
203 FutureWarning,
204 )
206 return getattr(self.comm, name)
209def deprecated_mpi(name):
210 warnings.warn(
211 'MPI was initialized in ase.parallel using a legacy mechanism. '
212 'In the future, this will result in a serial runtime '
213 'as far as ase.parallel is concerned. Please use the '
214 'ASE_PARALLEL_WORLD_HOOK mechanism instead. The legacy '
215 'initialization was triggered because no hook was specified, '
216 f'and the module {name} module was imported.',
217 FutureWarning,
218 )
221def _get_comm():
222 """Get the correct MPI world object."""
223 if 'mpi4py' in sys.modules:
224 deprecated_mpi('mpi4py')
225 return MPI4PY()
226 if '_gpaw' in sys.modules:
227 world = _gpaw_world()
228 if world is not None and getattr(world, 'backend', None) != 'serial':
229 deprecated_mpi('_gpaw')
230 return world
231 if '_asap' in sys.modules:
232 world = _asap_world()
233 if world is not None:
234 deprecated_mpi('_asap')
235 return world
236 return DummyMPI()
239class MPI4PY(MPICommunicator):
240 backend = 'ase-mpi4py'
242 def __init__(self, mpi4py_comm=None):
243 if mpi4py_comm is None:
244 from mpi4py import MPI
246 mpi4py_comm = MPI.COMM_WORLD
247 self.comm = mpi4py_comm
249 @property
250 def rank(self):
251 return self.comm.rank
253 @property
254 def size(self):
255 return self.comm.size
257 def _returnval(self, a, b):
258 """Behave correctly when working on scalars/arrays.
260 Either input is an array and we in-place write b (output from
261 mpi4py) back into a, or input is a scalar and we return the
262 corresponding output scalar."""
263 if np.isscalar(a):
264 assert np.isscalar(b)
265 return b
266 else:
267 assert not np.isscalar(b)
268 a[:] = b
269 return None
271 def sum(self, a, root=-1):
272 if root == -1:
273 b = self.comm.allreduce(a)
274 else:
275 b = self.comm.reduce(a, root)
276 if np.isscalar(a):
277 warnings.warn(
278 'Please use sum_scalar(...) for scalar arguments', FutureWarning
279 )
280 return self._returnval(a, b)
282 def sum_scalar(self, a, root=-1):
283 if root == -1:
284 b = self.comm.allreduce(a)
285 else:
286 b = self.comm.reduce(a, root)
287 return b
289 def split(self, split_size=None):
290 """Divide the communicator."""
291 # color - subgroup id
292 # key - new subgroup rank
293 if not split_size:
294 split_size = self.size
295 color = int(self.rank // (self.size / split_size))
296 key = int(self.rank % (self.size / split_size))
297 comm = self.comm.Split(color, key)
298 return MPI4PY(comm)
300 def barrier(self):
301 self.comm.barrier()
303 def abort(self, code):
304 self.comm.Abort(code)
306 def broadcast(self, a, root):
307 b = self.comm.bcast(a, root=root)
308 if self.rank == root:
309 if np.isscalar(a):
310 return a
311 return None
312 return self._returnval(a, b)
315def _asap_world():
316 import _asap
318 try:
319 world = _asap.Communicator()
320 except (AttributeError, RuntimeError):
321 return None
323 return world
326def _gpaw_world():
327 import _gpaw
329 if not hasattr(_gpaw, 'Communicator'):
330 return None
332 # Return the actual public (possibly wrapper) object
333 from gpaw.mpi import world
335 return world
338# Note to implementors:
339# Whoever sets this variable MUST check that it was not already set!
340# If it is set in two places, there are two competing parallel
341# mechanisms and that must be avoided.
342mpiworld_importpath = os.environ.get('ASE_PARALLEL_WORLD_HOOK')
344world: MPI | MPICommunicator
346if mpiworld_importpath is None:
347 # In the future this will be always serial!
348 # We should detect if we would set a real communicator here
349 # and issue a FutureWarning there.
350 mpiworld_module = None
351 world = MPI()
353 # Once we remove these MPI behaviours, all other MPI initialization
354 # code in ASE can be removed.
355else:
356 import importlib
358 mpiworld_module = importlib.import_module(mpiworld_importpath)
359 world = mpiworld_module.ASE_PARALLEL_WORLD_HOOK()
360 if world is None:
361 # The application declined to make a parallel MPI communicator
362 world = DummyMPI()
365def barrier():
366 world.barrier()
369def broadcast(obj, root=0, comm=world):
370 """Broadcast a Python object across an MPI communicator and return it."""
371 if comm.rank == root:
372 string = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
373 n = np.array([len(string)], int)
374 else:
375 string = None
376 n = np.empty(1, int)
377 comm.broadcast(n, root)
378 if comm.rank == root:
379 string = np.frombuffer(string, np.int8)
380 else:
381 string = np.zeros(n, np.int8)
382 comm.broadcast(string, root)
383 if comm.rank == root:
384 return obj
385 else:
386 return pickle.loads(string.tobytes())
389def parallel_function(func):
390 """Decorator for broadcasting from master to slaves using MPI.
392 Disable by passing parallel=False to the function. For a method,
393 you can also disable the parallel behavior by giving the instance
394 a self.serial = True.
395 """
397 @functools.wraps(func)
398 def new_func(*args, **kwargs):
399 parallel = kwargs.pop('parallel', True)
400 if (
401 world.size == 1
402 or (args and getattr(args[0], 'serial', False))
403 or not parallel
404 ):
405 # Disable:
406 return func(*args, **kwargs)
408 ex = None
409 result = None
410 if world.rank == 0:
411 try:
412 result = func(*args, **kwargs)
413 except Exception as x:
414 ex = x
415 ex, result = broadcast((ex, result))
416 if ex is not None:
417 raise ex
418 return result
420 return new_func
423def parallel_generator(generator):
424 """Decorator for broadcasting yields from master to slaves using MPI.
426 Disable by passing parallel=False to the function. For a method,
427 you can also disable the parallel behavior by giving the instance
428 a self.serial = True.
429 """
431 @functools.wraps(generator)
432 def new_generator(*args, **kwargs):
433 parallel = kwargs.pop('parallel', True)
434 if (
435 world.size == 1
436 or (args and getattr(args[0], 'serial', False))
437 or not parallel
438 ):
439 # Disable:
440 for result in generator(*args, **kwargs):
441 yield result
442 return
444 if world.rank == 0:
445 try:
446 for result in generator(*args, **kwargs):
447 broadcast((None, result))
448 yield result
449 except Exception as ex:
450 broadcast((ex, None))
451 raise ex
452 broadcast((None, None))
453 else:
454 ex2, result = broadcast((None, None))
455 if ex2 is not None:
456 raise ex2
457 while result is not None:
458 yield result
459 ex2, result = broadcast((None, None))
460 if ex2 is not None:
461 raise ex2
463 return new_generator
466def register_parallel_cleanup_function():
467 """Call MPI_Abort if python crashes.
469 This will terminate the processes on the other nodes."""
471 if world.size == 1:
472 return
474 def cleanup(sys=sys, time=time, world=world):
475 error = getattr(sys, 'last_type', None)
476 if error:
477 sys.stdout.flush()
478 sys.stderr.write(
479 (
480 'ASE CLEANUP (node %d): %s occurred. '
481 + 'Calling MPI_Abort!\n'
482 )
483 % (world.rank, error)
484 )
485 sys.stderr.flush()
486 # Give other nodes a moment to crash by themselves (perhaps
487 # producing helpful error messages):
488 time.sleep(3)
489 world.abort(42)
491 atexit.register(cleanup)
494def distribute_cpus(size, comm):
495 """Distribute cpus to tasks and calculators.
497 Input:
498 size: number of nodes per calculator
499 comm: total communicator object
501 Output:
502 communicator for this rank, number of calculators, index for this rank
503 """
505 assert size <= comm.size
506 assert comm.size % size == 0
508 tasks_rank = comm.rank // size
510 r0 = tasks_rank * size
511 ranks = np.arange(r0, r0 + size)
512 mycomm = comm.new_communicator(ranks)
514 return mycomm, comm.size // size, tasks_rank
517def myslice(ntotal, comm):
518 """Return the slice of your tasks for ntotal jobs"""
519 n = -(-ntotal // comm.size) # ceil divide
520 return slice(n * comm.rank, n * (comm.rank + 1))