Skip to content

Commit b4903f9

Browse files
committed
dsl: Misc fixes for subgrids
1 parent e9591ce commit b4903f9

6 files changed

Lines changed: 253 additions & 11 deletions

File tree

‎devito/mpi/distributed.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,41 @@ def parent(self):
567567
"""The parent distributor of this SubGridDistributor."""
568568
return self._parent
569569

570+
@property
571+
def neighborhood(self):
572+
"""
573+
As in `Distributor.neighborhood`, but skipping the MPI ranks owning no
574+
subsampled points: a rank between two populated ones may be empty, in
575+
which case the halo must come from the next populated rank. The empty
576+
ranks have no neighbours.
577+
"""
578+
# A rank is empty along `d` if its coordinate is, irrespective of the others
579+
populated = [[c for c, i in enumerate(dec) if len(i) > 0]
580+
for dec in self.decomposition]
581+
582+
ret = {}
583+
for i in product([LEFT, CENTER, RIGHT], repeat=self.ndim):
584+
neighbor = []
585+
for c, s, p in zip(self.mycoords, i, populated, strict=True):
586+
if s is LEFT:
587+
neighbor.append(max((j for j in p if j < c), default=None))
588+
elif s is RIGHT:
589+
neighbor.append(min((j for j in p if j > c), default=None))
590+
else:
591+
neighbor.append(c)
592+
593+
if self.loc_empty or None in neighbor:
594+
ret[i] = MPI.PROC_NULL
595+
else:
596+
ret[i] = self.comm.Get_cart_rank(neighbor)
597+
598+
# The neighbours along `d` are the diagonal ones with CENTER elsewhere
599+
for n, d in enumerate(self.dimensions):
600+
ret[d] = {s: ret[tuple(s if m == n else CENTER for m in range(self.ndim))]
601+
for s in (LEFT, RIGHT)}
602+
603+
return ret
604+
570605

571606
class SubDistributor(DenseDistributor):
572607

‎devito/operations/interpolators.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -297,15 +297,15 @@ def _rdim(self, subdomain=None, shifts=None):
297297
# If the interpolation operation is limited to a SubDomain,
298298
# use the SubDimensions of that SubDomain
299299
if subdomain:
300-
gdims = tuple(subdomain.dimension_map[d] for d in self._gdims)
300+
gdims = tuple(subdomain.dimension_map[d.root] for d in self._gdims)
301301
else:
302302
gdims = self._gdims
303303

304304
# Make radius dimension conditional to avoid OOB
305305
rdims = []
306306
pos = self.sfunction._position_map(shifts=shifts).values()
307307

308-
for (d, rd, p) in zip(gdims, self._cdim, pos, strict=True):
308+
for (d, gd, rd, p) in zip(gdims, self._gdims, self._cdim, pos, strict=True):
309309
# Add conditional to avoid OOB
310310
lb = sympy.And(rd + p >= d.symbolic_min - self.r, evaluate=False)
311311
ub = sympy.And(rd + p <= d.symbolic_max + self.r, evaluate=False)
@@ -318,7 +318,7 @@ def _rdim(self, subdomain=None, shifts=None):
318318
rank_populated = subdomain.distributor.rank_populated
319319
cond = sympy.And(rank_populated, cond)
320320

321-
rdims.append(self.sfunction._cond_rdim(d.root, cond))
321+
rdims.append(self.sfunction._cond_rdim(gd, cond))
322322

323323
return DimensionTuple(*rdims, getters=gdims)
324324

@@ -456,8 +456,8 @@ def _interp_idx(self, variables, implicit_dims=None, subdomain=None,
456456
# Index substitution to make in variables
457457
subs = {
458458
ki: c + p
459-
for ((k, c), p) in zip(mapper.items(), pos, strict=True)
460-
for ki in {k, k.root}
459+
for ((k, c), gd, p) in zip(mapper.items(), self._gdims, pos, strict=True)
460+
for ki in {k, gd, k.root}
461461
}
462462

463463
idx_subs = {v: v.subs(subs) for v in variables}

‎devito/passes/clusters/aliases.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,8 @@ def lower_aliases(aliases, meta, opt_maxpar, opt_block_temps):
754754
intervals[d] = i
755755
continue
756756

757-
assert not d.is_NonlinearDerived
757+
# Only a subsampled Dimension may be iterated over, e.g. a SubGrid's
758+
assert not d.is_NonlinearDerived or d.is_Conditional
758759

759760
# `d` is necessarily part of the write-to region, so we have to
760761
# 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):
772773
intervals[d] = interval
773774
else:
774775
pd = d.parent
775-
writeto.append(interval.relaxed)
776+
writeto.append(_relaxed(interval))
776777
# The lower/upper bounds belong to the parent BlockDimension
777778
intervals[d] = interval.zero()
778779
intervals[pd] = interval.switch(pd)
779780
else:
780-
writeto.append(interval.relaxed)
781+
writeto.append(_relaxed(interval))
781782
intervals[d] = interval
782783

783784
di = sub_iterators.get(d, d)
@@ -821,6 +822,20 @@ def lower_aliases(aliases, meta, opt_maxpar, opt_block_temps):
821822
return Schedule(*processed, dmapper=dict(dmapper), is_frame=aliases.is_frame)
822823

823824

825+
def _relaxed(interval):
826+
"""
827+
Relax `interval` to its root Dimension or, if iterating over a subsampled
828+
Dimension (e.g., a SubGrid's after `subsampling`), to that Dimension, which
829+
spans its own index space.
830+
"""
831+
d = interval.dim
832+
while d.is_Derived and not d.is_Conditional:
833+
d = d.parent
834+
if d.is_Conditional:
835+
return interval.switch(d)
836+
return interval.relaxed
837+
838+
824839
def make_variant(schedule, exprs, mapper):
825840
"""
826841
Create a Variant from a Schedule and the corresponding expressions.

‎devito/types/basic.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1439,7 +1439,15 @@ def indexify(self, indices=None, subs=None):
14391439

14401440
# Substitution for each index (spacing only used in own dimension)
14411441
subs = subs or {}
1442-
subs = [{**{d.spacing: 1, -d.spacing: -1}, **subs} for d in self.dimensions]
1442+
mappers = []
1443+
for d in self.dimensions:
1444+
mapper = {d.spacing: 1, -d.spacing: -1}
1445+
# A subsampled Dimension's spacing is a multiple of its root's, e.g.
1446+
# `2*h_x`, so rescale the root's instead to also map `4*h_x` to `2`
1447+
if d.spacing != d.root.spacing and d.root.spacing.is_Symbol:
1448+
mapper[d.root.spacing] = d.root.spacing/d.spacing
1449+
mappers.append({**mapper, **subs})
1450+
subs = mappers
14431451

14441452
# Indices after substitutions
14451453
indices = []

‎devito/types/grid.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,12 @@ def __factors_setup__(cls, parent, factor):
586586
if f < 1:
587587
raise ValueError(f"Subsampling factor must be >= 1, got `{f}`")
588588

589+
for d, n, f in zip(parent.dimensions, parent.shape, factors, strict=True):
590+
if f > 1 and f >= n:
591+
raise ValueError(f"Subsampling factor `{f}` leaves a single point "
592+
f"along `{d}`, so it must be smaller than its "
593+
f"size `{n}`")
594+
589595
return tuple(int(f) for f in factors)
590596

591597
@classmethod

‎tests/test_subsampling.py‎

Lines changed: 180 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77

88
from devito import (
99
Buffer, CondEq, ConditionalDimension, Constant, Eq, Function, Grid, Inc, Operator,
10-
SpaceDimension, SubDomain, SubGrid, TimeFunction, switchconfig
10+
PrecomputedSparseFunction, SpaceDimension, SparseFunction, SubDomain, SubGrid,
11+
TimeFunction, switchconfig
1112
)
12-
from devito.ir.iet import Conditional, Expression, FindNodes, Iteration
13+
from devito.ir.iet import Conditional, Expression, FindNodes, FindSymbols, Iteration
14+
from devito.mpi import MPI
1315
from devito.symbolics import retrieve_indexed
1416
from devito.tools import as_tuple
1517
from devito.types.dimension import SubsamplingOffset
@@ -841,11 +843,109 @@ def test_derivative_numerics(self):
841843

842844
assert np.allclose(d.data[1:-1, 1:-1], 3., atol=1e-4)
843845

846+
@pytest.mark.parametrize('so', [4, 8])
847+
@pytest.mark.parametrize('shape,factor,opt', [
848+
((33, 33), 2, 'noop'),
849+
((33, 33), 2, 'advanced'),
850+
((33, 33), (2, 3), 'advanced'),
851+
((33, 33), (2, 3), ('advanced', {'blockrelax': True})),
852+
((17, 17, 17), (2, 2, 4), 'advanced'),
853+
])
854+
def test_high_order_derivatives(self, so, shape, factor, opt):
855+
"""
856+
Stencils reaching beyond the adjacent SubGrid points match those on a
857+
plain Grid of the same shape and extent, also once CIRE kicks in.
858+
"""
859+
sub = SubGrid(Grid(shape=shape), factor=factor)
860+
plain = Grid(shape=sub.shape, extent=sub.extent)
861+
862+
results = []
863+
for grid, o in ((sub, opt), (plain, 'noop')):
864+
u = Function(name='u', grid=grid, space_order=so)
865+
v = Function(name='v', grid=grid, space_order=so)
866+
u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.)
867+
868+
op = Operator(Eq(v, u.laplace + u.dx.dy), opt=o)
869+
op.apply()
870+
results.append(np.array(v.data))
871+
872+
if grid is sub and opt != 'noop':
873+
assert any(i.is_Array for i in FindSymbols().visit(op))
874+
875+
assert np.abs(results[0] - results[1]).max() <= 1e-6*np.abs(results[1]).max()
876+
877+
@pytest.mark.parametrize('opt', [
878+
'noop', 'advanced',
879+
('advanced', {'blockrelax': True, 'cire-block-temps': False}),
880+
])
881+
def test_subdomain_high_order(self, opt):
882+
"""As above, for Functions on a SubDomain of the SubGrid."""
883+
sub = SubGrid(Grid(shape=(33, 33)), factor=2)
884+
plain = Grid(shape=sub.shape, extent=sub.extent)
885+
886+
results = []
887+
for grid, o in ((sub, opt), (plain, 'noop')):
888+
middle = Middle(grid=grid)
889+
u = Function(name='u', grid=middle, space_order=4)
890+
v = Function(name='v', grid=middle, space_order=4)
891+
u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.)
892+
893+
Operator(Eq(v, u.laplace + u.dx.dy), opt=o).apply()
894+
results.append(np.array(v.data))
895+
896+
assert np.abs(results[0] - results[1]).max() <= 1e-6*np.abs(results[1]).max()
897+
898+
@pytest.mark.parametrize('interpolation', ['linear', 'sinc', 'precomputed'])
899+
@pytest.mark.parametrize('subdomain', [False, True])
900+
def test_sparse_matches_plain(self, interpolation, subdomain):
901+
"""
902+
Interpolation and injection on a SubGrid match those on a plain Grid of
903+
the same shape and extent, including in the last cell and at the corners.
904+
"""
905+
sub = SubGrid(Grid(shape=(33, 33), extent=(32., 32.)), factor=2)
906+
plain = Grid(shape=sub.shape, extent=sub.extent)
907+
coords = np.array([[5., 5.], [12.5, 5.], [29., 29.], [31.9, 7.],
908+
[32., 32.], [32., 5.], [0., 0.]])
909+
npoint = len(coords)
910+
911+
results = []
912+
for grid in (sub, plain):
913+
target = Middle(grid=grid) if subdomain else grid
914+
u = Function(name='u', grid=target, space_order=4)
915+
v = Function(name='v', grid=target, space_order=4)
916+
u.data[:] = np.sin(np.arange(u.data.size).reshape(u.shape)/7.)
917+
918+
if interpolation == 'precomputed':
919+
gridpoints = np.minimum(coords // np.array(grid.spacing),
920+
np.array(grid.shape) - 2).astype(np.int32)
921+
coeffs = np.random.default_rng(0).uniform(size=(npoint, 2, 2))
922+
kwargs = {'r': 2, 'gridpoints': gridpoints,
923+
'interpolation_coeffs': coeffs.astype(np.float32)}
924+
sf = PrecomputedSparseFunction
925+
else:
926+
kwargs = {'coordinates': coords, 'interpolation': interpolation,
927+
'r': 2, 'space_order': 4}
928+
sf = SparseFunction
929+
930+
s = sf(name='s', grid=grid, npoint=npoint, **kwargs)
931+
Operator(s.interpolate(u)).apply()
932+
results.append(np.array(s.data))
933+
934+
s.data[:] = np.arange(1, npoint + 1)
935+
Operator(s.inject(v, expr=s)).apply()
936+
results.append(np.array(v.data))
937+
938+
assert np.array_equal(results[0], results[2])
939+
assert np.array_equal(results[1], results[3])
940+
844941
@pytest.mark.parametrize('factor,err', [
845942
(0, 'must be >= 1'),
846943
(-1, 'must be >= 1'),
847944
(2.5, 'Non-integer'),
848945
((2, 2, 2), 'Expected 1 or 2 factors'),
946+
(9, 'single point'),
947+
(10, 'single point'),
948+
((2, 9), 'single point'),
849949
])
850950
def test_invalid_factor(self, factor, err):
851951
grid = Grid(shape=(9, 9))
@@ -1377,6 +1477,84 @@ def test_conditional_dimension_built_without_mpi(self, mode):
13771477

13781478
assert np.all(g.data == np.arange(0, 21, 2)[g.local_indices])
13791479

1480+
@pytest.mark.parallel(mode=[(4, 'basic'), (4, 'diag2'), (4, 'full')])
1481+
@pytest.mark.parametrize('shape,topology,factor', [
1482+
((16, 24), (1, 4), (1, 10)),
1483+
((24, 24), (4, 1), (10, 1)),
1484+
((12, 16), (4, 1), (6, 1)),
1485+
])
1486+
def test_empty_ranks(self, mode, shape, topology, factor):
1487+
"""
1488+
The halo of a rank next to one owning no SubGrid points comes from the
1489+
next populated rank, diagonals included.
1490+
"""
1491+
grid = Grid(shape=shape, topology=topology)
1492+
sub = SubGrid(grid, factor=factor)
1493+
t = sub.stepping_dim
1494+
x, y = sub.dimensions
1495+
1496+
assert any(len(i) == 0 for d in sub.distributor.decomposition for i in d)
1497+
1498+
u = TimeFunction(name='u', grid=sub, space_order=1)
1499+
glob = np.sin(np.arange(np.prod(sub.shape)).reshape(sub.shape))
1500+
u.data[0] = glob
1501+
1502+
Operator(Eq(u.forward, u[t, x + 1, y] + u[t, x - 1, y + 1]
1503+
+ 2*u[t, x, y - 1])).apply(time_M=0)
1504+
1505+
# The empty ranks have nothing to check, and `local_indices` would give
1506+
# them `slice(0, -1)`
1507+
if not sub.distributor.loc_empty:
1508+
padded = np.pad(glob, 1)
1509+
expected = padded[2:, 1:-1] + padded[:-2, 2:] + 2*padded[1:-1, :-2]
1510+
assert np.allclose(np.asarray(u.data[1]), expected[u.local_indices[1:]])
1511+
1512+
@pytest.mark.parallel(mode=[4])
1513+
def test_sparse_empty_ranks(self, mode):
1514+
"""Sparse operations with ranks owning no SubGrid points."""
1515+
grid = Grid(shape=(24, 24), extent=(23., 23.), topology=(4, 1))
1516+
sub = SubGrid(grid, factor=(10, 1))
1517+
coords = np.random.default_rng(0).uniform(size=(20, 2))*np.array(sub.extent)
1518+
xx, yy = np.meshgrid(*[np.arange(n)*h for n, h in
1519+
zip(sub.shape, sub.spacing, strict=True)],
1520+
indexing='ij')
1521+
1522+
u = Function(name='u', grid=sub)
1523+
v = Function(name='v', grid=sub)
1524+
u.data[:] = xx + 10*yy
1525+
s = SparseFunction(name='s', grid=sub, npoint=len(coords), coordinates=coords)
1526+
1527+
# Linear interpolation is exact on a linear field
1528+
Operator(s.interpolate(u)).apply()
1529+
expected = coords[:, 0] + 10*coords[:, 1]
1530+
assert np.allclose(np.asarray(s.data), expected[s.local_indices], rtol=1e-5)
1531+
1532+
# The linear weights sum to one, so injection conserves the total
1533+
s.data[:] = 1.
1534+
Operator(s.inject(v, expr=s)).apply()
1535+
total = grid.distributor.comm.allreduce(float(np.sum(v.data)))
1536+
assert np.isclose(total, len(coords))
1537+
1538+
@pytest.mark.parallel(mode=[(2, 'basic'), (4, 'diag2')])
1539+
def test_high_order_mpi(self, mode):
1540+
"""High-order stencils on a SubGrid match a serial plain Grid."""
1541+
sub = SubGrid(Grid(shape=(33, 33)), factor=2)
1542+
plain = Grid(shape=sub.shape, extent=sub.extent, comm=MPI.COMM_SELF)
1543+
1544+
glob = np.sin(np.arange(np.prod(sub.shape)).reshape(sub.shape)/7.)
1545+
1546+
vs = []
1547+
for grid in (sub, plain):
1548+
u = Function(name='u', grid=grid, space_order=4)
1549+
v = Function(name='v', grid=grid, space_order=4)
1550+
u.data[:] = glob
1551+
1552+
Operator(Eq(v, u.laplace + u.dx.dy)).apply()
1553+
vs.append(v)
1554+
1555+
v, expected = vs[0], np.asarray(vs[1].data)[vs[0].local_indices]
1556+
assert np.abs(np.asarray(v.data) - expected).max() <= 1e-6*np.abs(expected).max()
1557+
13801558

13811559
class TestIncReduction:
13821560

0 commit comments

Comments
 (0)