Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
254b518
mpi: Preserve empty overlap regions during alignment
FabioLuporini Nov 18, 2026
578f61b
compiler: Use DimensionTuple for grid.origin_isymbols
FabioLuporini Nov 20, 2026
f515f91
compiler: Stop overlap2 at the first empty OWNED region
FabioLuporini Nov 23, 2026
ca72ed4
profiling: Measure the host time loop for performance without setup
FabioLuporini Nov 23, 2026
c180154
profiling: Keep time-loop accounting in the profiler
FabioLuporini Nov 23, 2026
954cada
profiling: Locate the stepping region after helper calls are rebuilt
FabioLuporini Nov 23, 2026
cf12071
profiling: Instrument the host loop independently of section hooks
FabioLuporini Nov 23, 2026
d96b640
profiling: Time the span of host stepping loops independently of sect…
FabioLuporini Nov 23, 2026
a9a6853
profiling: Find the host stepping span from iteration trees
FabioLuporini Nov 24, 2026
5e7730d
profiling: Instrument a single time loop directly
FabioLuporini Nov 24, 2026
76784a1
profiling: Name the selected iteration time_loop
FabioLuporini Nov 24, 2026
b0e64a1
mpi: Alias overlap3 to the overlap2 builder in OSS
FabioLuporini Nov 24, 2026
4429dca
mpi: Support native overlap3 halo builders
FabioLuporini Nov 24, 2026
a1ec76e
tests: Simplify the physical faces MPI regression
FabioLuporini Nov 24, 2026
e6c4de1
profiling: Preserve the autotuning timer type
FabioLuporini Nov 24, 2026
6e3d9a9
mpi: Explain neighbor-dependent CORE bounds
FabioLuporini Nov 24, 2026
ddbc175
mpi: Restore overlap2 regions and fix the profiling mock
FabioLuporini Nov 25, 2026
921d178
mpi: Hook overlap region and remainder construction
FabioLuporini Nov 25, 2026
5bd6e65
mpi: Rename the overlap region object hook
FabioLuporini Nov 25, 2026
53315e8
mpi: Pack empty OWNED regions last
FabioLuporini Nov 25, 2026
d4f44b0
mpi: Use runtime neighbor bounds in overlap2
FabioLuporini Nov 25, 2026
330f6b0
mpi: Share runtime region binding across overlap modes
FabioLuporini Nov 25, 2026
041ecc5
mpi: Inline overlap region construction
FabioLuporini Nov 25, 2026
b2d2ada
mpi: Document runtime region argument packing
FabioLuporini Nov 25, 2026
ac6c9fe
compiler: Represent sparse injection with LocalScatter
FabioLuporini Nov 26, 2026
26ad428
mpi: Use synchronous halo exchange for SubDomain Functions
FabioLuporini Nov 26, 2026
411aab5
fix: account for runtime staging arrays in lazy memory estimates
FabioLuporini Nov 27, 2026
8abdeef
fix: estimate irregular arrays from their maximum byte size
FabioLuporini Nov 27, 2026
9233059
fix: include estimable irregular arrays in the memory budget
FabioLuporini Nov 27, 2026
4ac1b1b
fix: estimate array memory at allocation sites
FabioLuporini Nov 27, 2026
292b778
fix: scope Operator memory estimates to the entry body
FabioLuporini Nov 27, 2026
d80e2ab
mpi: Share C struct generation and MPI constants
FabioLuporini Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,9 @@ Notes:
* The first line shows the total runtime of the Operator, including Python overhead, transition into executing the JIT-compiled binary, and any CPU-GPU data transfers.

* The two "Global performance" lines differ as follows: the <w/o setup> version excludes overhead (e.g., CPU-GPU data transfers) and better reflects actual compute performance, since such overheads are easily amortized way in production-grade runs when a simulation is executed over hundreds/thousands of timesteps.
With the native advanced profiler, a timer spans the time loop and MPI uses the longest
elapsed time across ranks. For Operators without a time loop, Devito adds the longest
rank time for each section.

* The "Local performance" section provides a breakdown by code section. These sections are determined by the Devito compiler based on internal heuristics. Typically, loops related to finite-difference evaluation are grouped together, while operations such as source injection or receiver interpolation are placed in separate sections.

Expand Down
6 changes: 5 additions & 1 deletion devito/core/autotuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ def autotune(operator, args, level, mode):
return args, {}

# Use a fresh Timer for auto-tuning
timer = Timer('timers', list(operator._profiler.all_sections))
timer = next((p for p in operator.parameters if isinstance(p, Timer)), None)
if timer is None:
return args, {}

timer = timer._rebuild()
at_args.update(timer._arg_values())

# Perform autotuning
Expand Down
39 changes: 39 additions & 0 deletions devito/finite_differences/differentiable.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
'Imag',
'IndexDerivative',
'IndexDerivativeProperty',
'LocalScatter',
'LocalSum',
'Real',
'Weights',
Expand Down Expand Up @@ -1109,6 +1110,44 @@ def _evaluate(self, **kwargs):
__reduce_ex__ = Pickable.__reduce_ex__


class LocalScatter(sympy.Expr, Evaluable, Pickable):

"""
A contribution to an indexed increment over a sparse footprint.

`dimensions` lists the sparse point axis followed by the support axes.
The enclosing increment provides the destination, iteration space and guards.
"""

__rargs__ = ('expr',)
__rkwargs__ = ('dimensions',)

is_commutative = True

def __new__(cls, expr, dimensions, **kwargs):
obj = sympy.Expr.__new__(cls, expr)
obj._dimensions = as_tuple(dimensions)
return obj

@property
def expr(self):
return self.args[0]

@property
def dimensions(self):
return self._dimensions

@cached_property
def dtype(self):
return extract_dtype(self.expr)

def _hashable_content(self):
return super()._hashable_content() + (self.dimensions,)

func = Evaluable._rebuild
__reduce_ex__ = Pickable.__reduce_ex__


class WeightsIndexed(Indexed):

@property
Expand Down
22 changes: 9 additions & 13 deletions devito/ir/clusters/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,22 +864,18 @@ def _normalize_reductions_dense(cluster, mapper, sregistry, platform):
@cluster_pass(mode='sparse')
def normalize_reductions_sparse(cluster, sregistry):
"""
Extract the right-hand sides of reduction Eq's in to temporaries.
Compute each indexed reduction's contribution in a scalar temporary.

Local scatters materialize the temporary when their layout is lowered.
"""
processed = []
for e in cluster.exprs:
if e.is_Reduction and e.lhs.is_Indexed:
# Transform `e` such that we reduce into a scalar (ultimately via
# atomic ops, though this part is carried out by a much later pass)
# For example, given `i = m[p_src]` (i.e., indirection array), turn:
# `u[t, i] += f(u[t, i], src, ...)`
# into
# `s = f(u[t, i], src, ...)`
# `u[t, i] += s`
name = sregistry.make_name()
v = Symbol(name=name, dtype=e.dtype)
processed.extend([e.func(v, e.rhs, operation=None),
e.func(e.lhs, v)])
if e.is_Reduction and \
e.lhs.is_Indexed and \
not e.local_scatters:
temp = Symbol(name=sregistry.make_name(), dtype=e.dtype)
processed.extend([e.func(temp, e.rhs, operation=None),
e.func(e.lhs, temp)])
else:
processed.append(e)

Expand Down
9 changes: 9 additions & 0 deletions devito/ir/clusters/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,11 @@ def local_sums(self):
"""
return tuple(s for e in self.exprs for s in e.local_sums)

@cached_property
def local_scatters(self):
"""The sparse contributions on indexed updates in this cluster."""
return tuple(s for e in self.exprs for s in e.local_scatters)

@cached_property
def scope(self):
return Scope(self.exprs)
Expand Down Expand Up @@ -694,6 +699,10 @@ def exprs(self):
def local_sums(self):
return tuple(s for c in self for s in c.local_sums)

@cached_property
def local_scatters(self):
return tuple(s for c in self for s in c.local_scatters)

@cached_property
def scope(self):
return Scope(exprs=self.exprs)
Expand Down
7 changes: 6 additions & 1 deletion devito/ir/equations/equation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import numpy as np
import sympy

from devito.finite_differences.differentiable import LocalSum, diff2sympy
from devito.finite_differences.differentiable import LocalScatter, LocalSum, diff2sympy
from devito.ir.equations.algorithms import dimension_sort, generate_conditionals
from devito.ir.support import (
Interval, IntervalGroup, IterationSpace, Stencil, bounded, detect_accesses
Expand Down Expand Up @@ -56,6 +56,11 @@ def local_sums(self):
"""The local sums in dependency order, with nested sums first."""
return tuple(filter_ordered(search(self, LocalSum, mode='all')))

@cached_property
def local_scatters(self):
"""The local scatter carried by this indexed update, if any."""
return (self.rhs,) if isinstance(self.rhs, LocalScatter) else ()

@property
def implicit_dims(self):
return self._implicit_dims
Expand Down
16 changes: 7 additions & 9 deletions devito/ir/iet/visitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
GenericVisitor, as_tuple, c_restrict_void_p, filter_ordered, filter_sorted, flatten,
is_external_ctype, natural_sort_key
)
from devito.tools.cgen import make_struct
from devito.types import (
ArrayObject, CompositeObject, DeviceMap, Dimension, IndexedData, Pointer
)
Expand Down Expand Up @@ -274,9 +275,7 @@ def _restrict_keyword(self):
return self.printer._restrict_keyword

def _gen_struct_decl(self, obj, masked=()):
"""
Convert ctypes.Struct -> cgen.Structure.
"""
"""Build the C declaration for an object's ctypes structure."""
ctype = obj._C_ctype
try:
while issubclass(ctype, ctypes._Pointer):
Expand All @@ -286,16 +285,15 @@ def _gen_struct_decl(self, obj, masked=()):
issubclass(ctype, NoDeclStruct):
return None
except TypeError:
# E.g., `ctype` is of type `dtypes_lowering.CustomDtype`
return None
# A backend-defined aggregate may provide its own declaration.
return getattr(obj, '_C_typedecl', None)

try:
return obj._C_typedecl
except AttributeError:
pass

# Most of the times we end up here -- a generic procedure to
# automatically derive a cgen.Structure from the object _C_ctype
# Derive the declaration from the object's ctypes fields.

try:
fields = obj.fields
Expand All @@ -310,9 +308,9 @@ def _gen_struct_decl(self, obj, masked=()):
cstr = self.ccode(ct)
if ct is c_restrict_void_p:
cstr = f'{cstr}{self._restrict_keyword}'
entries.append(c.Value(cstr, n))
entries.append((cstr, n))

return c.Struct(ctype.__name__, entries)
return make_struct(ctype.__name__, entries)

def _gen_value(self, obj, mode=1, masked=()):
"""
Expand Down
14 changes: 11 additions & 3 deletions devito/mpi/distributed.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from math import ceil, pow

import numpy as np
from cgen import Struct, Value
from sympy import Interval, factorint

from devito.data import CENTER, LEFT, RIGHT, Decomposition
Expand All @@ -15,6 +14,7 @@
EnrichedTuple, as_tuple, ctypes_to_cstr, filter_ordered, frozendict, is_integer,
memoized_meth
)
from devito.tools.cgen import make_struct
from devito.types import CompositeObject, Constant, Object
from devito.types.utils import DimensionTuple, GlobalLocal

Expand Down Expand Up @@ -961,6 +961,14 @@ def entries(self):
def neighborhood(self):
return self._neighborhood

@cached_property
def face_neighbors(self):
"""
Face ranks indexed by root dimension name and side.
"""
return {d.root.name: ranks for d, ranks in self.neighborhood.items()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Frozendict?

if not isinstance(d, tuple)}

@cached_property
def _C_typedecl(self):
# Overriding for better code readability
Expand All @@ -976,8 +984,8 @@ def _C_typedecl(self):
# With this override, we generate the one on the right
groups = [list(g) for k, g in groupby(self.pfields, key=lambda x: x[0][0])]
groups = [(j[0], i) for i, j in [zip(*g, strict=True) for g in groups]]
return Struct(self.pname, [Value(ctypes_to_cstr(i), ', '.join(j))
for i, j in groups])
return make_struct(self.pname, ((ctypes_to_cstr(i), ', '.join(j))
for i, j in groups))

def _arg_defaults(self):
values = super()._arg_defaults()
Expand Down
35 changes: 26 additions & 9 deletions devito/mpi/halo_scheme.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ def union(self, other):
OMapper = namedtuple('OMapper', 'core owned')


class HasNeighbor(sympy.Function):

"""
Flag indicating whether a receive can cross this root bound.

MPIRegion binds it from the runtime Grid's neighborhood when packing bounds.
"""

nargs = 1
is_integer = True
is_nonnegative = True


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this just be extracted from MPINeighbourhood?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I simplified everything now, take a new look, but short answer yes

class HaloScheme:

"""
Expand Down Expand Up @@ -261,6 +274,8 @@ def omapper(self):

The computed OMapper takes into account:

* The receive neighbors on the runtime Grid. CORE extends to faces
with no neighbor.
* The offsets induced by SubDomains/SubDimensions ("thickness");
* Any data alignment requirement of the underlying expressions
(`_alignment` attribute).
Expand All @@ -280,7 +295,7 @@ def omapper(self):
In this example, the "cumulative" OWNED size is (left=4, right=4), that is
the max on each DataSide across all Functions, namely ``u`` and ``v``.

The ``omapper`` will contain the following entries:
For a rank with neighbors on both sides, the bounds are:

[(((d, CORE, CENTER),), {d: (d_m + 4, d_M - 4)}),
(((d, OWNED, LEFT),), {d: (d_m, min(d_m + 3, d_M))}),
Expand Down Expand Up @@ -362,13 +377,12 @@ def omapper(self):
the max point is ``d_M = 1``, which implies that there is exactly one
point in this region, and this point is redundantly computed as it's
logically the same as that in the (OWNED, LEFT) region.

Notes
-----
For each Function, the '^' and 'o' are exactly the same on *all MPI
ranks*, so the output of this method is guaranteed to be consistent
across *all MPI ranks*.
"""
owned_size = {
d: (left * HasNeighbor(d.root.symbolic_min),
right * HasNeighbor(d.root.symbolic_max))
for d, (left, right) in self.owned_size.items()
}
items = [((d, CENTER), (d, LEFT), (d, RIGHT))
for d in filter_sorted(self.dimensions)]

Expand All @@ -377,7 +391,7 @@ def omapper(self):
where = []
mapper = {}
for d, s in item:
osl, osr = self.owned_size[d]
osl, osr = owned_size[d]

# Handle SubDomain/SubDimensions to-honor offsets
nl = Max(0, *[i for i, _ in self.honored.get(d, [])])
Expand Down Expand Up @@ -437,7 +451,10 @@ def omapper(self):
except KeyError:
continue

aligned_m = IntDiv(m, self._alignment) * self._alignment
# Preserve empty regions when rounding down a start index
aligned_m = sympy.Piecewise(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is Piecewise needed here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's a bug fix: empty regions have inverted bounds. For example, rounding the start of [2, 1] down to a multiple of four would turn it into [0, 1], causing two iterations. Piecewise preserves the inverted bounds in that case.

(IntDiv(m, self._alignment) * self._alignment, m <= M), (m, True)
)

processed[i] = (where, frozendict({**mapper, fvd: (aligned_m, M)}))

Expand Down
Loading
Loading