Skip to content

Commit 661aabc

Browse files
committed
mpi: Simplify sparse support rank mapping
Derive tensor support bounds directly from the radius and keep cell geometry in the interpolator. Preserve the interval optimization and test separate staggered support boxes.
1 parent ab971ff commit 661aabc

4 files changed

Lines changed: 61 additions & 44 deletions

File tree

‎devito/operations/interpolators.py‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,18 @@ def grid(self):
244244
def r(self):
245245
return self.sfunction.r
246246

247+
@property
248+
def _support_indices(self):
249+
"""Base cells for every staggering used by the sparse operations."""
250+
if not self._shifts_used:
251+
return [self.sfunction._coords_indices]
252+
253+
# Redistribution must use the same fp64 cells as the interpolation tables
254+
spacing, origin = self.grid._spacing_fp64, self.grid._origin_fp64
255+
return [_cell_indices(self.sfunction.coordinates_data, self.grid,
256+
shift, spacing, origin)
257+
for shift in self._shifts_used]
258+
247259
@cached_property
248260
def _coeff_dtype(self):
249261
# Weights are real even for complex-valued sparse fields.
@@ -398,11 +410,10 @@ def _arg_defaults(self, coords=None, sfunc=None, origin=None):
398410
if coords is None or sfunc is None:
399411
raise ValueError("No coordinates or sparse function provided")
400412

401-
# Fp64 grid geometry -- avoids fp32 rounding on cell boundaries.
402413
grid = sfunc.grid
403-
spacing = np.array([as_fp64_decimal(h) for h in grid.spacing])
404-
origin = np.array([as_fp64_decimal(o)
405-
for o in (origin or grid.origin)])
414+
spacing = grid._spacing_fp64
415+
origin = (np.array([as_fp64_decimal(o) for o in origin])
416+
if origin is not None else grid._origin_fp64)
406417

407418
args = {}
408419
for key in self._shifts_used or {None}:
@@ -654,15 +665,6 @@ class Coeffs(_HostTable):
654665
"""Per-dim interpolation weights, shape ``(npoint, 2*r)``."""
655666

656667

657-
def _resolved_geometry(grid, kwargs):
658-
"""Fp64 (spacing, origin) tuple honoring runtime `h_x`/`o_x`/... overrides."""
659-
spacing = np.array([as_fp64_decimal(kwargs.get(s.name, v)) for s, v
660-
in zip(grid.spacing_symbols, grid.spacing, strict=True)])
661-
origin = np.array([as_fp64_decimal(kwargs.get(o.name, v)) for o, v
662-
in zip(grid.origin_symbols, grid.origin, strict=True)])
663-
return spacing, origin
664-
665-
666668
def _positions_fp64(coords, grid, shifts, spacing, origin):
667669
"""Fp64 fractional grid position `(c - o - shift)/h` for each sparse point,
668670
computed in double precision to avoid boundary-crossing rounding errors

‎devito/types/grid.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from devito.finite_differences.elementary import Max, Min
1313
from devito.logger import warning
1414
from devito.mpi import MPI, Distributor, SubDistributor
15-
from devito.tools import ReducerMap, as_tuple, frozendict, is_integer
15+
from devito.tools import ReducerMap, as_fp64_decimal, as_tuple, frozendict, is_integer
1616
from devito.types.args import ArgProvider
1717
from devito.types.basic import Scalar
1818
from devito.types.dense import Function
@@ -252,6 +252,11 @@ def origin(self):
252252
"""Physical coordinates of the domain origin."""
253253
return self._origin
254254

255+
@cached_property
256+
def _origin_fp64(self):
257+
"""Origin in fp64, preserving the grid's decimal values."""
258+
return np.array([as_fp64_decimal(o) for o in self.origin])
259+
255260
@property
256261
def origin_symbols(self):
257262
"""Symbols representing the grid origin in each SpaceDimension."""
@@ -313,6 +318,11 @@ def spacing(self):
313318
spacing = (np.array(self.extent) / (np.array(self.shape) - 1)).astype(self.dtype)
314319
return as_tuple(spacing)
315320

321+
@cached_property
322+
def _spacing_fp64(self):
323+
"""Spacing in fp64, preserving the grid's decimal values."""
324+
return np.array([as_fp64_decimal(h) for h in self.spacing])
325+
316326
@cached_property
317327
def spacing_symbols(self):
318328
"""Symbols representing the grid spacing in each SpaceDimension."""

‎devito/types/sparse.py‎

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@
1111
from devito.operations import (
1212
LinearInterpolator, NearestInterpolator, PrecomputedInterpolator, SincInterpolator
1313
)
14-
from devito.operations.interpolators import _cell_indices
1514
from devito.symbolics import indexify, retrieve_function_carriers
1615
from devito.tools import (
17-
ReducerMap, as_fp64_decimal, as_tuple, dtype_to_mpidtype, filter_ordered, flatten,
18-
is_integer, memoized_meth, prod
16+
ReducerMap, as_tuple, dtype_to_mpidtype, filter_ordered, flatten, is_integer,
17+
memoized_meth, prod
1918
)
2019
from devito.types.basic import Symbol
2120
from devito.types.dense import DiscreteFunction, SubFunction
@@ -300,15 +299,6 @@ def _coords_indices(self):
300299
np.floor((self.coordinates_data - self.grid.origin) / self.grid.spacing)
301300
).astype(int)
302301

303-
@property
304-
def _support_indices(self):
305-
# Staggered tables may use a different base cell across an MPI
306-
# boundary. Match their fp64 geometry and actual stencil support.
307-
spacing = np.array([as_fp64_decimal(h) for h in self.grid.spacing])
308-
origin = np.array([as_fp64_decimal(o) for o in self.grid.origin])
309-
return [_cell_indices(self.coordinates_data, self.grid, shift, spacing, origin)
310-
for shift in self.interpolator._shifts_used] or [self._coords_indices]
311-
312302
@property
313303
def _support(self):
314304
"""
@@ -317,34 +307,31 @@ def _support(self):
317307
"""
318308
max_shape = np.array(self.grid.shape).reshape(1, self.grid.dim)
319309
minmax = lambda arr: np.minimum(max_shape, np.maximum(0, arr))
320-
return np.stack([minmax(index + s) for index in self._support_indices
310+
return np.stack([minmax(index + s) for index in self.interpolator._support_indices
321311
for s in self._point_support], axis=2)
322312

323313
@property
324314
def _dist_datamap(self):
325315
"""
326316
Mapper ``M : MPI rank -> required sparse data``.
327317
"""
328-
offsets = self._point_support
329-
lower, upper = offsets.min(axis=0), offsets.max(axis=0)
330-
if (len(offsets) != prod(upper - lower + 1)
331-
or len(np.unique(offsets, axis=0)) != len(offsets)):
332-
return self.grid.distributor.glb_to_rank(self._support) or {}
333-
334-
# A tensor stencil intersects a Cartesian rank exactly when its
335-
# intervals intersect in every dimension. Keep different shifts
336-
# separate: their union need not be one rectangular stencil.
318+
# `_point_increments` is a tensor product: [-r+1, r], or [0, 0] for nearest
319+
lower, upper = min(1 - self.r, 0), self.r
320+
321+
# Optimization: avoid enumerating the stencil (e.g. 512 points for r=4 in 3D).
322+
# Keep each staggering's box separate: their union may have gaps.
337323
bounds = [(np.clip(index + lower, 0, self.grid.shape),
338324
np.clip(index + upper, 0, self.grid.shape))
339-
for index in self._support_indices]
325+
for index in self.interpolator._support_indices]
340326
ret = {}
341327
for rank, ranges in enumerate(self.grid.distributor.all_ranges):
342328
if any(not r for r in ranges):
343329
continue
344330
mins = np.array([r[0] for r in ranges])
345331
maxs = np.array([r[-1] for r in ranges])
346-
mask = np.zeros(bounds[0][0].shape[0], dtype=bool)
332+
mask = np.zeros(self.npoint, dtype=bool)
347333
for low, high in bounds:
334+
# Match every axis of a box; any used staggering can qualify
348335
mask |= ((low <= maxs) & (high >= mins)).all(axis=1)
349336
if mask.any():
350337
ret[rank] = np.flatnonzero(mask).tolist()

‎tests/test_mpi.py‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -938,9 +938,10 @@ class CoordSlowSparseFunction(SparseTimeFunction):
938938
@pytest.mark.parametrize('ndim', [1, 2, 3])
939939
@pytest.mark.parametrize('interpolation,radius',
940940
[('nearest', 0), ('linear', 1), ('sinc', 4)])
941-
def test_tensor_support_rank_intersections(self, mode, ndim, interpolation, radius):
942-
"""Compact intervals match every point of wide, shifted tensor stencils."""
941+
def test_rank_map_equivalence(self, mode, ndim, interpolation, radius):
942+
"""Send each point to every rank owning a cell in its interpolation stencil."""
943943
grid = Grid(shape=(9,)*ndim, extent=(1.,)*ndim)
944+
# Include partition boundaries and coordinates outside the global domain
944945
coordinates = np.array([[value + (axis % 2)*0.125 for axis in range(ndim)]
945946
for value in (-0.25, 0., 0.125, 0.49, 0.5, 0.875,
946947
1., 1.25)],
@@ -951,11 +952,11 @@ def test_tensor_support_rank_intersections(self, mode, ndim, interpolation, radi
951952
plain = Function(name='support_plain', grid=grid, space_order=8)
952953
shifted = Function(name='support_shifted', grid=grid, space_order=8,
953954
staggered=grid.dimensions)
954-
src.inject(field=plain, expr=src)
955-
src.inject(field=shifted, expr=src)
955+
Operator(src.inject(field=(plain, shifted), expr=src), name='SparseSupport')
956956

957-
exhaustive = grid.distributor.glb_to_rank(src._support) or {}
958-
assert src._dist_datamap == exhaustive
957+
# Reference: enumerate all stencil cells, including the half-cell shift
958+
expected = grid.distributor.glb_to_rank(src._support) or {}
959+
assert src._dist_datamap == expected
959960

960961
@pytest.mark.parallel(mode=[2, 4])
961962
@pytest.mark.parametrize('override', [False, True])
@@ -981,6 +982,23 @@ def test_staggered_injection_support(self, mode, override):
981982
total = MPI.COMM_WORLD.allreduce(float(np.asarray(u.data).sum()), op=MPI.SUM)
982983
assert np.isclose(total, 1, rtol=0, atol=1e-7)
983984

985+
@pytest.mark.parallel(mode=4)
986+
@pytest.mark.parametrize('interpolation', ['nearest', 'linear'])
987+
def test_staggered_support_union(self, mode, interpolation):
988+
grid = Grid(shape=(8, 8), extent=(7., 7.), topology=(2, 2))
989+
x, y = grid.dimensions
990+
u = Function(name='ux', grid=grid, space_order=2, staggered=x)
991+
v = Function(name='uy', grid=grid, space_order=2, staggered=y)
992+
src = SparseFunction(name='src', grid=grid, npoint=1,
993+
interpolation=interpolation)
994+
src.coordinates.data[:] = 4.
995+
Operator(src.inject(field=(u, v), expr=src), name='SparseSupportUnion')
996+
997+
# Boxing the union would also send the point to rank 0
998+
ranks = (1, 2) if interpolation == 'nearest' else (1, 2, 3)
999+
expected = {r: [0] for r in ranks} if src.npoint else {}
1000+
assert src._dist_datamap == expected
1001+
9841002

9851003
class TestOperatorSimple:
9861004

0 commit comments

Comments
 (0)