From 04bbf2dd9af422c8b7c20face42eb0400bfa8896 Mon Sep 17 00:00:00 2001 From: Edward Caunt Date: Mon, 30 Nov 2026 14:38:04 +0000 Subject: [PATCH 1/5] compiler: Prevent HaloTouches from blocking topological fusion Every HaloTouch wrote the same mock Symbol, so all HaloTouches were totally ordered via output dependences. Combined with the mock WARs tying each HaloTouch to the Functions its owner writes, this could pin a HaloTouch between independent Clusters, preventing their fusion depending on the order of the input equations (e.g. equations over SubDomains given per equation rather than per SubDomain). * Each HaloTouch now writes its own mock Symbol, named via the SymbolRegistry * Fusion's topological sorting no longer schedules HaloTouches: they are drained as soon as ready, and reinserted after their predecessors and before their earliest successor, within the run of loop nests sharing loops with the latter, at the gap splitting the fewest shared loops. This preserves the existing halo exchange placement (e.g. no merging of the exchanges of different Functions) while allowing the fusion Co-Authored-By: Claude Opus 5.5 --- devito/ir/clusters/algorithms.py | 16 +++--- devito/passes/clusters/fusion.py | 84 ++++++++++++++++++++++++++++++-- tests/test_mpi.py | 57 ++++++++++++++++++++++ tests/test_subdomains.py | 45 +++++++++++++++++ 4 files changed, 191 insertions(+), 11 deletions(-) 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/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index cd00bf97bc..a49112551d 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -254,12 +254,28 @@ def _toposort(self, cgroups, prefix): return ClusterGroup(cgroups, prefix) dag = self._build_dag(cgroups, prefix) + position = {cg: n for n, cg in enumerate(cgroups)} def choose_element(queue, scheduled): - if not scheduled or len(queue) == 1: + # HaloTouches are drained as soon as ready, so as not to bias the + # schedule, and placed afterwards (see `_reinsert_halo_touches`) + for e in queue: + if e.is_halo_touch: + queue.remove(e) + return e + + if len(queue) == 1: return queue.pop() - k = self._key(scheduled[-1]) + try: + last = next(i for i in reversed(scheduled) if not i.is_halo_touch) + except StopIteration: + # Nothing scheduled yet, ensure stability + e = min(queue, key=position.get) + queue.remove(e) + return e + + k = self._key(last) m = {i: self._key(i) for i in queue} # First of all, ensure we preserve the integrity of the current scope @@ -280,18 +296,25 @@ def choose_element(queue, scheduled): 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)) + e = min(choosable, key=position.get) except ValueError: continue queue.remove(e) return e # Fallback - e = min(queue, key=lambda i: cgroups.index(i)) + e = min(queue, key=position.get) queue.remove(e) return e - return ClusterGroup(dag.topological_sort(choose_element), prefix) + processed = dag.topological_sort(choose_element) + + hts = [cg for cg in cgroups if cg.is_halo_touch] + if hts: + processed = [cg for cg in processed if not cg.is_halo_touch] + processed = _reinsert_halo_touches(processed, hts, dag) + + return ClusterGroup(processed, prefix) def _build_dag(self, cgroups, prefix): """ @@ -330,6 +353,57 @@ def _build_dag(self, cgroups, prefix): return dag +def _reinsert_halo_touches(cgroups, hts, dag): + """ + Insert the HaloTouches `hts`, kept out of the topological sorting, into the + sorted `cgroups`. Each goes after its predecessors and before its earliest + successor in `dag`, without leaving the run of loop nests sharing loops with + the latter, at the gap splitting the fewest shared loops. E.g., `HT(v)` goes + ahead of `u v`, rather than between `u` and `v`, so that these may still fuse. + """ + def nshared(g): + # The number of loops shared across the gap ahead of `cgroups[g]` + if g == 0 or g == len(cgroups): + return 0 + n = 0 + for i, j in zip(cgroups[g-1][-1].ispace, cgroups[g][0].ispace, strict=False): + if i != j: + break + n += 1 + return n + + index = {cg: n for n, cg in enumerate(cgroups)} + + preds = defaultdict(list) + for i, j in dag.edges: + preds[j].append(i) + + # The edges of `dag` follow the original order, so the earliest successors + # are found in reverse order, and the HaloTouches placed in order + hi = {} + for h in reversed(hts): + hi[h] = min((index[i] if i in index else hi[i] for i in dag.graph[h]), + default=len(cgroups)) + + slots = {} + for h in hts: + lo = max((index[i] + 1 if i in index else slots[i] for i in preds[h]), + default=0) + + start = hi[h] + while start > lo and nshared(start) > len(h[0].ispace): + start -= 1 + + slots[h] = min(range(start, hi[h] + 1), key=lambda g: (nshared(g), g)) + + processed = [] + for n in range(len(cgroups) + 1): + processed.extend(h for h in hts if slots[h] == n) + processed.extend(cgroups[n:n+1]) + + return processed + + @timed_pass() def fuse(clusters, toposort=False, options=None): """ diff --git a/tests/test_mpi.py b/tests/test_mpi.py index 8b2f6e79b7..c06e34586e 100644 --- a/tests/test_mpi.py +++ b/tests/test_mpi.py @@ -1800,6 +1800,63 @@ def test_avoid_merging_if_diff_functions(self, mode): check_halo_exchanges(op, 2, 2) + @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): grid = Grid(shape=(101, 101)) diff --git a/tests/test_subdomains.py b/tests/test_subdomains.py index 71012c02b5..39f0804fa5 100644 --- a/tests/test_subdomains.py +++ b/tests/test_subdomains.py @@ -417,6 +417,51 @@ def define(self, dimensions): for v, v_ref in states: np.testing.assert_allclose(v.data, v_ref.data) + def test_topofuse_subdomain_order(self): + """ + Ensure topofusion of independent equations over SubDomains does not depend + on their order, e.g. is not prevented by the HaloTouches of halo reads. + """ + + 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) + + 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, f.dx, subdomain=sd) for sd in (sd0, sd1)) + v0, v1 = (Eq(v.forward, g.dx, 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) + class TestMultiSubDomain: From 36570b40ce3f0c9fdcfeeab6a71d887fcc9cc626 Mon Sep 17 00:00:00 2001 From: Edward Caunt Date: Tue, 1 Dec 2026 10:37:30 +0000 Subject: [PATCH 2/5] mpi: Introduce halospot sinking --- devito/passes/clusters/fusion.py | 84 ++----------------------------- devito/passes/iet/mpi.py | 85 +++++++++++++++++++++++++++++++- tests/test_mpi.py | 48 +++++++++++++++--- 3 files changed, 129 insertions(+), 88 deletions(-) diff --git a/devito/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index a49112551d..cd00bf97bc 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -254,28 +254,12 @@ def _toposort(self, cgroups, prefix): return ClusterGroup(cgroups, prefix) dag = self._build_dag(cgroups, prefix) - position = {cg: n for n, cg in enumerate(cgroups)} def choose_element(queue, scheduled): - # HaloTouches are drained as soon as ready, so as not to bias the - # schedule, and placed afterwards (see `_reinsert_halo_touches`) - for e in queue: - if e.is_halo_touch: - queue.remove(e) - return e - - if len(queue) == 1: + if not scheduled or len(queue) == 1: return queue.pop() - try: - last = next(i for i in reversed(scheduled) if not i.is_halo_touch) - except StopIteration: - # Nothing scheduled yet, ensure stability - e = min(queue, key=position.get) - queue.remove(e) - return e - - k = self._key(last) + 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 @@ -296,25 +280,18 @@ def choose_element(queue, scheduled): choosable = [e for e in candidates if m[e].weak[:i] == k.weak[:i]] try: # Ensure stability - e = min(choosable, key=position.get) + e = min(choosable, key=lambda i: cgroups.index(i)) except ValueError: continue queue.remove(e) return e # Fallback - e = min(queue, key=position.get) + e = min(queue, key=lambda i: cgroups.index(i)) queue.remove(e) return e - processed = dag.topological_sort(choose_element) - - hts = [cg for cg in cgroups if cg.is_halo_touch] - if hts: - processed = [cg for cg in processed if not cg.is_halo_touch] - processed = _reinsert_halo_touches(processed, hts, dag) - - return ClusterGroup(processed, prefix) + return ClusterGroup(dag.topological_sort(choose_element), prefix) def _build_dag(self, cgroups, prefix): """ @@ -353,57 +330,6 @@ def _build_dag(self, cgroups, prefix): return dag -def _reinsert_halo_touches(cgroups, hts, dag): - """ - Insert the HaloTouches `hts`, kept out of the topological sorting, into the - sorted `cgroups`. Each goes after its predecessors and before its earliest - successor in `dag`, without leaving the run of loop nests sharing loops with - the latter, at the gap splitting the fewest shared loops. E.g., `HT(v)` goes - ahead of `u v`, rather than between `u` and `v`, so that these may still fuse. - """ - def nshared(g): - # The number of loops shared across the gap ahead of `cgroups[g]` - if g == 0 or g == len(cgroups): - return 0 - n = 0 - for i, j in zip(cgroups[g-1][-1].ispace, cgroups[g][0].ispace, strict=False): - if i != j: - break - n += 1 - return n - - index = {cg: n for n, cg in enumerate(cgroups)} - - preds = defaultdict(list) - for i, j in dag.edges: - preds[j].append(i) - - # The edges of `dag` follow the original order, so the earliest successors - # are found in reverse order, and the HaloTouches placed in order - hi = {} - for h in reversed(hts): - hi[h] = min((index[i] if i in index else hi[i] for i in dag.graph[h]), - default=len(cgroups)) - - slots = {} - for h in hts: - lo = max((index[i] + 1 if i in index else slots[i] for i in preds[h]), - default=0) - - start = hi[h] - while start > lo and nshared(start) > len(h[0].ispace): - start -= 1 - - slots[h] = min(range(start, hi[h] + 1), key=lambda g: (nshared(g), g)) - - processed = [] - for n in range(len(cgroups) + 1): - processed.extend(h for h in hts if slots[h] == n) - processed.extend(cgroups[n:n+1]) - - return processed - - @timed_pass() def fuse(clusters, toposort=False, options=None): """ 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_mpi.py b/tests/test_mpi.py index c06e34586e..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,38 @@ 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) - check_halo_exchanges(op, 2, 2) + op = Operator(eqns, opt=opt) + op(time_M=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): From 841576cff558585e2f762421dee0fe0dccf5da66 Mon Sep 17 00:00:00 2001 From: Edward Caunt Date: Thu, 3 Dec 2026 13:41:50 +0000 Subject: [PATCH 3/5] compiler: Topological fusion via ordered typed fusion Replace the greedy choice in `Fusion._toposort` with ordered typed fusion [Kennedy & McKinley, 1993]: one type at a time, each ClusterGroup joins the first group of its type it may fuse with (compatible IterationSpace, no fence or prefix anti-dependence in between, contraction keeps the DAG acyclic), and groups are emitted in topological order, ready HaloTouches first. The greedy choice could not see that scheduling a HaloTouch unblocks a fusible successor. Output dependences not carried by the prefix no longer glue Clusters into the same ClusterGroup at inner levels, as they only impose an order. Conservative WAWs between disjoint SubDomains made such groups atomic, preventing fusion. `Keys.type` extends `Keys.full` with the data type and the iteration Dimensions, which `Cluster.from_clusters` also requires, and keys both typed fusion and the actual fusion of adjacent Clusters. Co-Authored-By: Claude Opus 5.5 --- devito/passes/clusters/fusion.py | 151 ++++++++++++++++++++++--------- tests/test_dimension.py | 4 +- tests/test_operator.py | 19 ++++ tests/test_subdomains.py | 20 ++-- 4 files changed, 144 insertions(+), 50 deletions(-) diff --git a/devito/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index cd00bf97bc..de6bf631df 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -17,8 +17,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,8 +48,12 @@ 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 @@ -138,6 +145,14 @@ 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 + clusters = flatten([self.c]) + return (self.full, self.c.dtype, clusters[0].ispace.itdims, + clusters[-1].ispace.itdims) + class Fusion(Queue): @@ -172,7 +187,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 +202,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 +264,104 @@ 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} + return ClusterGroup(self._typed_fusion(cgroups, dag, prefix), prefix) - # 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 + 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. Groups are then emitted contiguously, in topological order. - # 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 + 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`: - compatible = [i for i in candidates if k.syncs == m[i].syncs] - candidates = compatible or candidates + u0 u1 h0 v0 h1 v1 ---> h0 u0 v0 h1 u1 v1 - # 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 + 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 + # ClusterGroups 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, cg): + # The IterationSpaces may have been constrained to prevent fusion (e.g., + # of non-adjacent stencil Clusters) + if not all(g[0].ispace.is_compatible(c.ispace) for c in cg): + return False + + # No fence or anti-dependence along `prefix` in between + if any(i.scope.has_barrier for i in cgroups[pos[g]:pos[cg]+1]) or \ + any(_fusion_hazards(i.sync_scope, cg.sync_scope, prefix) == BREAK + for i in members[g]): + return False + + # A direct edge only fixes the order of `g` and `cg`, an indirect path + # would make the contracted DAG cyclic + return not (indirect(g, cg) or indirect(cg, g)) + + # Wild ClusterGroups (e.g., HaloTouches) never fuse, so they get no type + types = defaultdict(list) + for cg in cgroups: + if not cg.is_wild: + types[self._key(cg).type].append(cg) + + for nodes in types.values(): + groups = [] + for cg in nodes: + g = next((g for g in groups if fusible(g, cg)), None) + if g is None: + groups.append(cg) + else: + head[cg] = g + members[g].extend(members.pop(cg)) - # Fallback - e = min(queue, key=lambda i: cgroups.index(i)) - queue.remove(e) - return e + # 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 - return ClusterGroup(dag.topological_sort(choose_element), prefix) + quotient = DAG(nodes=list(members), + edges=[(g, h) for g in members for h in successors(g)]) + return flatten(members[g] for g in quotient.topological_sort(choose_element)) - def _build_dag(self, cgroups, prefix): + 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 +374,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,9 +389,9 @@ 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 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_operator.py b/tests/test_operator.py index b87a9c02d3..be2e28080e 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -2294,6 +2294,25 @@ def test_wait_halts_topofuse(self): readers = [c for c in clusters if f in c.scope.reads] assert readers[0].syncs == c1.syncs + def test_dtype_typed_topofuse(self): + """ + 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=True) + + assert len(clusters) == 2 + assert [e.lhs.function for e in clusters[0].exprs] == [a, c] + def test_wait_leaves_scope_untouched(self): """ A wait on a Function orders its readers upon scheduling, but it is not diff --git a/tests/test_subdomains.py b/tests/test_subdomains.py index 39f0804fa5..ccbbc36cbb 100644 --- a/tests/test_subdomains.py +++ b/tests/test_subdomains.py @@ -417,10 +417,18 @@ def define(self, dimensions): for v, v_ref in states: np.testing.assert_allclose(v.data, v_ref.data) - def test_topofuse_subdomain_order(self): + @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. + 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): @@ -430,8 +438,8 @@ def __init__(self, side, **kwargs): super().__init__(**kwargs) def define(self, dimensions): - x, y = dimensions - return {x: x, y: (self.side, 4)} + 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) @@ -444,8 +452,8 @@ def define(self, dimensions): u = TimeFunction(name='u', grid=grid) v = TimeFunction(name='v', grid=grid) - u0, u1 = (Eq(u.forward, f.dx, subdomain=sd) for sd in (sd0, sd1)) - v0, v1 = (Eq(v.forward, g.dx, subdomain=sd) for sd in (sd0, sd1)) + 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]): From f4890cd95c66ff4bd33f00b40ff3546bdb8fef42 Mon Sep 17 00:00:00 2001 From: Edward Caunt Date: Fri, 4 Dec 2026 14:26:31 +0000 Subject: [PATCH 4/5] compiler: Introduce top-down topological fusion Add `toposort='topdown'`, which reorders Clusters from the outermost level inwards, so that each level is ordered before being divided, and then fuses them. With `toposort=True`, a Cluster moved at an outer level never reaches the inner groups it may fuse with, so the outcome depends on equation order. * `Reorder` runs ordered typed fusion top-down: a fine pass by `Keys.type`, then a coarse pass merging the groups that may share an outer loop * Clusters sharing storage the shared loop doesn't index (e.g. contracted temporaries) stay one indivisible unit * Unless tasks are fused, Clusters with locks stay in program order * HaloTouches no longer type a ClusterGroup nor constrain its compatibility, which also fixes `toposort=True` * Core CPU and GPU pipelines switch to `toposort='topdown'` Co-Authored-By: Claude Opus 5.5 --- devito/core/cpu.py | 4 +- devito/core/gpu.py | 4 +- devito/ir/stree/algorithms.py | 4 + devito/passes/clusters/fusion.py | 203 ++++++++++++++++++++++++++----- tests/test_operator.py | 76 ++++++++++-- tests/test_subdomains.py | 86 +++++++++++++ 6 files changed, 332 insertions(+), 45 deletions(-) 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/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 de6bf631df..a6ed112d6a 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 ( @@ -58,6 +59,27 @@ def _fusion_hazards(scope0, scope1, prefix): 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 + + def invariant(functions): + return {f for f in functions if not d._defines & set(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): """ @@ -148,8 +170,9 @@ def full(self): @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 - clusters = flatten([self.c]) + # 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) @@ -279,7 +302,9 @@ def _typed_fusion(self, cgroups, dag, prefix): (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. Groups are then emitted contiguously, in topological order. + 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 -------- @@ -294,7 +319,7 @@ def _typed_fusion(self, cgroups, dag, 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 - # ClusterGroups are visited in order + # groups are visited in order head = {cg: cg for cg in cgroups} members = {cg: [cg] for cg in cgroups} @@ -314,37 +339,42 @@ def indirect(src, dst): seen.update(stack) return False - def fusible(g, cg): - # The IterationSpaces may have been constrained to prevent fusion (e.g., - # of non-adjacent stencil Clusters) - if not all(g[0].ispace.is_compatible(c.ispace) for c in cg): + def fusible(g, h): + if not self._compatible(members[g], members[h]): return False # No fence or anti-dependence along `prefix` in between - if any(i.scope.has_barrier for i in cgroups[pos[g]:pos[cg]+1]) or \ - any(_fusion_hazards(i.sync_scope, cg.sync_scope, prefix) == BREAK - for i in members[g]): + 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 `cg`, an indirect path + # A direct edge only fixes the order of `g` and `h`, an indirect path # would make the contracted DAG cyclic - return not (indirect(g, cg) or indirect(cg, g)) - - # Wild ClusterGroups (e.g., HaloTouches) never fuse, so they get no type - types = defaultdict(list) - for cg in cgroups: - if not cg.is_wild: - types[self._key(cg).type].append(cg) - - for nodes in types.values(): - groups = [] - for cg in nodes: - g = next((g for g in groups if fusible(g, cg)), None) - if g is None: - groups.append(cg) - else: - head[cg] = g - members[g].extend(members.pop(cg)) + 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 @@ -355,7 +385,20 @@ def choose_element(queue, scheduled): quotient = DAG(nodes=list(members), edges=[(g, h) for g in members for h in successors(g)]) - return flatten(members[g] for g in quotient.topological_sort(choose_element)) + 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): """ @@ -397,6 +440,92 @@ def _build_dag(self, cgroups, prefix, outputs=True): 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): """ @@ -409,8 +538,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/tests/test_operator.py b/tests/test_operator.py index be2e28080e..c6a47e650b 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -25,14 +25,15 @@ 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.iet.languages.C import CDataManager from devito.symbolics import ListInitializer, indexify, retrieve_indexed @@ -2265,9 +2266,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,12 +2291,13 @@ 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 - def test_dtype_typed_topofuse(self): + @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. @@ -2308,11 +2311,68 @@ def test_dtype_typed_topofuse(self): clusters = [Cluster(i, i.ispace) for i in exprs] with timed_region('x'): - clusters = fuse(clusters, toposort=True) + 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_wait_leaves_scope_untouched(self): """ A wait on a Function orders its readers upon scheduling, but it is not @@ -2354,7 +2414,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 ccbbc36cbb..33dd314d87 100644 --- a/tests/test_subdomains.py +++ b/tests/test_subdomains.py @@ -470,6 +470,92 @@ def define(self, dimensions): 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: From 77452eb78034b589050b33447c26e352bcce0690 Mon Sep 17 00:00:00 2001 From: Edward Caunt Date: Fri, 4 Dec 2026 16:58:01 +0000 Subject: [PATCH 5/5] compiler: Fixup buffered TimeFunctions --- devito/passes/clusters/fusion.py | 3 ++- tests/test_operator.py | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/devito/passes/clusters/fusion.py b/devito/passes/clusters/fusion.py index a6ed112d6a..381b5cdfd4 100644 --- a/devito/passes/clusters/fusion.py +++ b/devito/passes/clusters/fusion.py @@ -70,8 +70,9 @@ def _shares_invariant(c0, c1, d): 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 d._defines & set(f.dimensions)} + 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) diff --git a/tests/test_operator.py b/tests/test_operator.py index c6a47e650b..006fb9b031 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -35,6 +35,7 @@ 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 @@ -2373,6 +2374,27 @@ def test_topdown_keeps_lock_order(self): 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