Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
789c5ca
Quadtree regridding: patches as the blocks of a balanced quadtree, an…
max-models Nov 25, 2026
b7b1d5b
docs: README.md as quarto renders it.
max-models Nov 25, 2026
e74d2d8
feat: Morton placement, a cheaper regrid transfer, and the quadtree b…
max-models Nov 25, 2026
5666903
Docstrings of the quadtree benchmark.
max-models Nov 25, 2026
8ae5cdc
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
7e60256
Morton placement over all levels, with the base level's load counted.
max-models Nov 25, 2026
6ad46a7
Quadtree benchmark results, Morton placement in the tutorial and the …
max-models Nov 25, 2026
dc62af1
feat: reuse the halo geometry of kept patches, and Morton cuts weight…
max-models Nov 25, 2026
8e21a5e
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
6638fee
feat: rebalance by cost, and the benchmark of halo reuse and marker-w…
max-models Nov 25, 2026
82ff47a
perf: markers grouped by patch with one sort, and marker counts from …
max-models Nov 25, 2026
478050a
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
74312f8
Benchmark warm-up, and the per-patch costs before and after.
max-models Nov 25, 2026
f5ed73c
perf: coverage per level for the node numbering, halo copies per pair…
max-models Nov 25, 2026
ff1a0b6
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
8ac2cc8
Results of the node numbering, accumulation and fields changes.
max-models Nov 25, 2026
44b2d18
feat: Hilbert placement, knapsack with cost, measured costs per patch.
max-models Nov 25, 2026
4f3b1bd
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
d718326
perf: linear deposit and gather over all patches at once, owners by t…
max-models Nov 25, 2026
9a9708d
Results of the last per-patch changes, and the changelog.
max-models Nov 25, 2026
9416ba5
Types for pyright.
max-models Nov 25, 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
12 changes: 11 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Changed

- Placement along a Hilbert curve (`placement="hilbert"`, cunumpy's `hilbert_encode`) next to
the Morton curve: `morton_ranks` is now `curve_ranks(..., curve="morton" | "hilbert")`.
`placement="balanced"` takes `cost` too, cut by `knapsack_ranks` (the largest cost first to
the least loaded rank). `cost` may also map a patch `(level, box)` to a measured cost, which
`deposit(..., times=...)` and `interpolate(..., times=...)` collect per patch;
`rebalance(cost, placement=...)` places by any of them.
- The cloud-in-cell `deposit` and `interpolate` add the markers of all patches in one pass
(one `bincount` into a buffer of the blocks; higher B-spline degrees keep mpifield's kernels
per patch); a marker's owner comes from a table where its patch is on one rank; the halo
signatures test all patches of a level at once.
- `regrid(..., fields=[...])`: the fields whose values are moved (default: all); the others
are allocated on the new hierarchy and zero.
- `CompositeNodes` finds the cells under finer patches from one coverage mask per level (it
Expand All @@ -33,7 +43,7 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
with clusters, but all patches have one size and a regrid keeps most of them. Tutorial
"Quadtree patches".
- `placement="morton"`: `regrid` puts the patches on the ranks along a Morton curve
(`morton_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs
(`curve_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs
of about equal cells with the base level's cells counted.
- Morton cuts weighted by cost: `regrid(..., placement="morton", cost=...)` weighs every patch
by its cells plus the cost of its leaf cells (`box_costs`), e.g. the markers of
Expand Down
34 changes: 34 additions & 0 deletions benchmarks/quadtree/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,40 @@ step, total:
(~33 ms). The next step there: keep the `CopyPlan` of the kept patches, or set up the
interpolation of all patches at once.

## One gather per array, markers in one pass (2026-11-25, last)

Against `devel` (with `regrid(fields=[])` on both sides): mpiarray's `CopyPlan` packs and
unpacks with one gather and one scatter per array (flat storage indices found when the plan
is built) and lays out its pieces with array operations; the cloud-in-cell deposit and
gather add the markers of all patches in one pass (`bincount` into a buffer of the blocks,
equal to mpifield's kernels to 1e-12); a marker's owner rank comes from a table where its
patch is on one rank; and the halo signatures test all patches of a level against each
other at once. Serial, median of 3 runs, ms per step:

| mesh | | tag | regrid | migrate | deposit | solver | solve | halos | gather | total |
|---|---|---|---|---|---|---|---|---|---|---|
| cluster | before | 35.2 | 2.8 | 17.1 | 25.9 | 107.7 | 6.3 | 8.2 | 25.0 | 228 |
| | after | 35.1 | 2.7 | 9.6 | 25.2 | 108.4 | 6.1 | 6.0 | 24.0 | 217 (−5%) |
| cluster, `max_patch_size=16` | before | 35.7 | 18.5 | 30.3 | 69.1 | 122.9 | 12.6 | 108.5 | 52.5 | 450 |
| | after | 38.3 | 19.4 | 11.9 | 43.9 | 118.5 | 12.8 | 83.7 | 27.0 | 356 (−21%) |
| quadtree, block 8 | before | 36.3 | 88.0 | 34.8 | 106.6 | 108.9 | 21.7 | 193.4 | 70.7 | 661 |
| | after | 36.9 | 93.6 | 14.7 | 69.5 | 110.9 | 22.3 | 108.3 | 29.4 | 486 (−26%) |
| quadtree, block 16 | before | 37.4 | 15.2 | 31.8 | 68.5 | 133.5 | 12.4 | 62.2 | 54.6 | 416 |
| | after | 35.5 | 14.5 | 11.4 | 39.9 | 131.5 | 12.0 | 37.5 | 25.8 | 308 (−26%) |
| quadtree, block 32 | before | 36.2 | 6.2 | 26.3 | 52.1 | 205.8 | 12.7 | 23.5 | 43.4 | 406 |
| | after | 37.3 | 6.7 | 10.8 | 34.3 | 210.2 | 13.0 | 16.9 | 25.3 | 355 (−13%) |

- The `CopyPlan` of the halos of 392 patches (4422 copies) builds in 23 ms (43 before) and
executes in 0.7 ms (10 before); the halos of blocks of 8 take 108 ms per step, from 193.
- Gather 71 → 29 ms and deposit 107 → 70 ms with blocks of 8; migrate about halves
everywhere (the owner check).
- Since the first run of this benchmark (1263 ms per step with blocks of 8, all fields
moved), the cycle on blocks of 8 is 2.6 times faster; the clusters' 327 ms are now 217.
- What is left with blocks of 8: the solver setup (111 ms: assembly and LU, which do not
depend on the patches), the halos (108: the interpolation records of the patches whose
neighbourhood changed, one per patch, and their copies), the regrid (94: the boxes and
the new hierarchy) and the deposit (70, of which the `accumulate_halos` schedule ~35).

## Fixed on the way

The regrid's transfer compared every new patch with every old one of its level, and copied
Expand Down
6 changes: 4 additions & 2 deletions src/patchwork/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
Patch,
box_costs,
cluster,
curve_ranks,
function_tags,
graded_nodes,
gradient_tags,
knapsack_ranks,
marker_counts,
marker_tags,
morton_ranks,
plot_patches,
quadtree_boxes,
)
Expand Down Expand Up @@ -91,12 +92,13 @@
"cell_body",
"box_costs",
"cluster",
"curve_ranks",
"function_tags",
"graded_nodes",
"gradient_tags",
"knapsack_ranks",
"marker_counts",
"marker_tags",
"morton_ranks",
"plot_patches",
"quadtree_boxes",
"solve_nodal_poisson",
Expand Down
6 changes: 4 additions & 2 deletions src/patchwork/mesh/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
from patchwork.mesh.regrid import (
box_costs,
cluster,
curve_ranks,
function_tags,
gradient_tags,
knapsack_ranks,
marker_counts,
marker_tags,
morton_ranks,
quadtree_boxes,
)

Expand All @@ -29,12 +30,13 @@
"Patch",
"box_costs",
"cluster",
"curve_ranks",
"function_tags",
"graded_nodes",
"gradient_tags",
"knapsack_ranks",
"marker_counts",
"marker_tags",
"morton_ranks",
"plot_patches",
"quadtree_boxes",
]
88 changes: 62 additions & 26 deletions src/patchwork/mesh/halos.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
from methodcard import ConvergenceProblem, method

if TYPE_CHECKING:
from collections.abc import Sequence

from patchwork.mesh.hierarchy import AMRHierarchy, Patch

Box = tuple[tuple[int, int], ...]
Expand Down Expand Up @@ -542,19 +544,6 @@ def _key(patch: Patch) -> tuple:
return (patch.level, patch.box, patch.ranks)


def _within(points: _Points, level: int, box: Box) -> tuple:
"""The keys of the patches of ``level`` that overlap ``box`` or one of its periodic images."""
shifts = points.shifts(level)
return tuple(
_key(other)
for other in points.near(level, box)
if any(
_overlap(box, _shift(points.own(other), shift)) is not None
for shift in shifts
)
)


class _HaloRecord:
"""The halo geometry of one patch, its fields named by patch keys.

Expand Down Expand Up @@ -663,22 +652,68 @@ def _coarse_fine(
if interpolation is not None:
self._interpolations.append(interpolation)

def _signature(self, points: _Points, patch: Patch) -> tuple:
"""What a patch's halo geometry depends on: itself and the patches within reach.
def _signatures(self, points: _Points) -> dict[int, tuple]:
"""What every patch's halo geometry depends on: itself and the patches within reach.

The patches of its level that may overlap its halo, and those of the level
below that may hold the coarse points of its interpolation, each as
``(level, box, ranks)``.
The patches of its level that overlap its halo, and those of the level
below that may hold the coarse points of its interpolation (a margin of
one coarse cell and the stencil's), each as ``(level, box, ranks)``, in the
order of the patches. All patches of a level are tested against all of
the level and the one below at once, periodic images included. Keyed by
``id`` of the patch.
"""
own = points.own(patch)
hierarchy = self._hierarchy
width = self._width
extended = tuple((lo - width, hi + width) for lo, hi in own)
same = _within(points, patch.level, extended)
if patch.level == 0:
return (_key(patch), same)
ratio = points.ratio
coarse = tuple((lo // ratio - 1, -(-hi // ratio) + 2) for lo, hi in extended)
return (_key(patch), same, _within(points, patch.level - 1, coarse))
result: dict[int, tuple] = {}

def boxes(patches: Sequence[Patch]) -> np.ndarray:
return np.array([points.own(p) for p in patches], dtype=np.int64).reshape(
len(patches), hierarchy.ndim, 2
)

def touching(regions: np.ndarray, level: int) -> tuple[list[Patch], np.ndarray]:
"""The patches of ``level`` and which of them overlap each region."""
candidates = list(hierarchy.patches_at_level(level))
theirs = boxes(candidates)
hit = np.zeros((regions.shape[0], theirs.shape[0]), dtype=bool)
for shift in points.shifts(level):
moved = theirs + np.asarray(shift, dtype=np.int64)[None, :, None]
lower = np.maximum(regions[:, None, :, 0], moved[None, :, :, 0])
upper = np.minimum(regions[:, None, :, 1], moved[None, :, :, 1])
hit |= np.all(lower < upper, axis=-1)
return candidates, hit

for level in range(hierarchy.max_level + 1):
if self._level is not None and level != self._level:
continue
mine = hierarchy.patches_at_level(level)
if not mine:
continue
own = boxes(mine)
extended = own + np.array([-width, width], dtype=np.int64)
same, hit = touching(extended, level)
below: list[Patch] = []
under = np.zeros((len(mine), 0), dtype=bool)
if level > 0:
coarse = np.stack(
[extended[..., 0] // ratio - 1, -(-extended[..., 1] // ratio) + 2],
axis=-1,
)
below, under = touching(coarse, level - 1)
for n, patch in enumerate(mine):
key = (
_key(patch),
tuple(_key(same[m]) for m in np.flatnonzero(hit[n]).tolist()),
)
if level > 0:
key += (
tuple(
_key(below[m]) for m in np.flatnonzero(under[n]).tolist()
),
)
result[id(patch)] = key
return result

def _record(self, points: _Points, patch: Patch, dtype: Any) -> _HaloRecord:
"""The halo geometry of one patch, with its fields as patch keys."""
Expand Down Expand Up @@ -805,10 +840,11 @@ def __init__(
self._pairs_used: dict[tuple, list] = {}
used: dict[tuple, _HaloRecord] = {}
patches = {_key(patch): patch for patch in hierarchy.patches}
signatures = self._signatures(points) if self._width else {}
for patch in hierarchy.patches if self._width else ():
if level is not None and patch.level != level:
continue
signature = self._signature(points, patch)
signature = signatures[id(patch)]
record = known.get(signature)
if record is None:
record = self._record(points, patch, dtype)
Expand Down
Loading
Loading