Skip to content

Commit 98490b4

Browse files
committed
mpi: Distribute Functions subsampled by ConditionalDimensions
1 parent 7867d93 commit 98490b4

10 files changed

Lines changed: 244 additions & 159 deletions

File tree

‎devito/ir/equations/algorithms.py‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from devito.finite_differences.differentiable import diff2sympy
66
from devito.ir.support import GuardFactor, bounded
77
from devito.logger import warning
8-
from devito.parameters import configuration
98
from devito.symbolics import (
109
IntDiv, retrieve_dimensions, retrieve_functions, retrieve_indexed, uxreplace
1110
)
@@ -157,12 +156,17 @@ def _lower_exprs(expressions, subs):
157156
# Add dimensions map to the mapper in case dimensions are used
158157
# as an expression, i.e. Eq(u, x, subdomain=xleft)
159158
mapper.update(dimension_map)
160-
# Dimensions used as an expression are global indices, unlike loop indices
161-
mapper.update(_make_global_index_map(expr, dimension_map))
162-
# Add the user-supplied substitutions
163-
mapper.update(subs)
164-
# Apply mapper to expression
165-
processed.append(uxreplace(expr, mapper))
159+
# Apply mapper and the user-supplied substitutions to expression
160+
lowered = uxreplace(expr, {**mapper, **subs})
161+
162+
# Dimensions used as an expression are global indices, unlike loop indices.
163+
# They only apply to the operands, not to metadata such as the implicit_dims
164+
global_map = _make_global_index_map(lowered, dimension_map)
165+
if global_map:
166+
mapper = {**mapper, **global_map, **subs}
167+
lowered = lowered._rebuild(*[uxreplace(i, mapper) for i in expr.args])
168+
169+
processed.append(lowered)
166170

167171
if isinstance(expressions, Iterable):
168172
return processed
@@ -207,22 +211,20 @@ def _make_dimension_map(expr):
207211

208212
def _make_global_index_map(expr, dimension_map):
209213
"""
210-
Map the Dimensions of a distributed Grid to the global indices they stand for
211-
when used as an expression, i.e. Eq(u, x + y) -> Eq(u[x, y], x + io_x + y + io_y).
212-
Dimensions indexing an Indexed are unaffected as the Indexed is replaced as a whole.
214+
Map the Dimensions of a Grid to the global indices they stand for when used
215+
as an expression in the lowered `expr`, i.e. Eq(u[x, y], x + y) maps `x` to
216+
`x + io_x` and `y` to `y + io_y`. As Indexeds are leaves, their indices are
217+
not expressions, and neither is the metadata, e.g. the axes of a transform.
213218
"""
214219
if not isinstance(expr, Eq):
215220
return {}
216221

217-
# Keyed on MPI codegen rather than on the rank count: the code may be
218-
# generated on a single rank and run on many (e.g., the DevitoPRO decoupler)
219-
if not configuration['mpi']:
220-
return {}
221-
222+
values = set(retrieve_dimensions(expr))
222223
grids = {f.grid.root for f in retrieve_functions(expr) if f.grid is not None}
223224
return {d: dimension_map.get(d, d) + o
224225
for grid in grids
225-
for d, o in zip(grid.dimensions, grid.origin_isymbols, strict=True)}
226+
for d, o in zip(grid.dimensions, grid.origin_isymbols, strict=True)
227+
if dimension_map.get(d, d) in values}
226228

227229

228230
def concretize_subdims(exprs, **kwargs):

‎devito/mpi/distributed.py‎

Lines changed: 50 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
from devito.data import CENTER, LEFT, RIGHT, Decomposition
1313
from devito.parameters import configuration
1414
from devito.tools import (
15-
EnrichedTuple, as_tuple, ctypes_to_cstr, filter_ordered, frozendict
15+
EnrichedTuple, as_tuple, ctypes_to_cstr, filter_ordered, frozendict, is_integer,
16+
memoized_meth
1617
)
1718
from devito.types import CompositeObject, Constant, Object
18-
from devito.types.utils import DimensionTuple
19+
from devito.types.utils import DimensionTuple, GlobalLocal
1920

2021
# Do not prematurely initialize MPI
2122
# This allows launching a Devito program from within another Python program
@@ -213,6 +214,25 @@ def loc_empty(self):
213214
"""This rank is empty"""
214215
return any(d.loc_empty for d in self.decomposition)
215216

217+
@memoized_meth
218+
def subsample(self, dimensions):
219+
"""
220+
The Distributor of the ConditionalDimensions in `dimensions` subsampling
221+
those of `self`, or `self` if there are none.
222+
"""
223+
subsampled = {d.parent: d for d in dimensions
224+
if d.is_Conditional and d.parent in self.dimensions
225+
and is_integer(d.factor)}
226+
if not subsampled or not self.is_parallel:
227+
return self
228+
229+
return SubGridDistributor(
230+
self,
231+
tuple(subsampled.get(d, d) for d in self.dimensions),
232+
tuple(subsampled[d].factor if d in subsampled else 1
233+
for d in self.dimensions)
234+
)
235+
216236

217237
class DenseDistributor(AbstractDistributor):
218238

@@ -300,6 +320,13 @@ def all_ranges(self):
300320
getters=self.dimensions))
301321
return tuple(ret)
302322

323+
@cached_property
324+
def size_map(self):
325+
"""Map between Dimensions and their global/local size."""
326+
return {d: GlobalLocal(g, l)
327+
for d, g, l in zip(self.dimensions, self.glb_shape, self.shape,
328+
strict=True)}
329+
303330
@cached_property
304331
def _obj_comm(self):
305332
"""An Object representing the MPI communicator."""
@@ -494,21 +521,33 @@ def _rebuild(self, shape=None, dimensions=None, comm=None):
494521
class SubGridDistributor(Distributor):
495522

496523
"""
497-
Decompose a SubGrid over a set of MPI processes in a manner consistent with
498-
the parent distributor: a rank owns the SubGrid points on its parent points.
524+
Decompose a subsampling of a parent Distributor's domain, e.g. a SubGrid, over
525+
the parent's MPI processes: a rank owns the subsampled points on its parent
526+
points.
499527
500528
Parameters
501529
----------
502-
subgrid : SubGrid
503-
The SubGrid to be decomposed.
530+
parent : Distributor
531+
The Distributor of the subsampled domain.
532+
dimensions : tuple of Dimensions
533+
The decomposed Dimensions, one per parent Dimension.
534+
factors : tuple of ints
535+
The subsampling factor along each Dimension.
504536
"""
505537

506-
def __init__(self, subgrid):
507-
self._parent = subgrid.parent.distributor
508-
self._factors = subgrid.factor
538+
def __init__(self, parent, dimensions, factors):
539+
shape = tuple((n + f - 1)//f
540+
for n, f in zip(parent.glb_shape, factors, strict=True))
541+
AbstractDistributor.__init__(self, shape, dimensions)
542+
543+
self._parent = parent
544+
self._factors = tuple(factors)
509545

510-
super().__init__(subgrid.shape, subgrid.dimensions, self.parent.comm,
511-
tuple(self.parent.topology))
546+
# Same processes and topology as the parent, hence the same communicator
547+
self._comm = parent.comm
548+
self._topology = parent.topology
549+
550+
self.__decomposition_setup__()
512551

513552
def __decomposition_setup__(self):
514553
"""

‎devito/types/dense.py‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -313,10 +313,15 @@ def shape_global(self):
313313
return self.shape
314314
retval = []
315315
for d, s in zip(self.dimensions, self.shape, strict=True):
316-
size = self.grid.size_map.get(d)
316+
size = self._size_map.get(d)
317317
retval.append(size.glb if size is not None else s)
318318
return tuple(retval)
319319

320+
@property
321+
def _size_map(self):
322+
"""Map between the decomposed Dimensions and their global/local size."""
323+
return self.grid.size_map
324+
320325
@property
321326
def symbolic_shape(self):
322327
return DimensionTuple(
@@ -894,7 +899,7 @@ def _arg_defaults(self, alias=None, metadata=None, estimate_memory=False):
894899

895900
# Collect default dimension arguments from all indices
896901
for a, i, s in zip(key.dimensions, self.dimensions, self.shape, strict=True):
897-
args.update(i._arg_defaults(_min=0, size=s, alias=a))
902+
args.update(i._arg_defaults(_min=0, size=s, alias=a, grid=self.grid))
898903

899904
return args
900905

@@ -923,7 +928,7 @@ def _arg_values(self, metadata=None, estimate_memory=False, **kwargs):
923928
# Add value overrides for all associated dimensions
924929
for i, s in zip(self.dimensions, new.shape, strict=True):
925930
size = s - sum(self._size_nodomain[i])
926-
values.update(i._arg_defaults(size=size))
931+
values.update(i._arg_defaults(size=size, grid=self.grid))
927932
else:
928933
values = self._arg_defaults(alias=self, metadata=metadata,
929934
estimate_memory=estimate_memory)
@@ -1092,8 +1097,19 @@ def _rebuild(self, *args, **kwargs):
10921097
@property
10931098
def _is_on_grid(self):
10941099
"""Whether the space Dimensions of `self` are those of its Grid."""
1095-
return (self.grid is not None and self.space_dimensions == self.grid.dimensions
1096-
and self.ndim == self.grid.dim + self.is_TimeDependent)
1100+
if self.grid is None or self.ndim != self.grid.dim:
1101+
return False
1102+
return self.space_dimensions == self.grid.dimensions
1103+
1104+
def __distributor_setup__(self, **kwargs):
1105+
distributor = super().__distributor_setup__(**kwargs)
1106+
if distributor is None:
1107+
return None
1108+
return distributor.subsample(self.dimensions)
1109+
1110+
@property
1111+
def _size_map(self):
1112+
return self._distributor.size_map
10971113

10981114
def __init_finalize__(self, *args, **kwargs):
10991115
super().__init_finalize__(*args, **kwargs)
@@ -1244,10 +1260,11 @@ def __shape_setup__(cls, **kwargs):
12441260
if len(shape) != len(dimensions):
12451261
raise ValueError("`shape` and `dimensions` must have the "
12461262
"same number of entries")
1263+
size_map = grid.distributor.subsample(tuple(dimensions)).size_map
12471264
loc_shape = []
12481265
for d, s in zip(dimensions, shape, strict=True):
1249-
if d in grid.dimensions:
1250-
size = grid.size_map[d]
1266+
if d in size_map:
1267+
size = size_map[d]
12511268
if size.glb != s and s is not None:
12521269
raise ValueError(f"Dimension `{d}` is given size `{s}`, "
12531270
f"while `grid` says `{d}` has size `{size.glb}`")
@@ -1630,6 +1647,12 @@ def _time_buffering(self):
16301647
def _time_buffering_default(self):
16311648
return self._time_buffering and not isinstance(self.save, Buffer)
16321649

1650+
@property
1651+
def _is_on_grid(self):
1652+
if self.grid is None or self.ndim != self.grid.dim + 1:
1653+
return False
1654+
return self.space_dimensions == self.grid.dimensions
1655+
16331656
def _arg_check(self, args, intervals, **kwargs):
16341657
super()._arg_check(args, intervals, **kwargs)
16351658

0 commit comments

Comments
 (0)