Repository navigation
dsl: Misc fixes for subgrids #3127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. iterated subdimension needs is_Strided |
||
|
|
||
| # `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)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure i understand why this is needed. The subsampling pass already does that. |
||
| # 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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Likely need to check Strided as well |
||
| return interval.switch(d) | ||
| return interval.relaxed | ||
|
|
||
|
|
||
| def make_variant(schedule, exprs, mapper): | ||
| """ | ||
| Create a Variant from a Schedule and the corresponding expressions. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is it touching |
||
| # `2*h_x`, so rescale the root's instead to also map `4*h_x` to `2` | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is it checking root here. self.dimension are the ones indxing |
||
| 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 = [] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This prevents using dummy tiny grids to build an operator, those shape checks should only be done at arg processing |
||
| 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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems to mix different things. The cire part should be tested as a standalone in the test_dse with the other cire test and checks the Array itself. |
||
| """ | ||
| 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': | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. there is utilities in test_interpolation for that. |
||
| 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: | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a very weird corner case. I don't see how practical usage of SubGrid would end up in such a setup. I understand what it does but i think this is overkill and such odd case should just error as this is not what the api is intended for.