Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Changed

- `deposit`, `interpolate`, `owner` and `migrate` group the markers by patch with one sort
instead of a scan of all markers per patch, and `marker_counts` histograms only the finest
level and sums it into the coarser ones: the quadtree benchmark's cycle 20-27% faster
(with mpiarray's faster `CopyPlan`).
- `locate_points` (Pyccel) is about twice as fast (35.7 to 15.9 ns per point on a two-level
hierarchy of picnic's extraction case), with the same results: the cell on each level is the
finest cell divided by the level's span in double precision instead of Pyccel's integer floor
Expand Down
33 changes: 33 additions & 0 deletions benchmarks/quadtree/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,39 @@ the mean.
halos and regrid. It pays where the markers dominate (many markers per cell, the push of a
real simulation, many nodes). The 7 clusters cannot be balanced by any cut (2.2, 3.0).

## Per-patch costs, before and after (2026-11-25, later)

The same benchmark (now with an untimed first cycle: the compiled kernels load at their first
call, which the runs above counted in their first step, ~30 ms per step in the deposit), on
`devel` and with three changes: mpiarray builds a `CopyPlan` with array operations over the
copies (116 → 43 ms for the 4422 copies of 392 patches), `deposit`, `interpolate` and the
owners group the markers by patch with one sort instead of a scan of all markers per patch,
and `marker_counts` histograms the finest level once and sums it into the coarser ones.
Serial, median of 3 runs, ms per step:

| mesh | | tag | regrid | migrate | deposit | solver | solve | halos | gather | total |
|---|---|---|---|---|---|---|---|---|---|---|
| cluster | before | 107.1 | 12.4 | 20.4 | 32.1 | 112.3 | 5.9 | 5.6 | 31.2 | 327 |
| | after | 36.6 | 15.1 | 17.8 | 27.6 | 111.4 | 6.1 | 5.6 | 26.2 | 246 (−25%) |
| cluster, `max_patch_size=16` | before | 105.4 | 94.5 | 40.5 | 103.5 | 127.1 | 12.5 | 124.0 | 74.5 | 682 |
| | after | 35.1 | 78.8 | 29.8 | 76.9 | 124.5 | 12.8 | 101.3 | 51.7 | 511 (−25%) |
| quadtree, block 8 | before | 105.6 | 285.9 | 65.9 | 206.4 | 180.2 | 22.7 | 265.8 | 130.9 | 1263 |
| | after | 35.8 | 239.1 | 35.7 | 140.3 | 182.8 | 21.9 | 203.6 | 69.1 | 928 (−27%) |
| quadtree, block 16 | before | 106.5 | 83.9 | 39.1 | 96.8 | 136.2 | 12.7 | 72.3 | 73.6 | 621 |
| | after | 36.6 | 65.9 | 29.5 | 77.2 | 138.4 | 12.4 | 56.8 | 50.9 | 468 (−25%) |
| quadtree, block 32 | before | 103.3 | 25.9 | 29.4 | 63.8 | 208.0 | 12.1 | 31.3 | 50.9 | 525 |
| | after | 35.8 | 27.7 | 26.6 | 54.0 | 200.1 | 11.7 | 20.7 | 42.3 | 419 (−20%) |

- Tagging is three times faster everywhere (one histogram instead of one per level).
- Gather, migrate and deposit lose their scan per patch: blocks of 8 gather in 69 ms instead
of 131, migrate in 36 instead of 66.
- Halos and the regrid gain from the cheaper `CopyPlan` (blocks of 8: 266 → 204 and
286 → 239 ms).
- What is left with blocks of 8: the regrid (239 ms, mostly the transfer's geometry per
patch), the halos (204, the geometry of the patches that do not reuse theirs), the solver
setup (183, mostly the composite node numbering) and the deposit (140, of which ~65 the
schedule of `accumulate_halos`, built per hierarchy like the halos').

## Fixed on the way

The regrid's transfer compared every new patch with every old one of its level, and copied
Expand Down
12 changes: 12 additions & 0 deletions benchmarks/quadtree/bench_quadtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ def markers(step: int):
**options,
)

# one untimed cycle: the compiled kernels load at their first call
mx, my, mq = mesh.migrate(x, y, q, name="rho")
mesh.deposit(mx, my, mq, "rho")
mesh.accumulate_halos("rho")
field = "rho"
if args.solve:
solver = NodalPoisson(mesh)
solver.solve(solver.nodes.from_patches("rho"), potential="phi")
field = "phi"
mesh.exchange_halos(field)
mesh.interpolate(mx, my, field)

kept, patches, cells, held = [], [], [], []
previous = {(p.level, p.box) for p in mesh.patches if p.level}
for step in range(1, args.steps + 1):
Expand Down
31 changes: 24 additions & 7 deletions src/patchwork/mesh/hierarchy.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ def _gather_blocks(
_GATHER_TAG = 7311


def _by_patch(found: Any) -> Iterator[tuple[int, Any]]:
"""The markers of each patch: ``(patch number, their indices)``, in the order of the patches.

One stable sort of the patch numbers (``-1``, outside the domain, left out),
instead of a scan of all markers for every patch; the indices of a patch are
in increasing order.
"""
import numpy as np

if not found.size:
return
order = np.argsort(found, kind="stable")
ordered = found[order]
numbers, starts = np.unique(ordered, return_index=True)
ends = np.append(starts[1:], ordered.size)
for number, start, end in zip(numbers, starts, ends, strict=True):
if number >= 0:
yield int(number), order[start:end]


@dataclass
class Patch:
"""One rectangular patch; its box uses level-local, half-open cell indices.
Expand Down Expand Up @@ -1399,15 +1419,14 @@ def _owners(self, found: Any, cell: tuple[Any, ...], name: str) -> Any:
blocks = self._schedule("blocks", name, _gather_blocks)
patches = self.patches
result = np.full(found.shape, -1, dtype=np.int64)
for number in np.unique(found[found >= 0]):
members, replicated = blocks[int(number)]
for number, chosen in _by_patch(found):
members, replicated = blocks[number]
if replicated:
raise ValueError(
f"field {name!r} is replicated (split=None) on the several ranks "
f"of the level-{patches[number].level} patch {patches[number].box}: "
"a point has no owner; allocate it with split=0"
)
chosen = np.flatnonzero(found == number)
local = [
c[chosen] - lo
for c, (lo, _) in zip(cell, patches[number].box, strict=True)
Expand Down Expand Up @@ -1663,8 +1682,7 @@ def deposit(
for patch in self.local_patches:
patch.field(name).local_with_halos[...] = 0.0
patches = self.patches
for number in np.unique(found[found >= 0]):
chosen = np.flatnonzero(found == number)
for number, chosen in _by_patch(found):
storage, grid = self._patch_block(patches[number], name, shape.degree)
positions = np.array([w[chosen] for w in wrapped])
# the kernels take the nodes component-last: a view with one component
Expand Down Expand Up @@ -1707,8 +1725,7 @@ def interpolate(
)
values = np.zeros(flat[0].size)
patches = self.patches
for number in np.unique(found[found >= 0]):
chosen = np.flatnonzero(found == number)
for number, chosen in _by_patch(found):
storage, grid = self._patch_block(patches[number], name, weights.degree)
positions = np.array([w[chosen] for w in wrapped])
result = np.zeros((1, chosen.size))
Expand Down
27 changes: 17 additions & 10 deletions src/patchwork/mesh/regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,24 @@ def marker_counts(
if any(hierarchy.periodic):
points = points.copy()
hierarchy.wrap(points)
counts = {}
for level in range(levels):
edges = [
hierarchy.node_positions(level, axis) for axis in range(points.shape[0])
]
found, _ = np.histogramdd(points.T, bins=edges)
mine = np.ascontiguousarray(found)
everyone = np.empty_like(mine)
hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM)
counts: dict[int, np.ndarray] = {}
if not levels:
return counts
# one histogram on the finest level; a coarser cell is the sum of its fine cells
top = levels - 1
edges = [hierarchy.node_positions(top, axis) for axis in range(points.shape[0])]
found, _ = np.histogramdd(points.T, bins=edges)
mine = np.ascontiguousarray(found)
everyone = np.empty_like(mine)
hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM)
ratio = hierarchy.refinement_ratio
for level in range(top, -1, -1):
if level < top:
blocks = [part for n in everyone.shape for part in (n // ratio, ratio)]
axes = tuple(range(1, 2 * everyone.ndim, 2))
everyone = everyone.reshape(blocks).sum(axis=axes)
counts[level] = np.where(_domain_cells(hierarchy, level), everyone, 0.0)
return counts
return dict(sorted(counts.items()))


def marker_tags(
Expand Down
16 changes: 16 additions & 0 deletions src/patchwork/tests/unit/test_quadtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,19 @@ def plane(x, y):
atol=1e-12,
)
assert mesh.rebalance().max_level == mesh.max_level # by cells alone


@pytest.mark.parametrize("graded", [False, True])
def test_marker_counts_of_every_level_are_its_own_histogram(graded) -> None:
from patchwork import graded_nodes, marker_counts

axis = graded_nodes(0.0, 1.0, [(0.0, 0.05), (1.0, 0.2)]) if graded else None
shape = (len(axis) - 1, 8) if graded else (8, 8)
mesh = AMRHierarchy(base_shape=shape, axis_nodes=(axis, None))
rng = np.random.default_rng(WORLD.Get_rank())
x, y = rng.uniform(0, 1, (2, 3000))
counts = marker_counts(mesh, x, y, levels=3)
for level, found in counts.items():
edges = [mesh.node_positions(level, a) for a in range(2)]
expected, _ = np.histogramdd(np.stack([x, y]).T, bins=edges)
np.testing.assert_array_equal(found, WORLD.allreduce(expected))