diff --git a/devito/core/cpu.py b/devito/core/cpu.py index 3435a472e6..fd072447f1 100644 --- a/devito/core/cpu.py +++ b/devito/core/cpu.py @@ -175,7 +175,7 @@ def _specialize_clusters(cls, clusters, **kwargs): sregistry = kwargs['sregistry'] # Toposort+Fusion (the former to expose more fusion opportunities) - clusters = fuse(clusters, toposort=True) + clusters = fuse(clusters, toposort='topdown') # Hoist and optimize Dimension-invariant sub-expressions clusters = cire(clusters, 'invariants', sregistry, options, platform) @@ -292,7 +292,7 @@ def callback(f, *args): 'cse': lambda i: cse(i, sregistry, options), 'opt-pows': optimize_pows, 'opt-hyperplanes': optimize_hyperplanes, - 'topofuse': lambda i: fuse(i, toposort=True, options=options) + 'topofuse': lambda i: fuse(i, toposort='topdown', options=options) } @classmethod diff --git a/devito/core/gpu.py b/devito/core/gpu.py index 536a06422e..b0582c6d6f 100644 --- a/devito/core/gpu.py +++ b/devito/core/gpu.py @@ -219,7 +219,7 @@ def _specialize_clusters(cls, clusters, **kwargs): sregistry = kwargs['sregistry'] # Toposort+Fusion (the former to expose more fusion opportunities) - clusters = fuse(clusters, toposort=True, options=options) + clusters = fuse(clusters, toposort='topdown', options=options) # Fission to increase parallelism clusters = fission(clusters) @@ -321,7 +321,7 @@ def _make_clusters_passes_mapper(cls, **kwargs): 'cire-sops': lambda i: cire(i, 'sops', sregistry, options, platform), 'cse': lambda i: cse(i, sregistry, options), 'opt-pows': optimize_pows, - 'topofuse': lambda i: fuse(i, toposort=True, options=options) + 'topofuse': lambda i: fuse(i, toposort='topdown', options=options) } @classmethod diff --git a/devito/ir/clusters/algorithms.py b/devito/ir/clusters/algorithms.py index 93b0c851ec..535c6640f6 100644 --- a/devito/ir/clusters/algorithms.py +++ b/devito/ir/clusters/algorithms.py @@ -51,7 +51,7 @@ def clusterize(exprs, **kwargs): clusters = normalize(clusters, **kwargs) # Derive the necessary communications for distributed-memory parallelism - clusters = communications(clusters) + clusters = communications(clusters, **kwargs) return ClusterGroup(clusters) @@ -479,12 +479,12 @@ def rule(size, e): @timed_pass(name='communications') -def communications(clusters): +def communications(clusters, **kwargs): """ Enrich a sequence of Clusters by adding special Clusters representing data communications for distributed parallelism. """ - clusters = HaloComms().process(clusters) + clusters = HaloComms(**kwargs).process(clusters) clusters = reduction_comms(clusters) check_halo_writes(clusters) @@ -501,7 +501,8 @@ class HaloComms(Queue): _q_guards_in_key = True _q_properties_in_key = True - B = Symbol(name='⊥') + def __init__(self, sregistry, **kwargs): + self.sregistry = sregistry def process(self, clusters): return self._process_fatd(clusters, 1, seen=set()) @@ -539,8 +540,11 @@ def callback(self, clusters, prefix, seen=None): # the args is important because that's what search functions honor! points = sorted(points, key=str) - # Construct the HaloTouch Cluster - expr = Eq(self.B, HaloTouch(*points, halo_scheme=hs)) + # Construct the HaloTouch Cluster. Each writes its own mock Symbol, as + # a shared one would totally order all HaloTouches via output + # dependences, preventing their reordering upon topological sorting + mock = Symbol(name=self.sregistry.make_name(prefix='⊥')) + expr = Eq(mock, HaloTouch(*points, halo_scheme=hs)) key0 = lambda i: i in prefix[:-1] or i in hs.loc_indices # noqa: B023 key1 = lambda i: not i._defines & set(hs.distributed_defined) # noqa: B023 diff --git a/devito/ir/stree/algorithms.py b/devito/ir/stree/algorithms.py index 01f3b5449e..25e9a73af9 100644 --- a/devito/ir/stree/algorithms.py +++ b/devito/ir/stree/algorithms.py @@ -51,6 +51,10 @@ def stree_build(clusters, profiler=None, **kwargs): break d = it0.dim + # TODO: a Cluster whose `halo_scheme` absorbed a HaloTouch doesn't reuse + # the previous Cluster's loop, so loop sharing depends on Cluster order, + # e.g. `f1 = f0; f2 = f0.dx` shares no `x` loop, while `f2 = f0.dx; + # f1 = f0` does. Fusion can't fix this; it needs halo-aware reuse here if needs_nodehalo(d, c.halo_scheme): break diff --git a/devito/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index cd00bf97bc..381b5cdfd4 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -1,11 +1,12 @@ from collections import Counter, defaultdict from functools import cached_property -from itertools import groupby +from itertools import combinations, groupby from devito.finite_differences import IndexDerivative from devito.ir.clusters import Cluster, ClusterGroup, Queue from devito.ir.support import ( - InitArray, PrefetchUpdate, ReleaseLock, Scope, SyncArray, WaitLock, WithLock + InitArray, PrefetchUpdate, ReleaseLock, Scope, SyncArray, WaitLock, WithLock, + null_ispace ) from devito.symbolics import search from devito.tools import ( @@ -17,8 +18,11 @@ # No hazard: fusion may proceed. NO_HAZARD = None -# Ordering hazard: preserve program order and forbid fusion. +# Ordering hazard: preserve program order. EDGE = 'edge' +# Output dependence not carried by the prefix: preserve program order, while +# fission along the prefix remains legal. +OUTPUT = 'output' # Prefix anti-dependence: break the execution flow across the pair. BREAK = 'break' @@ -45,12 +49,38 @@ def _fusion_hazards(scope0, scope1, prefix): if not (i.cause & prefix): return EDGE - for _ in scope.d_output_gen(): + # A carried output dependence takes precedence over any non-carried one + causes = [i.cause for i in scope.d_output_gen()] + if any(c & prefix for c in causes): return EDGE + elif causes: + return OUTPUT return NO_HAZARD +def _shares_invariant(c0, c1, d): + """ + True if some storage not indexed by `d` is written by either Cluster and + accessed by the other, False otherwise. Aliased storage (e.g., reused + buffers) is assumed to share one Function object. + """ + # Wild Clusters (e.g., HaloTouches) never share a loop; they still end up + # within a unit spanning them + if c0.is_wild or c1.is_wild: + return False + + # E.g., `u(t, x)` is indexed by `time`, through the SteppingDimension `t` + def invariant(functions): + return {f for f in functions if not any(d in i._defines for i in f.dimensions)} + + accessed0 = set(c0.scope.writes) | set(c0.scope.reads) + accessed1 = set(c1.scope.writes) | set(c1.scope.reads) + + return bool(invariant(c0.scope.writes) & accessed1 or + invariant(c1.scope.writes) & accessed0) + + class Keys(CacheInstances): """ @@ -138,6 +168,15 @@ def weak(self): def full(self): return self.strict + self.weak + @cached_property + def type(self): + # `full` is necessary, not sufficient, for fusion (see `Cluster.from_clusters`), + # e.g. the SubDimensions of different SubDomains compare equal there. + # HaloTouches never fuse, so they don't type a ClusterGroup + clusters = [c for c in flatten([self.c]) if not c.is_halo_touch] or [self.c] + return (self.full, self.c.dtype, clusters[0].ispace.itdims, + clusters[-1].ispace.itdims) + class Fusion(Queue): @@ -172,7 +211,7 @@ def callback(self, cgroups, prefix): clusters = ClusterGroup(cgroups) # Fusion - key = lambda c: self._key(c).full + key = lambda c: self._key(c).type processed = [] for _, group in groupby(clusters, key=key): g = list(group) @@ -187,9 +226,10 @@ def callback(self, cgroups, prefix): processed.extend(maybe_fusible) # Maximize effectiveness of topo-sorting at next stage by only - # grouping together Clusters characterized by data dependencies + # grouping together Clusters characterized by data dependencies, output + # dependences aside, which only impose an order, enforced at the next stage if self.toposort and prefix: - dag = self._build_dag(processed, prefix) + dag = self._build_dag(processed, prefix, outputs=False) mapper = dag.connected_components(enumerated=True) groups = groupby(processed, key=mapper.get) return [ClusterGroup(tuple(g), prefix) for _, g in groups] @@ -248,55 +288,124 @@ def _toposort(self, cgroups, prefix): # Are there any ClusterGroups that could potentially be topologically # reordered? If not, do not waste time - counter = Counter(self._key(cg).strict for cg in cgroups) + counter = Counter(self._key(cg).type for cg in cgroups) if len(counter.most_common()) == 1 or \ not any(v > 1 for it, v in counter.most_common()): return ClusterGroup(cgroups, prefix) dag = self._build_dag(cgroups, prefix) - def choose_element(queue, scheduled): - if not scheduled or len(queue) == 1: - return queue.pop() - - k = self._key(scheduled[-1]) - m = {i: self._key(i) for i in queue} - - # First of all, ensure we preserve the integrity of the current scope - candidates = [i for i in queue if k.last.ispace == m[i].first.ispace] - - compatible = [i for i in candidates if k.last.guards == m[i].first.guards] - candidates = compatible or candidates - - # If the current scope is over, we maximize fusion - fusible = [i for i in queue if k.itintervals == m[i].itintervals] - candidates = candidates or fusible - - compatible = [i for i in candidates if k.syncs == m[i].syncs] - candidates = compatible or candidates - - # Process the `weak` part of the key - for i in range(len(k.weak), -1, -1): - choosable = [e for e in candidates if m[e].weak[:i] == k.weak[:i]] - try: - # Ensure stability - e = min(choosable, key=lambda i: cgroups.index(i)) - except ValueError: - continue - queue.remove(e) - return e - - # Fallback - e = min(queue, key=lambda i: cgroups.index(i)) - queue.remove(e) - return e - - return ClusterGroup(dag.topological_sort(choose_element), prefix) + return ClusterGroup(self._typed_fusion(cgroups, dag, prefix), prefix) - def _build_dag(self, cgroups, prefix): + def _typed_fusion(self, cgroups, dag, prefix): + """ + Order `cgroups` via ordered typed fusion [Kennedy & McKinley, 1993]. One type + (see `Keys.type`) at a time, in order of first appearance, each ClusterGroup + joins the first group of its type that it may fuse with, i.e. no fence or + anti-dependence along `prefix` lies between them, and the contracted DAG stays + acyclic. With more than one type per ClusterGroup (see `_types`), each pass + merges whole groups of the previous one. Groups are then emitted + contiguously, in topological order. + + Examples + -------- + With `u0, v0` and `u1, v1` over a left and a right SubDomain, conservative + WAWs `u0 -> u1`, `v0 -> v1`, and HaloTouches `h0, h1` for `v`: + + u0 u1 h0 v0 h1 v1 ---> h0 u0 v0 h1 u1 v1 + + That is two loop nests, while the greedy choice of `u1` after `u0` gives four. + """ + prefix = frozenset(i.dim for i in as_tuple(prefix)) + pos = {cg: n for n, cg in enumerate(cgroups)} + + # A group is identified by its head, i.e. its first member, as within a type + # groups are visited in order + head = {cg: cg for cg in cgroups} + members = {cg: [cg] for cg in cgroups} + + def successors(g): + return {head[i] for cg in members[g] for i in dag.downstream(cg)} - {g} + + # ponytail: DFS per candidate, incremental reachability if `cgroups` grows + def indirect(src, dst): + # Is there a path `src -> ... -> dst` through some other group? + stack = list(successors(src) - {dst}) + seen = set(stack) + while stack: + g = stack.pop() + if g is dst: + return True + stack.extend(successors(g) - seen) + seen.update(stack) + return False + + def fusible(g, h): + if not self._compatible(members[g], members[h]): + return False + + # No fence or anti-dependence along `prefix` in between + both = sorted(members[g] + members[h], key=pos.get) + if any(i.scope.has_barrier + for i in cgroups[pos[both[0]]:pos[both[-1]]+1]): + return False + if any(_fusion_hazards(i.sync_scope, j.sync_scope, prefix) == BREAK + for i, j in combinations(both, 2) + if (i in members[g]) != (j in members[g])): + return False + + # A direct edge only fixes the order of `g` and `h`, an indirect path + # would make the contracted DAG cyclic + return not (indirect(g, h) or indirect(h, g)) + + # One pass per type, finest first, each merging the groups of the previous + for key in self._types(): + # Wild ClusterGroups (e.g., HaloTouches) never fuse, so they get no type + types = defaultdict(list) + for g in list(members): + if not g.is_wild: + types[key(g)].append(g) + + for nodes in types.values(): + groups = [] + for h in nodes: + g = next((g for g in groups if fusible(g, h)), None) + if g is None: + groups.append(h) + else: + for cg in members[h]: + head[cg] = g + members[g].extend(members.pop(h)) + + # Ready wild groups go first, as they would otherwise split the loops shared + # by the groups around them; then, stability + def choose_element(queue, scheduled): + g = min(queue, key=lambda g: (not g.is_wild, pos[g])) + queue.remove(g) + return g + + quotient = DAG(nodes=list(members), + edges=[(g, h) for g in members for h in successors(g)]) + return flatten(sorted(members[g], key=pos.get) + for g in quotient.topological_sort(choose_element)) + + def _types(self): + # The typing passes of `_typed_fusion` + return (lambda cg: self._key(cg).type,) + + def _compatible(self, g, h): + # The IterationSpaces may have been constrained to prevent fusion (e.g., + # of non-adjacent stencil Clusters); HaloTouches never fuse, so they don't + # constrain it + return all(c0.ispace.is_compatible(c1.ispace) + for c0 in flatten(g) if not c0.is_halo_touch + for c1 in flatten(h) if not c1.is_halo_touch) + + def _build_dag(self, cgroups, prefix, outputs=True): """ A DAG representing the data dependences across the ClusterGroups within - a given scope. + a given scope. With `outputs=False`, output dependences not carried by + `prefix` are ignored, as they don't prevent fission. """ prefix = frozenset(i.dim for i in as_tuple(prefix)) @@ -309,6 +418,8 @@ def _build_dag(self, cgroups, prefix): fenced = fenced or cg1.scope.has_barrier hazard = _fusion_hazards(cg0.sync_scope, cg1.sync_scope, prefix) + if hazard == OUTPUT and not outputs: + hazard = NO_HAZARD if not (hazard or fenced): continue @@ -322,14 +433,100 @@ def _build_dag(self, cgroups, prefix): for cg2 in cgroups[n1+1:]: dag.add_edge(cg1, cg2) break - elif fenced or hazard == EDGE: - # Any anti- and iaw-dependences impose that `cg1` follows `cg0` - # and forbid any sort of fusion. Fences have the same effect + elif fenced or hazard in (EDGE, OUTPUT): + # Any anti- and iaw-dependences impose that `cg1` follows `cg0`, + # i.e. preserve program order. Fences have the same effect dag.add_edge(cg0, cg1) return dag +class Reorder(Fusion): + + """ + Reorder Clusters, outermost level first, such that those that may share a + loop are contiguous before the next level is divided. Each level sees single + Clusters rather than the groups fixed at inner levels, which `Fusion` with + `toposort=True` reorders as indivisible units. + """ + + def __init__(self, options=None): + super().__init__(True, options) + + def process(self, clusters): + # `_process_fatd` applies `callback` from depth 1, i.e. not at the root + return self._process_fatd(self.callback(clusters, null_ispace), 1) + + def callback(self, clusters, prefix): + # Each unit may share the loop one level down + depth = len(prefix) + 1 + cgroups = [ClusterGroup(u, u[0].ispace[:depth]) + for u in self._units(clusters, depth)] + if len(cgroups) <= 2: + return clusters + + dag = self._build_dag(cgroups, prefix) + + return flatten(self._typed_fusion(cgroups, dag, prefix)) + + def _units(self, clusters, depth): + """ + Split `clusters` into indivisible units. Clusters sharing the loop one level + down through storage that loop doesn't index (e.g., a contracted temporary + `r[y]` within `x`) must keep sharing it, as `Scope` can't see that each + iteration overwrites what the previous iteration read. Such a pair, and all + Clusters in between, make one unit. + """ + units = [] + for k, g in groupby(clusters, key=lambda c: self._make_key(c, depth)): + g = list(g) + + # The last Cluster that each Cluster must stay with + reach = list(range(len(g))) + if len(k[0]) == depth: + d = k[0][-1].dim + # ponytail: all pairs per loop, per-Function spans if runs grow + for i, j in combinations(range(len(g)), 2): + if _shares_invariant(g[i], g[j], d): + reach[i] = j + + unit, stop = [], -1 + for n, c in enumerate(g): + unit.append(c) + stop = max(stop, reach[n]) + if n == stop: + units.append(unit) + unit = [] + + return units + + def _types(self): + # Then, above a Cluster's innermost level, merge the groups that may + # share a loop, e.g. `a[x, y]` and `c[x, z]` may share `x` + def level(cg): + key = self._key(cg) + return key.full if len(cg.ispace) < len(cg[0].ispace) else key.type + + return (*super()._types(), level) + + def _compatible(self, g, h): + # Unless the tasks are to be fused, Clusters handing over to asynchronous + # tasks stay in program order, as gathering them would delay the tasks' + # activation, e.g. two `WaitLock` copies `b0 = u; b1 = u` would move both + # `ReleaseLock`s after `b1 = u` + locks = (WaitLock, ReleaseLock, WithLock) + if not self.fuse_tasks and \ + any(isinstance(s, locks) + for c in flatten([g, h]) for s in flatten(c.syncs.values())): + return False + + # Only the loops to be shared, i.e. those of the ClusterGroups + n0 = len(g[0].ispace) + n1 = len(h[0].ispace) + return all(c0.ispace[:n0].is_compatible(c1.ispace[:n1]) + for c0 in flatten(g) for c1 in flatten(h)) + + @timed_pass() def fuse(clusters, toposort=False, options=None): """ @@ -342,8 +539,16 @@ def fuse(clusters, toposort=False, options=None): If `toposort='maximal'`, then `toposort` is performed, iteratively, multiple times to actually maximize Clusters fusion. Hence, this is more aggressive than `toposort=True`. + + If `toposort='topdown'`, then the Clusters are reordered from the outermost + level inwards, so that each level is divided after its reordering, and then + fused. Unlike `toposort=True`, Clusters made adjacent at an outer level may + then fuse at the inner ones too. """ - if toposort != 'maximal': + if toposort == 'topdown': + clusters = Reorder(options).process(clusters) + return Fusion(False, options).process(clusters) + elif toposort != 'maximal': return Fusion(toposort, options).process(clusters) nxt = clusters diff --git a/devito/passes/iet/mpi.py b/devito/passes/iet/mpi.py index eccdc9879f..4b606fd129 100644 --- a/devito/passes/iet/mpi.py +++ b/devito/passes/iet/mpi.py @@ -4,8 +4,8 @@ from sympy import S from devito.ir.iet import ( - Call, Expression, FindNodes, FindWithin, HaloSpot, Iteration, MapHaloSpots, MapNodes, - Transformer, retrieve_iteration_tree + Call, Conditional, Expression, FindNodes, FindWithin, HaloSpot, Iteration, + MapHaloSpots, MapNodes, Transformer, retrieve_iteration_tree ) from devito.ir.support import PARALLEL, Scope from devito.mpi.reduction_scheme import DistReduce @@ -24,8 +24,15 @@ def optimize_halospots(iet, **kwargs): Optimize the HaloSpots in ``iet``. HaloSpots may be dropped, hoisted, merged and moved around in order to improve the halo exchange performance. """ + # Separate HaloSpots per consumer only pay off with computation-communication + # overlap; otherwise, fewer HaloSpots mean fewer (bundled) messages + mode = str(kwargs['options']['mpi']) + overlap = 'overlap' in mode or 'full' in mode + iet = _drop_reduction_halospots(iet) iet = _hoist_redundant_from_conditionals(iet) + if overlap: + iet = _sink_halospots(iet) iet = _merge_halospots(iet) iet = _hoist_invariant(iet) iet = _drop_if_unwritten(iet, **kwargs) @@ -119,6 +126,80 @@ def _hoist_redundant_from_conditionals(iet): return iet +def _sink_halospots(iet): + """ + Sink the halo exchanges of the Functions a HaloSpot does not access down to + the first subsequent loop nest reading them, unless written or guarded before. + HaloSpots of different Functions may have been merged upon lowering, while + each should rather overlap with the computation requiring it. Only applied in + MPI modes featuring such overlap. + + Examples + -------- + for time for time + haloupd u[t0], v[t0] haloupd u[t0] + W u[t1] - R u[t0] ---> W u[t1] - R u[t0] + haloupd v[t0] + W v[t1] - R v[t0], u[t1] W v[t1] - R v[t0], u[t1] + """ + def accesses(node): + exprs = FindNodes(Expression).visit(node) + return set().union(*[e.reads for e in exprs]), {e.write for e in exprs} + + def destination(functions, nests, guarded): + # The first of `nests` reading `functions`, unless written or guarded before. + # Lowering normally ensures neither, but dependence analysis may miss writes + # (e.g., through different iteration Dimensions) + for i in nests: + if i in guarded: + return None + reads, writes = accesses(i) + if functions & reads: + return i + if functions & writes: + return None + return None + + mapper = HaloSpotMapper() + nodes = MapNodes(Iteration, (HaloSpot, Iteration, Expression), 'immediate') + for it, v in nodes.visit(iet).items(): + if it is None: + continue + + # Nothing within a Conditional moves, as it may not execute + guarded = set().union(*[FindNodes((HaloSpot, Iteration, Expression)).visit(i) + for i in FindNodes(Conditional).visit(it)]) + + # The loop nests (or HaloSpots wrapping them) within `it`, in order + nests, nested = [], set() + for i in v: + if i not in nested: + nests.append(i) + nested.update(FindNodes((Iteration, Expression)).visit(i)) + + for n, hs in enumerate(nests): + if not isinstance(hs, HaloSpot) or hs in guarded: + continue + + # The Functions exchanged by `hs` but not accessed in the nest it wraps + reads, writes = accesses(hs) + candidates = [f for f, hse in hs.fmapper.items() + if not {f, hse.bundle} & (reads | writes)] + + # Safe regardless of what `hs` accesses: each exchange stays under `it`, + # ahead of its first reader and never past a write or into a Conditional + for f in candidates: + # Move the exchange of `f` down to the first nest reading it + i = destination({f, hs.fmapper[f].bundle}, nests[n+1:], guarded) + if i is not None: + mapper.drop(hs, f) + mapper.add(i, hs.halo_scheme.project(f)) + + iet = mapper.apply(iet) + + return iet + + def _merge_halospots(iet): """ Merge HaloSpots on the same IET level when data dependences allow it. This diff --git a/tests/test_dimension.py b/tests/test_dimension.py index 3e28210fe5..fd82373468 100644 --- a/tests/test_dimension.py +++ b/tests/test_dimension.py @@ -2272,14 +2272,14 @@ def test_topofusion_w_subdims_conddims_v3(self): assert exprs[0].write is f assert exprs[1].write is g - exprs = FindNodes(Expression).visit(bns['x2_blk0']) + exprs = FindNodes(Expression).visit(bns['x1_blk0']) assert len(exprs) == 3 assert isinstance(exprs[0].expr.lhs, Temp) assert exprs[1].write is fsave assert exprs[2].write is gsave # Additional nest due to anti-dependence - exprs = FindNodes(Expression).visit(bns['x1_blk0']) + exprs = FindNodes(Expression).visit(bns['x2_blk0']) assert len(exprs) == 2 assert exprs[1].write is h diff --git a/tests/test_mpi.py b/tests/test_mpi.py index 8b2f6e79b7..8990b26ae4 100644 --- a/tests/test_mpi.py +++ b/tests/test_mpi.py @@ -1781,10 +1781,16 @@ def test_avoid_merging_if_no_locindices(self, mode): assert np.allclose(f.data_ro_domain[5:], [8., 8., 8., 6., 5.], rtol=R) assert np.allclose(g.data_ro_domain[0, 5:], [16., 16., 14., 13., 6.], rtol=R) - @pytest.mark.parallel(mode=1) - def test_avoid_merging_if_diff_functions(self, mode): - grid = Grid(shape=(4, 4, 4)) - x, y, z = grid.dimensions + @pytest.mark.parallel(mode=[(1, 'basic'), (1, 'diag2'), (1, 'overlap'), + (1, 'full'), (2, 'basic'), (2, 'overlap'), + (2, 'overlap2'), (2, 'full'), (4, 'diag2'), + (4, 'overlap')]) + def test_merging_diff_functions(self, mode): + """ + Halo exchanges of different Functions are merged, and so bundled, unless + kept apart to overlap with the computation requiring each. + """ + grid = Grid(shape=(8, 8, 8)) u = TimeFunction(name="u", grid=grid, space_order=2) U = TimeFunction(name="U", grid=grid, space_order=2) @@ -1795,10 +1801,95 @@ def test_avoid_merging_if_diff_functions(self, mode): eqns += src.inject(field=u.forward, expr=src) eqns += [Eq(U.forward, U.dx + u.forward)] - op = Operator(eqns) - _ = op.cfunction + def run(opt): + # Rank-dependent data, so that stale halos are detected + for f, m in ((u, 7), (U, 5)): + f.data[:] = (np.arange(np.prod(f.shape_global)) % m + 1).reshape( + f.shape_global + ) + src.data[:] = np.arange(1, 4).reshape(3, 1) + + op = Operator(eqns, opt=opt) + op(time_M=2) - check_halo_exchanges(op, 2, 2) + return op, [np.array(f.data_ro_domain) for f in (u, U)] + + # Without any halo exchange optimization, as reference + _, reference = run(('advanced', {'opt-comms': False})) + + op, results = run('advanced') + for i, j in zip(results, reference, strict=True): + assert np.allclose(i, j, rtol=1e-7) + + mode = configuration['mpi'] + if 'overlap' in mode or 'full' in mode: + _, tloop = check_halo_exchanges(op, 2, 2) + + # Each exchange precedes the computation requiring it, and only that + calls = FindNodes((HaloUpdateCall, ComputeCall)).visit(tloop) + n = [isinstance(c, ComputeCall) for c in calls].index(True) + assert u in calls[n-1].functions + assert any(U in c.functions for c in calls[n+1:] + if isinstance(c, HaloUpdateCall)) + else: + check_halo_exchanges(op, 1, 1) + + @pytest.mark.parallel(mode=[2, 4]) + def test_haloupdate_subdomain_order(self, mode): + """ + Ensure the halo exchanges remain correct when topofusion reorders + independent equations over SubDomains. + """ + + class Side(SubDomain): + + def __init__(self, side, **kwargs): + self.side = side + super().__init__(**kwargs) + + def define(self, dimensions): + x, y = dimensions + return {x: x, y: (self.side, 4)} + + grid = Grid(shape=(16, 16)) + sd0 = Side('left', name='sd0', grid=grid) + sd1 = Side('right', name='sd1', grid=grid) + + p, q, u, v = (TimeFunction(name=i, grid=grid, space_order=2) + for i in ('p', 'q', 'u', 'v')) + + # `p` and `q` are written at every step, so their halo exchanges survive + eqns = [Eq(p.forward, p + 1), Eq(q.forward, 2*q)] + u0, u1 = (Eq(u.forward, u + p.dx, subdomain=sd) for sd in (sd0, sd1)) + v0, v1 = (Eq(v.forward, v + q.dx, subdomain=sd) for sd in (sd0, sd1)) + + def run(eqns, opt): + for f in (p, q, u, v): + f.data[:] = 0 + ramp = np.arange(grid.shape[0], dtype=grid.dtype) + p.data[0] = ramp[:, None]**2 + q.data[0] = 1 + ramp[:, None] + + op = Operator(eqns, opt=opt) + op(time_M=3) + + return op, [np.array(f.data) for f in (p, q, u, v)] + + # Without topofusion, as reference + _, reference = run(eqns + [u0, v0, u1, v1], 'noop') + + R = 1e-07 + ops = [] + for order in ([u0, v0, u1, v1], [u0, u1, v0, v1]): + op, results = run(eqns + order, 'advanced') + for i, j in zip(results, reference, strict=True): + assert np.allclose(i, j, rtol=R) + ops.append(op) + + op0, op1 = ops + assert len(retrieve_iteration_tree(op0)) == len(retrieve_iteration_tree(op1)) + assert len(FindNodes(HaloUpdateCall).visit(op0)) == \ + len(FindNodes(HaloUpdateCall).visit(op1)) @pytest.mark.parallel(mode=1) def test_merge_haloupdate_if_diff_locindices(self, mode): diff --git a/tests/test_operator.py b/tests/test_operator.py index b87a9c02d3..006fb9b031 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -25,15 +25,17 @@ from devito.arch.archinfo import Device from devito.exceptions import InvalidOperator from devito.finite_differences.differentiable import diff2sympy -from devito.ir.clusters import Cluster +from devito.ir.clusters import Cluster, clusterize from devito.ir.equations import ClusterizedEq, LoweredEq from devito.ir.equations.algorithms import lower_exprs from devito.ir.iet import ( Callable, Conditional, Expression, FindNodes, FindSymbols, IsPerfectIteration, Iteration, Section, TimedList, retrieve_iteration_tree ) -from devito.ir.support import Any, Backward, Forward, WaitLock +from devito.ir.support import Any, Backward, Forward, ReleaseLock, WaitLock +from devito.ir.support.symregistry import SymbolRegistry from devito.passes.clusters import fuse +from devito.passes.clusters.fusion import _shares_invariant from devito.passes.iet.languages.C import CDataManager from devito.symbolics import ListInitializer, indexify, retrieve_indexed from devito.tools import as_fp64_decimal, flatten, powerset, timed_region @@ -2265,9 +2267,10 @@ def test_topofuse_preserves_nonadjacent_fission(self): op = Operator(eqns, opt=('topofuse', {'openmp': False})) - assert_structure(op, ['x,y', 'x', 'x,y']) + assert_structure(op, ['x,y', 'x,y', 'x']) - def test_wait_halts_topofuse(self): + @pytest.mark.parametrize('toposort', [True, 'topdown']) + def test_wait_halts_topofuse(self, toposort): """ No reader of a Function is scheduled ahead of a wait on it, e.g. for its prefetch to complete, even to fuse with a Cluster with the same guards. @@ -2289,11 +2292,109 @@ def test_wait_halts_topofuse(self): c2 = c2.rebuild(guards=guards) with timed_region('x'): - clusters = fuse([c0, c1, c2], toposort=True) + clusters = fuse([c0, c1, c2], toposort=toposort) readers = [c for c in clusters if f in c.scope.reads] assert readers[0].syncs == c1.syncs + @pytest.mark.parametrize('toposort', [True, 'topdown']) + def test_dtype_typed_topofuse(self, toposort): + """ + Clusters of the same data type fuse across one of a different data type, + which would otherwise prevent their fusion. + """ + grid = Grid(shape=(4, 4)) + + a, c = [Function(name=i, grid=grid) for i in 'ac'] + b = Function(name='b', grid=grid, dtype=np.float64) + + exprs = [LoweredEq(i) for i in lower_exprs([Eq(a, 1), Eq(b, 2), Eq(c, 3)])] + clusters = [Cluster(i, i.ispace) for i in exprs] + + with timed_region('x'): + clusters = fuse(clusters, toposort=toposort) + + assert len(clusters) == 2 + assert [e.lhs.function for e in clusters[0].exprs] == [a, c] + + @pytest.mark.parametrize('toposort', [True, 'topdown']) + def test_halotouch_typed_topofuse(self, toposort): + """Typed topofusion fuses Clusters across a HaloTouch heading a group.""" + grid = Grid(shape=(4, 4)) + + p = TimeFunction(name='p', grid=grid, space_order=2) + f0, f1, f2 = [Function(name=f'f{i}', grid=grid) for i in range(3)] + + # The HaloTouch of `p` heads the group of `f0` + with timed_region('x'): + exprs = Operator._lower_exprs([Eq(f0, p.dx), Eq(f1, f0), Eq(f2, p)], + options={}) + clusters = clusterize(exprs, sregistry=SymbolRegistry(), + options={'mpi': False, 'mapify-reduce': False}) + clusters = fuse(clusters, toposort=toposort) + + assert [c.is_halo_touch for c in clusters] == [True, False, False] + assert [e.lhs.function for e in clusters[1].exprs] == [f0, f2] + + def test_topdown_outer_sharing(self): + """Top-down topofusion shares an outer loop regardless of equation order.""" + grid = Grid(shape=(4, 4, 4)) + x, y, z = grid.dimensions + + a = Function(name='a', dimensions=(x, y), shape=(4, 4)) + b = Function(name='b', dimensions=(y,), shape=(4,)) + c = Function(name='c', dimensions=(x, z), shape=(4, 4)) + + for eqns in permutations([Eq(a, 1), Eq(b, 2), Eq(c, 3)]): + op = Operator(eqns, opt=('topofuse', {'openmp': False})) + + assert len([i for i in FindNodes(Iteration).visit(op) if i.dim is x]) == 1 + + def test_topdown_keeps_lock_order(self): + """Top-down topofusion doesn't move a lock release past another lock's wait.""" + grid = Grid(shape=(4, 4)) + y = grid.dimensions[1] + + a, b, f = [Function(name=i, grid=grid) for i in 'abf'] + c = Function(name='c', grid=grid, dtype=np.float64) + locks = [Lock(name=f'lock{i}', dimensions=CustomDimension(name=f'ld{i}', + symbolic_size=1)) + for i in range(2)] + + exprs = [LoweredEq(i) for i in lower_exprs([Eq(a, f), Eq(c, 1), Eq(b, f)])] + c0, c1, c2 = [Cluster(i, i.ispace) for i in exprs] + + # `c0` and `c2` share a type, so they would be gathered ahead of `c1` + c0 = c0.rebuild(syncs={y: (WaitLock(locks[0][0], f),)}) + c1 = c1.rebuild(syncs={y: (ReleaseLock(locks[0][0], f),)}) + c2 = c2.rebuild(syncs={y: (WaitLock(locks[1][0], f),)}) + + with timed_region('x'): + clusters = fuse([c0, c1, c2], toposort='topdown') + + assert [c.syncs for c in clusters] == [c0.syncs, c1.syncs, c2.syncs] + + def test_shares_invariant_buffered(self): + """ + A buffered TimeFunction is indexed by `time`, through its SteppingDimension, + so it doesn't keep the Clusters accessing it together along `time`. + """ + grid = Grid(shape=(4, 4)) + time = grid.time_dim + + u = TimeFunction(name='u', grid=grid) + f, g = [Function(name=i, grid=grid) for i in 'fg'] + + with timed_region('x'): + exprs = Operator._lower_exprs([Eq(u.forward, u + 1), Eq(f, u.forward), + Eq(g, f + u)], options={}) + c0, c1, c2 = clusterize(exprs, sregistry=SymbolRegistry(), + options={'mpi': False, 'mapify-reduce': False}) + + assert not _shares_invariant(c0, c1, time) + # Unlike `f`, overwritten at each iteration of `time` + assert _shares_invariant(c1, c2, time) + def test_wait_leaves_scope_untouched(self): """ A wait on a Function orders its readers upon scheduling, but it is not @@ -2335,7 +2436,7 @@ def test_nonadjacent_constraints_preserve_directions(self): op = Operator(eqns, opt=('topofuse', {'openmp': False})) - assert_structure(op, ['x,y', 'x', 'x,y'], 'x,y,y') + assert_structure(op, ['x', 'x,y', 'x,y'], 'x,y,y') iterations = FindNodes(Iteration).visit(op) assert iterations[0].direction is Backward diff --git a/tests/test_subdomains.py b/tests/test_subdomains.py index 71012c02b5..33dd314d87 100644 --- a/tests/test_subdomains.py +++ b/tests/test_subdomains.py @@ -417,6 +417,145 @@ def define(self, dimensions): for v, v_ref in states: np.testing.assert_allclose(v.data, v_ref.data) + @pytest.mark.parametrize('split, du, dv', [ + ('y', 'dx', 'dx'), + ('y', 'dx', 'dy'), + ('y', 'dy', 'dx'), + ('x', 'dx', 'dy'), + ('x', 'dy', 'dx'), + ]) + def test_topofuse_subdomain_order(self, split, du, dv): + """ + Ensure topofusion of independent equations over SubDomains does not depend + on their order, e.g. is not prevented by the HaloTouches of halo reads, + including when HaloTouch insertion differs between the Functions. + """ + + class Side(SubDomain): + + def __init__(self, side, **kwargs): + self.side = side + super().__init__(**kwargs) + + def define(self, dimensions): + return {d: (self.side, 4) if d.name == split else d + for d in dimensions} + + grid = Grid(shape=(16, 16)) + sd0 = Side('left', name='sd0', grid=grid) + sd1 = Side('right', name='sd1', grid=grid) + + f = Function(name='f', grid=grid, space_order=2) + g = Function(name='g', grid=grid, space_order=2) + f.data[:] = np.arange(f.data.size, dtype=grid.dtype).reshape(f.data.shape) + g.data[:] = np.sin(f.data) + + u = TimeFunction(name='u', grid=grid) + v = TimeFunction(name='v', grid=grid) + u0, u1 = (Eq(u.forward, getattr(f, du), subdomain=sd) for sd in (sd0, sd1)) + v0, v1 = (Eq(v.forward, getattr(g, dv), subdomain=sd) for sd in (sd0, sd1)) + + results = [] + for eqns in ([u0, v0, u1, v1], [u0, u1, v0, v1]): + op = Operator(eqns, opt=('topofuse', {'openmp': False})) + + # `u0, v0` and `u1, v1` fuse, whatever the order + assert len(retrieve_iteration_tree(op)) == 2 + + u.data[:] = 0 + v.data[:] = 0 + op(time_M=1) + results.append((u.data.copy(), v.data.copy())) + + for i, j in zip(*results, strict=True): + np.testing.assert_allclose(i, j) + + def test_topofuse_dependent_order(self): + """ + Ensure topofusion of independent equations over a SubDomain does not depend + on their order when one of them is grouped with a dependent equation, e.g. + across the HaloTouch of an equation over another SubDomain. + """ + + class Side(SubDomain): + + def __init__(self, side, **kwargs): + self.side = side + super().__init__(**kwargs) + + def define(self, dimensions): + x, y = dimensions + return {x: x, y: (self.side, 4)} + + grid = Grid(shape=(16, 16)) + sd0 = Side('left', name='sd0', grid=grid) + sd1 = Side('right', name='sd1', grid=grid) + + a = Function(name='a', grid=grid, space_order=2) + b = Function(name='b', grid=grid, space_order=2) + u = TimeFunction(name='u', grid=grid, space_order=2) + w = TimeFunction(name='w', grid=grid, space_order=2) + p = TimeFunction(name='p', grid=grid, space_order=2) + p.data[:] = np.sin(np.arange(p.data.size)).reshape(p.data.shape) + + ea = Eq(a, p, subdomain=sd1) + # Reads `a` along `y`, so cannot fuse with `ea` + eu = Eq(u.forward, a.dy, subdomain=sd1) + # The halo read of `p` gets a HaloTouch + ew = Eq(w.forward, p.dx, subdomain=sd0) + eb = Eq(b, p, subdomain=sd1) + + results = [] + for eqns in ([ea, eb, eu, ew], [ea, eu, ew, eb]): + op = Operator(eqns, opt=('topofuse', {'openmp': False})) + + # `ea, eb` fuse, whatever the order + assert len(retrieve_iteration_tree(op)) == 3 + + for f in (a, b, u, w): + f.data[:] = 0 + op(time_M=1) + results.append([f.data.copy() for f in (a, b, u, w)]) + + for i, j in zip(*results, strict=True): + np.testing.assert_allclose(i, j) + + def test_topofuse_contracted_temp(self): + """ + Topofusion after `cire-sops` keeps a contracted temporary within the loop + it was contracted along. + """ + + class Slab(SubDomain): + + name = 'slab' + + def define(self, dimensions): + x, y = dimensions + return {x: ('left', 3), y: y} + + grid = Grid(shape=(11, 11)) + slab = Slab(grid=grid) + + f = TimeFunction(name='f', grid=grid, space_order=4) + phi = TimeFunction(name='phi', grid=grid, space_order=4) + init = np.sin(np.arange(f.data[0].size)).reshape(f.data[0].shape) + + # The temporary of `f.dy` is contracted within `x`, while the HaloTouch + # of `phi.dy` lies in between its producer and consumer + eqns = [Eq(phi, f.dy, subdomain=slab), + Eq(f.forward, f + 0.01*(phi.dy + f.dy.dy), subdomain=slab)] + + results = [] + for opt in ('noop', ('cire-sops', 'topofuse', {'openmp': False})): + f.data[:] = 0 + f.data[0] = init + phi.data[:] = 0 + Operator(eqns, opt=opt).apply(time_M=0) + results.append(np.array(f.data[1])) + + np.testing.assert_allclose(*results, atol=1e-6) + class TestMultiSubDomain: