diff --git a/devito/mpi/distributed.py b/devito/mpi/distributed.py index 8cd3cb2f5e..d7231e6089 100644 --- a/devito/mpi/distributed.py +++ b/devito/mpi/distributed.py @@ -567,6 +567,41 @@ def parent(self): """The parent distributor of this SubGridDistributor.""" return self._parent + @property + def neighborhood(self): + """ + As in `Distributor.neighborhood`, but skipping the MPI ranks owning no + subsampled points: a rank between two populated ones may be empty, in + which case the halo must come from the next populated rank. The empty + ranks have no neighbours. + """ + # A rank is empty along `d` if its coordinate is, irrespective of the others + populated = [[c for c, i in enumerate(dec) if len(i) > 0] + for dec in self.decomposition] + + ret = {} + for i in product([LEFT, CENTER, RIGHT], repeat=self.ndim): + neighbor = [] + for c, s, p in zip(self.mycoords, i, populated, strict=True): + if s is LEFT: + neighbor.append(max((j for j in p if j < c), default=None)) + elif s is RIGHT: + neighbor.append(min((j for j in p if j > c), default=None)) + else: + neighbor.append(c) + + if self.loc_empty or None in neighbor: + ret[i] = MPI.PROC_NULL + else: + ret[i] = self.comm.Get_cart_rank(neighbor) + + # The neighbours along `d` are the diagonal ones with CENTER elsewhere + for n, d in enumerate(self.dimensions): + ret[d] = {s: ret[tuple(s if m == n else CENTER for m in range(self.ndim))] + for s in (LEFT, RIGHT)} + + return ret + class SubDistributor(DenseDistributor): diff --git a/devito/operations/interpolators.py b/devito/operations/interpolators.py index 050999aff4..1ae05149fc 100644 --- a/devito/operations/interpolators.py +++ b/devito/operations/interpolators.py @@ -297,7 +297,7 @@ def _rdim(self, subdomain=None, shifts=None): # If the interpolation operation is limited to a SubDomain, # use the SubDimensions of that SubDomain if subdomain: - gdims = tuple(subdomain.dimension_map[d] for d in self._gdims) + gdims = tuple(subdomain.dimension_map[d.root] for d in self._gdims) else: gdims = self._gdims @@ -305,7 +305,7 @@ def _rdim(self, subdomain=None, shifts=None): rdims = [] pos = self.sfunction._position_map(shifts=shifts).values() - for (d, rd, p) in zip(gdims, self._cdim, pos, strict=True): + for (d, gd, rd, p) in zip(gdims, self._gdims, self._cdim, pos, strict=True): # Add conditional to avoid OOB lb = sympy.And(rd + p >= d.symbolic_min - self.r, evaluate=False) ub = sympy.And(rd + p <= d.symbolic_max + self.r, evaluate=False) @@ -318,7 +318,7 @@ def _rdim(self, subdomain=None, shifts=None): rank_populated = subdomain.distributor.rank_populated cond = sympy.And(rank_populated, cond) - rdims.append(self.sfunction._cond_rdim(d.root, cond)) + rdims.append(self.sfunction._cond_rdim(gd, cond)) return DimensionTuple(*rdims, getters=gdims) @@ -456,8 +456,8 @@ def _interp_idx(self, variables, implicit_dims=None, subdomain=None, # Index substitution to make in variables subs = { ki: c + p - for ((k, c), p) in zip(mapper.items(), pos, strict=True) - for ki in {k, k.root} + for ((k, c), gd, p) in zip(mapper.items(), self._gdims, pos, strict=True) + for ki in {k, gd, k.root} } idx_subs = {v: v.subs(subs) for v in variables} diff --git a/devito/passes/clusters/aliases.py b/devito/passes/clusters/aliases.py index 4574321de3..4192dc31b6 100644 --- a/devito/passes/clusters/aliases.py +++ b/devito/passes/clusters/aliases.py @@ -754,7 +754,8 @@ def lower_aliases(aliases, meta, opt_maxpar, opt_block_temps): intervals[d] = i continue - assert not d.is_NonlinearDerived + # Only a subsampled Dimension may be iterated over, e.g. a SubGrid's + assert not d.is_NonlinearDerived or d.is_Conditional # `d` is necessarily part of the write-to region, so we have to # adjust the Interval's stamp. For example, consider `i=x[0,0]<1>` @@ -772,12 +773,12 @@ def lower_aliases(aliases, meta, opt_maxpar, opt_block_temps): intervals[d] = interval else: pd = d.parent - writeto.append(interval.relaxed) + writeto.append(_relaxed(interval)) # The lower/upper bounds belong to the parent BlockDimension intervals[d] = interval.zero() intervals[pd] = interval.switch(pd) else: - writeto.append(interval.relaxed) + writeto.append(_relaxed(interval)) intervals[d] = interval di = sub_iterators.get(d, d) @@ -821,6 +822,20 @@ def lower_aliases(aliases, meta, opt_maxpar, opt_block_temps): return Schedule(*processed, dmapper=dict(dmapper), is_frame=aliases.is_frame) +def _relaxed(interval): + """ + Relax `interval` to its root Dimension or, if iterating over a subsampled + Dimension (e.g., a SubGrid's after `subsampling`), to that Dimension, which + spans its own index space. + """ + d = interval.dim + while d.is_Derived and not d.is_Conditional: + d = d.parent + if d.is_Conditional: + return interval.switch(d) + return interval.relaxed + + def make_variant(schedule, exprs, mapper): """ Create a Variant from a Schedule and the corresponding expressions. diff --git a/devito/types/basic.py b/devito/types/basic.py index fc8940f5e9..21767d432d 100644 --- a/devito/types/basic.py +++ b/devito/types/basic.py @@ -1439,7 +1439,15 @@ def indexify(self, indices=None, subs=None): # Substitution for each index (spacing only used in own dimension) subs = subs or {} - subs = [{**{d.spacing: 1, -d.spacing: -1}, **subs} for d in self.dimensions] + mappers = [] + for d in self.dimensions: + mapper = {d.spacing: 1, -d.spacing: -1} + # A subsampled Dimension's spacing is a multiple of its root's, e.g. + # `2*h_x`, so rescale the root's instead to also map `4*h_x` to `2` + if d.spacing != d.root.spacing and d.root.spacing.is_Symbol: + mapper[d.root.spacing] = d.root.spacing/d.spacing + mappers.append({**mapper, **subs}) + subs = mappers # Indices after substitutions indices = [] diff --git a/devito/types/grid.py b/devito/types/grid.py index 635aff5bba..d74c4bb4c3 100644 --- a/devito/types/grid.py +++ b/devito/types/grid.py @@ -586,6 +586,12 @@ def __factors_setup__(cls, parent, factor): if f < 1: raise ValueError(f"Subsampling factor must be >= 1, got `{f}`") + for d, n, f in zip(parent.dimensions, parent.shape, factors, strict=True): + if f > 1 and f >= n: + raise ValueError(f"Subsampling factor `{f}` leaves a single point " + f"along `{d}`, so it must be smaller than its " + f"size `{n}`") + return tuple(int(f) for f in factors) @classmethod diff --git a/tests/test_subsampling.py b/tests/test_subsampling.py index 33bae4be94..51006cdd00 100644 --- a/tests/test_subsampling.py +++ b/tests/test_subsampling.py @@ -7,9 +7,11 @@ from devito import ( Buffer, CondEq, ConditionalDimension, Constant, Eq, Function, Grid, Inc, Operator, - SpaceDimension, SubDomain, SubGrid, TimeFunction, switchconfig + PrecomputedSparseFunction, SpaceDimension, SparseFunction, SubDomain, SubGrid, + TimeFunction, switchconfig ) -from devito.ir.iet import Conditional, Expression, FindNodes, Iteration +from devito.ir.iet import Conditional, Expression, FindNodes, FindSymbols, Iteration +from devito.mpi import MPI from devito.symbolics import retrieve_indexed from devito.tools import as_tuple from devito.types.dimension import SubsamplingOffset @@ -841,11 +843,109 @@ def test_derivative_numerics(self): assert np.allclose(d.data[1:-1, 1:-1], 3., atol=1e-4) + @pytest.mark.parametrize('so', [4, 8]) + @pytest.mark.parametrize('shape,factor,opt', [ + ((33, 33), 2, 'noop'), + ((33, 33), 2, 'advanced'), + ((33, 33), (2, 3), 'advanced'), + ((33, 33), (2, 3), ('advanced', {'blockrelax': True})), + ((17, 17, 17), (2, 2, 4), 'advanced'), + ]) + def test_high_order_derivatives(self, so, shape, factor, opt): + """ + Stencils reaching beyond the adjacent SubGrid points match those on a + plain Grid of the same shape and extent, also once CIRE kicks in. + """ + sub = SubGrid(Grid(shape=shape), factor=factor) + plain = Grid(shape=sub.shape, extent=sub.extent) + + results = [] + for grid, o in ((sub, opt), (plain, 'noop')): + u = Function(name='u', grid=grid, space_order=so) + v = Function(name='v', grid=grid, space_order=so) + u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.) + + op = Operator(Eq(v, u.laplace + u.dx.dy), opt=o) + op.apply() + results.append(np.array(v.data)) + + if grid is sub and opt != 'noop': + assert any(i.is_Array for i in FindSymbols().visit(op)) + + assert np.abs(results[0] - results[1]).max() <= 1e-6*np.abs(results[1]).max() + + @pytest.mark.parametrize('opt', [ + 'noop', 'advanced', + ('advanced', {'blockrelax': True, 'cire-block-temps': False}), + ]) + def test_subdomain_high_order(self, opt): + """As above, for Functions on a SubDomain of the SubGrid.""" + sub = SubGrid(Grid(shape=(33, 33)), factor=2) + plain = Grid(shape=sub.shape, extent=sub.extent) + + results = [] + for grid, o in ((sub, opt), (plain, 'noop')): + middle = Middle(grid=grid) + u = Function(name='u', grid=middle, space_order=4) + v = Function(name='v', grid=middle, space_order=4) + u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.) + + Operator(Eq(v, u.laplace + u.dx.dy), opt=o).apply() + results.append(np.array(v.data)) + + assert np.abs(results[0] - results[1]).max() <= 1e-6*np.abs(results[1]).max() + + @pytest.mark.parametrize('interpolation', ['linear', 'sinc', 'precomputed']) + @pytest.mark.parametrize('subdomain', [False, True]) + def test_sparse_matches_plain(self, interpolation, subdomain): + """ + Interpolation and injection on a SubGrid match those on a plain Grid of + the same shape and extent, including in the last cell and at the corners. + """ + sub = SubGrid(Grid(shape=(33, 33), extent=(32., 32.)), factor=2) + plain = Grid(shape=sub.shape, extent=sub.extent) + coords = np.array([[5., 5.], [12.5, 5.], [29., 29.], [31.9, 7.], + [32., 32.], [32., 5.], [0., 0.]]) + npoint = len(coords) + + results = [] + for grid in (sub, plain): + target = Middle(grid=grid) if subdomain else grid + u = Function(name='u', grid=target, space_order=4) + v = Function(name='v', grid=target, space_order=4) + u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.) + + if interpolation == 'precomputed': + gridpoints = np.minimum(coords // np.array(grid.spacing), + np.array(grid.shape) - 2).astype(np.int32) + coeffs = np.random.default_rng(0).uniform(size=(npoint, 2, 2)) + kwargs = {'r': 2, 'gridpoints': gridpoints, + 'interpolation_coeffs': coeffs.astype(np.float32)} + sf = PrecomputedSparseFunction + else: + kwargs = {'coordinates': coords, 'interpolation': interpolation, + 'r': 2, 'space_order': 4} + sf = SparseFunction + + s = sf(name='s', grid=grid, npoint=npoint, **kwargs) + Operator(s.interpolate(u)).apply() + results.append(np.array(s.data)) + + s.data[:] = np.arange(1, npoint + 1) + Operator(s.inject(v, expr=s)).apply() + results.append(np.array(v.data)) + + assert np.array_equal(results[0], results[2]) + assert np.array_equal(results[1], results[3]) + @pytest.mark.parametrize('factor,err', [ (0, 'must be >= 1'), (-1, 'must be >= 1'), (2.5, 'Non-integer'), ((2, 2, 2), 'Expected 1 or 2 factors'), + (9, 'single point'), + (10, 'single point'), + ((2, 9), 'single point'), ]) def test_invalid_factor(self, factor, err): grid = Grid(shape=(9, 9)) @@ -1377,6 +1477,84 @@ def test_conditional_dimension_built_without_mpi(self, mode): assert np.all(g.data == np.arange(0, 21, 2)[g.local_indices]) + @pytest.mark.parallel(mode=[(4, 'basic'), (4, 'diag2'), (4, 'full')]) + @pytest.mark.parametrize('shape,topology,factor', [ + ((16, 24), (1, 4), (1, 10)), + ((24, 24), (4, 1), (10, 1)), + ((12, 16), (4, 1), (6, 1)), + ]) + def test_empty_ranks(self, mode, shape, topology, factor): + """ + The halo of a rank next to one owning no SubGrid points comes from the + next populated rank, diagonals included. + """ + grid = Grid(shape=shape, topology=topology) + sub = SubGrid(grid, factor=factor) + t = sub.stepping_dim + x, y = sub.dimensions + + assert any(len(i) == 0 for d in sub.distributor.decomposition for i in d) + + u = TimeFunction(name='u', grid=sub, space_order=1) + glob = np.sin(np.arange(np.prod(sub.shape)).reshape(sub.shape)) + u.data[0] = glob + + Operator(Eq(u.forward, u[t, x + 1, y] + u[t, x - 1, y + 1] + + 2*u[t, x, y - 1])).apply(time_M=0) + + # The empty ranks have nothing to check, and `local_indices` would give + # them `slice(0, -1)` + if not sub.distributor.loc_empty: + padded = np.pad(glob, 1) + expected = padded[2:, 1:-1] + padded[:-2, 2:] + 2*padded[1:-1, :-2] + assert np.allclose(np.asarray(u.data[1]), expected[u.local_indices[1:]]) + + @pytest.mark.parallel(mode=[4]) + def test_sparse_empty_ranks(self, mode): + """Sparse operations with ranks owning no SubGrid points.""" + grid = Grid(shape=(24, 24), extent=(23., 23.), topology=(4, 1)) + sub = SubGrid(grid, factor=(10, 1)) + coords = np.random.default_rng(0).uniform(size=(20, 2))*np.array(sub.extent) + xx, yy = np.meshgrid(*[np.arange(n)*h for n, h in + zip(sub.shape, sub.spacing, strict=True)], + indexing='ij') + + u = Function(name='u', grid=sub) + v = Function(name='v', grid=sub) + u.data[:] = xx + 10*yy + s = SparseFunction(name='s', grid=sub, npoint=len(coords), coordinates=coords) + + # Linear interpolation is exact on a linear field + Operator(s.interpolate(u)).apply() + expected = coords[:, 0] + 10*coords[:, 1] + assert np.allclose(np.asarray(s.data), expected[s.local_indices], rtol=1e-5) + + # The linear weights sum to one, so injection conserves the total + s.data[:] = 1. + Operator(s.inject(v, expr=s)).apply() + total = grid.distributor.comm.allreduce(float(np.sum(v.data))) + assert np.isclose(total, len(coords)) + + @pytest.mark.parallel(mode=[(2, 'basic'), (4, 'diag2')]) + def test_high_order_mpi(self, mode): + """High-order stencils on a SubGrid match a serial plain Grid.""" + sub = SubGrid(Grid(shape=(33, 33)), factor=2) + plain = Grid(shape=sub.shape, extent=sub.extent, comm=MPI.COMM_SELF) + + glob = np.sin(np.arange(np.prod(sub.shape)).reshape(sub.shape)/7.) + + vs = [] + for grid in (sub, plain): + u = Function(name='u', grid=grid, space_order=4) + v = Function(name='v', grid=grid, space_order=4) + u.data[:] = glob + + Operator(Eq(v, u.laplace + u.dx.dy)).apply() + vs.append(v) + + v, expected = vs[0], np.asarray(vs[1].data)[vs[0].local_indices] + assert np.abs(np.asarray(v.data) - expected).max() <= 1e-6*np.abs(expected).max() + class TestIncReduction: