Skip to content

Commit 4fedfd3

Browse files
committed
mpi: Distribute Functions subsampled by ConditionalDimensions
1 parent 739178a commit 4fedfd3

10 files changed

Lines changed: 225 additions & 67 deletions

File tree

‎devito/ir/equations/algorithms.py‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@
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 (
10-
IntDiv, retrieve_dimensions, retrieve_functions, retrieve_indexed, uxreplace
9+
IntDiv, q_leaf, retrieve_dimensions, retrieve_functions, retrieve_indexed, uxreplace
1110
)
1211
from devito.tools import (
1312
Ordering, as_tuple, filter_ordered, filter_sorted, flatten, frozendict
@@ -214,15 +213,24 @@ def _make_global_index_map(expr, dimension_map):
214213
if not isinstance(expr, Eq):
215214
return {}
216215

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-
222216
grids = {f.grid.root for f in retrieve_functions(expr) if f.grid is not None}
217+
values = _value_dimensions(expr)
223218
return {d: dimension_map.get(d, d) + o
224219
for grid in grids
225-
for d, o in zip(grid.dimensions, grid.origin_isymbols, strict=True)}
220+
for d, o in zip(grid.dimensions, grid.origin_isymbols, strict=True)
221+
if d in values}
222+
223+
224+
def _value_dimensions(expr):
225+
"""
226+
The Dimensions used as values in `expr`, that is neither as the indices of a
227+
Function nor as the metadata of an object, e.g. the axes of a transform.
228+
"""
229+
if isinstance(expr, Dimension):
230+
return {expr}
231+
if q_leaf(expr) or isinstance(expr, AbstractFunction):
232+
return set()
233+
return set().union(*[_value_dimensions(a) for a in expr.args])
226234

227235

228236
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: 21 additions & 5 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)
@@ -1095,6 +1100,16 @@ def _is_on_grid(self):
10951100
return (self.grid is not None and self.space_dimensions == self.grid.dimensions
10961101
and self.ndim == self.grid.dim + self.is_TimeDependent)
10971102

1103+
def __distributor_setup__(self, **kwargs):
1104+
distributor = super().__distributor_setup__(**kwargs)
1105+
if distributor is None:
1106+
return None
1107+
return distributor.subsample(self.dimensions)
1108+
1109+
@property
1110+
def _size_map(self):
1111+
return self._distributor.size_map
1112+
10981113
def __init_finalize__(self, *args, **kwargs):
10991114
super().__init_finalize__(*args, **kwargs)
11001115

@@ -1242,10 +1257,11 @@ def __shape_setup__(cls, **kwargs):
12421257
if len(shape) != len(dimensions):
12431258
raise ValueError("`shape` and `dimensions` must have the "
12441259
"same number of entries")
1260+
size_map = grid.distributor.subsample(tuple(dimensions)).size_map
12451261
loc_shape = []
12461262
for d, s in zip(dimensions, shape, strict=True):
1247-
if d in grid.dimensions:
1248-
size = grid.size_map[d]
1263+
if d in size_map:
1264+
size = size_map[d]
12491265
if size.glb != s and s is not None:
12501266
raise ValueError(f"Dimension `{d}` is given size `{s}`, "
12511267
f"while `grid` says `{d}` has size `{size.glb}`")

‎devito/types/dimension.py‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def _arg_names(self):
258258
"""Tuple of argument names introduced by the Dimension."""
259259
return (self.name, self.size_name, self.max_name, self.min_name)
260260

261-
def _arg_defaults(self, _min=None, size=None, alias=None):
261+
def _arg_defaults(self, _min=None, size=None, alias=None, **kwargs):
262262
"""
263263
A map of default argument values defined by the Dimension.
264264
@@ -271,6 +271,8 @@ def _arg_defaults(self, _min=None, size=None, alias=None):
271271
alias : Dimension, optional
272272
To get the min/max/size names under which to store values. Use
273273
self's if None.
274+
grid : Grid, optional
275+
The Grid of the data-carrying object, if any.
274276
"""
275277
dim = alias or self
276278
return {dim.min_name: _min or 0,
@@ -436,7 +438,7 @@ def __init_finalize__(self, name, spacing=None, default_value=None, **kwargs):
436438
def symbolic_size(self):
437439
return sympy.Number(self._default_value)
438440

439-
def _arg_defaults(self, _min=None, size=None, alias=None):
441+
def _arg_defaults(self, _min=None, size=None, alias=None, **kwargs):
440442
dim = alias or self
441443
size = size or dim._default_value
442444
return {dim.min_name: _min or 0, dim.size_name: size,
@@ -987,7 +989,10 @@ def _arg_values(self, grid=None, **kwargs):
987989

988990
# Runtime arguments bind by name, even when different spacing dtypes
989991
# make the compiled and runtime Grid Dimensions distinct symbols
990-
root = next(d for d in grid.dimensions if d.name == self.root.name)
992+
grid = grid.root
993+
root = next((d for d in grid.dimensions if d.name == self.root.name), None)
994+
if root is None:
995+
return {self.name: 0}
991996

992997
return {self.name: -grid.origin_ioffset[root] % self.factor}
993998

@@ -1021,9 +1026,10 @@ class ConditionalDimension(DerivedDimension):
10211026
lowering for example combining Function's ConditionalDimension with
10221027
an Equation's implicit_dim. All Dimensions within an equation
10231028
must have `Or` relation for the final combined condition to be Or.
1024-
offset : SubsamplingOffset, optional, default=0
1029+
offset : SubsamplingOffset, optional
10251030
The intercept of the map onto the parent Dimension, that is
1026-
``parent = factor*self + offset``.
1031+
``parent = factor*self + offset``. Defaults to a SubsamplingOffset when
1032+
subsampling a space Dimension, and to 0 otherwise.
10271033
10281034
Examples
10291035
--------
@@ -1121,7 +1127,7 @@ class ConditionalDimension(DerivedDimension):
11211127
('factor', 'condition', 'indirect', 'relation', 'offset')
11221128

11231129
def __init_finalize__(self, name, parent=None, factor=None, condition=None,
1124-
indirect=False, relation=sympy.And, offset=0, **kwargs):
1130+
indirect=False, relation=sympy.And, offset=None, **kwargs):
11251131
# `parent=None` degenerates to a ConditionalDimension outside of
11261132
# any iteration space
11271133
if parent is None:
@@ -1140,11 +1146,20 @@ def __init_finalize__(self, name, parent=None, factor=None, condition=None,
11401146
else:
11411147
raise ValueError("factor must be an integer")
11421148

1143-
self._offset = offset
1149+
self._offset = self.__offset_setup__(offset)
11441150
self._condition = condition
11451151
self._indirect = indirect
11461152
self._relation = relation
11471153

1154+
def __offset_setup__(self, offset=None):
1155+
if offset is not None:
1156+
return offset
1157+
# A space Dimension is subsampled on its global indices
1158+
if not self.is_Space or not is_integer(self._factor):
1159+
return 0
1160+
return SubsamplingOffset(name=f'{self.name}o', root=self.root,
1161+
factor=self._factor)
1162+
11481163
@property
11491164
def is_Injective(self):
11501165
"""
@@ -1253,7 +1268,7 @@ def _arg_values(self, interval, grid=None, args=None, **kwargs):
12531268

12541269
return vals
12551270

1256-
def _arg_defaults(self, _min=None, size=None, alias=None):
1271+
def _arg_defaults(self, _min=None, size=None, alias=None, grid=None, **kwargs):
12571272
defaults = super()._arg_defaults(_min=_min, size=size, alias=alias)
12581273

12591274
# We can also add the parent's default endpoint. Note that exactly
@@ -1275,10 +1290,10 @@ def _arg_defaults(self, _min=None, size=None, alias=None):
12751290
raise ValueError(f"Incompatible size for ConditionalDimension "
12761291
f"{self.name}: {size} < {size0}")
12771292
else:
1278-
# Given a factor the last time index is factor*(size - 1)
1279-
# The maximum allowed value is then factor*size - 1, plus at
1280-
# most factor - 1 for an offset
1281-
stop = d0 + factor*size + (factor - 1 if dim.offset else 0)
1293+
# Given a factor the last index is factor*(size - 1) + offset
1294+
# The maximum allowed value is then factor*size - 1 + offset
1295+
offset = dim.offset and dim.offset._arg_values(grid=grid)[dim.offset.name]
1296+
stop = d0 + factor*size + offset
12821297
defaults[dim.parent.max_name] = range(d0, stop)
12831298

12841299
return defaults

‎devito/types/grid.py‎

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import math
2-
from collections import namedtuple
32
from functools import cached_property
43
from itertools import product
54

@@ -18,16 +17,13 @@
1817
from devito.types.dense import Function
1918
from devito.types.dimension import (
2019
ConditionalDimension, DefaultDimension, Dimension, MultiSubDimension, SpaceDimension,
21-
Spacing, SteppingDimension, SubDimension, SubsamplingOffset, TimeDimension
20+
Spacing, SteppingDimension, SubDimension, TimeDimension
2221
)
23-
from devito.types.utils import DimensionTuple
22+
from devito.types.utils import DimensionTuple, GlobalLocal
2423

2524
__all__ = ['Border', 'Grid', 'SubDomain', 'SubDomainSet', 'SubGrid']
2625

2726

28-
GlobalLocal = namedtuple('GlobalLocal', 'glb loc')
29-
30-
3127
class CartesianDiscretization:
3228

3329
"""
@@ -537,10 +533,7 @@ def __init__(self, parent, factor, name='s', **kwargs):
537533
)
538534

539535
dimensions = tuple(
540-
d if f == 1 else ConditionalDimension(
541-
f'{d.name}{name}', parent=d, factor=f,
542-
offset=self.__offset_setup__(parent, d, f, name)
543-
)
536+
d if f == 1 else ConditionalDimension(f'{d.name}{name}', parent=d, factor=f)
544537
for d, f in zip(parent.dimensions, factors, strict=True)
545538
)
546539

@@ -568,15 +561,7 @@ def __init__(self, parent, factor, name='s', **kwargs):
568561
self._stepping_dim = parent.stepping_dim
569562

570563
def __distributor_setup__(self, shape, dimensions, comm):
571-
return SubGridDistributor(self)
572-
573-
@classmethod
574-
def __offset_setup__(cls, parent, d, factor, name):
575-
# Keyed on MPI codegen rather than on the rank count, as for the global
576-
# index map: the code may be generated on one rank and run on many
577-
if not configuration['mpi']:
578-
return 0
579-
return SubsamplingOffset(name=f'{d.name}{name}o', root=d, factor=factor)
564+
return SubGridDistributor(self.parent.distributor, dimensions, self._factors)
580565

581566
@classmethod
582567
def __factors_setup__(cls, parent, factor):

‎devito/types/utils.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
'DeviceLayer',
1414
'DimensionTuple',
1515
'DiskLayer',
16+
'GlobalLocal',
1617
'HierarchyLayer',
1718
'HostLayer',
1819
'IgnoreDimSort',
@@ -39,6 +40,7 @@ class Stagger(Tag):
3940

4041

4142
Size = namedtuple('Size', 'left right')
43+
GlobalLocal = namedtuple('GlobalLocal', 'glb loc')
4244
Offset = namedtuple('Offset', 'left right')
4345

4446

‎examples/userapi/05_conditional_dimension.ipynb‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,10 @@
184184
" lowering for example combining Function's ConditionalDimension with\n",
185185
" an Equation's implicit_dim. All Dimensions within an equation\n",
186186
" must have `Or` relation for the final combined condition to be Or.\n",
187-
" offset : SubsamplingOffset, optional, default=0\n",
187+
" offset : SubsamplingOffset, optional\n",
188188
" The intercept of the map onto the parent Dimension, that is\n",
189-
" ``parent = factor*self + offset``.\n",
189+
" ``parent = factor*self + offset``. Defaults to a SubsamplingOffset when\n",
190+
" subsampling a space Dimension, and to 0 otherwise.\n",
190191
"\n",
191192
" Examples\n",
192193
" --------\n",

0 commit comments

Comments
 (0)