Skip to content

Commit afa5529

Browse files
compiler: Minor tweaks for improved MPI modes (#3123)
* mpi: Preserve empty overlap regions during alignment Rounding down an inclusive lower bound can turn an empty CORE or OWNED region into executable points. Keep the original lower bound when it already exceeds the upper bound. * compiler: Use DimensionTuple for grid.origin_isymbols * compiler: Stop overlap2 at the first empty OWNED region * profiling: Measure the host time loop for performance without setup Bracket the time-stepping region with a native timer and reduce its elapsed time once across MPI ranks. Keep the section-based measurement for Operators without a time loop. * profiling: Keep time-loop accounting in the profiler * profiling: Locate the stepping region after helper calls are rebuilt * profiling: Instrument the host loop independently of section hooks * profiling: Time the span of host stepping loops independently of sections * profiling: Find the host stepping span from iteration trees * profiling: Instrument a single time loop directly * profiling: Name the selected iteration time_loop * mpi: Alias overlap3 to the overlap2 builder in OSS * mpi: Support native overlap3 halo builders Allow a halo builder to place lifetime hooks and declare backend aggregates in the generated Operator. * tests: Simplify the physical faces MPI regression * profiling: Preserve the autotuning timer type * mpi: Explain neighbor-dependent CORE bounds * mpi: Restore overlap2 regions and fix the profiling mock * mpi: Hook overlap region and remainder construction * mpi: Rename the overlap region object hook * mpi: Pack empty OWNED regions last * mpi: Use runtime neighbor bounds in overlap2 * mpi: Share runtime region binding across overlap modes * mpi: Inline overlap region construction * mpi: Document runtime region argument packing * compiler: Represent sparse injection with LocalScatter * mpi: Use synchronous halo exchange for SubDomain Functions Select the fallback from the HaloSpot and enable the full-mode regression. Reuse runtime face ranks from MPINeighborhood, document region packing, and cache Grid index origin symbols. * fix: account for runtime staging arrays in lazy memory estimates * fix: estimate irregular arrays from their maximum byte size * fix: include estimable irregular arrays in the memory budget * fix: estimate array memory at allocation sites * fix: scope Operator memory estimates to the entry body * mpi: Share C struct generation and MPI constants Add a guarded example of LocalScatter lowering.
1 parent e9591ce commit afa5529

29 files changed

Lines changed: 629 additions & 137 deletions

‎FAQ.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,9 @@ Notes:
844844
* The first line shows the total runtime of the Operator, including Python overhead, transition into executing the JIT-compiled binary, and any CPU-GPU data transfers.
845845

846846
* The two "Global performance" lines differ as follows: the <w/o setup> version excludes overhead (e.g., CPU-GPU data transfers) and better reflects actual compute performance, since such overheads are easily amortized way in production-grade runs when a simulation is executed over hundreds/thousands of timesteps.
847+
With the native advanced profiler, a timer spans the time loop and MPI uses the longest
848+
elapsed time across ranks. For Operators without a time loop, Devito adds the longest
849+
rank time for each section.
847850

848851
* The "Local performance" section provides a breakdown by code section. These sections are determined by the Devito compiler based on internal heuristics. Typically, loops related to finite-difference evaluation are grouped together, while operations such as source injection or receiver interpolation are placed in separate sections.
849852

‎devito/core/autotuning.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,11 @@ def autotune(operator, args, level, mode):
9090
return args, {}
9191

9292
# Use a fresh Timer for auto-tuning
93-
timer = Timer('timers', list(operator._profiler.all_sections))
93+
timer = next((p for p in operator.parameters if isinstance(p, Timer)), None)
94+
if timer is None:
95+
return args, {}
96+
97+
timer = timer._rebuild()
9498
at_args.update(timer._arg_values())
9599

96100
# Perform autotuning

‎devito/finite_differences/differentiable.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
'Imag',
3636
'IndexDerivative',
3737
'IndexDerivativeProperty',
38+
'LocalScatter',
3839
'LocalSum',
3940
'Real',
4041
'Weights',
@@ -1109,6 +1110,44 @@ def _evaluate(self, **kwargs):
11091110
__reduce_ex__ = Pickable.__reduce_ex__
11101111

11111112

1113+
class LocalScatter(sympy.Expr, Evaluable, Pickable):
1114+
1115+
"""
1116+
A contribution to an indexed increment over a sparse footprint.
1117+
1118+
`dimensions` lists the sparse point axis followed by the support axes.
1119+
The enclosing increment provides the destination, iteration space and guards.
1120+
"""
1121+
1122+
__rargs__ = ('expr',)
1123+
__rkwargs__ = ('dimensions',)
1124+
1125+
is_commutative = True
1126+
1127+
def __new__(cls, expr, dimensions, **kwargs):
1128+
obj = sympy.Expr.__new__(cls, expr)
1129+
obj._dimensions = as_tuple(dimensions)
1130+
return obj
1131+
1132+
@property
1133+
def expr(self):
1134+
return self.args[0]
1135+
1136+
@property
1137+
def dimensions(self):
1138+
return self._dimensions
1139+
1140+
@cached_property
1141+
def dtype(self):
1142+
return extract_dtype(self.expr)
1143+
1144+
def _hashable_content(self):
1145+
return super()._hashable_content() + (self.dimensions,)
1146+
1147+
func = Evaluable._rebuild
1148+
__reduce_ex__ = Pickable.__reduce_ex__
1149+
1150+
11121151
class WeightsIndexed(Indexed):
11131152

11141153
@property

‎devito/ir/clusters/algorithms.py‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -864,22 +864,18 @@ def _normalize_reductions_dense(cluster, mapper, sregistry, platform):
864864
@cluster_pass(mode='sparse')
865865
def normalize_reductions_sparse(cluster, sregistry):
866866
"""
867-
Extract the right-hand sides of reduction Eq's in to temporaries.
867+
Compute each indexed reduction's contribution in a scalar temporary.
868+
869+
Local scatters materialize the temporary when their layout is lowered.
868870
"""
869871
processed = []
870872
for e in cluster.exprs:
871-
if e.is_Reduction and e.lhs.is_Indexed:
872-
# Transform `e` such that we reduce into a scalar (ultimately via
873-
# atomic ops, though this part is carried out by a much later pass)
874-
# For example, given `i = m[p_src]` (i.e., indirection array), turn:
875-
# `u[t, i] += f(u[t, i], src, ...)`
876-
# into
877-
# `s = f(u[t, i], src, ...)`
878-
# `u[t, i] += s`
879-
name = sregistry.make_name()
880-
v = Symbol(name=name, dtype=e.dtype)
881-
processed.extend([e.func(v, e.rhs, operation=None),
882-
e.func(e.lhs, v)])
873+
if e.is_Reduction and \
874+
e.lhs.is_Indexed and \
875+
not e.local_scatters:
876+
temp = Symbol(name=sregistry.make_name(), dtype=e.dtype)
877+
processed.extend([e.func(temp, e.rhs, operation=None),
878+
e.func(e.lhs, temp)])
883879
else:
884880
processed.append(e)
885881

‎devito/ir/clusters/cluster.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,11 @@ def local_sums(self):
155155
"""
156156
return tuple(s for e in self.exprs for s in e.local_sums)
157157

158+
@cached_property
159+
def local_scatters(self):
160+
"""The sparse contributions on indexed updates in this cluster."""
161+
return tuple(s for e in self.exprs for s in e.local_scatters)
162+
158163
@cached_property
159164
def scope(self):
160165
return Scope(self.exprs)
@@ -694,6 +699,10 @@ def exprs(self):
694699
def local_sums(self):
695700
return tuple(s for c in self for s in c.local_sums)
696701

702+
@cached_property
703+
def local_scatters(self):
704+
return tuple(s for c in self for s in c.local_scatters)
705+
697706
@cached_property
698707
def scope(self):
699708
return Scope(exprs=self.exprs)

‎devito/ir/equations/equation.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import numpy as np
55
import sympy
66

7-
from devito.finite_differences.differentiable import LocalSum, diff2sympy
7+
from devito.finite_differences.differentiable import LocalScatter, LocalSum, diff2sympy
88
from devito.ir.equations.algorithms import dimension_sort, generate_conditionals
99
from devito.ir.support import (
1010
Interval, IntervalGroup, IterationSpace, Stencil, bounded, detect_accesses
@@ -56,6 +56,11 @@ def local_sums(self):
5656
"""The local sums in dependency order, with nested sums first."""
5757
return tuple(filter_ordered(search(self, LocalSum, mode='all')))
5858

59+
@cached_property
60+
def local_scatters(self):
61+
"""The local scatter carried by this indexed update, if any."""
62+
return (self.rhs,) if isinstance(self.rhs, LocalScatter) else ()
63+
5964
@property
6065
def implicit_dims(self):
6166
return self._implicit_dims

‎devito/ir/iet/visitors.py‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
GenericVisitor, as_tuple, c_restrict_void_p, filter_ordered, filter_sorted, flatten,
3232
is_external_ctype, natural_sort_key
3333
)
34+
from devito.tools.cgen import make_struct
3435
from devito.types import (
3536
ArrayObject, CompositeObject, DeviceMap, Dimension, IndexedData, Pointer
3637
)
@@ -274,9 +275,7 @@ def _restrict_keyword(self):
274275
return self.printer._restrict_keyword
275276

276277
def _gen_struct_decl(self, obj, masked=()):
277-
"""
278-
Convert ctypes.Struct -> cgen.Structure.
279-
"""
278+
"""Build the C declaration for an object's ctypes structure."""
280279
ctype = obj._C_ctype
281280
try:
282281
while issubclass(ctype, ctypes._Pointer):
@@ -286,16 +285,15 @@ def _gen_struct_decl(self, obj, masked=()):
286285
issubclass(ctype, NoDeclStruct):
287286
return None
288287
except TypeError:
289-
# E.g., `ctype` is of type `dtypes_lowering.CustomDtype`
290-
return None
288+
# A backend-defined aggregate may provide its own declaration.
289+
return getattr(obj, '_C_typedecl', None)
291290

292291
try:
293292
return obj._C_typedecl
294293
except AttributeError:
295294
pass
296295

297-
# Most of the times we end up here -- a generic procedure to
298-
# automatically derive a cgen.Structure from the object _C_ctype
296+
# Derive the declaration from the object's ctypes fields.
299297

300298
try:
301299
fields = obj.fields
@@ -310,9 +308,9 @@ def _gen_struct_decl(self, obj, masked=()):
310308
cstr = self.ccode(ct)
311309
if ct is c_restrict_void_p:
312310
cstr = f'{cstr}{self._restrict_keyword}'
313-
entries.append(c.Value(cstr, n))
311+
entries.append((cstr, n))
314312

315-
return c.Struct(ctype.__name__, entries)
313+
return make_struct(ctype.__name__, entries)
316314

317315
def _gen_value(self, obj, mode=1, masked=()):
318316
"""

‎devito/mpi/distributed.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from math import ceil, pow
77

88
import numpy as np
9-
from cgen import Struct, Value
109
from sympy import Interval, factorint
1110

1211
from devito.data import CENTER, LEFT, RIGHT, Decomposition
@@ -15,6 +14,7 @@
1514
EnrichedTuple, as_tuple, ctypes_to_cstr, filter_ordered, frozendict, is_integer,
1615
memoized_meth
1716
)
17+
from devito.tools.cgen import make_struct
1818
from devito.types import CompositeObject, Constant, Object
1919
from devito.types.utils import DimensionTuple, GlobalLocal
2020

@@ -961,6 +961,14 @@ def entries(self):
961961
def neighborhood(self):
962962
return self._neighborhood
963963

964+
@cached_property
965+
def face_neighbors(self):
966+
"""
967+
Face ranks indexed by root dimension name and side.
968+
"""
969+
return {d.root.name: ranks for d, ranks in self.neighborhood.items()
970+
if not isinstance(d, tuple)}
971+
964972
@cached_property
965973
def _C_typedecl(self):
966974
# Overriding for better code readability
@@ -976,8 +984,8 @@ def _C_typedecl(self):
976984
# With this override, we generate the one on the right
977985
groups = [list(g) for k, g in groupby(self.pfields, key=lambda x: x[0][0])]
978986
groups = [(j[0], i) for i, j in [zip(*g, strict=True) for g in groups]]
979-
return Struct(self.pname, [Value(ctypes_to_cstr(i), ', '.join(j))
980-
for i, j in groups])
987+
return make_struct(self.pname, ((ctypes_to_cstr(i), ', '.join(j))
988+
for i, j in groups))
981989

982990
def _arg_defaults(self):
983991
values = super()._arg_defaults()

‎devito/mpi/halo_scheme.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,19 @@ def union(self, other):
9292
OMapper = namedtuple('OMapper', 'core owned')
9393

9494

95+
class HasNeighbor(sympy.Function):
96+
97+
"""
98+
Flag indicating whether a receive can cross this root bound.
99+
100+
MPIRegion binds it from the runtime Grid's neighborhood when packing bounds.
101+
"""
102+
103+
nargs = 1
104+
is_integer = True
105+
is_nonnegative = True
106+
107+
95108
class HaloScheme:
96109

97110
"""
@@ -261,6 +274,8 @@ def omapper(self):
261274
262275
The computed OMapper takes into account:
263276
277+
* The receive neighbors on the runtime Grid. CORE extends to faces
278+
with no neighbor.
264279
* The offsets induced by SubDomains/SubDimensions ("thickness");
265280
* Any data alignment requirement of the underlying expressions
266281
(`_alignment` attribute).
@@ -280,7 +295,7 @@ def omapper(self):
280295
In this example, the "cumulative" OWNED size is (left=4, right=4), that is
281296
the max on each DataSide across all Functions, namely ``u`` and ``v``.
282297
283-
The ``omapper`` will contain the following entries:
298+
For a rank with neighbors on both sides, the bounds are:
284299
285300
[(((d, CORE, CENTER),), {d: (d_m + 4, d_M - 4)}),
286301
(((d, OWNED, LEFT),), {d: (d_m, min(d_m + 3, d_M))}),
@@ -362,13 +377,12 @@ def omapper(self):
362377
the max point is ``d_M = 1``, which implies that there is exactly one
363378
point in this region, and this point is redundantly computed as it's
364379
logically the same as that in the (OWNED, LEFT) region.
365-
366-
Notes
367-
-----
368-
For each Function, the '^' and 'o' are exactly the same on *all MPI
369-
ranks*, so the output of this method is guaranteed to be consistent
370-
across *all MPI ranks*.
371380
"""
381+
owned_size = {
382+
d: (left * HasNeighbor(d.root.symbolic_min),
383+
right * HasNeighbor(d.root.symbolic_max))
384+
for d, (left, right) in self.owned_size.items()
385+
}
372386
items = [((d, CENTER), (d, LEFT), (d, RIGHT))
373387
for d in filter_sorted(self.dimensions)]
374388

@@ -377,7 +391,7 @@ def omapper(self):
377391
where = []
378392
mapper = {}
379393
for d, s in item:
380-
osl, osr = self.owned_size[d]
394+
osl, osr = owned_size[d]
381395

382396
# Handle SubDomain/SubDimensions to-honor offsets
383397
nl = Max(0, *[i for i, _ in self.honored.get(d, [])])
@@ -437,7 +451,10 @@ def omapper(self):
437451
except KeyError:
438452
continue
439453

440-
aligned_m = IntDiv(m, self._alignment) * self._alignment
454+
# Preserve empty regions when rounding down a start index
455+
aligned_m = sympy.Piecewise(
456+
(IntDiv(m, self._alignment) * self._alignment, m <= M), (m, True)
457+
)
441458

442459
processed[i] = (where, frozendict({**mapper, fvd: (aligned_m, M)}))
443460

0 commit comments

Comments
 (0)