From 789c5ca83b0fd0881c7fe9b92328fbc5caebade0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:01:20 +0000 Subject: [PATCH 01/24] Quadtree regridding: patches as the blocks of a balanced quadtree, and tags from marker counts. --- CHANGELOG.md | 10 + README.md | 5 +- README.qmd | 5 +- docs/src/content/docs/examples/index.md | 3 + src/patchwork/__init__.py | 6 +- src/patchwork/mesh/__init__.py | 12 +- src/patchwork/mesh/hierarchy.py | 63 ++++- src/patchwork/mesh/regrid.py | 188 ++++++++++++- src/patchwork/tests/unit/test_mpi.py | 1 + src/patchwork/tests/unit/test_quadtree.py | 217 +++++++++++++++ tutorials/13_quadtree_patches.ipynb | 323 ++++++++++++++++++++++ 11 files changed, 808 insertions(+), 25 deletions(-) create mode 100644 src/patchwork/tests/unit/test_quadtree.py create mode 100644 tutorials/13_quadtree_patches.ipynb diff --git a/CHANGELOG.md b/CHANGELOG.md index ea98e3b..c67d66b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- Quadtree regridding: `AMRHierarchy.regrid(method="quadtree", block_size=16)` places the + patches as the blocks of a quadtree (an octree in 3D) instead of Berger-Rigoutsos clusters: + every level is cut into aligned square blocks of `block_size` cells, a block holding a tag is + a patch, the blocks of a level are the children of those below, and the tree is balanced by + the nesting margin. Blocks at the edge of the domain or of forbidden cells are cut to their + allowed cells. `quadtree_boxes` gives the boxes on their own. More cells are refined than + with clusters, but all patches have one size and a regrid keeps most of them. Tutorial + "Quadtree patches". +- `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than + `per_cell` markers, counted over all ranks. - Graded axes: `AMRHierarchy(axis_nodes=...)` takes, per axis, `None` (uniform) or the physical positions of the base nodes. The map from the logical coordinate (the one of the patches, levels and kernels) to the physical one is linear in every base cell, so every leaf diff --git a/README.md b/README.md index a8ab8ae..b57212d 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,9 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field’s change across a cell, a function of the position, or by -hand), and it covers them with properly nested patches (Berger-Rigoutsos -clustering) and moves the fields over. +hand), and it covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with +`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells +that hold too many markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), `owner` and `migrate` diff --git a/README.qmd b/README.qmd index d16900c..21115b5 100644 --- a/README.qmd +++ b/README.qmd @@ -57,8 +57,9 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field's change across a cell, a function of the position, or by hand), and it -covers them with properly nested patches (Berger-Rigoutsos clustering) and moves -the fields over. +covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with +`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells +that hold too many markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), diff --git a/docs/src/content/docs/examples/index.md b/docs/src/content/docs/examples/index.md index e40eb7d..36acb3e 100644 --- a/docs/src/content/docs/examples/index.md +++ b/docs/src/content/docs/examples/index.md @@ -35,6 +35,9 @@ Step by step, from a first hierarchy to stencils on patches: 12. [Graded axes](/patchwork/examples/12-graded-axes/): cells that grow smoothly away from a wall (`axis_nodes`), a boundary layer resolved with a few dozen cells, and grading combined with patches. +13. [Quadtree patches](/patchwork/examples/13-quadtree-patches/): `regrid(method="quadtree")`, + patches as the equal blocks of a quadtree, refinement by the number of markers per cell + (`marker_tags`), and how much of the mesh a regrid keeps. Every notebook in `tutorials/` is executed when the site is built and published here with its outputs. Download a notebook from its page to run the steps yourself. diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index fd56bc9..df91035 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -18,7 +18,9 @@ function_tags, graded_nodes, gradient_tags, + marker_tags, plot_patches, + quadtree_boxes, ) from patchwork.solvers import ( AMGBackend, @@ -86,9 +88,11 @@ "cell_body", "cluster", "function_tags", - "gradient_tags", "graded_nodes", + "gradient_tags", + "marker_tags", "plot_patches", + "quadtree_boxes", "solve_nodal_poisson", "solve_poisson", ] diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index b1abce5..898391e 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -11,7 +11,13 @@ from patchwork.mesh.hierarchy import AMRHierarchy, IndexBox, Patch from patchwork.mesh.plotting import plot_patches from patchwork.mesh.reflux import FluxRegister -from patchwork.mesh.regrid import cluster, function_tags, gradient_tags +from patchwork.mesh.regrid import ( + cluster, + function_tags, + gradient_tags, + marker_tags, + quadtree_boxes, +) __all__ = [ "AMRHierarchy", @@ -20,7 +26,9 @@ "Patch", "cluster", "function_tags", - "gradient_tags", "graded_nodes", + "gradient_tags", + "marker_tags", "plot_patches", + "quadtree_boxes", ] diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 2199ac2..232a98a 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -987,6 +987,8 @@ def regrid( self, tags: Mapping[int, Any], *, + method: str = "cluster", + block_size: int = 16, efficiency: float = 0.7, buffer: int = 1, nesting: int = 1, @@ -1005,9 +1007,19 @@ def regrid( from the data it holds, and the tags are combined over the ranks. Level by level from the coarsest, the tagged cells, grown by - ``buffer`` cells, are covered with boxes by - `cluster` (at least ``efficiency`` of their - cells tagged, at most ``max_patch_size`` cells of the new level long). + ``buffer`` cells, are covered with boxes. ``method`` says how: + + - ``"cluster"`` (the default): by `cluster`, the Berger-Rigoutsos + algorithm (at least ``efficiency`` of their cells tagged, at most + ``max_patch_size`` cells of the new level long): few patches, fitted + to the tags; + - ``"quadtree"``: by `quadtree_boxes`, the blocks of a quadtree (an + octree in 3D), square patches of ``block_size`` cells of their level, + aligned so that the blocks of a level are the children of those of the + level below: more patches, all of one size, and a block is added or + removed without moving the others. ``efficiency`` and + ``max_patch_size`` do not apply. + A level also covers, with a margin, what the finer levels need, and each patch keeps ``nesting`` cells of the level below between itself and that level's edge (the edge of the domain excepted). The base level @@ -1037,19 +1049,42 @@ def regrid( the largest first. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ - from patchwork.mesh.regrid import combine_tags, new_boxes, transfer + from patchwork.mesh.regrid import ( + combine_tags, + new_boxes, + quadtree_boxes, + transfer, + ) + if method not in ("cluster", "quadtree"): + raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") + if method == "quadtree" and max_patch_size is not None: + raise ValueError( + "max_patch_size does not apply to method='quadtree': " + "every patch is one block of block_size cells" + ) combined = combine_tags(self, tags) - boxes = new_boxes( - self, - combined, - efficiency=efficiency, - buffer=buffer, - nesting=nesting, - max_patch_size=max_patch_size, - min_patch_size=min_patch_size, - forbid=forbid, - ) + if method == "quadtree": + boxes = quadtree_boxes( + self, + combined, + block_size=block_size, + buffer=buffer, + nesting=nesting, + min_patch_size=min_patch_size, + forbid=forbid, + ) + else: + boxes = new_boxes( + self, + combined, + efficiency=efficiency, + buffer=buffer, + nesting=nesting, + max_patch_size=max_patch_size, + min_patch_size=min_patch_size, + forbid=forbid, + ) base = self.patches_at_level(0) new = AMRHierarchy.__new__(AMRHierarchy) new._communicators = self._communicators diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 8f92ff5..cb48c0d 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -4,11 +4,19 @@ 1. **Tagging** marks the cells of each level that need the next finer level: `gradient_tags` where a field changes by more than a threshold across a - cell, `function_tags` where a function of the position says so, or any + cell, `function_tags` where a function of the position says so, + `marker_tags` where a cell holds more than a number of markers, or any boolean array of a level's shape. -2. **Clustering** (`cluster`, the Berger-Rigoutsos algorithm) covers the - tagged cells of a level with few boxes (intervals in 1D, rectangles in 2D), each at least ``efficiency`` - full of tagged cells and at most ``max_size`` cells long. +2. **Placing the patches**, in one of two ways: + + - clustering (`cluster`, the Berger-Rigoutsos algorithm) covers the + tagged cells of a level with few boxes (intervals in 1D, rectangles in 2D), + each at least ``efficiency`` full of tagged cells and at most ``max_size`` + cells long; + - a quadtree (an octree in 3D, `quadtree_boxes`) cuts every level into + aligned square blocks of ``block_size`` cells and refines each block that + holds a tag: the blocks of level ``k + 1`` are the children of those of + level ``k``, and every patch is one block. 3. `AMRHierarchy.regrid` builds the new hierarchy from the boxes, level by level from the coarsest, and moves the fields into it: copied where an old patch of the same level was, else @@ -87,6 +95,44 @@ def function_tags( return tags +def marker_tags( + hierarchy: AMRHierarchy, *coordinates: Any, per_cell: float, levels: int +) -> dict[int, np.ndarray]: + """Tag the cells of levels ``0 .. levels - 1`` that hold more than ``per_cell`` markers. + + ``marker_tags(x, ...)`` in 1D, ``marker_tags(x, y, ...)`` in 2D: the + positions of this rank's markers (arrays of one shape). The markers are + counted in the cells of every level, whether a patch covers them or not, and + the counts are added over the ranks (collective over ``comm``), so every + rank gets the same tags. Refinement driven by these tags stops where the + cells of a level hold at most ``per_cell`` markers each, as a particle tree + stops splitting at its leaf capacity. Markers outside the domain (and in the + notch of an L) are not counted. + """ + if len(coordinates) != hierarchy.ndim: + raise ValueError( + f"marker_tags takes {hierarchy.ndim} coordinate arrays, " + f"got {len(coordinates)}" + ) + if levels < 0: + raise ValueError("levels must not be negative") + points = np.stack([np.ravel(np.asarray(c, dtype=float)) for c in coordinates]) + if any(hierarchy.periodic): + points = points.copy() + hierarchy.wrap(points) + tags = {} + for level in range(levels): + edges = [ + hierarchy.node_positions(level, axis) for axis in range(points.shape[0]) + ] + counts, _ = np.histogramdd(points.T, bins=edges) + mine = np.ascontiguousarray(counts) + everyone = np.empty_like(mine) + hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM) + tags[level] = (everyone > per_cell) & _domain_cells(hierarchy, level) + return tags + + @sp.profile("patchwork.gradient_tags", tags=PROFILE_TAGS) @method( equations={ @@ -535,6 +581,140 @@ def new_boxes( return boxes +def _refine(mask: np.ndarray, ratio: int) -> np.ndarray: + """The fine cells of every true coarse cell: ``mask`` repeated ``ratio`` times per axis.""" + for axis in range(mask.ndim): + mask = np.repeat(mask, ratio, axis=axis) + return mask + + +def _blocks(mask: np.ndarray, size: int) -> np.ndarray: + """Which aligned blocks of ``size`` cells per axis hold a true cell (a partial last block counts).""" + padded = np.zeros([-(-n // size) * size for n in mask.shape], dtype=bool) + padded[tuple(slice(0, n) for n in mask.shape)] = mask + return _coarsen(padded, size) + + +def _block_cells(blocks: np.ndarray, size: int, shape: tuple[int, ...]) -> np.ndarray: + """The cells of the true blocks, cut to ``shape``.""" + cells = _refine(blocks, size) + return cells[tuple(slice(0, n) for n in shape)] + + +@method( + equations={ + "blocks": r"B^{k}_{\mathbf m} = \prod_{d} [\, m_d b,\ (m_d + 1) b \,) \text{ (cells of level } k\text{)}, \quad \text{refined} \iff B^{k}_{\mathbf m} \text{ holds a tag of level } k - 1", + "children": r"B^{k+1}_{\mathbf m'} \subset B^{k}_{\mathbf m} \iff \lfloor \mathbf m' / r \rfloor = \mathbf m \quad (2^d \text{ children for } r = 2)", + }, + assumptions=( + "each patch is one block of `block_size` cells of its level, aligned to multiples of `block_size`; the last block of a level may be shorter, and a block that crosses the edge of the domain or a forbidden cell is cut into rectangles of its allowed cells", + "a level is refined, with a margin of `nesting` cells, wherever a finer block needs it, so the blocks are properly nested (a balanced tree)", + ), + references=( + "[MacNeice et al., Comput. Phys. Commun. 126, 330 (2000)](https://doi.org/10.1016/S0010-4655(99)00501-9)", + "[Burstedde, Wilcox and Ghattas, SIAM J. Sci. Comput. 33, 1103 (2011)](https://doi.org/10.1137/100791634)", + ), +) +def quadtree_boxes( + hierarchy: AMRHierarchy, + tags: Mapping[int, np.ndarray], + *, + block_size: int, + buffer: int, + nesting: int, + min_patch_size: int = 1, + forbid: Any = None, +) -> dict[int, list[IndexBox]]: + """The boxes of every refined level as the blocks of a quadtree (an octree in 3D). + + Every level is cut into aligned blocks of ``block_size`` cells per axis. + A block of level ``k + 1`` is a patch when a tag of level ``k``, grown by + ``buffer`` cells, lies under it, or when a finer block needs it: each block + keeps ``nesting`` cells of the level below between itself and that level's + edge (the edge of the domain excepted), so the level below is refined + around it too. With a refinement ratio of two, the blocks of level ``k + 1`` + under a block of level ``k`` are its four children (eight in 3D): the + patches are the nodes of a tree, all of one size, and the tree is balanced. + + A block that crosses the edge of the domain (the notch of an L), a + forbidden cell (``forbid`` as for `AMRHierarchy.regrid`) or the margin + the level below needs is cut into rectangles of its allowed cells, which may + then be narrower than ``block_size``; ``min_patch_size`` widens those + pieces as `cluster` does. ``block_size`` is in cells of the new level and + must be a multiple of the refinement ratio. + """ + ratio = hierarchy.refinement_ratio + periodic = hierarchy.periodic + if int(block_size) != block_size or block_size < ratio or block_size % ratio: + raise ValueError( + f"block_size must be a multiple of the refinement ratio {ratio}, " + f"got {block_size}" + ) + if buffer < 0 or nesting < 0: + raise ValueError("buffer and nesting must not be negative") + if min_patch_size < 1: + raise ValueError("min_patch_size must be at least 1") + size = int(block_size) // ratio # a block of level k + 1, in cells of level k + levels = [level for level, values in tags.items() if values.any()] + top = max(levels) + 1 if levels else 0 + # top down: the blocks each level needs, for its own tags and the finer blocks + refined: dict[int, np.ndarray] = {} # level k + 1 -> its blocks, over level k + margin: np.ndarray | None = None # cells of level k the finer blocks need + for level in range(top - 1, -1, -1): + domain = _domain_cells(hierarchy, level) + need = _grow( + tags.get(level, np.zeros(domain.shape, dtype=bool)), + buffer, + periodic, + outside=False, + ) + if margin is not None: + need |= _coarsen(margin, ratio) + need &= domain + refined[level + 1] = _blocks(need, size) + cells = _block_cells(refined[level + 1], size, domain.shape) & domain + margin = _grow(cells, nesting, periodic, outside=False) + # bottom up: each needed block, cut to the cells where its level may go + boxes: dict[int, list[IndexBox]] = {} + covered = _domain_cells(hierarchy, 0) + min_size = -(-min_patch_size // ratio) + for level in range(top): + domain = _domain_cells(hierarchy, level) + allowed = _shrink(covered | ~domain, nesting, periodic) & covered + forbidden = _forbidden_cells(hierarchy, forbid, level + 1) + if forbidden is not None: + allowed &= ~_coarsen(forbidden, ratio) + found: list[IndexBox] = [] + for index in zip(*np.nonzero(refined[level + 1]), strict=True): + block = tuple( + (int(m) * size, min((int(m) + 1) * size, n)) + for m, n in zip(index, domain.shape, strict=True) + ) + inside = allowed[tuple(slice(lo, hi) for lo, hi in block)] + if inside.all(): + parts = [block] + elif inside.any(): + parts = [ + tuple( + (lo + a, lo + b) + for (lo, _), (a, b) in zip(block, part, strict=True) + ) + for part in cluster(inside, 1.0, None, inside, min_size) + ] + else: + continue + found.extend(parts) + if not found: + break + boxes[level + 1] = [ + tuple((lo * ratio, hi * ratio) for lo, hi in box) for box in sorted(found) + ] + covered = np.zeros(hierarchy.level_shape(level + 1), dtype=bool) + for box in boxes[level + 1]: + covered[tuple(slice(lo, hi) for lo, hi in box)] = True + return boxes + + @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). diff --git a/src/patchwork/tests/unit/test_mpi.py b/src/patchwork/tests/unit/test_mpi.py index 2866592..55b5217 100644 --- a/src/patchwork/tests/unit/test_mpi.py +++ b/src/patchwork/tests/unit/test_mpi.py @@ -44,6 +44,7 @@ def test_patches_on_some_ranks_give_what_one_rank_gives(ranks: int) -> None: [ "test_halos.py", "test_regrid.py", + "test_quadtree.py", "test_markers.py", "test_reflux.py", "test_line_patches.py", diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py new file mode 100644 index 0000000..d91051b --- /dev/null +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -0,0 +1,217 @@ +"""Quadtree regridding (``regrid(method="quadtree")``) and tagging by marker counts. + +Runs serially and under ``mpirun -n N python -m pytest`` (see ``test_mpi.py``). +""" + +from __future__ import annotations + +import numpy as np +import pytest +from maybempi import MPI + +from patchwork import AMRHierarchy, function_tags, marker_tags, quadtree_boxes +from patchwork.mesh.regrid import combine_tags + +WORLD = MPI.COMM_WORLD +SIZE = WORLD.Get_size() + + +def ring(x, y): + return np.abs(np.hypot(x - 0.5, y - 0.5) - 0.3) < 0.03 + + +def boxes_of(mesh, level): + return sorted(patch.box for patch in mesh.patches_at_level(level)) + + +def covered(mesh, level): + cells = np.zeros(mesh.level_shape(level), dtype=bool) + for box in boxes_of(mesh, level): + cells[tuple(slice(lo, hi) for lo, hi in box)] = True + return cells + + +@pytest.mark.parametrize("block_size", [4, 8, 16]) +def test_quadtree_patches_are_aligned_blocks_whose_parents_are_blocks( + block_size, +) -> None: + mesh = AMRHierarchy(base_shape=(32, 32)) + tags = function_tags(mesh, ring, levels=3) + new = mesh.regrid(tags, method="quadtree", block_size=block_size) + assert new.max_level == 3 + for level in range(1, new.max_level + 1): + for box in boxes_of(new, level): + for lo, hi in box: # one whole, aligned block of its level + assert lo % block_size == 0 + assert hi - lo == block_size + if level == 1: + continue + # inside one block of the level below: the patches form a tree + parents = [ + parent + for parent in boxes_of(new, level - 1) + if all( + 2 * plo <= lo and hi <= 2 * phi + for (lo, hi), (plo, phi) in zip(box, parent, strict=True) + ) + ] + assert len(parents) == 1 + # every tag of the level below is covered + assert np.all( + covered(new, level)[np.repeat(np.repeat(tags[level - 1], 2, 0), 2, 1)] + ) + + +def test_quadtree_blocks_far_away_stay_when_a_tag_goes() -> None: + mesh = AMRHierarchy(base_shape=(32, 32)) + + def blobs(both): + def tag(x, y): + near = np.hypot(x - 0.2, y - 0.2) < 0.06 + far = np.hypot(x - 0.8, y - 0.8) < 0.06 + return near | far if both else near + + return tag + + one = mesh.regrid( + function_tags(mesh, blobs(False), levels=2), method="quadtree", block_size=8 + ) + two = mesh.regrid( + function_tags(mesh, blobs(True), levels=2), method="quadtree", block_size=8 + ) + for level in (1, 2): + near = [ + b for b in boxes_of(two, level) if b[0][1] <= one.level_shape(level)[0] // 2 + ] + assert near == boxes_of(one, level) + + +def test_quadtree_moves_a_linear_field_exactly() -> None: + mesh = AMRHierarchy(base_shape=(16, 16)) + mesh.allocate_field("u", centering="node") + mesh.allocate_field("c") + + def plane(x, y): + return 1.0 + 2.0 * x - 3.0 * y + + for patch in mesh.local_patches: + patch.field("u").local[...] = plane(*patch.local_node_coordinates(mesh, "u")) + patch.field("c").local[...] = plane(*patch.local_cell_centers(mesh, "c")) + for tag in (lambda x, y: x < 0.4, lambda x, y: y > 0.7): + mesh = mesh.regrid( + function_tags(mesh, tag, levels=2), method="quadtree", block_size=4 + ) + assert mesh.max_level == 2 + for patch in mesh.local_patches: + x, y = patch.local_node_coordinates(mesh, "u") + np.testing.assert_allclose(patch.field("u").local, plane(x, y), atol=1e-12) + x, y = patch.local_cell_centers(mesh, "c") + np.testing.assert_allclose(patch.field("c").local, plane(x, y), atol=1e-12) + + +def test_quadtree_blocks_are_cut_at_the_edge_of_an_l_and_at_forbidden_cells() -> None: + mesh = AMRHierarchy( + base_shape=(16, 16), + base_boxes=[((0, 8), (0, 16)), ((8, 16), (8, 16))], # an L of area 3/4 + ) + tags = {0: np.ones((16, 16), dtype=bool)} + new = mesh.regrid(tags, method="quadtree", block_size=12, nesting=0) + inside = np.zeros((32, 32), dtype=bool) + inside[:16, :] = True + inside[16:, 16:] = True + assert np.array_equal(covered(new, 1), inside) + + forbid = {1: np.zeros((32, 32), dtype=bool)} + forbid[1][:, 30:] = True + new = mesh.regrid(tags, method="quadtree", block_size=12, nesting=0, forbid=forbid) + assert np.array_equal(covered(new, 1), inside & ~forbid[1]) + + +def test_quadtree_keeps_the_nesting_margin_and_periodic_axes() -> None: + mesh = AMRHierarchy(base_shape=(16, 16), periodic=(True, False)) + tags = function_tags( + mesh, lambda x, y: (x < 0.05) & (np.abs(y - 0.5) < 0.05), levels=2 + ) + new = mesh.regrid(tags, method="quadtree", block_size=4, nesting=2) + level1 = covered(new, 1) + # the level-2 blocks at x = 0 need level 1 on both sides of the seam + assert level1[0].any() and level1[-1].any() + assert new.max_level == 2 + + +@pytest.mark.parametrize("ndim", [1, 3]) +def test_quadtree_in_one_and_three_dimensions(ndim) -> None: + mesh = AMRHierarchy(base_shape=(8,) * ndim) + tags = {0: np.zeros((8,) * ndim, dtype=bool)} + tags[0][(3,) * ndim] = True + new = mesh.regrid(tags, method="quadtree", block_size=4) + for box in boxes_of(new, 1): + assert all(lo % 4 == 0 and hi - lo == 4 for lo, hi in box) + assert covered(new, 1)[(6,) * ndim] + + +def test_quadtree_boxes_is_usable_on_its_own() -> None: + mesh = AMRHierarchy(base_shape=(16, 16)) + tags = combine_tags(mesh, {0: np.eye(16, dtype=bool)}) + boxes = quadtree_boxes(mesh, tags, block_size=8, buffer=0, nesting=0) + assert boxes == { + 1: [ + ((0, 8), (0, 8)), + ((8, 16), (8, 16)), + ((16, 24), (16, 24)), + ((24, 32), (24, 32)), + ] + } + assert quadtree_boxes(mesh, {}, block_size=8, buffer=0, nesting=0) == {} + + +def test_quadtree_checks_its_arguments() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + tags = {0: np.ones((8, 8), dtype=bool)} + with pytest.raises(ValueError, match="method"): + mesh.regrid(tags, method="octopus") + with pytest.raises(ValueError, match="max_patch_size"): + mesh.regrid(tags, method="quadtree", max_patch_size=8) + for size in (1, 3, 2.5): + with pytest.raises(ValueError, match="block_size"): + mesh.regrid(tags, method="quadtree", block_size=size) + with pytest.raises(ValueError, match="negative"): + mesh.regrid(tags, method="quadtree", buffer=-1) + with pytest.raises(ValueError, match="min_patch_size"): + mesh.regrid(tags, method="quadtree", min_patch_size=0) + + +def test_marker_tags_count_the_markers_of_every_rank() -> None: + mesh = AMRHierarchy(base_shape=(4, 4), periodic=(True, False)) + rank = WORLD.Get_rank() + # each rank holds a share of 9 markers in cell (1, 2), 3 in cell (3, 0) + x = np.array([0.3] * 9 + [0.9] * 3) + y = np.array([0.6] * 9 + [0.1] * 3) + mine = slice(rank, None, SIZE) + tags = marker_tags( + mesh, x[mine] + 1.0, y[mine], per_cell=4, levels=2 + ) # wrapped in x + expected = np.zeros((4, 4), dtype=bool) + expected[1, 2] = True + assert np.array_equal(tags[0], expected) + assert tags[1].sum() == 1 and tags[1][2, 4] # level 1: all 9 in one cell still + assert marker_tags(mesh, x[mine], y[mine], per_cell=9, levels=1)[0].sum() == 0 + with pytest.raises(ValueError, match="coordinate"): + marker_tags(mesh, x, per_cell=1, levels=1) + with pytest.raises(ValueError, match="levels"): + marker_tags(mesh, x, y, per_cell=1, levels=-1) + + +def test_marker_tags_skip_the_notch_of_an_l() -> None: + mesh = AMRHierarchy( + base_shape=(4, 4), base_boxes=[((0, 2), (0, 4)), ((2, 4), (2, 4))] + ) + x, y = np.full(10, 0.8), np.full(10, 0.2) # in the notch + assert not marker_tags(mesh, x, y, per_cell=1, levels=1)[0].any() + + +def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + tags = {0: np.ones((8, 8), dtype=bool)} + new = mesh.regrid(tags, method="quadtree", block_size=4, forbid=lambda x, y: x > -1) + assert new.max_level == 0 diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb new file mode 100644 index 0000000..5eb019c --- /dev/null +++ b/tutorials/13_quadtree_patches.ipynb @@ -0,0 +1,323 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "# Quadtree patches\n", + "\n", + "`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\n", + "tagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n", + "[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\n", + "aligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\n", + "the blocks of a level are the children of those of the level below, so the patches are the\n", + "nodes of a quadtree (an octree in 3D), all of one size.\n", + "\n", + "Both give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\n", + "solvers work on either. They differ in how many patches there are, how many cells are\n", + "refined, and how much the mesh changes when the tags change a little." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "\n", + "from patchwork import (\n", + " AMRHierarchy,\n", + " NodalPoisson,\n", + " function_tags,\n", + " marker_tags,\n", + " plot_patches,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "2", + "metadata": {}, + "source": [ + "## Clusters and blocks\n", + "\n", + "The same tags, a ring refined by three levels, placed both ways:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [ + "mesh = AMRHierarchy(base_shape=(32, 32))\n", + "\n", + "\n", + "def ring(x, y):\n", + " return np.abs(np.hypot(x - 0.5, y - 0.5) - 0.3) < 0.03\n", + "\n", + "\n", + "tags = function_tags(mesh, ring, levels=3)\n", + "meshes = {\n", + " \"cluster\": mesh.regrid(tags, max_patch_size=32),\n", + " \"quadtree\": mesh.regrid(tags, method=\"quadtree\", block_size=16),\n", + "}\n", + "\n", + "\n", + "def cells(mesh, level):\n", + " return sum(\n", + " int(np.prod([hi - lo for lo, hi in patch.box]))\n", + " for patch in mesh.patches_at_level(level)\n", + " )\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)\n", + "for ax, (method, new) in zip(axes, meshes.items(), strict=True):\n", + " plot_patches(new, ax=ax, show_grid=False)\n", + " ax.set_title(f\"{method}: {len(new.patches)} patches\")\n", + " for level in range(1, new.max_level + 1):\n", + " print(\n", + " f\"{method:8s} level {level}: {len(new.patches_at_level(level)):3d} patches, \"\n", + " f\"{cells(new, level):6d} cells\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "4", + "metadata": {}, + "source": [ + "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\n", + "blocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\n", + "size for every patch, and patches that are easy to share out between ranks.\n", + "\n", + "## The blocks form a tree\n", + "\n", + "A block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n", + "(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\n", + "exactly one block of the level below, its parent, and each parent has four children. Where a\n", + "block is refined, the level below is refined around it as well, with a margin of `nesting`\n", + "cells, so neighbouring blocks differ by at most one level: the tree is balanced." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5", + "metadata": {}, + "outputs": [], + "source": [ + "tree = meshes[\"quadtree\"]\n", + "child = tree.patches_at_level(3)[0]\n", + "parent = next(\n", + " patch\n", + " for patch in tree.patches_at_level(2)\n", + " if all(\n", + " 2 * lo <= clo and chi <= 2 * hi\n", + " for (clo, chi), (lo, hi) in zip(child.box, patch.box, strict=True)\n", + " )\n", + ")\n", + "print(\"block of level 3:\", child.box, \" its parent on level 2:\", parent.box)" + ] + }, + { + "cell_type": "markdown", + "id": "6", + "metadata": {}, + "source": [ + "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\n", + "it may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n", + "\n", + "## Refining by the number of markers\n", + "\n", + "`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\n", + "particle tree stops splitting a box when it holds few enough particles; regridding with these\n", + "tags stops refining where the cells hold few enough markers. The markers are counted over all\n", + "ranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\n", + "background:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7", + "metadata": {}, + "outputs": [], + "source": [ + "rng = np.random.default_rng(3)\n", + "\n", + "\n", + "def markers(n, cx, cy):\n", + " x = np.concatenate(\n", + " [\n", + " rng.normal(cx, 0.04, n),\n", + " rng.normal(0.7, 0.1, n // 2),\n", + " rng.uniform(0, 1, n // 4),\n", + " ]\n", + " )\n", + " y = np.concatenate(\n", + " [\n", + " rng.normal(cy, 0.04, n),\n", + " rng.normal(0.35, 0.06, n // 2),\n", + " rng.uniform(0, 1, n // 4),\n", + " ]\n", + " )\n", + " inside = (x > 0) & (x < 1) & (y > 0) & (y < 1)\n", + " return x[inside], y[inside]\n", + "\n", + "\n", + "x, y = markers(40_000, 0.3, 0.6)\n", + "base = AMRHierarchy(base_shape=(32, 32))\n", + "base.allocate_field(\"rho\", centering=\"node\")\n", + "mesh = base\n", + "for _ in range(3): # a level can only be tagged once it exists: one more each time\n", + " mesh = mesh.regrid(\n", + " marker_tags(mesh, x, y, per_cell=20, levels=3), method=\"quadtree\", block_size=16\n", + " )\n", + "\n", + "fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", + "ax.plot(x[::10], y[::10], \",\", color=\"0.5\")\n", + "plot_patches(mesh, ax=ax, show_grid=False)\n", + "ax.set_title(f\"{len(mesh.patches)} patches, {mesh.max_level} levels\")" + ] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": {}, + "source": [ + "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\n", + "potential (grounded faces)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": {}, + "outputs": [], + "source": [ + "charge = np.full(x.size, 1.0 / x.size)\n", + "mx, my, mq = mesh.migrate(x, y, charge, name=\"rho\")\n", + "mesh.deposit(mx, my, mq, \"rho\")\n", + "mesh.accumulate_halos(\"rho\")\n", + "\n", + "solver = NodalPoisson(mesh)\n", + "density = solver.nodes.from_patches(\"rho\") / solver.nodes.volumes\n", + "solver.solve(density, potential=\"phi\")\n", + "print(f\"total charge {solver.nodes.from_patches('rho').sum():.6f}\")\n", + "fig, ax = plot_patches(mesh, field=\"phi\", show_grid=False)" + ] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, + "source": [ + "## Following a moving beam\n", + "\n", + "The beam moves to the right, and the mesh is regridded after every step. Between two regrids\n", + "the clusters are recut wherever the tags change, even by a few cells, while the quadtree\n", + "adds and removes blocks only where the beam has come or gone and keeps the others as they\n", + "are: the same patches, on the same ranks, with their fields copied rather than\n", + "interpolated. Kept patches are grey, new ones red:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11", + "metadata": {}, + "outputs": [], + "source": [ + "from matplotlib.patches import Rectangle\n", + "\n", + "\n", + "def draw(ax, mesh, previous):\n", + " for patch in mesh.patches:\n", + " if patch.level == 0:\n", + " continue\n", + " (i0, i1), (j0, j1) = patch.box\n", + " xs = mesh.node_positions(patch.level, 0)\n", + " ys = mesh.node_positions(patch.level, 1)\n", + " kept = (patch.level, patch.box) in previous\n", + " ax.add_patch(\n", + " Rectangle(\n", + " (xs[i0], ys[j0]),\n", + " xs[i1] - xs[i0],\n", + " ys[j1] - ys[j0],\n", + " fill=not kept,\n", + " facecolor=\"tab:red\",\n", + " edgecolor=\"0.4\" if kept else \"tab:red\",\n", + " alpha=0.6 if kept else 0.35,\n", + " lw=0.8,\n", + " )\n", + " )\n", + " ax.set_xlim(0, 1)\n", + " ax.set_ylim(0, 1)\n", + " ax.set_aspect(\"equal\")\n", + "\n", + "\n", + "fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)\n", + "for ax, (method, options) in zip(\n", + " axes, [(\"cluster\", {}), (\"quadtree\", {\"block_size\": 8})], strict=True\n", + "):\n", + " mesh, previous, kept = base, set(), []\n", + " for step in range(12):\n", + " x, y = markers(40_000, 0.25 + 0.04 * step, 0.6)\n", + " tags = marker_tags(mesh, x, y, per_cell=20, levels=3)\n", + " new = mesh.regrid(tags, method=method, **options)\n", + " boxes = {(patch.level, patch.box) for patch in new.patches if patch.level}\n", + " if step > 3: # once all levels are there\n", + " kept.append(len(boxes & previous) / len(boxes))\n", + " if step == 11:\n", + " draw(ax, new, previous)\n", + " mesh, previous = new, boxes\n", + " refined = sum(cells(mesh, level) for level in range(1, mesh.max_level + 1))\n", + " ax.set_title(\n", + " f\"{method}: {len(boxes)} patches, {refined} refined cells,\\n\"\n", + " f\"{np.mean(kept):.0%} of the patches kept per regrid\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "12", + "metadata": {}, + "source": [ + "The few new blocks far from the beam come from the uniform background: its count per cell\n", + "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", + "markers per cell than `per_cell` in the background they would not appear.\n", + "\n", + "## Which one to use\n", + "\n", + "- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n", + " change slowly and the per-patch overhead matters.\n", + "- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n", + " and a regrid leaves most of them untouched: the choice when the tags change every few\n", + " steps, as with markers that move, and for spreading many equal patches over ranks\n", + " (`placement=\"balanced\"`).\n", + "\n", + "`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\n", + "many patches; large blocks give few patches and refine more cells." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From b7b1d5b443014ffe1c7367fc621e1241141a4fb9 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:03:04 +0000 Subject: [PATCH 02/24] docs: README.md as quarto renders it. --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b57212d..6540a9f 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,10 @@ A hierarchy can also be the axisymmetric r–z plane `regrid` places the patches itself: tag the cells that need finer cells (by a field’s change across a cell, a function of the position, or by -hand), and it covers them with properly nested patches (Berger-Rigoutsos clustering, or the blocks of a quadtree with -`method="quadtree"`) and moves the fields over; `marker_tags` tags the cells -that hold too many markers. +hand), and it covers them with properly nested patches (Berger-Rigoutsos +clustering, or the blocks of a quadtree with `method="quadtree"`) and +moves the fields over; `marker_tags` tags the cells that hold too many +markers. Markers live on the patches too: `locate` finds the finest patch of each point (a compiled kernel with the `pyccel` extra), `owner` and `migrate` From e74d2d895d5cc1a3b4a69250642bb392cb8db2e5 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:47:22 +0000 Subject: [PATCH 03/24] feat: Morton placement, a cheaper regrid transfer, and the quadtree benchmark. --- benchmarks/quadtree/README.md | 16 +++ benchmarks/quadtree/bench_quadtree.py | 162 ++++++++++++++++++++++ benchmarks/quadtree/run.py | 129 +++++++++++++++++ src/patchwork/__init__.py | 2 + src/patchwork/mesh/__init__.py | 2 + src/patchwork/mesh/hierarchy.py | 34 +++-- src/patchwork/mesh/regrid.py | 68 +++++++-- src/patchwork/tests/unit/test_quadtree.py | 51 ++++++- 8 files changed, 445 insertions(+), 19 deletions(-) create mode 100644 benchmarks/quadtree/README.md create mode 100644 benchmarks/quadtree/bench_quadtree.py create mode 100644 benchmarks/quadtree/run.py diff --git a/benchmarks/quadtree/README.md b/benchmarks/quadtree/README.md new file mode 100644 index 0000000..f5c1c7f --- /dev/null +++ b/benchmarks/quadtree/README.md @@ -0,0 +1,16 @@ +# Quadtree patches against clustered ones + +`bench_quadtree.py` runs a particle-in-cell cycle on a mesh that follows a moving beam of +markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve, exchange +the halos and gather, each a scope-profiler region. `run.py` runs it for clustered patches +(`method="cluster"`, with and without `max_patch_size`) and quadtree blocks of 8, 16 and 32 +cells, and prints a table; under MPI it compares `placement="balanced"` with +`placement="morton"` (without the solve, which the LU backend does not distribute). + +```sh +python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve +python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid +python benchmarks/quadtree/run.py --out /tmp/quadtree --steps 40 --base 128 # any option of bench_quadtree.py +``` + +`RESULTS.md` has the numbers of the last run. diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py new file mode 100644 index 0000000..0e32870 --- /dev/null +++ b/benchmarks/quadtree/bench_quadtree.py @@ -0,0 +1,162 @@ +"""Quadtree patches against clustered ones in a particle-in-cell cycle. + +A beam of markers (a Gaussian of width ``--width``, ``--markers`` of them, on a uniform +background) moves across the unit square on a ``--base`` x ``--base`` base, and every step + +- ``tag``: `marker_tags` (more than ``--per-cell`` markers per cell, ``--levels`` levels); +- ``regrid``: `regrid` with ``--method`` (``cluster`` or ``quadtree`` with ``--block-size``) + and ``--placement`` (``balanced`` or ``morton``); +- ``migrate``, ``deposit``: the markers to their patches' ranks, cloud-in-cell deposit and + `accumulate_halos`; +- ``solver``, ``solve``: a new `NodalPoisson` on the new mesh and its solve (serial only, + or with ``--solve`` where the LU backend is enough); +- ``halos``: `exchange_halos` of the potential (or of the charge without a solve); +- ``gather``: `interpolate` at the markers. + +Each part is a scope-profiler region (``quadtree_bench.``); run with + + scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py --method quadtree + mpiexec -n 4 scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py \\ + --placement morton --no-solve + +and read the times with ``scope-profiler inspect prof.h5 --sort total``. Rank 0 also prints +one JSON line with the mesh: patches, refined cells, the share of patches a regrid keeps, +and the cells per rank. +""" + +from __future__ import annotations + +import argparse +import json + +import numpy as np +import scope_profiler as sp +from maybempi import MPI + +from patchwork import AMRHierarchy, NodalPoisson, marker_tags + + +def beam(rng, count: int, width: float, centre: tuple[float, float]): + """Markers of a Gaussian beam on a uniform background (a fifth of them), in the unit square.""" + dense = count * 4 // 5 + x = np.concatenate( + [rng.normal(centre[0], width, dense), rng.uniform(0, 1, count - dense)] + ) + y = np.concatenate( + [rng.normal(centre[1], width, dense), rng.uniform(0, 1, count - dense)] + ) + inside = (x > 0) & (x < 1) & (y > 0) & (y < 1) + return x[inside], y[inside] + + +def refined_cells(mesh) -> int: + return sum( + int(np.prod([hi - lo for lo, hi in patch.box])) + for patch in mesh.patches + if patch.level + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--method", choices=["cluster", "quadtree"], default="quadtree") + parser.add_argument("--block-size", type=int, default=16) + parser.add_argument("--max-patch-size", type=int, default=None) + parser.add_argument( + "--placement", choices=["balanced", "morton"], default="balanced" + ) + parser.add_argument("--base", type=int, default=64) + parser.add_argument("--levels", type=int, default=3) + parser.add_argument("--markers", type=int, default=200_000) + parser.add_argument("--per-cell", type=float, default=20.0) + parser.add_argument("--width", type=float, default=0.06) + parser.add_argument("--steps", type=int, default=20) + parser.add_argument("--speed", type=float, default=0.01, help="beam shift per step") + parser.add_argument("--no-solve", dest="solve", action="store_false") + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args() + + comm = MPI.COMM_WORLD + rank, size = comm.Get_rank(), comm.Get_size() + rng = np.random.default_rng(args.seed + rank) + options = ( + {"method": "quadtree", "block_size": args.block_size} + if args.method == "quadtree" + else {"method": "cluster", "max_patch_size": args.max_patch_size} + ) + mesh = AMRHierarchy( + base_shape=(args.base, args.base), + placement=args.placement, + comm=comm, + ) + mesh.allocate_field("rho", centering="node") + if args.solve: + mesh.allocate_field("phi", centering="node") + + def markers(step: int): + x, y = beam( + rng, args.markers // size, args.width, (0.25 + args.speed * step, 0.5) + ) + return x, y, np.full(x.size, 1.0 / args.markers) + + # build the levels on the first beam, one level per regrid, untimed + x, y, q = markers(0) + for _ in range(args.levels): + mesh = mesh.regrid( + marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels), + **options, + ) + + kept, patches, cells = [], [], [] + previous = {(p.level, p.box) for p in mesh.patches if p.level} + for step in range(1, args.steps + 1): + x, y, q = markers(step) + with sp.region("quadtree_bench.tag"): + tags = marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels) + with sp.region("quadtree_bench.regrid"): + mesh = mesh.regrid(tags, **options) + boxes = {(p.level, p.box) for p in mesh.patches if p.level} + kept.append(len(boxes & previous) / max(len(boxes), 1)) + previous = boxes + patches.append(len(boxes)) + cells.append(refined_cells(mesh)) + with sp.region("quadtree_bench.migrate"): + mx, my, mq = mesh.migrate(x, y, q, name="rho") + with sp.region("quadtree_bench.deposit"): + mesh.deposit(mx, my, mq, "rho") + mesh.accumulate_halos("rho") + field = "rho" + if args.solve: + with sp.region("quadtree_bench.solver"): + solver = NodalPoisson(mesh) + with sp.region("quadtree_bench.solve"): + density = solver.nodes.from_patches("rho") / solver.nodes.volumes + solver.solve(density, potential="phi") + field = "phi" + with sp.region("quadtree_bench.halos"): + mesh.exchange_halos(field) + with sp.region("quadtree_bench.gather"): + mesh.interpolate(mx, my, field) + + load = mesh.cells_on_rank + if rank == 0: + print( + json.dumps( + { + "method": args.method, + "block_size": args.block_size + if args.method == "quadtree" + else None, + "placement": args.placement, + "ranks": size, + "patches": float(np.mean(patches)), + "refined_cells": float(np.mean(cells)), + "kept": float(np.mean(kept)), + "load_imbalance": max(load) / (sum(load) / len(load)), + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py new file mode 100644 index 0000000..5d8998f --- /dev/null +++ b/benchmarks/quadtree/run.py @@ -0,0 +1,129 @@ +"""Run `bench_quadtree.py` for several meshes and placements and print a table of the times. + + python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve + python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid + +Every configuration runs ``--repeats`` times under ``scope-profiler run``; the table gives +the median over the repeats of the mean time per step of each region (ms), and the mesh of +the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and +the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).parent +BENCH = HERE / "bench_quadtree.py" +PROFILER = Path(sys.executable).with_name("scope-profiler") +PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather") + +#: (label, arguments) of the meshes compared +MESHES = [ + ("cluster", ["--method", "cluster"]), + ("cluster, max 16", ["--method", "cluster", "--max-patch-size", "16"]), + ("quadtree 8", ["--method", "quadtree", "--block-size", "8"]), + ("quadtree 16", ["--method", "quadtree", "--block-size", "16"]), + ("quadtree 32", ["--method", "quadtree", "--block-size", "32"]), +] + + +def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict]: + """One profiled run: the JSON line of the mesh and the mean ms per step of each part.""" + command = [str(PROFILER), "run", "-o", str(output), str(BENCH), *arguments] + if ranks > 1: + command = ["mpiexec", "-n", str(ranks), "--oversubscribe", *command] + env = os.environ | { + "OMPI_ALLOW_RUN_AS_ROOT": "1", + "OMPI_ALLOW_RUN_AS_ROOT_CONFIRM": "1", + "OMP_NUM_THREADS": "1", + } + result = subprocess.run( + command, capture_output=True, text=True, env=env, check=True + ) + mesh = next( + json.loads(line) + for line in result.stdout.splitlines() + if line.startswith("{") and '"method"' in line + ) + inspected = subprocess.run( + [str(PROFILER), "inspect", str(output), "--json", "--top", "50"], + capture_output=True, + text=True, + check=True, + ) + regions = json.loads(inspected.stdout)["regions"]["items"] + times = {} + for region in regions: + name = region["name"] + if name.startswith("quadtree_bench."): + # the slowest rank's mean per call + times[name.split(".", 1)[1]] = ( + 1e3 * region["max"] if ranks > 1 else 1e3 * region["avg"] + ) + return mesh, times + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--ranks", type=int, default=1) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--placements", nargs="+", default=None) + args, bench = parser.parse_known_args() + args.out.mkdir(parents=True, exist_ok=True) + placements = args.placements or ( + ["balanced", "morton"] if args.ranks > 1 else ["balanced"] + ) + extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"]) + + header = [ + "mesh", + "placement", + "patches", + "refined", + "kept", + "imbalance", + *PARTS, + "total", + ] + print("| " + " | ".join(header) + " |") + print("|" + "---|" * len(header)) + for label, arguments in MESHES: + for placement in placements: + runs = [] + for repeat in range(args.repeats): + name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5" + runs.append( + run_once( + [*arguments, "--placement", placement, *extra], + args.ranks, + args.out / name, + ) + ) + mesh = runs[0][0] + times = { + part: float(np.median([t.get(part, 0.0) for _, t in runs])) + for part in PARTS + } + total = sum(times.values()) + cells = [ + f"{mesh['patches']:.0f}", + f"{mesh['refined_cells']:.0f}", + f"{mesh['kept']:.0%}", + f"{mesh['load_imbalance']:.2f}", + *(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS), + f"{total:.1f}", + ] + print(f"| {label} | {placement} | " + " | ".join(cells) + " |", flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index df91035..97e3893 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -19,6 +19,7 @@ graded_nodes, gradient_tags, marker_tags, + morton_ranks, plot_patches, quadtree_boxes, ) @@ -91,6 +92,7 @@ "graded_nodes", "gradient_tags", "marker_tags", + "morton_ranks", "plot_patches", "quadtree_boxes", "solve_nodal_poisson", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index 898391e..a50e190 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -16,6 +16,7 @@ function_tags, gradient_tags, marker_tags, + morton_ranks, quadtree_boxes, ) @@ -29,6 +30,7 @@ "graded_nodes", "gradient_tags", "marker_tags", + "morton_ranks", "plot_patches", "quadtree_boxes", ] diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 232a98a..ca73b1b 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -299,10 +299,15 @@ class AMRHierarchy: on several, over which mpiarray splits its fields. ``placement`` says where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so - far, or a function ``placement(level, box)`` that returns the ranks (as - ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a - ``"balanced"`` patch with more cells than that is split over as many of - the least loaded ranks as it needs (at most all of them). + far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the + patches (each level's patches, in the order of the curve, cut into + pieces of about equal cells, one piece per rank, so that neighbouring + patches tend to share a rank; a patch added by `add_patch` goes where + ``"balanced"`` would put it), or a function ``placement(level, box)`` that + returns the ranks (as ``ranks`` of `add_patch` takes them). With + ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is + split over as many of the least loaded ranks as it needs (at most all of + them); a ``"morton"`` patch stays on one rank. The domain is the rectangle of ``base_shape`` cells, or with ``base_boxes`` the union of those boxes of base cells: an L, a T, a rectangle with a notch. @@ -477,9 +482,10 @@ def __init__( ) self.geometry = geometry self.comm = mpa.default_comm() if comm is None else comm - if not callable(placement) and placement not in ("all", "balanced"): + if not callable(placement) and placement not in ("all", "balanced", "morton"): raise ValueError( - f"placement must be 'all', 'balanced' or a function, got {placement!r}" + "placement must be 'all', 'balanced', 'morton' or a function, " + f"got {placement!r}" ) if max_cells_per_rank is not None and int(max_cells_per_rank) < 1: raise ValueError("max_cells_per_rank must be at least 1") @@ -1046,7 +1052,7 @@ def regrid( are dropped, as are those that would need patches too close to it. New patches are placed by ``placement`` (default: this hierarchy's), - the largest first. Collective over ``comm``; this hierarchy is left as + the largest first, or along a Morton curve with ``"morton"``. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ from patchwork.mesh.regrid import ( @@ -1101,9 +1107,17 @@ def regrid( geometry=self.geometry, axis_nodes=self.axis_nodes, ) - for level in sorted(boxes): - for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): - new.add_patch(level, box) + if new.placement == "morton": + from patchwork.mesh.regrid import morton_ranks + + for level in sorted(boxes): + ranks = morton_ranks(boxes[level], self.comm.Get_size()) + for box, rank in zip(boxes[level], ranks, strict=True): + new.add_patch(level, box, ranks=rank) + else: + for level in sorted(boxes): + for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): + new.add_patch(level, box) for name, spec in self._field_specs.items(): if spec["conservative"]: self.restrict(name) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index cb48c0d..1208422 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -33,6 +33,7 @@ import itertools from typing import TYPE_CHECKING, Any +import cunumpy as xp import mpiarray as mpa import numpy as np import scope_profiler as sp @@ -50,7 +51,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Mapping + from collections.abc import Callable, Mapping, Sequence from patchwork.mesh.hierarchy import AMRHierarchy, IndexBox @@ -715,6 +716,48 @@ def quadtree_boxes( return boxes +@method( + equations={ + "key": r"k(\mathbf i) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b(i_d)\, 2^{bD + d} \quad \text{(the lower corner of a patch)}", + "ranks": r"r(B) = \min\left(R - 1, \left\lfloor R\, \frac{C_{ list[int]: + """The rank of each box of one level: the boxes along a Morton curve, cut into ``size`` pieces. + + The boxes are ordered by the Morton (Z-order) key of their lower corner, + which keeps boxes that are close in space close in the order, and the + order is cut where the running count of cells passes ``k / size`` of all + cells: each rank gets a run of neighbouring boxes with about the same + number of cells. Returns the ranks in the order of ``boxes``. + """ + if size < 1: + raise ValueError(f"size must be at least 1, got {size}") + cells = [int(np.prod([hi - lo for lo, hi in box])) for box in boxes] + corners = np.array([[lo for lo, _ in box] for box in boxes], dtype=np.uint64) + if corners.size and corners.shape[1] > 1: + keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D + else: # 1D: the curve is the axis + keys = corners.reshape(-1) + order = sorted(range(len(boxes)), key=lambda n: (int(keys[n]), boxes[n])) + total = sum(cells) + ranks = [0] * len(boxes) + before = 0 + for n in order: + middle = before + cells[n] / 2 + ranks[n] = min(size - 1, int(size * middle / total)) if total else 0 + before += cells[n] + return ranks + + @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). @@ -743,9 +786,10 @@ def new_field(patch: Any) -> Any: for patch in new.patches_at_level(level): own = points.own(patch) origin = tuple(lo for lo, _ in own) - covered = np.zeros([hi - lo for lo, hi in own], dtype=bool) + # the old patches near this one (a bin index, not every pair) + mine = [] for previous in ( - old.patches_at_level(level) if level <= old.max_level else () + old_points.near(level, own) if level <= old.max_level else () ): theirs = old_points.own(previous) their_origin = tuple(lo for lo, _ in theirs) @@ -758,11 +802,19 @@ def new_field(patch: Any) -> Any: tuple(-d - o for d, o in zip(shift, their_origin, strict=True)), ) target = _shift(part, tuple(-o for o in origin)) - copies.append( - (old_field(previous), source, new_field(patch), target) - ) - covered[tuple(slice(s, e) for s, e in target)] = True - if level == 0: + mine.append((old_field(previous), source, new_field(patch), target)) + # the last copy of a point wins: drop the copies that later ones overwrite + # entirely (an old patch with the same box makes its neighbours' shared + # nodes redundant), so that a kept patch costs one copy, not one per neighbour + covered = np.zeros([hi - lo for lo, hi in own], dtype=bool) + kept = [] + for copy in reversed(mine): + where = tuple(slice(s, e) for s, e in copy[3]) + if not covered[where].all(): + kept.append(copy) + covered[where] = True + copies.extend(reversed(kept)) + if level == 0 or covered.all(): continue index = tuple( values + o diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index d91051b..18d5503 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -9,7 +9,13 @@ import pytest from maybempi import MPI -from patchwork import AMRHierarchy, function_tags, marker_tags, quadtree_boxes +from patchwork import ( + AMRHierarchy, + function_tags, + marker_tags, + morton_ranks, + quadtree_boxes, +) from patchwork.mesh.regrid import combine_tags WORLD = MPI.COMM_WORLD @@ -215,3 +221,46 @@ def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: tags = {0: np.ones((8, 8), dtype=bool)} new = mesh.regrid(tags, method="quadtree", block_size=4, forbid=lambda x, y: x > -1) assert new.max_level == 0 + + +def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: + # sixteen 2 x 2 blocks of a 8 x 8 level: the Z curve visits the quadrants in turn + boxes = [ + ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) + ] + ranks = morton_ranks(boxes, 4) + for box, rank in zip(boxes, ranks, strict=True): + (i0, _), (j0, _) = box + assert rank == 2 * (i0 >= 4) + (j0 >= 4) or rank == (i0 >= 4) + 2 * (j0 >= 4) + assert sorted(ranks) == [r for r in range(4) for _ in range(4)] + # unequal boxes: the cells per rank differ by at most one box + boxes = [((0, 8), (0, 8)), ((8, 10), (0, 2)), ((8, 10), (2, 4)), ((10, 12), (0, 2))] + cells = [64, 4, 4, 4] + ranks = morton_ranks(boxes, 2) + load = [ + sum(c for c, r in zip(cells, ranks, strict=True) if r == k) for k in range(2) + ] + assert sum(load) == 76 and max(load) - min(load) <= 64 + assert morton_ranks(boxes, 1) == [0, 0, 0, 0] + assert morton_ranks([], 3) == [] + with pytest.raises(ValueError, match="size"): + morton_ranks(boxes, 0) + + +def test_regrid_places_the_blocks_along_the_morton_curve() -> None: + mesh = AMRHierarchy(base_shape=(16, 16), placement="morton") + mesh.allocate_field("u", centering="node") + tags = function_tags(mesh, ring, levels=2) + new = mesh.regrid(tags, method="quadtree", block_size=8) + assert new.placement == "morton" + for level in (1, 2): + patches = new.patches_at_level(level) + expected = morton_ranks([p.box for p in patches], SIZE) + assert [p.ranks for p in patches] == [(r,) for r in expected] + # the next regrid keeps the placement; a patch added by hand is balanced + again = new.regrid(tags, method="quadtree", block_size=8, fill_halos=True) + assert again.placement == "morton" + added = again.add_patch(3, ((40, 48), (40, 48))) + assert len(added.ranks) == 1 + with pytest.raises(ValueError, match="morton"): + AMRHierarchy(base_shape=(4, 4), placement="hilbert") From 566690308acddd06f5be8d5c4dda7b651d457ea4 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:47:38 +0000 Subject: [PATCH 04/24] Docstrings of the quadtree benchmark. --- benchmarks/quadtree/bench_quadtree.py | 4 +++- benchmarks/quadtree/run.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 0e32870..7113df3 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -1,4 +1,4 @@ -"""Quadtree patches against clustered ones in a particle-in-cell cycle. +r"""Quadtree patches against clustered ones in a particle-in-cell cycle. A beam of markers (a Gaussian of width ``--width``, ``--markers`` of them, on a uniform background) moves across the unit square on a ``--base`` x ``--base`` base, and every step @@ -50,6 +50,7 @@ def beam(rng, count: int, width: float, centre: tuple[float, float]): def refined_cells(mesh) -> int: + """The cells of the patches above the base level.""" return sum( int(np.prod([hi - lo for lo, hi in patch.box])) for patch in mesh.patches @@ -58,6 +59,7 @@ def refined_cells(mesh) -> int: def main() -> None: + """Run the cycle and print the mesh of the run as one JSON line.""" parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--method", choices=["cluster", "quadtree"], default="quadtree") parser.add_argument("--block-size", type=int, default=16) diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index 5d8998f..db9efa4 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -72,6 +72,7 @@ def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict def main() -> None: + """Run every configuration and print the table.""" parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--ranks", type=int, default=1) From 7e602560aac6d098ca7c0eec70cdf3dec7bcd243 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 04:55:48 +0000 Subject: [PATCH 05/24] Morton placement over all levels, with the base level's load counted. --- src/patchwork/mesh/hierarchy.py | 16 ++++-- src/patchwork/mesh/regrid.py | 70 +++++++++++++++-------- src/patchwork/tests/unit/test_quadtree.py | 37 ++++++------ 3 files changed, 78 insertions(+), 45 deletions(-) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index ca73b1b..044aa1e 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -300,9 +300,10 @@ class AMRHierarchy: where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the - patches (each level's patches, in the order of the curve, cut into - pieces of about equal cells, one piece per rank, so that neighbouring - patches tend to share a rank; a patch added by `add_patch` goes where + patches (`morton_ranks`: the patches of all levels in the order of the + curve, cut into runs of about equal cells with the base level counted, + one run per rank, so that neighbouring patches and the patches over them + tend to share a rank; a patch added by `add_patch` goes where ``"balanced"`` would put it), or a function ``placement(level, box)`` that returns the ranks (as ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is @@ -1110,9 +1111,14 @@ def regrid( if new.placement == "morton": from patchwork.mesh.regrid import morton_ranks + ranks = morton_ranks( + boxes, + self.comm.Get_size(), + ratio=self.refinement_ratio, + load=new.cells_on_rank, # the base level + ) for level in sorted(boxes): - ranks = morton_ranks(boxes[level], self.comm.Get_size()) - for box, rank in zip(boxes[level], ranks, strict=True): + for box, rank in zip(boxes[level], ranks[level], strict=True): new.add_patch(level, box, ranks=rank) else: for level in sorted(boxes): diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 1208422..81a5df6 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -718,44 +718,66 @@ def quadtree_boxes( @method( equations={ - "key": r"k(\mathbf i) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b(i_d)\, 2^{bD + d} \quad \text{(the lower corner of a patch)}", - "ranks": r"r(B) = \min\left(R - 1, \left\lfloor R\, \frac{C_{ list[int]: - """The rank of each box of one level: the boxes along a Morton curve, cut into ``size`` pieces. - - The boxes are ordered by the Morton (Z-order) key of their lower corner, - which keeps boxes that are close in space close in the order, and the - order is cut where the running count of cells passes ``k / size`` of all - cells: each rank gets a run of neighbouring boxes with about the same - number of cells. Returns the ranks in the order of ``boxes``. +def morton_ranks( + boxes: Mapping[int, Sequence[IndexBox]], + size: int, + *, + ratio: int = 2, + load: Sequence[float] | None = None, +) -> dict[int, list[int]]: + """The rank of each box: the boxes of all levels along a Morton curve, cut into ``size`` runs. + + ``boxes`` maps a level to its boxes. Every box gets the Morton (Z-order) + key of its lower corner in cells of the finest level, so that boxes close + in space are close on the curve whatever their level, and a box comes + before the finer boxes at the same corner. Walking the curve, a rank takes + boxes until its cells, with the ``load`` it already has (the cells of the + base level, say), reach an equal share of all cells; then the next rank + goes on. Returns, per level, the ranks in the order of ``boxes[level]``. """ if size < 1: raise ValueError(f"size must be at least 1, got {size}") - cells = [int(np.prod([hi - lo for lo, hi in box])) for box in boxes] - corners = np.array([[lo for lo, _ in box] for box in boxes], dtype=np.uint64) - if corners.size and corners.shape[1] > 1: + weights = [0.0] * size if load is None else [float(w) for w in load] + if len(weights) != size: + raise ValueError(f"load needs {size} values, got {len(weights)}") + items = [ + (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) + ] + result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} + if not items: + return result + top = max(level for level, _, _ in items) + corners = np.array( + [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], + dtype=np.uint64, + ) + if corners.shape[1] > 1: keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D else: # 1D: the curve is the axis keys = corners.reshape(-1) - order = sorted(range(len(boxes)), key=lambda n: (int(keys[n]), boxes[n])) - total = sum(cells) - ranks = [0] * len(boxes) - before = 0 - for n in order: - middle = before + cells[n] / 2 - ranks[n] = min(size - 1, int(size * middle / total)) if total else 0 - before += cells[n] - return ranks + cells = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + share = (sum(weights) + sum(cells)) / size + rank = 0 + for k in sorted(range(len(items)), key=lambda k: (int(keys[k]), items[k][0])): + while rank < size - 1 and weights[rank] + cells[k] / 2 > share: + rank += 1 + level, n, _ = items[k] + result[level][n] = rank + weights[rank] += cells[k] + return result @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 18d5503..8c5d2fd 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -228,23 +228,23 @@ def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: boxes = [ ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) ] - ranks = morton_ranks(boxes, 4) + ranks = morton_ranks({1: boxes}, 4)[1] for box, rank in zip(boxes, ranks, strict=True): (i0, _), (j0, _) = box - assert rank == 2 * (i0 >= 4) + (j0 >= 4) or rank == (i0 >= 4) + 2 * (j0 >= 4) - assert sorted(ranks) == [r for r in range(4) for _ in range(4)] - # unequal boxes: the cells per rank differ by at most one box - boxes = [((0, 8), (0, 8)), ((8, 10), (0, 2)), ((8, 10), (2, 4)), ((10, 12), (0, 2))] - cells = [64, 4, 4, 4] - ranks = morton_ranks(boxes, 2) - load = [ - sum(c for c, r in zip(cells, ranks, strict=True) if r == k) for k in range(2) - ] - assert sum(load) == 76 and max(load) - min(load) <= 64 - assert morton_ranks(boxes, 1) == [0, 0, 0, 0] - assert morton_ranks([], 3) == [] + assert rank == (i0 >= 4) + 2 * (j0 >= 4) # the first axis is the lowest bit + # a rank that holds the base already takes fewer patches + loaded = morton_ranks({1: boxes}, 2, load=[32, 0])[1] + assert loaded.count(0) == 4 and loaded.count(1) == 12 + # a patch and the finer patch over it are neighbours on the curve + levels = {1: [((0, 4), (0, 4)), ((4, 8), (4, 8))], 2: [((0, 4), (0, 4))]} + assert morton_ranks(levels, 2) == {1: [0, 1], 2: [0]} + assert morton_ranks({1: boxes}, 1)[1] == [0] * 16 + assert morton_ranks({}, 3) == {} + assert morton_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D with pytest.raises(ValueError, match="size"): - morton_ranks(boxes, 0) + morton_ranks({1: boxes}, 0) + with pytest.raises(ValueError, match="load"): + morton_ranks({1: boxes}, 2, load=[1.0]) def test_regrid_places_the_blocks_along_the_morton_curve() -> None: @@ -253,10 +253,15 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: tags = function_tags(mesh, ring, levels=2) new = mesh.regrid(tags, method="quadtree", block_size=8) assert new.placement == "morton" + boxes = {level: [p.box for p in new.patches_at_level(level)] for level in (1, 2)} + base = AMRHierarchy(base_shape=(16, 16), placement="morton").cells_on_rank + expected = morton_ranks(boxes, SIZE, load=base) for level in (1, 2): patches = new.patches_at_level(level) - expected = morton_ranks([p.box for p in patches], SIZE) - assert [p.ranks for p in patches] == [(r,) for r in expected] + assert [p.ranks for p in patches] == [(r,) for r in expected[level]] + # the cells per rank differ by less than the largest patch + load = new.cells_on_rank + assert max(load) - min(load) <= max(256, max(base)) # the next regrid keeps the placement; a patch added by hand is balanced again = new.regrid(tags, method="quadtree", block_size=8, fill_halos=True) assert again.placement == "morton" From 6ad46a78d5dfe11c72a745de0bcc22df8c3ceebe Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 05:02:53 +0000 Subject: [PATCH 06/24] Quadtree benchmark results, Morton placement in the tutorial and the changelog. --- CHANGELOG.md | 5 +++ benchmarks/quadtree/RESULTS.md | 65 +++++++++++++++++++++++++++++ benchmarks/quadtree/run.py | 32 +++++++------- tutorials/13_quadtree_patches.ipynb | 61 +++++++++++++++++++++++++++ 4 files changed, 147 insertions(+), 16 deletions(-) create mode 100644 benchmarks/quadtree/RESULTS.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c67d66b..3b6b634 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,11 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). allowed cells. `quadtree_boxes` gives the boxes on their own. More cells are refined than 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 + of about equal cells with the base level's cells counted. +- Benchmark `benchmarks/quadtree`: clusters against quadtree blocks in a particle-in-cell + cycle, serially and under MPI with both placements (`RESULTS.md`). - `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than `per_cell` markers, counted over all ranks. - Graded axes: `AMRHierarchy(axis_nodes=...)` takes, per axis, `None` (uniform) or the diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md new file mode 100644 index 0000000..117534c --- /dev/null +++ b/benchmarks/quadtree/RESULTS.md @@ -0,0 +1,65 @@ +# Results + +2026-11-25, a cloud container with 4 cores (Intel Xeon, 2.1 GHz), one thread per rank, +`bench_quadtree.py` defaults: a 64 x 64 base, 3 levels, 200,000 markers (four fifths in a +Gaussian beam of width 0.06 moving by 0.01 per step), `per_cell=20`, 20 timed steps. Times +are the median of 3 runs of the mean ms per step; under MPI on the rank where the part is +largest. "kept" is the share of the patches of a regrid that were there before it. + +## Serial, with the solve + +| mesh | patches | refined cells | kept | tag | regrid | migrate | deposit | solver | solve | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---|---|---|---| +| cluster | 8 | 27,864 | 0% | 73.9 | 10.3 | 22.0 | 57.8 | 114.1 | 6.2 | 4.7 | 31.2 | 320 | +| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 73.2 | 98.6 | 43.6 | 132.7 | 133.8 | 13.1 | 100.0 | 78.2 | 673 | +| quadtree, block 8 | 386 | 24,714 | 92% | 70.6 | 277.0 | 64.9 | 231.4 | 179.7 | 23.4 | 295.5 | 131.4 | 1274 | +| quadtree, block 16 | 121 | 30,925 | 91% | 72.4 | 75.3 | 40.0 | 126.4 | 135.1 | 12.4 | 94.5 | 74.6 | 631 | +| quadtree, block 32 | 49 | 50,330 | 94% | 72.3 | 26.0 | 31.2 | 88.6 | 204.6 | 13.0 | 43.0 | 53.5 | 532 | + +## 4 ranks, without the solve + +| mesh | placement | imbalance | tag | regrid | migrate | deposit | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---| +| cluster | balanced | 2.18 | 30.6 | 7.5 | 13.3 | 59.9 | 4.4 | 18.8 | 135 | +| cluster | morton | 2.19 | 32.0 | 7.6 | 12.4 | 57.5 | 4.8 | 23.0 | 137 | +| cluster, `max_patch_size=16` | balanced | 1.01 | 24.2 | 51.7 | 19.1 | 53.9 | 97.5 | 15.8 | 262 | +| cluster, `max_patch_size=16` | morton | 1.01 | 29.9 | 46.3 | 18.4 | 61.7 | 101.4 | 20.1 | 278 | +| quadtree, block 8 | balanced | 1.00 | 27.5 | 214.2 | 32.2 | 91.2 | 296.3 | 24.8 | 686 | +| quadtree, block 8 | morton | 1.00 | 30.7 | 189.0 | 30.9 | 95.9 | 273.5 | 25.3 | 645 | +| quadtree, block 16 | balanced | 1.02 | 24.6 | 39.4 | 17.8 | 60.5 | 96.6 | 16.6 | 256 | +| quadtree, block 16 | morton | 1.02 | 27.4 | 47.1 | 19.6 | 56.8 | 95.9 | 18.1 | 265 | +| quadtree, block 32 | balanced | 1.02 | 29.3 | 24.6 | 18.0 | 58.1 | 47.1 | 15.5 | 193 | +| quadtree, block 32 | morton | 1.02 | 25.5 | 17.3 | 14.5 | 49.7 | 36.3 | 15.2 | 158 | + +Imbalance: the largest cells per rank over the mean (the base level counted). + +## What they say + +- **The cost follows the number of patches, not how they are placed.** Regrid, halos, + deposit and gather grow with the patches: 8 clusters take 320 ms per step, 386 blocks of 8 + cells 1274 ms. At about the same number of patches the quadtree is as fast as clusters + (block 16, 121 patches: 631 ms; clusters cut to 16 cells, 134 patches: 673 ms), its + regrid a little faster since most of its patches are copied, not interpolated. +- **What the quadtree keeps is not reused yet.** 91-94% of its patches survive a regrid, + but the hierarchy is new, so the halo schedules (`build_schedule`, most of "halos"), the + composite node numbering and the solver are built again from scratch. Reusing them for + kept patches is where the quadtree could win; picnic's solver already reuses the grids and + probed operators of kept boxes (see picnic's `adaptive_rebuild_cost.py --method quadtree`). +- **Large blocks refine many cells**: blocks of 32 cover 50,330 cells for the 27,864 the + clusters need; the solver setup grows with them (205 ms against 114 ms). +- **Morton and balanced placement are within the noise on one node** (about 10% between + repeats). Morton keeps neighbouring patches and the patches over them on one rank, which + saves messages between nodes; within a node the messages are cheap and the halo time is + the schedule, built in Python. The few large clusters cannot be balanced by either (2.2). +- On four ranks tagging and gathering take about half as long as serially, but the deposit + does not get faster (58 ms serially, 50-96 ms on the slowest rank): the placements balance + cells, and the beam's patches hold most markers. Marker-weighted cuts of the Morton curve + are patchwork step 8e. + +## Fixed on the way + +The regrid's transfer compared every new patch with every old one of its level, and copied +the nodes a new patch shares with its old neighbours although an old patch with the same box +already had them. With the bin index of the halo schedules and without the copies that a +later one overwrites, the regrid of the 386-block mesh went from 866 ms to 277 ms per step +(serial), with the same values. diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index db9efa4..4bd7d42 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -4,7 +4,8 @@ python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid Every configuration runs ``--repeats`` times under ``scope-profiler run``; the table gives -the median over the repeats of the mean time per step of each region (ms), and the mesh of +the median over the repeats of the mean time per step of each region (ms; under MPI on the +rank where it is largest), and the mesh of the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``. """ @@ -53,21 +54,20 @@ def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict for line in result.stdout.splitlines() if line.startswith("{") and '"method"' in line ) - inspected = subprocess.run( - [str(PROFILER), "inspect", str(output), "--json", "--top", "50"], - capture_output=True, - text=True, - check=True, - ) - regions = json.loads(inspected.stdout)["regions"]["items"] - times = {} - for region in regions: - name = region["name"] - if name.startswith("quadtree_bench."): - # the slowest rank's mean per call - times[name.split(".", 1)[1]] = ( - 1e3 * region["max"] if ranks > 1 else 1e3 * region["avg"] - ) + times: dict[str, float] = {} + for rank in range(ranks): # the slowest rank's mean per step of each part + inspected = subprocess.run( + [str(PROFILER), "inspect", str(output), "--json", "--top", "50"] + + (["--ranks", str(rank)] if ranks > 1 else []), + capture_output=True, + text=True, + check=True, + ) + for region in json.loads(inspected.stdout)["regions"]["items"]: + name = region["name"] + if name.startswith("quadtree_bench."): + part = name.split(".", 1)[1] + times[part] = max(times.get(part, 0.0), 1e3 * region["avg"]) return mesh, times diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index 5eb019c..be9d882 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -289,6 +289,67 @@ "cell_type": "markdown", "id": "12", "metadata": {}, + "source": [ + "## Placing the blocks on ranks\n", + "\n", + "Under MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n", + "(Z-order) curve (`morton_ranks`): the patches of all levels in the order of the curve, keyed\n", + "by their lower corner in cells of the finest level, cut into runs of about equal cells, the\n", + "base level's cells counted. Neighbouring patches, and a patch and the patches over it, then\n", + "tend to share a rank, which saves messages between ranks. Here the ranks four processes would\n", + "give the patches of the beam's mesh:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13", + "metadata": {}, + "outputs": [], + "source": [ + "from patchwork import morton_ranks\n", + "\n", + "boxes = {\n", + " level: [patch.box for patch in mesh.patches_at_level(level)]\n", + " for level in range(1, mesh.max_level + 1)\n", + "}\n", + "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "colours = plt.get_cmap(\"tab10\").colors\n", + "\n", + "fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", + "for level in sorted(boxes):\n", + " xs, ys = mesh.node_positions(level, 0), mesh.node_positions(level, 1)\n", + " for ((i0, i1), (j0, j1)), rank in zip(boxes[level], ranks[level], strict=True):\n", + " ax.add_patch(\n", + " Rectangle(\n", + " (xs[i0], ys[j0]),\n", + " xs[i1] - xs[i0],\n", + " ys[j1] - ys[j0],\n", + " facecolor=colours[rank],\n", + " edgecolor=\"k\",\n", + " alpha=0.25,\n", + " lw=0.6,\n", + " )\n", + " )\n", + "ax.set_xlim(0, 1)\n", + "ax.set_ylim(0, 1)\n", + "ax.set_aspect(\"equal\")\n", + "cells = [\n", + " sum(\n", + " (hi0 - lo0) * (hi1 - lo1)\n", + " for level in boxes\n", + " for ((lo0, hi0), (lo1, hi1)), r in zip(boxes[level], ranks[level], strict=True)\n", + " if r == rank\n", + " )\n", + " for rank in range(4)\n", + "]\n", + "ax.set_title(f\"refined cells per rank: {cells} (rank 0 also has the base)\")" + ] + }, + { + "cell_type": "markdown", + "id": "14", + "metadata": {}, "source": [ "The few new blocks far from the beam come from the uniform background: its count per cell\n", "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", From dc62af1c34a53eeab12f583286a5e1f21f5ada9f Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 06:55:27 +0000 Subject: [PATCH 07/24] feat: reuse the halo geometry of kept patches, and Morton cuts weighted by marker counts. --- benchmarks/quadtree/bench_quadtree.py | 29 +++- benchmarks/quadtree/run.py | 20 ++- src/patchwork/__init__.py | 4 + src/patchwork/mesh/__init__.py | 4 + src/patchwork/mesh/halos.py | 170 +++++++++++++++++++++- src/patchwork/mesh/hierarchy.py | 25 +++- src/patchwork/mesh/regrid.py | 123 ++++++++++++---- src/patchwork/tests/unit/test_quadtree.py | 126 ++++++++++++++++ 8 files changed, 457 insertions(+), 44 deletions(-) diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 7113df3..df60150 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -5,7 +5,8 @@ - ``tag``: `marker_tags` (more than ``--per-cell`` markers per cell, ``--levels`` levels); - ``regrid``: `regrid` with ``--method`` (``cluster`` or ``quadtree`` with ``--block-size``) - and ``--placement`` (``balanced`` or ``morton``); + and ``--placement`` (``balanced`` or ``morton``, with ``--marker-cost`` the Morton cuts + weighted by the markers: `marker_counts` times the cost of a marker against a cell); - ``migrate``, ``deposit``: the markers to their patches' ranks, cloud-in-cell deposit and `accumulate_halos`; - ``solver``, ``solve``: a new `NodalPoisson` on the new mesh and its solve (serial only, @@ -33,7 +34,7 @@ import scope_profiler as sp from maybempi import MPI -from patchwork import AMRHierarchy, NodalPoisson, marker_tags +from patchwork import AMRHierarchy, NodalPoisson, marker_counts, marker_tags def beam(rng, count: int, width: float, centre: tuple[float, float]): @@ -67,6 +68,12 @@ def main() -> None: parser.add_argument( "--placement", choices=["balanced", "morton"], default="balanced" ) + parser.add_argument( + "--marker-cost", + type=float, + default=0.0, + help="what a marker costs against a cell: weighs the Morton cuts (with morton)", + ) parser.add_argument("--base", type=int, default=64) parser.add_argument("--levels", type=int, default=3) parser.add_argument("--markers", type=int, default=200_000) @@ -109,14 +116,22 @@ def markers(step: int): **options, ) - kept, patches, cells = [], [], [] + 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): x, y, q = markers(step) with sp.region("quadtree_bench.tag"): - tags = marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels) + counts = marker_counts(mesh, x, y, levels=args.levels + 1) + tags = { + level: counts[level] > args.per_cell for level in range(args.levels) + } + weigh = {} + if args.marker_cost and args.placement == "morton": + weigh["cost"] = { + level: args.marker_cost * found for level, found in counts.items() + } with sp.region("quadtree_bench.regrid"): - mesh = mesh.regrid(tags, **options) + mesh = mesh.regrid(tags, **options, **weigh) boxes = {(p.level, p.box) for p in mesh.patches if p.level} kept.append(len(boxes & previous) / max(len(boxes), 1)) previous = boxes @@ -124,6 +139,7 @@ def markers(step: int): cells.append(refined_cells(mesh)) with sp.region("quadtree_bench.migrate"): mx, my, mq = mesh.migrate(x, y, q, name="rho") + held.append(comm.allgather(mx.size)) with sp.region("quadtree_bench.deposit"): mesh.deposit(mx, my, mq, "rho") mesh.accumulate_halos("rho") @@ -155,6 +171,9 @@ def markers(step: int): "refined_cells": float(np.mean(cells)), "kept": float(np.mean(kept)), "load_imbalance": max(load) / (sum(load) / len(load)), + "marker_imbalance": float( + np.mean([max(h) / (sum(h) / len(h)) for h in held]) + ), } ) ) diff --git a/benchmarks/quadtree/run.py b/benchmarks/quadtree/run.py index 4bd7d42..9447c53 100644 --- a/benchmarks/quadtree/run.py +++ b/benchmarks/quadtree/run.py @@ -7,7 +7,9 @@ the median over the repeats of the mean time per step of each region (ms; under MPI on the rank where it is largest), and the mesh of the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and -the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``. +the load imbalance (largest cells per rank over the mean) and the marker imbalance (largest +markers per rank over the mean, after `migrate`). ``morton, markers`` weighs the Morton cuts +with the markers, a marker costing a tenth of a cell. Profiles are written to ``--out``. """ from __future__ import annotations @@ -26,6 +28,13 @@ PROFILER = Path(sys.executable).with_name("scope-profiler") PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather") +#: the placements compared under MPI, and their arguments +PLACEMENTS = { + "balanced": ["--placement", "balanced"], + "morton": ["--placement", "morton"], + "morton, markers": ["--placement", "morton", "--marker-cost", "0.1"], +} + #: (label, arguments) of the meshes compared MESHES = [ ("cluster", ["--method", "cluster"]), @@ -81,7 +90,7 @@ def main() -> None: args, bench = parser.parse_known_args() args.out.mkdir(parents=True, exist_ok=True) placements = args.placements or ( - ["balanced", "morton"] if args.ranks > 1 else ["balanced"] + list(PLACEMENTS) if args.ranks > 1 else ["balanced"] ) extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"]) @@ -92,6 +101,7 @@ def main() -> None: "refined", "kept", "imbalance", + "markers", *PARTS, "total", ] @@ -101,10 +111,11 @@ def main() -> None: for placement in placements: runs = [] for repeat in range(args.repeats): - name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5" + name = f"{label}_{placement}_{args.ranks}_{repeat}".replace(", ", "_") + name = name.replace(" ", "") + ".h5" runs.append( run_once( - [*arguments, "--placement", placement, *extra], + [*arguments, *PLACEMENTS[placement], *extra], args.ranks, args.out / name, ) @@ -120,6 +131,7 @@ def main() -> None: f"{mesh['refined_cells']:.0f}", f"{mesh['kept']:.0%}", f"{mesh['load_imbalance']:.2f}", + f"{mesh['marker_imbalance']:.2f}", *(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS), f"{total:.1f}", ] diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index 97e3893..d40902b 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -14,10 +14,12 @@ FluxRegister, IndexBox, Patch, + box_costs, cluster, function_tags, graded_nodes, gradient_tags, + marker_counts, marker_tags, morton_ranks, plot_patches, @@ -87,10 +89,12 @@ "PetscSystem", "__version__", "cell_body", + "box_costs", "cluster", "function_tags", "graded_nodes", "gradient_tags", + "marker_counts", "marker_tags", "morton_ranks", "plot_patches", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index a50e190..0db5ce8 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -12,9 +12,11 @@ from patchwork.mesh.plotting import plot_patches from patchwork.mesh.reflux import FluxRegister from patchwork.mesh.regrid import ( + box_costs, cluster, function_tags, gradient_tags, + marker_counts, marker_tags, morton_ranks, quadtree_boxes, @@ -25,10 +27,12 @@ "FluxRegister", "IndexBox", "Patch", + "box_costs", "cluster", "function_tags", "graded_nodes", "gradient_tags", + "marker_counts", "marker_tags", "morton_ranks", "plot_patches", diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 81192e9..2ee124a 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -523,6 +523,40 @@ def error(spacing: float) -> float: ), problem=_halo_problem, ) +def _key(patch: Patch) -> tuple: + """A patch as its level, box and ranks: the same in the hierarchies a regrid makes.""" + 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. + + ``copies`` are ``(source, box, target, box)`` with each array a slot: + ``("field", key)``, ``("coarse", key)`` (the field interpolated from) or + ``("buffer", shape)``, the patch's buffer of coarse values; ``None`` where + this rank does not hold the array. ``interpolation`` is the buffer's shape, + the storage index, the buffer points and the weights of the halo points + interpolated from the level below, or ``None``. + """ + + def __init__(self, copies: list[tuple], interpolation: tuple | None) -> None: + self.copies = copies + self.interpolation = interpolation + + class HaloExchange: """Fill the halo of every patch of field ``name``; see the module docstring. @@ -598,6 +632,112 @@ 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. + + 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)``. + """ + own = points.own(patch) + 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)) + + def _record(self, points: _Points, patch: Patch, dtype: Any) -> _HaloRecord: + """The halo geometry of one patch, with its fields as patch keys.""" + slots: dict[int, tuple] = {} + own_field, coarse_field = self._field, self._coarse_field + + def field(other: Patch) -> Any: + array = own_field(other) + if array is not None: + slots[id(array)] = ("field", _key(other)) + return array + + def coarse(other: Patch) -> Any: + array = coarse_field(other) + if array is not None: + slots[id(array)] = ("coarse", _key(other)) + return array + + copies: list[tuple] = [] + self._field, self._coarse_field = field, coarse # type: ignore[method-assign] + try: + covered = self._same_level(points, patch, copies) + interpolations: list = [] + if patch.level > 0: + before = self._interpolations + self._interpolations = interpolations + try: + self._coarse_fine(points, patch, covered, dtype, copies) + finally: + self._interpolations = before + finally: + del self._field, self._coarse_field # back to the methods + buffer = None + interpolation = None + if interpolations: + (found,) = interpolations + buffer = found.buffer + slots[id(buffer)] = ("buffer", tuple(buffer.shape)) + interpolation = ( + tuple(buffer.shape), + found.index, + found.flat, + found.weights, + ) + else: + for _, _, target, _ in copies: # a buffer on a rank without points + if target is not None and id(target) not in slots: + buffer = target + slots[id(target)] = ("buffer", tuple(target.shape)) + template = [ + ( + None if source is None else slots[id(source)], + source_box, + None if target is None else slots[id(target)], + target_box, + ) + for source, source_box, target, target_box in copies + ] + return _HaloRecord(template, interpolation) + + def _bind( + self, record: _HaloRecord, patch: Patch, patches: dict, dtype: Any + ) -> None: + """The copies and the interpolation of a record, on this hierarchy's arrays.""" + buffer = None + + def resolve(slot: tuple | None) -> Any: + nonlocal buffer + if slot is None: + return None + kind, key = slot + if kind == "buffer": + if buffer is None: + buffer = mpa.zeros(key, dtype=dtype, split=None, comm=patch.comm) + return buffer + other = patches[key] + return self._field(other) if kind == "field" else self._coarse_field(other) + + for source, source_box, target, target_box in record.copies: + self._copies.append( + (resolve(source), source_box, resolve(target), target_box) + ) + if record.interpolation is not None: + shape, index, flat, weights = record.interpolation + if buffer is None: + buffer = mpa.zeros(shape, dtype=dtype, split=None, comm=patch.comm) + self._interpolations.append( + _Bilinear(self._field(patch), index, buffer, flat, weights) + ) + def __init__( self, hierarchy: AMRHierarchy, @@ -610,6 +750,12 @@ def __init__( With ``level``, only for the patches of that level; with ``below``, interpolating field ``below`` of the level below instead of ``name``. + + The geometry of each patch's halo (which points come from which patch, + and the interpolation weights) is kept on the hierarchy, by centering, + width and type, and handed on by `AMRHierarchy.regrid`: a patch with the + same box and ranks, and the same patches within reach of its halo, reuses + it instead of finding it again. """ spec = hierarchy._field_specs[name] self._hierarchy = hierarchy @@ -617,16 +763,28 @@ def __init__( self._below = name if below is None else below self._level = level self._width = int(spec["halo"]) - points = _Points(hierarchy, spec["centering"] == "node") - copies: list[tuple] = [] + nodal = spec["centering"] == "node" + points = _Points(hierarchy, nodal) + self._copies: list[tuple] = [] self._interpolations: list[_Bilinear] = [] + dtype = spec["dtype"] + kind = ("halo", nodal, self._width, np.dtype(dtype).str, repr(spec["split"])) + known = hierarchy._halo_records.get(kind, {}) + used: dict[tuple, _HaloRecord] = {} + patches = {_key(patch): patch for patch in hierarchy.patches} for patch in hierarchy.patches if self._width else (): if level is not None and patch.level != level: continue - covered = self._same_level(points, patch, copies) - if patch.level > 0: - self._coarse_fine(points, patch, covered, spec["dtype"], copies) - self._plan = mpa.CopyPlan(copies, comm=hierarchy.comm) + signature = self._signature(points, patch) + record = known.get(signature) + if record is None: + record = self._record(points, patch, dtype) + used[signature] = record + self._bind(record, patch, patches, dtype) + # keep the records of this mesh (all of them after a full build) + hierarchy._halo_records[kind] = used if level is None else {**known, **used} + self._plan = mpa.CopyPlan(self._copies, comm=hierarchy.comm) + del self._copies def execute(self) -> None: """Fill the halos. Collective over the hierarchy's communicator.""" diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 044aa1e..da9a9ff 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -501,6 +501,9 @@ def __init__( self._cells_on_rank = [0.0] * self.comm.Get_size() # halo exchanges and restrictions, by kind and field; rebuilt after add_patch self._schedules: dict[tuple[str, str], Any] = {} + # the halo geometry of each patch, kept across add_patch and regrid (halos.py) + if not hasattr(self, "_halo_records"): + self._halo_records: dict[tuple, dict] = {} # which patch owns each cell of every level, rebuilt after add_patch (locate) self._locators: tuple[Any, ...] | None = None self._field_specs: dict[str, dict[str, Any]] = {} @@ -1003,6 +1006,7 @@ def regrid( min_patch_size: int = 1, forbid: Any = None, placement: str | Callable[[int, IndexBox], Any] | None = None, + cost: Mapping[int, Any] | None = None, fill_halos: bool = False, ) -> AMRHierarchy: """A new hierarchy with patches over the tagged cells, and the fields moved to it. @@ -1053,7 +1057,12 @@ def regrid( are dropped, as are those that would need patches too close to it. New patches are placed by ``placement`` (default: this hierarchy's), - the largest first, or along a Morton curve with ``"morton"``. Collective over ``comm``; this hierarchy is left as + the largest first, or along a Morton curve with ``"morton"``. With + ``"morton"``, ``cost`` weighs the patches by more than their cells: a + mapping from a level to a per-cell cost of that level's shape, in units + of one cell (the markers of `marker_counts` times what a marker costs + against a cell), counted in the patch where the cell is a leaf + (`box_costs`), so that a rank with a dense beam gets fewer cells. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ from patchwork.mesh.regrid import ( @@ -1065,6 +1074,11 @@ def regrid( if method not in ("cluster", "quadtree"): raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") + if ( + cost is not None + and (self.placement if placement is None else placement) != "morton" + ): + raise ValueError("cost weighs the patches of placement='morton' only") if method == "quadtree" and max_patch_size is not None: raise ValueError( "max_patch_size does not apply to method='quadtree': " @@ -1095,6 +1109,7 @@ def regrid( base = self.patches_at_level(0) new = AMRHierarchy.__new__(AMRHierarchy) new._communicators = self._communicators + new._halo_records = dict(self._halo_records) # the kept patches reuse theirs new.__init__( # type: ignore[misc] self.base_shape, # type: ignore[arg-type] self.bounds, # type: ignore[arg-type] @@ -1109,13 +1124,17 @@ def regrid( axis_nodes=self.axis_nodes, ) if new.placement == "morton": - from patchwork.mesh.regrid import morton_ranks + from patchwork.mesh.regrid import box_costs, morton_ranks + weights, load = None, list(new.cells_on_rank) # the base level + if cost is not None: + weights, load = box_costs(new, boxes, cost) ranks = morton_ranks( boxes, self.comm.Get_size(), ratio=self.refinement_ratio, - load=new.cells_on_rank, # the base level + load=load, + weights=weights, ) for level in sorted(boxes): for box, rank in zip(boxes[level], ranks[level], strict=True): diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 81a5df6..2be6e38 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -96,23 +96,23 @@ def function_tags( return tags -def marker_tags( - hierarchy: AMRHierarchy, *coordinates: Any, per_cell: float, levels: int +def marker_counts( + hierarchy: AMRHierarchy, *coordinates: Any, levels: int ) -> dict[int, np.ndarray]: - """Tag the cells of levels ``0 .. levels - 1`` that hold more than ``per_cell`` markers. - - ``marker_tags(x, ...)`` in 1D, ``marker_tags(x, y, ...)`` in 2D: the - positions of this rank's markers (arrays of one shape). The markers are - counted in the cells of every level, whether a patch covers them or not, and - the counts are added over the ranks (collective over ``comm``), so every - rank gets the same tags. Refinement driven by these tags stops where the - cells of a level hold at most ``per_cell`` markers each, as a particle tree - stops splitting at its leaf capacity. Markers outside the domain (and in the - notch of an L) are not counted. + """The number of markers in every cell of levels ``0 .. levels - 1``, over all ranks. + + ``marker_counts(x, ...)`` in 1D, ``marker_counts(x, y, ...)`` in 2D: the + positions of this rank's markers (arrays of one shape). Every level is + counted whole, whether a patch covers a cell or not, and the counts are + added over the ranks (collective over ``comm``): every rank gets the same + arrays, of the levels' shapes (`AMRHierarchy.level_shape`). Markers + outside the domain (and in the notch of an L) are not counted. The counts + make the tags of `marker_tags` and, scaled to the cost of a marker, the + ``cost`` of `AMRHierarchy.regrid`. """ if len(coordinates) != hierarchy.ndim: raise ValueError( - f"marker_tags takes {hierarchy.ndim} coordinate arrays, " + f"marker counts take {hierarchy.ndim} coordinate arrays, " f"got {len(coordinates)}" ) if levels < 0: @@ -121,17 +121,32 @@ def marker_tags( if any(hierarchy.periodic): points = points.copy() hierarchy.wrap(points) - tags = {} + counts = {} for level in range(levels): edges = [ hierarchy.node_positions(level, axis) for axis in range(points.shape[0]) ] - counts, _ = np.histogramdd(points.T, bins=edges) - mine = np.ascontiguousarray(counts) + found, _ = np.histogramdd(points.T, bins=edges) + mine = np.ascontiguousarray(found) everyone = np.empty_like(mine) hierarchy.comm.Allreduce(mine, everyone, op=MPI.SUM) - tags[level] = (everyone > per_cell) & _domain_cells(hierarchy, level) - return tags + counts[level] = np.where(_domain_cells(hierarchy, level), everyone, 0.0) + return counts + + +def marker_tags( + hierarchy: AMRHierarchy, *coordinates: Any, per_cell: float, levels: int +) -> dict[int, np.ndarray]: + """Tag the cells of levels ``0 .. levels - 1`` that hold more than ``per_cell`` markers. + + ``marker_tags(x, ...)`` in 1D, ``marker_tags(x, y, ...)`` in 2D, counted + by `marker_counts` (collective over ``comm``, the same tags on every + rank). Refinement driven by these tags stops where the cells of a level + hold at most ``per_cell`` markers each, as a particle tree stops splitting + at its leaf capacity. + """ + counts = marker_counts(hierarchy, *coordinates, levels=levels) + return {level: found > per_cell for level, found in counts.items()} @sp.profile("patchwork.gradient_tags", tags=PROFILE_TAGS) @@ -737,6 +752,7 @@ def morton_ranks( *, ratio: int = 2, load: Sequence[float] | None = None, + weights: Mapping[int, Sequence[float]] | None = None, ) -> dict[int, list[int]]: """The rank of each box: the boxes of all levels along a Morton curve, cut into ``size`` runs. @@ -746,13 +762,16 @@ def morton_ranks( before the finer boxes at the same corner. Walking the curve, a rank takes boxes until its cells, with the ``load`` it already has (the cells of the base level, say), reach an equal share of all cells; then the next rank - goes on. Returns, per level, the ranks in the order of ``boxes[level]``. + goes on. ``weights`` (per level, one per box) replaces the cells of a box + by its cost, in the units of ``load``: with `box_costs`, the cells plus the + markers on them. Returns, per level, the ranks in the order of + ``boxes[level]``. """ if size < 1: raise ValueError(f"size must be at least 1, got {size}") - weights = [0.0] * size if load is None else [float(w) for w in load] - if len(weights) != size: - raise ValueError(f"load needs {size} values, got {len(weights)}") + loads = [0.0] * size if load is None else [float(w) for w in load] + if len(loads) != size: + raise ValueError(f"load needs {size} values, got {len(loads)}") items = [ (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) ] @@ -768,18 +787,70 @@ def morton_ranks( keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D else: # 1D: the curve is the axis keys = corners.reshape(-1) - cells = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] - share = (sum(weights) + sum(cells)) / size + if weights is None: + costs = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + else: + for level in boxes: + if len(weights[level]) != len(boxes[level]): + raise ValueError(f"weights of level {level} need one value per box") + costs = [float(weights[level][n]) for level, n, _ in items] + share = (sum(loads) + sum(costs)) / size rank = 0 for k in sorted(range(len(items)), key=lambda k: (int(keys[k]), items[k][0])): - while rank < size - 1 and weights[rank] + cells[k] / 2 > share: + while rank < size - 1 and loads[rank] + costs[k] / 2 > share: rank += 1 level, n, _ = items[k] result[level][n] = rank - weights[rank] += cells[k] + loads[rank] += costs[k] return result +def box_costs( + hierarchy: AMRHierarchy, + boxes: Mapping[int, Sequence[IndexBox]], + cost: Mapping[int, Any], +) -> tuple[dict[int, list[float]], list[float]]: + """The cost of each new box and of each rank's base patches: cells plus the cost of the leaf cells. + + ``cost`` maps a level to a per-cell cost of that level's shape, in units of + one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a cell; + a missing level costs nothing beyond its cells). A cell's cost goes to the + box where it is a leaf, not covered by a finer box, since that is where its + markers deposit and gather. ``hierarchy`` holds the base level (the patches + of level 0 with their ranks). Returns the weights of ``boxes`` per level and + the load of every rank from the base level, for `morton_ranks`. + """ + ratio = hierarchy.refinement_ratio + top = max(boxes, default=0) + leaf_cost = {} + for level in range(top + 1): + shape = hierarchy.level_shape(level) + values = cost.get(level) + if values is None: + values = np.zeros(shape) + values = np.asarray(values, dtype=float) + if values.shape != shape: + raise ValueError( + f"cost of level {level} has the shape {values.shape}, not {shape}" + ) + leaf = np.ones(shape, dtype=bool) + for box in boxes.get(level + 1, ()): + leaf[tuple(slice(lo // ratio, hi // ratio) for lo, hi in box)] = False + leaf_cost[level] = np.where(leaf, values, 0.0) + + def weight(level: int, box: IndexBox) -> float: + where = tuple(slice(lo, hi) for lo, hi in box) + cells = float(np.prod([hi - lo for lo, hi in box])) + return cells + float(leaf_cost[level][where].sum()) + + weights = {level: [weight(level, box) for box in boxes[level]] for level in boxes} + load = [0.0] * hierarchy.comm.Get_size() + for patch in hierarchy.patches_at_level(0): + for rank in patch.ranks: + load[rank] += weight(0, patch.box) / len(patch.ranks) + return weights, load + + @sp.profile("patchwork.regrid_transfer", tags=PROFILE_TAGS) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 8c5d2fd..e7de635 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -269,3 +269,129 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: assert len(added.ranks) == 1 with pytest.raises(ValueError, match="morton"): AMRHierarchy(base_shape=(4, 4), placement="hilbert") + + +@pytest.mark.parametrize("centering", ["node", "cell"]) +def test_kept_patches_reuse_their_halo_geometry(centering, monkeypatch) -> None: + from patchwork.mesh import halos + + def blob(cx): + return lambda x, y: np.hypot(x - cx, y - 0.5) < 0.12 + + mesh = AMRHierarchy(base_shape=(32, 32), placement="morton") + mesh.allocate_field("u", centering=centering, halo=2) + for _ in range(2): + mesh = mesh.regrid( + function_tags(mesh, blob(0.4), levels=2), method="quadtree", block_size=4 + ) + mesh.exchange_halos("u") # the records of this mesh + + built = [] + record = halos.HaloExchange._record + monkeypatch.setattr( + halos.HaloExchange, + "_record", + lambda self, *args: built.append(args[1]) or record(self, *args), + ) + moved = mesh.regrid( + function_tags(mesh, blob(0.42), levels=2), method="quadtree", block_size=4 + ) + kept = {(p.level, p.box) for p in mesh.patches} & { + (p.level, p.box) for p in moved.patches + } + + def fill(hierarchy): + for patch in hierarchy.local_patches: + coordinates = ( + patch.local_node_coordinates(hierarchy, "u") + if centering == "node" + else patch.local_cell_centers(hierarchy, "u") + ) + patch.field("u").local[...] = ( + 1.0 + 2.0 * coordinates[0] - 3.0 * coordinates[1] + ) + + fill(moved) + moved.exchange_halos("u") + reused = len(moved.patches) - len(built) + assert 0 < reused <= len(kept) # only kept patches can reuse their geometry + # the same halos as a hierarchy that finds every patch's geometry again + fresh = moved.regrid( + function_tags(mesh, blob(0.42), levels=2), method="quadtree", block_size=4 + ) + fresh._halo_records.clear() + assert [(p.level, p.box) for p in fresh.patches] == [ + (p.level, p.box) for p in moved.patches + ] + fill(fresh) + fresh.exchange_halos("u") + for a, b in zip(moved.local_patches, fresh.local_patches, strict=True): + np.testing.assert_array_equal( + np.asarray(a.field("u").local_with_halos), + np.asarray(b.field("u").local_with_halos), + ) + + +def test_marker_weights_move_the_cuts_of_the_morton_curve() -> None: + from patchwork import box_costs, marker_counts + + boxes = { + 1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(4)] + } # four boxes of 4 cells + assert morton_ranks(boxes, 2) == {1: [0, 0, 1, 1]} + # the first box costs as much as the other three: it gets a rank to itself + heavy = {1: [12.0, 4.0, 4.0, 4.0]} + assert morton_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} + with pytest.raises(ValueError, match="weights"): + morton_ranks(boxes, 2, weights={1: [1.0]}) + + mesh = AMRHierarchy(base_shape=(8, 8)) + rank = WORLD.Get_rank() + # 64 markers in base cell (1, 1), shared out over the ranks + x = np.full(64, 0.19)[rank::SIZE] + y = np.full(64, 0.19)[rank::SIZE] + counts = marker_counts(mesh, x, y, levels=2) + assert counts[0][1, 1] == 64 and counts[0].sum() == 64 + assert counts[1][3, 3] == 64 + # level 1 covers base cells 0..3 x 0..1: the markers are on its leaf cells + new = {1: [((0, 8), (0, 4))]} + weights, load = box_costs(mesh, new, {0: counts[0], 1: counts[1]}) + assert weights == {1: [32.0 + 64.0]} + assert sum(load) == 64.0 # the base's cells; the markers are on the finer patch + with pytest.raises(ValueError, match="shape"): + box_costs(mesh, new, {0: np.zeros((3, 3))}) + + +def test_regrid_with_marker_costs_gives_the_dense_patches_fewer_cells() -> None: + from patchwork import box_costs, marker_counts + + mesh = AMRHierarchy(base_shape=(16, 16), placement="morton") + rng = np.random.default_rng(WORLD.Get_rank()) + x = np.concatenate([rng.normal(0.3, 0.04, 4000), rng.uniform(0, 1, 1000)]) % 1 + y = np.concatenate([rng.normal(0.3, 0.04, 4000), rng.uniform(0, 1, 1000)]) % 1 + for _ in range(2): + tags = marker_tags(mesh, x, y, per_cell=8 * SIZE, levels=2) + mesh = mesh.regrid(tags, method="quadtree", block_size=4) + counts = marker_counts(mesh, x, y, levels=3) + cost = {level: 0.5 * found for level, found in counts.items()} + plain = mesh.regrid(tags, method="quadtree", block_size=4) + weighted = mesh.regrid(tags, method="quadtree", block_size=4, cost=cost) + assert [(p.level, p.box) for p in weighted.patches] == [ + (p.level, p.box) for p in plain.patches + ] + + def costs(hierarchy): # cells plus half the markers of the leaf cells, per rank + boxes = { + level: [p.box for p in hierarchy.patches_at_level(level)] + for level in range(1, hierarchy.max_level + 1) + } + weights, load = box_costs(hierarchy, boxes, cost) + for level, values in weights.items(): + patches = hierarchy.patches_at_level(level) + for patch, value in zip(patches, values, strict=True): + load[patch.ranks[0]] += value + return load + + assert max(costs(weighted)) <= max(costs(plain)) + 1e-9 + with pytest.raises(ValueError, match="morton"): + AMRHierarchy(base_shape=(4, 4)).regrid({0: np.ones((4, 4), bool)}, cost=cost) From 6638feed737a548950944d6d5acb1bd826db65a0 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 07:11:24 +0000 Subject: [PATCH 08/24] feat: rebalance by cost, and the benchmark of halo reuse and marker-weighted cuts. --- CHANGELOG.md | 7 ++ benchmarks/quadtree/README.md | 3 +- benchmarks/quadtree/RESULTS.md | 90 ++++++++------- src/patchwork/mesh/hierarchy.py | 128 +++++++++++++--------- src/patchwork/tests/unit/test_quadtree.py | 51 +++++++++ tutorials/13_quadtree_patches.ipynb | 97 +++++++++++----- 6 files changed, 258 insertions(+), 118 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c83e853..68c2fab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,13 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - `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 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 + `marker_counts` times what a marker costs against a cell; `rebalance(cost)` places the + patches of a hierarchy again by them and moves the fields. +- The halo geometry of every patch (its copies and interpolation weights) is kept on the + hierarchy and handed on by `regrid`: a patch with the same box and ranks and the same + patches within reach of its halo reuses it instead of finding it again. - Benchmark `benchmarks/quadtree`: clusters against quadtree blocks in a particle-in-cell cycle, serially and under MPI with both placements (`RESULTS.md`). - `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than diff --git a/benchmarks/quadtree/README.md b/benchmarks/quadtree/README.md index f5c1c7f..b87df40 100644 --- a/benchmarks/quadtree/README.md +++ b/benchmarks/quadtree/README.md @@ -5,7 +5,8 @@ markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve, the halos and gather, each a scope-profiler region. `run.py` runs it for clustered patches (`method="cluster"`, with and without `max_patch_size`) and quadtree blocks of 8, 16 and 32 cells, and prints a table; under MPI it compares `placement="balanced"` with -`placement="morton"` (without the solve, which the LU backend does not distribute). +`placement="morton"`, by cells and weighted by the markers (`cost`, a marker costing a +tenth of a cell), without the solve, which the LU backend does not distribute. ```sh python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 117534c..92df15b 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -4,57 +4,73 @@ `bench_quadtree.py` defaults: a 64 x 64 base, 3 levels, 200,000 markers (four fifths in a Gaussian beam of width 0.06 moving by 0.01 per step), `per_cell=20`, 20 timed steps. Times are the median of 3 runs of the mean ms per step; under MPI on the rank where the part is -largest. "kept" is the share of the patches of a regrid that were there before it. +largest. "kept" is the share of the patches of a regrid that were there before it. "tag" +counts the markers on one level more than it tags, for the cost of `morton, markers`. ## Serial, with the solve +With the halo geometry of kept patches reused (patchwork 10c; the numbers in brackets are +the halos without it, from the first run of this benchmark). + | mesh | patches | refined cells | kept | tag | regrid | migrate | deposit | solver | solve | halos | gather | total | |---|---|---|---|---|---|---|---|---|---|---|---|---| -| cluster | 8 | 27,864 | 0% | 73.9 | 10.3 | 22.0 | 57.8 | 114.1 | 6.2 | 4.7 | 31.2 | 320 | -| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 73.2 | 98.6 | 43.6 | 132.7 | 133.8 | 13.1 | 100.0 | 78.2 | 673 | -| quadtree, block 8 | 386 | 24,714 | 92% | 70.6 | 277.0 | 64.9 | 231.4 | 179.7 | 23.4 | 295.5 | 131.4 | 1274 | -| quadtree, block 16 | 121 | 30,925 | 91% | 72.4 | 75.3 | 40.0 | 126.4 | 135.1 | 12.4 | 94.5 | 74.6 | 631 | -| quadtree, block 32 | 49 | 50,330 | 94% | 72.3 | 26.0 | 31.2 | 88.6 | 204.6 | 13.0 | 43.0 | 53.5 | 532 | +| cluster | 8 | 27,864 | 0% | 106.2 | 10.7 | 20.3 | 55.6 | 113.7 | 5.9 | 8.1 (4.7) | 30.1 | 351 | +| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 101.5 | 85.5 | 38.7 | 130.8 | 124.3 | 12.5 | 120.7 (100.0) | 74.6 | 689 | +| quadtree, block 8 | 386 | 24,714 | 92% | 105.6 | 284.7 | 65.1 | 229.2 | 184.0 | 23.9 | 273.7 (295.5) | 134.7 | 1301 | +| quadtree, block 16 | 121 | 30,925 | 91% | 100.0 | 66.6 | 37.2 | 113.7 | 130.8 | 11.4 | 78.2 (94.5) | 68.2 | 606 | +| quadtree, block 32 | 49 | 50,330 | 94% | 102.1 | 30.4 | 29.4 | 84.9 | 199.4 | 12.1 | 28.4 (43.0) | 50.9 | 538 | ## 4 ranks, without the solve -| mesh | placement | imbalance | tag | regrid | migrate | deposit | halos | gather | total | -|---|---|---|---|---|---|---|---|---|---| -| cluster | balanced | 2.18 | 30.6 | 7.5 | 13.3 | 59.9 | 4.4 | 18.8 | 135 | -| cluster | morton | 2.19 | 32.0 | 7.6 | 12.4 | 57.5 | 4.8 | 23.0 | 137 | -| cluster, `max_patch_size=16` | balanced | 1.01 | 24.2 | 51.7 | 19.1 | 53.9 | 97.5 | 15.8 | 262 | -| cluster, `max_patch_size=16` | morton | 1.01 | 29.9 | 46.3 | 18.4 | 61.7 | 101.4 | 20.1 | 278 | -| quadtree, block 8 | balanced | 1.00 | 27.5 | 214.2 | 32.2 | 91.2 | 296.3 | 24.8 | 686 | -| quadtree, block 8 | morton | 1.00 | 30.7 | 189.0 | 30.9 | 95.9 | 273.5 | 25.3 | 645 | -| quadtree, block 16 | balanced | 1.02 | 24.6 | 39.4 | 17.8 | 60.5 | 96.6 | 16.6 | 256 | -| quadtree, block 16 | morton | 1.02 | 27.4 | 47.1 | 19.6 | 56.8 | 95.9 | 18.1 | 265 | -| quadtree, block 32 | balanced | 1.02 | 29.3 | 24.6 | 18.0 | 58.1 | 47.1 | 15.5 | 193 | -| quadtree, block 32 | morton | 1.02 | 25.5 | 17.3 | 14.5 | 49.7 | 36.3 | 15.2 | 158 | +`morton, markers` weighs the Morton cuts by `cost`: the markers of `marker_counts`, a marker +costing a tenth of a cell. + +| mesh | placement | cells imbalance | markers imbalance | tag | regrid | migrate | deposit | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---|---| +| cluster | balanced | 2.18 | 3.04 | 45.5 | 8.0 | 10.6 | 59.7 | 5.5 | 19.2 | 149 | +| cluster | morton | 2.19 | 3.04 | 46.4 | 9.8 | 10.9 | 62.1 | 5.6 | 23.6 | 159 | +| cluster | morton, markers | 2.19 | 3.04 | 46.7 | 9.5 | 10.1 | 53.1 | 5.6 | 19.8 | 145 | +| cluster, `max_patch_size=16` | balanced | 1.01 | 1.36 | 41.2 | 52.9 | 18.3 | 62.8 | 124.3 | 17.4 | 317 | +| cluster, `max_patch_size=16` | morton | 1.01 | 1.35 | 41.9 | 49.9 | 20.8 | 61.4 | 110.7 | 18.9 | 303 | +| cluster, `max_patch_size=16` | morton, markers | 1.11 | 1.22 | 40.5 | 55.3 | 19.3 | 60.7 | 128.7 | 17.2 | 322 | +| quadtree, block 8 | balanced | 1.00 | 1.31 | 40.8 | 215.3 | 28.7 | 92.6 | 395.5 | 23.4 | 796 | +| quadtree, block 8 | morton | 1.00 | 1.26 | 46.4 | 199.5 | 29.9 | 89.4 | 267.4 | 26.6 | 659 | +| quadtree, block 8 | morton, markers | 1.09 | 1.16 | 46.2 | 220.1 | 31.7 | 90.8 | 297.3 | 29.7 | 716 | +| quadtree, block 16 | balanced | 1.02 | 1.28 | 44.4 | 62.6 | 20.8 | 69.0 | 131.4 | 18.4 | 347 | +| quadtree, block 16 | morton | 1.02 | 1.35 | 46.9 | 63.2 | 27.2 | 63.2 | 105.0 | 20.5 | 326 | +| quadtree, block 16 | morton, markers | 1.13 | 1.24 | 48.6 | 67.4 | 21.0 | 68.1 | 104.0 | 18.0 | 327 | +| quadtree, block 32 | balanced | 1.02 | 1.28 | 42.6 | 23.3 | 16.4 | 58.0 | 44.9 | 13.9 | 199 | +| quadtree, block 32 | morton | 1.02 | 1.55 | 44.6 | 21.3 | 17.0 | 61.3 | 51.5 | 16.4 | 212 | +| quadtree, block 32 | morton, markers | 1.18 | 1.41 | 46.7 | 26.6 | 19.3 | 57.9 | 40.3 | 16.3 | 207 | -Imbalance: the largest cells per rank over the mean (the base level counted). +Imbalance: the largest cells (base level counted) or markers (after `migrate`) per rank over +the mean. ## What they say - **The cost follows the number of patches, not how they are placed.** Regrid, halos, - deposit and gather grow with the patches: 8 clusters take 320 ms per step, 386 blocks of 8 - cells 1274 ms. At about the same number of patches the quadtree is as fast as clusters - (block 16, 121 patches: 631 ms; clusters cut to 16 cells, 134 patches: 673 ms), its - regrid a little faster since most of its patches are copied, not interpolated. -- **What the quadtree keeps is not reused yet.** 91-94% of its patches survive a regrid, - but the hierarchy is new, so the halo schedules (`build_schedule`, most of "halos"), the - composite node numbering and the solver are built again from scratch. Reusing them for - kept patches is where the quadtree could win; picnic's solver already reuses the grids and - probed operators of kept boxes (see picnic's `adaptive_rebuild_cost.py --method quadtree`). + deposit and gather grow with the patches: 8 clusters take 351 ms per step, 386 blocks of 8 + cells 1301 ms. At about the same number of patches the quadtree is as fast as clusters + (block 16, 121 patches: 606 ms; clusters cut to 16 cells, 134 patches: 689 ms). +- **Reusing the halo geometry of kept patches saves 7-34% of the halos** (block 8: 296 → + 274 ms, block 16: 95 → 78 ms, block 32: 43 → 28 ms). Not more, for two reasons: about + a third of the patches still find their geometry again (kept patches whose neighbours or + coarse patches changed, and new ones), and building the `mpiarray.CopyPlan` of the + exchange from the copies is now the largest part (about 100 of 250 ms at 386 patches: + per-copy Python and a pickled `allgather`), and it is built for every new hierarchy. Next: + a cheaper `CopyPlan` in mpiarray (patchwork 8k). The clusters gain nothing, their patches are + recut every regrid, and pay a few ms for checking the signatures (8 clusters: 4.7 → 8.1 ms). - **Large blocks refine many cells**: blocks of 32 cover 50,330 cells for the 27,864 the - clusters need; the solver setup grows with them (205 ms against 114 ms). -- **Morton and balanced placement are within the noise on one node** (about 10% between - repeats). Morton keeps neighbouring patches and the patches over them on one rank, which - saves messages between nodes; within a node the messages are cheap and the halo time is - the schedule, built in Python. The few large clusters cannot be balanced by either (2.2). -- On four ranks tagging and gathering take about half as long as serially, but the deposit - does not get faster (58 ms serially, 50-96 ms on the slowest rank): the placements balance - cells, and the beam's patches hold most markers. Marker-weighted cuts of the Morton curve - are patchwork step 8e. + clusters need; the solver setup grows with them (199 ms against 114 ms). +- **Morton placement**: on one node within the noise of `balanced` for most meshes (about + 10% between repeats); the halos of blocks of 8 are faster with it (267 against 396 ms), + where the patches are small and many. +- **Weighing the cuts by the markers** (`morton, markers`) lowers the marker imbalance (blocks + of 8: 1.26 → 1.16, 16: 1.35 → 1.24, 32: 1.55 → 1.41, clusters cut to 16: 1.35 → 1.22) for a + higher cell imbalance (1.09-1.18), as asked. The step time does not change measurably on + four ranks: with 200,000 markers the deposit and gather take 60-120 ms against the cells' + 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). ## Fixed on the way diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index da9a9ff..822de85 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -971,6 +971,63 @@ def restrict(self, name: str, *, level: int | None = None) -> None: self._schedule("restrict", name, Restriction).execute(level=level) + def _rebuilt( + self, + boxes: Mapping[int, Sequence[IndexBox]], + placement: Any, + cost: Mapping[int, Any] | None, + fill_halos: bool, + ) -> AMRHierarchy: + """A hierarchy with this base and the refined ``boxes``, with the fields moved over.""" + from patchwork.mesh.regrid import transfer + + base = self.patches_at_level(0) + new = AMRHierarchy.__new__(AMRHierarchy) + new._communicators = self._communicators + new._halo_records = dict(self._halo_records) # the kept patches reuse theirs + new.__init__( # type: ignore[misc] + self.base_shape, # type: ignore[arg-type] + self.bounds, # type: ignore[arg-type] + refinement_ratio=self.refinement_ratio, + periodic=self.periodic, + base_boxes=[patch.box for patch in base], + base_ranks=[patch.ranks for patch in base], + placement=self.placement if placement is None else placement, + max_cells_per_rank=self.max_cells_per_rank, + comm=self.comm, + geometry=self.geometry, + axis_nodes=self.axis_nodes, + ) + if new.placement == "morton": + from patchwork.mesh.regrid import box_costs, morton_ranks + + weights, load = None, list(new.cells_on_rank) # the base level + if cost is not None: + weights, load = box_costs(new, boxes, cost) + ranks = morton_ranks( + boxes, + self.comm.Get_size(), + ratio=self.refinement_ratio, + load=load, + weights=weights, + ) + for level in sorted(boxes): + for box, rank in zip(boxes[level], ranks[level], strict=True): + new.add_patch(level, box, ranks=rank) + else: + for level in sorted(boxes): + for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): + new.add_patch(level, box) + for name, spec in self._field_specs.items(): + if spec["conservative"]: + self.restrict(name) + new.allocate_field(name, **spec) + transfer(self, new, name) + if fill_halos: + for name in new.field_names: + new.exchange_halos(name) + return new + @sp.profile("patchwork.mesh.regrid", tags=PROFILE_TAGS) @method( equations={ @@ -1065,12 +1122,7 @@ def regrid( (`box_costs`), so that a rank with a dense beam gets fewer cells. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ - from patchwork.mesh.regrid import ( - combine_tags, - new_boxes, - quadtree_boxes, - transfer, - ) + from patchwork.mesh.regrid import combine_tags, new_boxes, quadtree_boxes if method not in ("cluster", "quadtree"): raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") @@ -1106,52 +1158,26 @@ def regrid( min_patch_size=min_patch_size, forbid=forbid, ) - base = self.patches_at_level(0) - new = AMRHierarchy.__new__(AMRHierarchy) - new._communicators = self._communicators - new._halo_records = dict(self._halo_records) # the kept patches reuse theirs - new.__init__( # type: ignore[misc] - self.base_shape, # type: ignore[arg-type] - self.bounds, # type: ignore[arg-type] - refinement_ratio=self.refinement_ratio, - periodic=self.periodic, - base_boxes=[patch.box for patch in base], - base_ranks=[patch.ranks for patch in base], - placement=self.placement if placement is None else placement, - max_cells_per_rank=self.max_cells_per_rank, - comm=self.comm, - geometry=self.geometry, - axis_nodes=self.axis_nodes, - ) - if new.placement == "morton": - from patchwork.mesh.regrid import box_costs, morton_ranks + return self._rebuilt(boxes, placement, cost, fill_halos) - weights, load = None, list(new.cells_on_rank) # the base level - if cost is not None: - weights, load = box_costs(new, boxes, cost) - ranks = morton_ranks( - boxes, - self.comm.Get_size(), - ratio=self.refinement_ratio, - load=load, - weights=weights, - ) - for level in sorted(boxes): - for box, rank in zip(boxes[level], ranks[level], strict=True): - new.add_patch(level, box, ranks=rank) - else: - for level in sorted(boxes): - for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): - new.add_patch(level, box) - for name, spec in self._field_specs.items(): - if spec["conservative"]: - self.restrict(name) - new.allocate_field(name, **spec) - transfer(self, new, name) - if fill_halos: - for name in new.field_names: - new.exchange_halos(name) - return new + @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) + def rebalance( + self, cost: Mapping[int, Any] | None = None, *, fill_halos: bool = False + ) -> AMRHierarchy: + """The same patches placed again along the Morton curve, by ``cost``; fields moved. + + Every refined patch goes to a rank by `morton_ranks`, weighed by its + cells plus the ``cost`` of its leaf cells as in `regrid` (`box_costs`; + without ``cost`` by its cells). The base level stays where it is. Every + field is copied to the patches' new ranks; send the markers after them + with `migrate`. The new hierarchy places its regrids along the curve as + well (``placement="morton"``). Collective over ``comm``. + """ + boxes = { + level: [patch.box for patch in self.patches_at_level(level)] + for level in range(1, self.max_level + 1) + } + return self._rebuilt(boxes, "morton", cost, fill_halos) def integral(self, name: str) -> float: """The integral of field ``name`` over the domain, from the finest values. diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index e7de635..92f8a1b 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -395,3 +395,54 @@ def costs(hierarchy): # cells plus half the markers of the leaf cells, per rank assert max(costs(weighted)) <= max(costs(plain)) + 1e-9 with pytest.raises(ValueError, match="morton"): AMRHierarchy(base_shape=(4, 4)).regrid({0: np.ones((4, 4), bool)}, cost=cost) + + +def test_rebalance_moves_the_patches_and_their_fields_to_the_weighted_ranks() -> None: + from patchwork import box_costs, marker_counts + + mesh = AMRHierarchy(base_shape=(16, 16), placement="balanced") + mesh.allocate_field("u", centering="node") + mesh.allocate_field("c") + mesh = mesh.regrid( + function_tags(mesh, ring, levels=2), method="quadtree", block_size=4 + ) + mesh = mesh.regrid( + function_tags(mesh, ring, levels=2), method="quadtree", block_size=4 + ) + + def plane(x, y): + return 1.0 + 2.0 * x - 3.0 * y + + for patch in mesh.local_patches: + patch.field("u").local[...] = plane(*patch.local_node_coordinates(mesh, "u")) + patch.field("c").local[...] = plane(*patch.local_cell_centers(mesh, "c")) + x = np.full(100, 0.21)[WORLD.Get_rank() :: SIZE] + y = np.full(100, 0.5)[WORLD.Get_rank() :: SIZE] + cost = marker_counts(mesh, x, y, levels=3) + moved = mesh.rebalance(cost) + + assert moved.placement == "morton" + assert [(p.level, p.box) for p in moved.patches] == [ + (p.level, p.box) for p in mesh.patches + ] + boxes = { + level: [p.box for p in mesh.patches_at_level(level)] + for level in range(1, mesh.max_level + 1) + } + weights, load = box_costs(moved, boxes, cost) + expected = morton_ranks(boxes, SIZE, load=load, weights=weights) + for level in boxes: + ranks = [p.ranks for p in moved.patches_at_level(level)] + assert ranks == [(r,) for r in expected[level]] + for patch in moved.local_patches: + np.testing.assert_allclose( + patch.field("u").local, + plane(*patch.local_node_coordinates(moved, "u")), + atol=1e-12, + ) + np.testing.assert_allclose( + patch.field("c").local, + plane(*patch.local_cell_centers(moved, "c")), + atol=1e-12, + ) + assert mesh.rebalance().max_level == mesh.max_level # by cells alone diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index be9d882..470002a 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -307,49 +307,88 @@ "metadata": {}, "outputs": [], "source": [ - "from patchwork import morton_ranks\n", + "from patchwork import box_costs, marker_counts, morton_ranks\n", "\n", "boxes = {\n", " level: [patch.box for patch in mesh.patches_at_level(level)]\n", " for level in range(1, mesh.max_level + 1)\n", "}\n", - "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", "colours = plt.get_cmap(\"tab10\").colors\n", "\n", - "fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", - "for level in sorted(boxes):\n", - " xs, ys = mesh.node_positions(level, 0), mesh.node_positions(level, 1)\n", - " for ((i0, i1), (j0, j1)), rank in zip(boxes[level], ranks[level], strict=True):\n", - " ax.add_patch(\n", - " Rectangle(\n", - " (xs[i0], ys[j0]),\n", - " xs[i1] - xs[i0],\n", - " ys[j1] - ys[j0],\n", - " facecolor=colours[rank],\n", - " edgecolor=\"k\",\n", - " alpha=0.25,\n", - " lw=0.6,\n", + "\n", + "def draw_ranks(ranks, title):\n", + " fig, ax = plt.subplots(figsize=(6, 6), constrained_layout=True)\n", + " for level in sorted(boxes):\n", + " xs, ys = mesh.node_positions(level, 0), mesh.node_positions(level, 1)\n", + " for ((i0, i1), (j0, j1)), rank in zip(boxes[level], ranks[level], strict=True):\n", + " ax.add_patch(\n", + " Rectangle(\n", + " (xs[i0], ys[j0]),\n", + " xs[i1] - xs[i0],\n", + " ys[j1] - ys[j0],\n", + " facecolor=colours[rank],\n", + " edgecolor=\"k\",\n", + " alpha=0.25,\n", + " lw=0.6,\n", + " )\n", " )\n", - " )\n", - "ax.set_xlim(0, 1)\n", - "ax.set_ylim(0, 1)\n", - "ax.set_aspect(\"equal\")\n", - "cells = [\n", - " sum(\n", - " (hi0 - lo0) * (hi1 - lo1)\n", - " for level in boxes\n", - " for ((lo0, hi0), (lo1, hi1)), r in zip(boxes[level], ranks[level], strict=True)\n", - " if r == rank\n", - " )\n", - " for rank in range(4)\n", - "]\n", - "ax.set_title(f\"refined cells per rank: {cells} (rank 0 also has the base)\")" + " ax.set_xlim(0, 1)\n", + " ax.set_ylim(0, 1)\n", + " ax.set_aspect(\"equal\")\n", + " ax.set_title(title)\n", + "\n", + "\n", + "def per_rank(ranks, values, base):\n", + " \"\"\"The sum of ``values`` per rank, with the base level's ``base`` on rank 0.\"\"\"\n", + " totals = [base, 0.0, 0.0, 0.0]\n", + " for level in boxes:\n", + " for value, rank in zip(values[level], ranks[level], strict=True):\n", + " totals[rank] += value\n", + " return [round(total) for total in totals]\n", + "\n", + "\n", + "cells = {\n", + " level: [np.prod([hi - lo for lo, hi in b]) for b in boxes[level]] for level in boxes\n", + "}\n", + "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "draw_ranks(ranks, f\"cells per rank: {per_rank(ranks, cells, 1024)}\")" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, + "source": [ + "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\n", + "the markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\n", + "its cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\n", + "patch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n", + "`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\n", + "hierarchy again by them and moves the fields (send the markers after them with `migrate`).\n", + "The ranks with the beam now get fewer cells and about the same cost:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "15", + "metadata": {}, + "outputs": [], + "source": [ + "counts = marker_counts(mesh, x, y, levels=mesh.max_level + 1)\n", + "cost = {level: 0.1 * found for level, found in counts.items()}\n", + "weights, (base,) = box_costs(mesh, boxes, cost) # one rank here: the base's cost\n", + "weighted = morton_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", + "print(\"cells per rank:\", per_rank(weighted, cells, 1024))\n", + "print(\"cost per rank, by cells: \", per_rank(ranks, weights, base))\n", + "print(\"cost per rank, by markers: \", per_rank(weighted, weights, base))\n", + "draw_ranks(weighted, \"the same patches, cut by cells plus markers\")" + ] + }, + { + "cell_type": "markdown", + "id": "16", + "metadata": {}, "source": [ "The few new blocks far from the beam come from the uniform background: its count per cell\n", "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", From 82ff47a66b4f96e39e48bf8681645503954e1989 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 08:26:18 +0000 Subject: [PATCH 09/24] perf: markers grouped by patch with one sort, and marker counts from one histogram. --- benchmarks/quadtree/bench_quadtree.py | 12 +++++++++ src/patchwork/mesh/hierarchy.py | 31 ++++++++++++++++++----- src/patchwork/mesh/regrid.py | 27 ++++++++++++-------- src/patchwork/tests/unit/test_quadtree.py | 16 ++++++++++++ 4 files changed, 69 insertions(+), 17 deletions(-) diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index df60150..789696c 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -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): diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 822de85..1a666f9 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -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. @@ -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) @@ -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 @@ -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)) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 2be6e38..92f434d 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -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( diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 92f8a1b..95c9d33 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -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)) From 74312f86275237d7cf7bff8e3d98cee471460bb9 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 08:34:19 +0000 Subject: [PATCH 10/24] Benchmark warm-up, and the per-patch costs before and after. --- CHANGELOG.md | 4 ++++ benchmarks/quadtree/RESULTS.md | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68c2fab..658b7eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 92df15b..12f7cf8 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -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 From f5ed73ccb9da1d49a39ac3632690ce95bd1553ee Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 10:31:07 +0000 Subject: [PATCH 11/24] perf: coverage per level for the node numbering, halo copies per pair, owners by rank table, and regrid(fields=). --- benchmarks/quadtree/bench_quadtree.py | 9 +++ src/patchwork/mesh/accumulate.py | 18 ++++-- src/patchwork/mesh/halos.py | 74 +++++++++++++++++------ src/patchwork/mesh/hierarchy.py | 18 +++++- src/patchwork/spaces/nodes.py | 26 ++++---- src/patchwork/tests/unit/test_quadtree.py | 21 +++++++ 6 files changed, 129 insertions(+), 37 deletions(-) diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 789696c..c94e3a0 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -82,6 +82,11 @@ def main() -> None: parser.add_argument("--steps", type=int, default=20) parser.add_argument("--speed", type=float, default=0.01, help="beam shift per step") parser.add_argument("--no-solve", dest="solve", action="store_false") + parser.add_argument( + "--move-fields", + action="store_true", + help="move the fields at every regrid (default: none, they are recomputed)", + ) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() @@ -93,6 +98,10 @@ def main() -> None: if args.method == "quadtree" else {"method": "cluster", "max_patch_size": args.max_patch_size} ) + if ( + not args.move_fields + ): # the charge is deposited again and the potential solved for + options["fields"] = [] mesh = AMRHierarchy( base_shape=(args.base, args.base), placement=args.placement, diff --git a/src/patchwork/mesh/accumulate.py b/src/patchwork/mesh/accumulate.py index 93cc9c9..cdae9a5 100644 --- a/src/patchwork/mesh/accumulate.py +++ b/src/patchwork/mesh/accumulate.py @@ -87,9 +87,15 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: axes.append(index % lattice[axis] if periodic[axis] else index) table[np.ix_(*axes)] = number - from patchwork.mesh.hierarchy import _gather_blocks + from patchwork.mesh.hierarchy import _by_patch, _gather_blocks blocks = hierarchy._schedule("blocks", name, _gather_blocks) + # the rank of every patch held by one rank (-1 for several) + single = np.full(len(patches), -1, dtype=np.int64) + for number in range(len(patches)): + members, replicated = blocks[number] + if len(members) == 1 and not replicated: + single[number] = members[0][0] # per local patch: the storage of the nodes that move, and where each goes self._moves: list[dict[str, Any]] = [] for number, patch in enumerate(patches): @@ -137,15 +143,17 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: where = np.nonzero(moving) owners = owner[where] at = [values[where] for values in target] - destination = np.empty(owners.size, dtype=np.int64) - for held in np.unique(owners): - members, replicated = blocks[int(held)] + # an owner on one rank: that rank; else the rank whose block has the node + destination = single[owners] + several = np.flatnonzero(destination < 0) + for held, part in _by_patch(owners[several]): + chosen = several[part] + members, replicated = blocks[held] if replicated: raise ValueError( f"field {name!r} is replicated (split=None) on the several ranks " f"of a patch: allocate it with split=0 to accumulate" ) - chosen = np.flatnonzero(owners == held) for rank, bounds in members: inside = np.ones(chosen.size, dtype=bool) for values, (a0, a1) in zip(at, bounds, strict=True): diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 2ee124a..193da3a 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -120,6 +120,7 @@ def __init__(self, hierarchy: AMRHierarchy, nodal: bool) -> None: self.ratio = hierarchy.refinement_ratio self.periodic = hierarchy.periodic self._domains: dict[int, np.ndarray] = {} + self._wholes: dict[int, bool] = {} self._indices: dict[int, tuple[tuple[Patch, ...], _BoxIndex]] = {} def own(self, patch: Patch) -> Box: @@ -164,6 +165,12 @@ def _domain(self, level: int) -> np.ndarray: self._domains[level] = cells return self._domains[level] + def _whole(self, level: int) -> bool: + """Whether the domain fills the box of the level (no notch).""" + if level not in self._wholes: + self._wholes[level] = bool(self._domain(level).all()) + return self._wholes[level] + def in_domain(self, level: int, *index: np.ndarray) -> np.ndarray: """Whether points (level indices, possibly beyond the domain) are in it. @@ -172,6 +179,13 @@ def in_domain(self, level: int, *index: np.ndarray) -> np.ndarray: """ cells = self._domain(level) shape = cells.shape + if self._whole(level): # the domain fills its box: a bounds check + inside = np.ones(index[0].shape, dtype=bool) + top = 1 if self.nodal else 0 + for axis, values in enumerate(index): + if not self.periodic[axis]: + inside &= (values >= 0) & (values < shape[axis] + top) + return inside offsets = ( itertools.product((0, -1), repeat=len(index)) if self.nodal @@ -569,18 +583,25 @@ def _field(self, patch: Patch) -> Any: def _coarse_field(self, patch: Patch) -> Any: return patch.field(self._below) if patch.is_local else None - def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray: - """Copies from the patches of the same level; the halo points they cover.""" - own = points.own(patch) - width = self._width - extended = tuple((lo - width, hi + width) for lo, hi in own) - covered = np.zeros([hi - lo for lo, hi in extended], dtype=bool) - covered[(slice(width, -width),) * len(own)] = True - origin = tuple(lo for lo, _ in own) - for other in points.near(patch.level, extended): + def _pair( + self, points: _Points, patch: Patch, other: Patch, extended: Box + ) -> list[tuple]: + """The copies from ``other`` into the halo of ``patch`` (same level), found once. + + ``(source box, target box, covered slices)`` for every part, across periodic + faces too. They depend on the two boxes only, so they are kept by the pair + on the hierarchy and handed on by `AMRHierarchy.regrid`. + """ + key = (patch.level, patch.box, other.box) + found = self._pairs_known.get(key) + if found is None: + own = points.own(patch) + width = self._width + origin = tuple(lo for lo, _ in own) other_origin = tuple(lo for lo, _ in points.own(other)) + found = [] for shift in points.shifts(patch.level): - if other is patch and not any(shift): + if other.box == patch.box and not any(shift): continue theirs = _shift(points.own(other), shift) for frame in _frame(own, width): @@ -592,15 +613,25 @@ def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray tuple(-d - o for d, o in zip(shift, other_origin, strict=True)), ) target = _shift(part, tuple(-o for o in origin)) - copies.append( - (self._field(other), source, self._field(patch), target) + cover = tuple( + slice(s - e0, t - e0) + for (s, t), (e0, _) in zip(part, extended, strict=True) ) - covered[ - tuple( - slice(s - e0, t - e0) - for (s, t), (e0, _) in zip(part, extended, strict=True) - ) - ] = True + found.append((source, target, cover)) + self._pairs_used[key] = found + return found + + def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray: + """Copies from the patches of the same level; the halo points they cover.""" + own = points.own(patch) + width = self._width + extended = tuple((lo - width, hi + width) for lo, hi in own) + covered = np.zeros([hi - lo for lo, hi in extended], dtype=bool) + covered[(slice(width, -width),) * len(own)] = True + for other in points.near(patch.level, extended): + for source, target, cover in self._pair(points, patch, other, extended): + copies.append((self._field(other), source, self._field(patch), target)) + covered[cover] = True return covered def _coarse_fine( @@ -770,6 +801,8 @@ def __init__( dtype = spec["dtype"] kind = ("halo", nodal, self._width, np.dtype(dtype).str, repr(spec["split"])) known = hierarchy._halo_records.get(kind, {}) + self._pairs_known = hierarchy._halo_records.get(("pairs", *kind), {}) + self._pairs_used: dict[tuple, list] = {} used: dict[tuple, _HaloRecord] = {} patches = {_key(patch): patch for patch in hierarchy.patches} for patch in hierarchy.patches if self._width else (): @@ -783,6 +816,11 @@ def __init__( self._bind(record, patch, patches, dtype) # keep the records of this mesh (all of them after a full build) hierarchy._halo_records[kind] = used if level is None else {**known, **used} + pairs = self._pairs_used + if level is not None: + pairs = {**self._pairs_known, **pairs} + hierarchy._halo_records[("pairs", *kind)] = pairs + del self._pairs_known, self._pairs_used self._plan = mpa.CopyPlan(self._copies, comm=hierarchy.comm) del self._copies diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 1a666f9..30ed0e3 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -997,6 +997,7 @@ def _rebuilt( placement: Any, cost: Mapping[int, Any] | None, fill_halos: bool, + fields: Sequence[str] | None = None, ) -> AMRHierarchy: """A hierarchy with this base and the refined ``boxes``, with the fields moved over.""" from patchwork.mesh.regrid import transfer @@ -1038,10 +1039,16 @@ def _rebuilt( for level in sorted(boxes): for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): new.add_patch(level, box) + moved = set(self._field_specs if fields is None else fields) + unknown = moved - set(self._field_specs) + if unknown: + raise KeyError(f"hierarchy has no field {sorted(unknown)[0]!r}") for name, spec in self._field_specs.items(): + new.allocate_field(name, **spec) + if name not in moved: + continue # allocated, zero if spec["conservative"]: self.restrict(name) - new.allocate_field(name, **spec) transfer(self, new, name) if fill_halos: for name in new.field_names: @@ -1085,6 +1092,7 @@ def regrid( placement: str | Callable[[int, IndexBox], Any] | None = None, cost: Mapping[int, Any] | None = None, fill_halos: bool = False, + fields: Sequence[str] | None = None, ) -> AMRHierarchy: """A new hierarchy with patches over the tagged cells, and the fields moved to it. @@ -1120,7 +1128,11 @@ def regrid( fine cells of a coarse cell keep its mean: its `integral` is the same before and after. Halos are not filled unless ``fill_halos`` (then `exchange_halos` runs for every field of the new - hierarchy). + hierarchy). ``fields`` names the fields whose values are moved + (default: all); the others are allocated on the new hierarchy and + zero, which saves the transfer of a field that is computed again + right after the regrid, such as a charge deposited from the markers + or a potential solved for. ``min_patch_size`` is the shortest side a patch may have, in cells of its own level (rounded up to whole cells of the level below): a patch @@ -1178,7 +1190,7 @@ def regrid( min_patch_size=min_patch_size, forbid=forbid, ) - return self._rebuilt(boxes, placement, cost, fill_halos) + return self._rebuilt(boxes, placement, cost, fill_halos, fields) @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) def rebalance( diff --git a/src/patchwork/spaces/nodes.py b/src/patchwork/spaces/nodes.py index d998f23..ea3ff64 100644 --- a/src/patchwork/spaces/nodes.py +++ b/src/patchwork/spaces/nodes.py @@ -370,20 +370,24 @@ def __init__(self, hierarchy: AMRHierarchy) -> None: self._spacing = np.asarray(hierarchy.spacing(finest), dtype=float) self._origin = np.asarray(hierarchy.lower_bound, dtype=float) + # the cells of every level under a finer patch (one may lie over several patches) + under = {} + for level in range(finest): + mask = np.zeros(hierarchy.level_shape(level), dtype=bool) + for child in hierarchy.patches_at_level(level + 1): + mask[tuple(slice(c0 // ratio, c1 // ratio) for c0, c1 in child.box)] = ( + True + ) + under[level] = mask lowers, spans, owners = [], [], [] for patch in hierarchy.patches: span = ratio ** (finest - patch.level) - covered = np.zeros(patch.shape, dtype=bool) - for child in hierarchy.patches_at_level(patch.level + 1): - # a finer patch may lie over several patches of this level - covered[ - tuple( - slice( - max(c0 // ratio, i0) - i0, max(min(c1 // ratio, i1) - i0, 0) - ) - for (c0, c1), (i0, i1) in zip(child.box, patch.box, strict=True) - ) - ] = True + if patch.level in under: + covered = under[patch.level][ + tuple(slice(i0, i1) for i0, i1 in patch.box) + ] + else: + covered = np.zeros(patch.shape, dtype=bool) index = np.nonzero(~covered) lowers.append( np.column_stack( diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 95c9d33..61ad51b 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -462,3 +462,24 @@ def test_marker_counts_of_every_level_are_its_own_histogram(graded) -> None: 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)) + + +def test_regrid_moves_only_the_fields_asked_for() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + mesh.allocate_field("u", centering="node") + mesh.allocate_field("rho", conservative=True) + for patch in mesh.local_patches: + patch.field("u").local[...] = 1.0 + patch.field("rho").local[...] = 2.0 + tags = function_tags(mesh, lambda x, y: x < 0.5, levels=1) + moved = mesh.regrid(tags, fields=["u"]) + assert moved.field_names == mesh.field_names + for patch in moved.local_patches: + assert np.all(patch.field("u").local == 1.0) + assert not np.any(patch.field("rho").local) + assert all( + np.all(p.field("rho").local == 2.0) + for p in mesh.regrid(tags, fields=None).local_patches + ) + with pytest.raises(KeyError, match="phi"): + mesh.regrid(tags, fields=["phi"]) From 8ac2cc822650242c888c629589da91760beca276 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 10:42:33 +0000 Subject: [PATCH 12/24] Results of the node numbering, accumulation and fields changes. --- CHANGELOG.md | 6 ++++++ benchmarks/quadtree/RESULTS.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 658b7eb..c90a4d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- `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 + compared every patch with every patch of the next level); the `accumulate_halos` schedule + takes the rank of a node's owner from a table; halo copies between two patches are kept + per pair across regrids; `in_domain` is a bounds check where the domain fills its box. - `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 diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 12f7cf8..136aabe 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -105,6 +105,37 @@ Serial, median of 3 runs, ms per step: 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'). +## Node numbering, accumulation, halo pairs and `regrid(fields=...)` (2026-11-25, later) + +Against `devel` after the changes above. `CompositeNodes` finds the cells under finer +patches from one coverage mask per level instead of every patch against every patch of the +next level; the schedule of `accumulate_halos` takes the rank of a node's owner from a table +where the owner is on one rank; the halo copies between two patches of a level are kept per +pair; `in_domain` is a bounds check where the domain fills its box; and `regrid` takes +`fields`, the fields to move (the others are new and zero). Serial, median of 3 runs, ms per +step, total: + +| mesh | devel (all fields moved) | this, all fields moved | this, `fields=[]` | +|---|---|---|---| +| cluster | 241 | 245 | 225 (−7%) | +| cluster, `max_patch_size=16` | 496 | 495 | 430 (−13%) | +| quadtree, block 8 | 938 | 837 (−11%) | 632 (−33%) | +| quadtree, block 16 | 474 | 455 (−4%) | 388 (−18%) | +| quadtree, block 32 | 427 | 442 (within the noise) | 401 (−6%) | + +- With many patches the node numbering was quadratic: blocks of 8, solver setup 180 → + 111 ms (the numbering itself 143 → 24 ms); the rest of the setup is the assembly and the + LU factorisation, which do not depend on the patches. +- The deposit's accumulation schedule: 141 → 112 ms with blocks of 8. +- Not moving the fields that are computed again after the regrid (the charge, deposited; + the potential, solved for) leaves the regrid with the boxes and the new hierarchy: + blocks of 8, 253 → 84 ms; clusters, 14 → 3 ms. +- The halos did not get faster from the pair cache (195 → 186 ms with blocks of 8, within + the noise): what is left of their schedule is the `CopyPlan` (~65 ms), the coarse-to-fine + interpolation of the patches whose neighbourhood changed (~35 ms) and the signatures + (~33 ms). The next step there: keep the `CopyPlan` of the kept patches, or set up the + interpolation of all patches at once. + ## Fixed on the way The regrid's transfer compared every new patch with every old one of its level, and copied From 44b2d18abe77102d6b69b33ac0ab25a494ca2d88 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 11:43:29 +0000 Subject: [PATCH 13/24] feat: Hilbert placement, knapsack with cost, measured costs per patch. --- CHANGELOG.md | 2 +- src/patchwork/__init__.py | 6 +- src/patchwork/mesh/__init__.py | 6 +- src/patchwork/mesh/hierarchy.py | 131 +++++++++++----- src/patchwork/mesh/regrid.py | 181 +++++++++++++++++----- src/patchwork/tests/unit/test_quadtree.py | 125 +++++++++++++-- tutorials/13_quadtree_patches.ipynb | 108 ++----------- 7 files changed, 361 insertions(+), 198 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c90a4d7..490535a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,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 diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index d40902b..51177af 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -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, ) @@ -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", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index 0db5ce8..56e2ff7 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -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, ) @@ -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", ] diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 30ed0e3..3bdf1a4 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -2,6 +2,7 @@ from __future__ import annotations +import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -89,6 +90,9 @@ def _gather_blocks( return result +#: The placements a hierarchy takes by name (besides a function of the patch). +_PLACEMENTS = ("all", "balanced", "morton", "hilbert") + #: Tag of the messages that carry a gathered patch field to another rank. _GATHER_TAG = 7311 @@ -319,16 +323,17 @@ class AMRHierarchy: on several, over which mpiarray splits its fields. ``placement`` says where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so - far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the - patches (`morton_ranks`: the patches of all levels in the order of the - curve, cut into runs of about equal cells with the base level counted, - one run per rank, so that neighbouring patches and the patches over them - tend to share a rank; a patch added by `add_patch` goes where + far, ``"morton"`` or ``"hilbert"`` along that space-filling curve when + `regrid` places the patches (`curve_ranks`: the patches of all levels in + the order of the curve, cut into runs of about equal cells with the base + level counted, one run per rank, so that neighbouring patches and the + patches over them tend to share a rank; the Hilbert curve has no jumps, so + its runs are more compact; a patch added by `add_patch` goes where ``"balanced"`` would put it), or a function ``placement(level, box)`` that returns the ranks (as ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is split over as many of the least loaded ranks as it needs (at most all of - them); a ``"morton"`` patch stays on one rank. + them); a patch placed along a curve stays on one rank. The domain is the rectangle of ``base_shape`` cells, or with ``base_boxes`` the union of those boxes of base cells: an L, a T, a rectangle with a notch. @@ -503,10 +508,10 @@ def __init__( ) self.geometry = geometry self.comm = mpa.default_comm() if comm is None else comm - if not callable(placement) and placement not in ("all", "balanced", "morton"): + if not callable(placement) and placement not in _PLACEMENTS: raise ValueError( - "placement must be 'all', 'balanced', 'morton' or a function, " - f"got {placement!r}" + f"placement must be one of {', '.join(map(repr, _PLACEMENTS))} " + f"or a function, got {placement!r}" ) if max_cells_per_rank is not None and int(max_cells_per_rank) < 1: raise ValueError("max_cells_per_rank must be at least 1") @@ -1019,19 +1024,26 @@ def _rebuilt( geometry=self.geometry, axis_nodes=self.axis_nodes, ) - if new.placement == "morton": - from patchwork.mesh.regrid import box_costs, morton_ranks + if new.placement in ("morton", "hilbert") or ( + new.placement == "balanced" and cost is not None + ): + from patchwork.mesh.regrid import box_costs, curve_ranks, knapsack_ranks weights, load = None, list(new.cells_on_rank) # the base level if cost is not None: weights, load = box_costs(new, boxes, cost) - ranks = morton_ranks( - boxes, - self.comm.Get_size(), - ratio=self.refinement_ratio, - load=load, - weights=weights, - ) + size = self.comm.Get_size() + if new.placement == "balanced": + ranks = knapsack_ranks(boxes, size, load=load, weights=weights) + else: + ranks = curve_ranks( + boxes, + size, + curve=new.placement, + ratio=self.refinement_ratio, + load=load, + weights=weights, + ) for level in sorted(boxes): for box, rank in zip(boxes[level], ranks[level], strict=True): new.add_patch(level, box, ranks=rank) @@ -1145,24 +1157,32 @@ def regrid( is used for every refined level. Tags that would need a forbidden cell are dropped, as are those that would need patches too close to it. - New patches are placed by ``placement`` (default: this hierarchy's), - the largest first, or along a Morton curve with ``"morton"``. With - ``"morton"``, ``cost`` weighs the patches by more than their cells: a - mapping from a level to a per-cell cost of that level's shape, in units - of one cell (the markers of `marker_counts` times what a marker costs - against a cell), counted in the patch where the cell is a leaf - (`box_costs`), so that a rank with a dense beam gets fewer cells. Collective over ``comm``; this hierarchy is left as + New patches are placed by ``placement`` (default: this hierarchy's): + the largest first with ``"balanced"``, or along a space-filling curve + with ``"morton"`` or ``"hilbert"``. With these three, ``cost`` weighs + the patches by more than their cells (`box_costs`): a mapping from a + level to a per-cell cost of that level's shape, in units of one cell + (the markers of `marker_counts` times what a marker costs against a + cell), counted in the patch where the cell is a leaf, or a mapping from + a patch ``(level, box)`` to a measured cost (``deposit(..., + times=...)``). ``"balanced"`` with a cost is the greedy knapsack + (`knapsack_ranks`): the most even, without locality. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ from patchwork.mesh.regrid import combine_tags, new_boxes, quadtree_boxes if method not in ("cluster", "quadtree"): raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") - if ( - cost is not None - and (self.placement if placement is None else placement) != "morton" + if cost is not None and ( + self.placement if placement is None else placement + ) not in ( + "balanced", + "morton", + "hilbert", ): - raise ValueError("cost weighs the patches of placement='morton' only") + raise ValueError( + "cost weighs the patches of placement 'balanced', 'morton' or 'hilbert'" + ) if method == "quadtree" and max_patch_size is not None: raise ValueError( "max_patch_size does not apply to method='quadtree': " @@ -1194,22 +1214,34 @@ def regrid( @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) def rebalance( - self, cost: Mapping[int, Any] | None = None, *, fill_halos: bool = False + self, + cost: Mapping[int, Any] | None = None, + *, + placement: str = "morton", + fill_halos: bool = False, ) -> AMRHierarchy: - """The same patches placed again along the Morton curve, by ``cost``; fields moved. - - Every refined patch goes to a rank by `morton_ranks`, weighed by its - cells plus the ``cost`` of its leaf cells as in `regrid` (`box_costs`; - without ``cost`` by its cells). The base level stays where it is. Every - field is copied to the patches' new ranks; send the markers after them - with `migrate`. The new hierarchy places its regrids along the curve as - well (``placement="morton"``). Collective over ``comm``. + """The same patches placed again by ``cost``; fields moved. + + Every refined patch goes to a rank along a space-filling curve + (``placement`` ``"morton"`` or ``"hilbert"``, `curve_ranks`) or by the + greedy knapsack (``"balanced"``, `knapsack_ranks`), weighed by its cells + plus the ``cost`` of its leaf cells, or by measured costs per patch, as + in `regrid` (`box_costs`; without ``cost`` by its cells). The base + level stays where it is. Every field is copied to the patches' new + ranks; send the markers after them with `migrate`. The new hierarchy + places its regrids the same way. Collective over ``comm``. """ + if placement not in ("balanced", "morton", "hilbert"): + raise ValueError( + f"rebalance places by 'balanced', 'morton' or 'hilbert', got {placement!r}" + ) boxes = { level: [patch.box for patch in self.patches_at_level(level)] for level in range(1, self.max_level + 1) } - return self._rebuilt(boxes, "morton", cost, fill_halos) + if placement == "balanced" and cost is None: + cost = {} # by cells: the knapsack, not the order of add_patch + return self._rebuilt(boxes, placement, cost, fill_halos) def integral(self, name: str) -> float: """The integral of field ``name`` over the domain, from the finest values. @@ -1643,6 +1675,7 @@ def deposit( name: str | None = None, reset: bool = True, splines: Any = 1, + times: dict | None = None, ) -> None: """Deposit the charge of markers on the node-centered field ``name``, patch by patch. @@ -1667,6 +1700,10 @@ def deposit( ``mpifield.splines(p).halo`` nodes (2 from degree 2 on). Where the stencil would reach past the edge of the marker's patch it folds onto the patch's edge nodes, so the total is kept; such charge stays on the patch. + + ``times``, a dict, collects the seconds spent on the markers of every + patch, added to the value of its ``(level, box)``: costs measured on + this rank, for `regrid` and `rebalance` (sum them over the ranks first). """ import numpy as np @@ -1695,16 +1732,24 @@ def deposit( patch.field(name).local_with_halos[...] = 0.0 patches = self.patches for number, chosen in _by_patch(found): + start = time.perf_counter() 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 shape.nodes.scatter_block( positions, charge[chosen], storage[..., None], grid ) + if times is not None: + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + time.perf_counter() - start @sp.profile("patchwork.interpolate", tags=PROFILE_TAGS) def interpolate( - self, *arguments: Any, name: str | None = None, splines: Any = 1 + self, + *arguments: Any, + name: str | None = None, + splines: Any = 1, + times: dict | None = None, ) -> Any: """Interpolate the node-centered field ``name`` at markers, each in its own patch. @@ -1721,6 +1766,8 @@ def interpolate( ``splines`` is the B-spline degree of the weights (1, 2 or 3) or an `mpifield.Splines`, as for `deposit`, whose transpose this is for the same degree, the fold at the patch edges included. + + ``times`` collects the seconds spent per patch, as in `deposit`. """ import numpy as np @@ -1738,11 +1785,15 @@ def interpolate( values = np.zeros(flat[0].size) patches = self.patches for number, chosen in _by_patch(found): + start = time.perf_counter() 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)) weights.nodes.gather_block(positions, storage[..., None], result, grid) values[chosen] = result[0] + if times is not None: + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + time.perf_counter() - start return values.reshape(shape) @sp.profile("patchwork.accumulate_halos", tags=PROFILE_TAGS) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 92f434d..f39e964 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -738,44 +738,79 @@ def quadtree_boxes( return boxes +def _curve_keys(items: list[tuple], ratio: int, curve: str) -> list[int]: + """The key of every ``(level, n, box)`` on a curve: its lower corner in finest cells.""" + top = max(level for level, _, _ in items) + corners = np.array( + [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], + dtype=np.uint64, + ) + if corners.shape[1] == 1: # 1D: the curve is the axis + return corners.reshape(-1).tolist() + if curve == "morton": + return xp.algorithms.morton_encode(*corners.T).tolist() + levels = max(1, int(corners.max()).bit_length()) + return xp.algorithms.hilbert_encode(*corners.T, levels=levels).tolist() + + +def _costs( + boxes: Mapping[int, Sequence[IndexBox]], + items: list[tuple], + weights: Mapping[int, Sequence[float]] | None, +) -> list[float]: + """The cost of every item: its cells, or its weight.""" + if weights is None: + return [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + for level in boxes: + if len(weights[level]) != len(boxes[level]): + raise ValueError(f"weights of level {level} need one value per box") + return [float(weights[level][n]) for level, n, _ in items] + + @method( equations={ - "key": r"k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}", - "ranks": r"\text{along the curve, rank } q \text{ takes boxes while } w_q + |B|/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B |B|\Big)", + "morton": r"k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}", + "hilbert": r"k(B) = H\big(r^{L - \ell}\, \mathbf i\big), \quad H \text{ the Hilbert index (Skilling's construction): consecutive keys are neighbouring cells}", + "ranks": r"\text{along the curve, rank } q \text{ takes boxes while } w_q + c_B/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B c_B\Big)", }, assumptions=( "the patches of all refined levels on one curve, a coarse patch before the finer ones at the same corner, so that a patch and the patches over it tend to share a rank", - "the load a rank already has (the base level) counts: such a rank takes fewer patches", + "the cost $c_B$ of a box is its cells, or its weight (`box_costs`); the load a rank already has (the base level) counts", "a patch stays on one rank", ), references=( "[Morton, IBM technical report (1966)](https://dominoweb.draco.res.ibm.com/reports/Morton1966.pdf)", + "[Skilling, AIP Conf. Proc. 707, 381 (2004)](https://doi.org/10.1063/1.1751381)", "[Burstedde, Wilcox and Ghattas, SIAM J. Sci. Comput. 33, 1103 (2011)](https://doi.org/10.1137/100791634)", ), ) -def morton_ranks( +def curve_ranks( boxes: Mapping[int, Sequence[IndexBox]], size: int, *, + curve: str = "morton", ratio: int = 2, load: Sequence[float] | None = None, weights: Mapping[int, Sequence[float]] | None = None, ) -> dict[int, list[int]]: - """The rank of each box: the boxes of all levels along a Morton curve, cut into ``size`` runs. - - ``boxes`` maps a level to its boxes. Every box gets the Morton (Z-order) - key of its lower corner in cells of the finest level, so that boxes close - in space are close on the curve whatever their level, and a box comes - before the finer boxes at the same corner. Walking the curve, a rank takes - boxes until its cells, with the ``load`` it already has (the cells of the - base level, say), reach an equal share of all cells; then the next rank - goes on. ``weights`` (per level, one per box) replaces the cells of a box - by its cost, in the units of ``load``: with `box_costs`, the cells plus the - markers on them. Returns, per level, the ranks in the order of + """The rank of each box: the boxes of all levels along a space-filling curve, cut into ``size`` runs. + + ``boxes`` maps a level to its boxes. Every box gets the key of its lower + corner, in cells of the finest level, on the ``curve``: ``"morton"`` (the + Z-order curve) or ``"hilbert"`` (without the Z's jumps, so that the run of + a rank is more compact). Boxes close in space are close on the curve + whatever their level, and a box comes before the finer boxes at the same + corner. Walking the curve, a rank takes boxes until its cost, with the + ``load`` it already has (the cells of the base level, say), reaches an equal + share of all costs; then the next rank goes on. The cost of a box is its + cells, or ``weights`` (per level, one per box, in the units of ``load``; + see `box_costs`). Returns, per level, the ranks in the order of ``boxes[level]``. """ if size < 1: raise ValueError(f"size must be at least 1, got {size}") + if curve not in ("morton", "hilbert"): + raise ValueError(f"curve must be 'morton' or 'hilbert', got {curve!r}") loads = [0.0] * size if load is None else [float(w) for w in load] if len(loads) != size: raise ValueError(f"load needs {size} values, got {len(loads)}") @@ -785,25 +820,11 @@ def morton_ranks( result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} if not items: return result - top = max(level for level, _, _ in items) - corners = np.array( - [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], - dtype=np.uint64, - ) - if corners.shape[1] > 1: - keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D - else: # 1D: the curve is the axis - keys = corners.reshape(-1) - if weights is None: - costs = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] - else: - for level in boxes: - if len(weights[level]) != len(boxes[level]): - raise ValueError(f"weights of level {level} need one value per box") - costs = [float(weights[level][n]) for level, n, _ in items] + keys = _curve_keys(items, ratio, curve) + costs = _costs(boxes, items, weights) share = (sum(loads) + sum(costs)) / size rank = 0 - for k in sorted(range(len(items)), key=lambda k: (int(keys[k]), items[k][0])): + for k in sorted(range(len(items)), key=lambda k: (keys[k], items[k][0])): while rank < size - 1 and loads[rank] + costs[k] / 2 > share: rank += 1 level, n, _ = items[k] @@ -812,21 +833,99 @@ def morton_ranks( return result +@method( + equations={ + "greedy": r"c_{B_1} \ge c_{B_2} \ge \dots, \qquad r(B_k) = \arg\min_q w_q \text{ (the lowest such rank)}, \quad w_{r(B_k)} \mathrel{+}= c_{B_k}", + }, + assumptions=( + "the greedy (longest processing time first) solution of the knapsack-like partition: the largest cost at most 4/3 of the best possible", + "no locality: neighbouring patches may land on any ranks", + ), + references=( + "[Graham, SIAM J. Appl. Math. 17, 416 (1969)](https://doi.org/10.1137/0117039)", + ), +) +def knapsack_ranks( + boxes: Mapping[int, Sequence[IndexBox]], + size: int, + *, + load: Sequence[float] | None = None, + weights: Mapping[int, Sequence[float]] | None = None, +) -> dict[int, list[int]]: + """The rank of each box: the largest cost first, each to the rank with the least so far. + + The greedy solution of cutting the boxes into ``size`` sets of equal cost, + what ``placement="balanced"`` does with cells, here with the ``weights`` of + `box_costs` and the ``load`` the ranks already have. Balances better than a + curve, but neighbouring boxes may land on different ranks. Returns, per + level, the ranks in the order of ``boxes[level]``. + """ + if size < 1: + raise ValueError(f"size must be at least 1, got {size}") + loads = [0.0] * size if load is None else [float(w) for w in load] + if len(loads) != size: + raise ValueError(f"load needs {size} values, got {len(loads)}") + items = [ + (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) + ] + result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} + costs = _costs(boxes, items, weights) + for k in sorted( + range(len(items)), key=lambda k: (-costs[k], items[k][0], items[k][2]) + ): + rank = min(range(size), key=lambda q: (loads[q], q)) + level, n, _ = items[k] + result[level][n] = rank + loads[rank] += costs[k] + return result + + def box_costs( hierarchy: AMRHierarchy, boxes: Mapping[int, Sequence[IndexBox]], cost: Mapping[int, Any], ) -> tuple[dict[int, list[float]], list[float]]: - """The cost of each new box and of each rank's base patches: cells plus the cost of the leaf cells. - - ``cost`` maps a level to a per-cell cost of that level's shape, in units of - one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a cell; - a missing level costs nothing beyond its cells). A cell's cost goes to the - box where it is a leaf, not covered by a finer box, since that is where its - markers deposit and gather. ``hierarchy`` holds the base level (the patches - of level 0 with their ranks). Returns the weights of ``boxes`` per level and - the load of every rank from the base level, for `morton_ranks`. + """The cost of each new box and of each rank's base patches. + + ``cost`` is one of two things: + + - a mapping from a level to a per-cell cost of that level's shape, in units + of one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a + cell; a missing level costs nothing beyond its cells): a box costs its + cells plus the cost of its leaf cells, the cells no finer box covers, + since that is where their markers deposit and gather; + - a mapping from a patch, ``(level, box)``, to its cost, e.g. the seconds + measured with ``deposit(..., times=...)`` and ``interpolate(..., + times=...)``: a box costs its own value, and a box without one the mean + cost per cell of those that have one. + + ``hierarchy`` holds the base level (the patches of level 0 with their + ranks). Returns the weights of ``boxes`` per level and the load of every + rank from the base level, for `curve_ranks` and `knapsack_ranks`. """ + if any(isinstance(key, tuple) for key in cost): + measured = { + (int(level), tuple(tuple(side) for side in box)): float(value) + for (level, box), value in cost.items() + } + cells = sum(float(np.prod([hi - lo for lo, hi in box])) for _, box in measured) + per_cell = sum(measured.values()) / cells if cells else 0.0 + + def measured_weight(level: int, box: IndexBox) -> float: + found = measured.get((level, box)) + if found is not None: + return found + return per_cell * float(np.prod([hi - lo for lo, hi in box])) + + weights = { + level: [measured_weight(level, box) for box in boxes[level]] + for level in boxes + } + load = [0.0] * hierarchy.comm.Get_size() + for patch in hierarchy.patches_at_level(0): + for rank in patch.ranks: + load[rank] += measured_weight(0, patch.box) / len(patch.ranks) + return weights, load ratio = hierarchy.refinement_ratio top = max(boxes, default=0) leaf_cost = {} diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 61ad51b..7e0d984 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -11,9 +11,9 @@ from patchwork import ( AMRHierarchy, + curve_ranks, function_tags, marker_tags, - morton_ranks, quadtree_boxes, ) from patchwork.mesh.regrid import combine_tags @@ -223,28 +223,28 @@ def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: assert new.max_level == 0 -def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: +def test_curve_ranks_follow_the_z_curve_with_equal_cells() -> None: # sixteen 2 x 2 blocks of a 8 x 8 level: the Z curve visits the quadrants in turn boxes = [ ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) ] - ranks = morton_ranks({1: boxes}, 4)[1] + ranks = curve_ranks({1: boxes}, 4)[1] for box, rank in zip(boxes, ranks, strict=True): (i0, _), (j0, _) = box assert rank == (i0 >= 4) + 2 * (j0 >= 4) # the first axis is the lowest bit # a rank that holds the base already takes fewer patches - loaded = morton_ranks({1: boxes}, 2, load=[32, 0])[1] + loaded = curve_ranks({1: boxes}, 2, load=[32, 0])[1] assert loaded.count(0) == 4 and loaded.count(1) == 12 # a patch and the finer patch over it are neighbours on the curve levels = {1: [((0, 4), (0, 4)), ((4, 8), (4, 8))], 2: [((0, 4), (0, 4))]} - assert morton_ranks(levels, 2) == {1: [0, 1], 2: [0]} - assert morton_ranks({1: boxes}, 1)[1] == [0] * 16 - assert morton_ranks({}, 3) == {} - assert morton_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D + assert curve_ranks(levels, 2) == {1: [0, 1], 2: [0]} + assert curve_ranks({1: boxes}, 1)[1] == [0] * 16 + assert curve_ranks({}, 3) == {} + assert curve_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D with pytest.raises(ValueError, match="size"): - morton_ranks({1: boxes}, 0) + curve_ranks({1: boxes}, 0) with pytest.raises(ValueError, match="load"): - morton_ranks({1: boxes}, 2, load=[1.0]) + curve_ranks({1: boxes}, 2, load=[1.0]) def test_regrid_places_the_blocks_along_the_morton_curve() -> None: @@ -255,7 +255,7 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: assert new.placement == "morton" boxes = {level: [p.box for p in new.patches_at_level(level)] for level in (1, 2)} base = AMRHierarchy(base_shape=(16, 16), placement="morton").cells_on_rank - expected = morton_ranks(boxes, SIZE, load=base) + expected = curve_ranks(boxes, SIZE, load=base) for level in (1, 2): patches = new.patches_at_level(level) assert [p.ranks for p in patches] == [(r,) for r in expected[level]] @@ -268,7 +268,7 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: added = again.add_patch(3, ((40, 48), (40, 48))) assert len(added.ranks) == 1 with pytest.raises(ValueError, match="morton"): - AMRHierarchy(base_shape=(4, 4), placement="hilbert") + AMRHierarchy(base_shape=(4, 4), placement="peano") @pytest.mark.parametrize("centering", ["node", "cell"]) @@ -338,12 +338,12 @@ def test_marker_weights_move_the_cuts_of_the_morton_curve() -> None: boxes = { 1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(4)] } # four boxes of 4 cells - assert morton_ranks(boxes, 2) == {1: [0, 0, 1, 1]} + assert curve_ranks(boxes, 2) == {1: [0, 0, 1, 1]} # the first box costs as much as the other three: it gets a rank to itself heavy = {1: [12.0, 4.0, 4.0, 4.0]} - assert morton_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} + assert curve_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} with pytest.raises(ValueError, match="weights"): - morton_ranks(boxes, 2, weights={1: [1.0]}) + curve_ranks(boxes, 2, weights={1: [1.0]}) mesh = AMRHierarchy(base_shape=(8, 8)) rank = WORLD.Get_rank() @@ -430,7 +430,7 @@ def plane(x, y): for level in range(1, mesh.max_level + 1) } weights, load = box_costs(moved, boxes, cost) - expected = morton_ranks(boxes, SIZE, load=load, weights=weights) + expected = curve_ranks(boxes, SIZE, load=load, weights=weights) for level in boxes: ranks = [p.ranks for p in moved.patches_at_level(level)] assert ranks == [(r,) for r in expected[level]] @@ -483,3 +483,96 @@ def test_regrid_moves_only_the_fields_asked_for() -> None: ) with pytest.raises(KeyError, match="phi"): mesh.regrid(tags, fields=["phi"]) + + +def test_hilbert_runs_are_contiguous_and_balanced() -> None: + from patchwork import curve_ranks + + boxes = [ + ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(8) for j in range(8) + ] + ranks = curve_ranks({1: boxes}, 3, curve="hilbert")[1] + assert sorted(set(ranks)) == [0, 1, 2] + counts = [ranks.count(r) for r in range(3)] + assert max(counts) - min(counts) <= 1 + # every rank's boxes are connected through shared faces: the curve has no jumps + for rank in range(3): + mine = { + (b[0][0] // 2, b[1][0] // 2) + for b, r in zip(boxes, ranks, strict=True) + if r == rank + } + seen, todo = set(), [next(iter(mine))] + while todo: + cell = todo.pop() + if cell in seen: + continue + seen.add(cell) + i, j = cell + todo += [ + c for c in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)) if c in mine + ] + assert seen == mine + with pytest.raises(ValueError, match="curve"): + curve_ranks({1: boxes}, 3, curve="peano") + + +def test_knapsack_balances_the_weights() -> None: + from patchwork import knapsack_ranks + + boxes = {1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(6)]} + weights = {1: [7.0, 5.0, 4.0, 3.0, 3.0, 2.0]} + ranks = knapsack_ranks(boxes, 2, weights=weights)[1] + load = [ + sum(w for w, r in zip(weights[1], ranks, strict=True) if r == q) + for q in range(2) + ] + assert sorted(load) == [12.0, 12.0] + assert knapsack_ranks(boxes, 2, load=[100.0, 0.0])[1] == [1] * 6 + with pytest.raises(ValueError, match="load"): + knapsack_ranks(boxes, 2, load=[1.0]) + with pytest.raises(ValueError, match="size"): + knapsack_ranks(boxes, 0) + + +def test_measured_times_per_patch_weigh_the_placement() -> None: + from patchwork import box_costs + + mesh = AMRHierarchy(base_shape=(16, 16), placement="hilbert") + mesh.allocate_field("rho", centering="node") + mesh = mesh.regrid( + function_tags(mesh, ring, levels=1), method="quadtree", block_size=8 + ) + rng = np.random.default_rng(WORLD.Get_rank()) + x, y = rng.uniform(0.2, 0.4, (2, 500)) + q = np.ones(x.size) + mx, my, mq = mesh.migrate(x, y, q, name="rho") + times: dict = {} + mesh.deposit(mx, my, mq, "rho", times=times) + mesh.interpolate(mx, my, "rho", times=times) + # a rank may hold no markers: count over all ranks (and fail on all of them) + assert WORLD.allreduce(len(times)) > 0 + assert all(value >= 0.0 for value in times.values()) + assert all( + (level, box) in {(p.level, p.box) for p in mesh.patches} for level, box in times + ) + # a patch with a cost gets it, one without the mean per cell + boxes = {1: [p.box for p in mesh.patches_at_level(1)]} + known = boxes[1][0] + weights, load = box_costs(mesh, boxes, {(1, known): 640.0}) + assert weights[1][0] == 640.0 + assert np.allclose(weights[1][1:], 640.0 / 64 * 64) + moved = mesh.rebalance( + {(p.level, p.box): float(n) for n, p in enumerate(mesh.patches)} + ) + assert moved.placement == "morton" + for placement in ("balanced", "hilbert"): + again = mesh.rebalance(placement=placement) + assert [(p.level, p.box) for p in again.patches] == [ + (p.level, p.box) for p in mesh.patches + ] + assert again.placement == placement + with pytest.raises(ValueError, match="rebalance"): + mesh.rebalance(placement="all") + with pytest.raises(ValueError, match="cost weighs"): + AMRHierarchy(base_shape=(4, 4)).regrid({0: np.ones((4, 4), bool)}, cost={}) diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index 470002a..e0d6c26 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -4,20 +4,7 @@ "cell_type": "markdown", "id": "0", "metadata": {}, - "source": [ - "# Quadtree patches\n", - "\n", - "`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\n", - "tagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n", - "[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\n", - "aligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\n", - "the blocks of a level are the children of those of the level below, so the patches are the\n", - "nodes of a quadtree (an octree in 3D), all of one size.\n", - "\n", - "Both give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\n", - "solvers work on either. They differ in how many patches there are, how many cells are\n", - "refined, and how much the mesh changes when the tags change a little." - ] + "source": "# Quadtree patches\n\n`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\ntagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\naligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\nthe blocks of a level are the children of those of the level below, so the patches are the\nnodes of a quadtree (an octree in 3D), all of one size.\n\nBoth give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\nsolvers work on either. They differ in how many patches there are, how many cells are\nrefined, and how much the mesh changes when the tags change a little." }, { "cell_type": "code", @@ -42,11 +29,7 @@ "cell_type": "markdown", "id": "2", "metadata": {}, - "source": [ - "## Clusters and blocks\n", - "\n", - "The same tags, a ring refined by three levels, placed both ways:" - ] + "source": "## Clusters and blocks\n\nThe same tags, a ring refined by three levels, placed both ways:" }, { "cell_type": "code", @@ -91,19 +74,7 @@ "cell_type": "markdown", "id": "4", "metadata": {}, - "source": [ - "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\n", - "blocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\n", - "size for every patch, and patches that are easy to share out between ranks.\n", - "\n", - "## The blocks form a tree\n", - "\n", - "A block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n", - "(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\n", - "exactly one block of the level below, its parent, and each parent has four children. Where a\n", - "block is refined, the level below is refined around it as well, with a margin of `nesting`\n", - "cells, so neighbouring blocks differ by at most one level: the tree is balanced." - ] + "source": "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\nblocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\nsize for every patch, and patches that are easy to share out between ranks.\n\n## The blocks form a tree\n\nA block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\nexactly one block of the level below, its parent, and each parent has four children. Where a\nblock is refined, the level below is refined around it as well, with a margin of `nesting`\ncells, so neighbouring blocks differ by at most one level: the tree is balanced." }, { "cell_type": "code", @@ -129,18 +100,7 @@ "cell_type": "markdown", "id": "6", "metadata": {}, - "source": [ - "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\n", - "it may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n", - "\n", - "## Refining by the number of markers\n", - "\n", - "`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\n", - "particle tree stops splitting a box when it holds few enough particles; regridding with these\n", - "tags stops refining where the cells hold few enough markers. The markers are counted over all\n", - "ranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\n", - "background:" - ] + "source": "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\nit may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n\n## Refining by the number of markers\n\n`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\nparticle tree stops splitting a box when it holds few enough particles; regridding with these\ntags stops refining where the cells hold few enough markers. The markers are counted over all\nranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\nbackground:" }, { "cell_type": "code", @@ -190,10 +150,7 @@ "cell_type": "markdown", "id": "8", "metadata": {}, - "source": [ - "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\n", - "potential (grounded faces)." - ] + "source": "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\npotential (grounded faces)." }, { "cell_type": "code", @@ -218,15 +175,7 @@ "cell_type": "markdown", "id": "10", "metadata": {}, - "source": [ - "## Following a moving beam\n", - "\n", - "The beam moves to the right, and the mesh is regridded after every step. Between two regrids\n", - "the clusters are recut wherever the tags change, even by a few cells, while the quadtree\n", - "adds and removes blocks only where the beam has come or gone and keeps the others as they\n", - "are: the same patches, on the same ranks, with their fields copied rather than\n", - "interpolated. Kept patches are grey, new ones red:" - ] + "source": "## Following a moving beam\n\nThe beam moves to the right, and the mesh is regridded after every step. Between two regrids\nthe clusters are recut wherever the tags change, even by a few cells, while the quadtree\nadds and removes blocks only where the beam has come or gone and keeps the others as they\nare: the same patches, on the same ranks, with their fields copied rather than\ninterpolated. Kept patches are grey, new ones red:" }, { "cell_type": "code", @@ -289,16 +238,7 @@ "cell_type": "markdown", "id": "12", "metadata": {}, - "source": [ - "## Placing the blocks on ranks\n", - "\n", - "Under MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n", - "(Z-order) curve (`morton_ranks`): the patches of all levels in the order of the curve, keyed\n", - "by their lower corner in cells of the finest level, cut into runs of about equal cells, the\n", - "base level's cells counted. Neighbouring patches, and a patch and the patches over it, then\n", - "tend to share a rank, which saves messages between ranks. Here the ranks four processes would\n", - "give the patches of the beam's mesh:" - ] + "source": "## Placing the blocks on ranks\n\nUnder MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n(Z-order) curve (`curve_ranks`): the patches of all levels in the order of the curve, keyed\nby their lower corner in cells of the finest level, cut into runs of about equal cells, the\nbase level's cells counted. Neighbouring patches, and a patch and the patches over it, then\ntend to share a rank, which saves messages between ranks. Here the ranks four processes would\ngive the patches of the beam's mesh:" }, { "cell_type": "code", @@ -307,7 +247,7 @@ "metadata": {}, "outputs": [], "source": [ - "from patchwork import box_costs, marker_counts, morton_ranks\n", + "from patchwork import box_costs, curve_ranks, marker_counts\n", "\n", "boxes = {\n", " level: [patch.box for patch in mesh.patches_at_level(level)]\n", @@ -350,7 +290,7 @@ "cells = {\n", " level: [np.prod([hi - lo for lo, hi in b]) for b in boxes[level]] for level in boxes\n", "}\n", - "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "ranks = curve_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", "draw_ranks(ranks, f\"cells per rank: {per_rank(ranks, cells, 1024)}\")" ] }, @@ -358,15 +298,7 @@ "cell_type": "markdown", "id": "14", "metadata": {}, - "source": [ - "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\n", - "the markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\n", - "its cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\n", - "patch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n", - "`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\n", - "hierarchy again by them and moves the fields (send the markers after them with `migrate`).\n", - "The ranks with the beam now get fewer cells and about the same cost:" - ] + "source": "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\nthe markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\nits cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\npatch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\nhierarchy again by them and moves the fields (send the markers after them with `migrate`).\nThe ranks with the beam now get fewer cells and about the same cost:" }, { "cell_type": "code", @@ -378,7 +310,7 @@ "counts = marker_counts(mesh, x, y, levels=mesh.max_level + 1)\n", "cost = {level: 0.1 * found for level, found in counts.items()}\n", "weights, (base,) = box_costs(mesh, boxes, cost) # one rank here: the base's cost\n", - "weighted = morton_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", + "weighted = curve_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", "print(\"cells per rank:\", per_rank(weighted, cells, 1024))\n", "print(\"cost per rank, by cells: \", per_rank(ranks, weights, base))\n", "print(\"cost per rank, by markers: \", per_rank(weighted, weights, base))\n", @@ -389,23 +321,7 @@ "cell_type": "markdown", "id": "16", "metadata": {}, - "source": [ - "The few new blocks far from the beam come from the uniform background: its count per cell\n", - "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", - "markers per cell than `per_cell` in the background they would not appear.\n", - "\n", - "## Which one to use\n", - "\n", - "- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n", - " change slowly and the per-patch overhead matters.\n", - "- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n", - " and a regrid leaves most of them untouched: the choice when the tags change every few\n", - " steps, as with markers that move, and for spreading many equal patches over ranks\n", - " (`placement=\"balanced\"`).\n", - "\n", - "`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\n", - "many patches; large blocks give few patches and refine more cells." - ] + "source": "The few new blocks far from the beam come from the uniform background: its count per cell\nfluctuates around `per_cell` there, so a block or two switches on or off. With fewer\nmarkers per cell than `per_cell` in the background they would not appear.\n\n## Which one to use\n\n- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n change slowly and the per-patch overhead matters.\n- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n and a regrid leaves most of them untouched: the choice when the tags change every few\n steps, as with markers that move, and for spreading many equal patches over ranks\n (`placement=\"balanced\"`).\n\n`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\nmany patches; large blocks give few patches and refine more cells." } ], "metadata": { From d718326450875362b819799899f1c15e23b64ec2 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 11:56:19 +0000 Subject: [PATCH 14/24] perf: linear deposit and gather over all patches at once, owners by table, halo signatures as arrays. --- src/patchwork/mesh/halos.py | 82 +++++++++----- src/patchwork/mesh/hierarchy.py | 133 ++++++++++++++++++++++- src/patchwork/tests/unit/test_markers.py | 39 +++++++ 3 files changed, 225 insertions(+), 29 deletions(-) diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 193da3a..b9fce23 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -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], ...] @@ -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. @@ -663,22 +652,62 @@ 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 = 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) + 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])), + ) + if level > 0: + key += (tuple(_key(below[m]) for m in np.flatnonzero(under[n])),) + 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.""" @@ -805,10 +834,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) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 3bdf1a4..cbbd753 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -2,6 +2,7 @@ from __future__ import annotations +import itertools import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -97,6 +98,20 @@ def _gather_blocks( _GATHER_TAG = 7311 +def _share_time( + times: dict, patches: Sequence[Any], owner: Any, seconds: float +) -> None: + """Add ``seconds`` spent on markers of several patches to ``times``, split by markers.""" + import numpy as np + + if not owner.size: + return + numbers, counts = np.unique(owner, return_counts=True) + for number, count in zip(numbers.tolist(), counts.tolist(), strict=True): + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + seconds * count / owner.size + + def _by_patch(found: Any) -> Iterator[tuple[int, Any]]: """The markers of each patch: ``(patch number, their indices)``, in the order of the patches. @@ -1462,8 +1477,15 @@ 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, chosen in _by_patch(found): + # a patch on one rank: that rank, for all its markers at once + single = np.full(len(patches) + 1, -1, dtype=np.int64) + for number, (members, replicated) in blocks.items(): + if len(members) == 1 and not replicated: + single[number] = members[0][0] + result = single[found] # -1 (outside the domain) picks the last entry + several = np.flatnonzero((result < 0) & (found >= 0)) + for number, part in _by_patch(found[several]): + chosen = several[part] members, replicated = blocks[number] if replicated: raise ValueError( @@ -1637,6 +1659,80 @@ def _patch_block(self, patch: Patch, name: str, degree: int) -> tuple[Any, Any]: start = [f + lo for f, lo in zip(first, lower, strict=True)] return block, self._grid(patch, start, block.shape) + def _linear_corners( + self, found: Any, cell: tuple[Any, ...], wrapped: Any, name: str + ) -> tuple[Any, list[tuple[Any, Any]], list[tuple[int, int, Any]], int]: + """The cloud-in-cell corners of all markers at once, in one buffer of the blocks. + + Every marker in the domain reads or writes the ``2**ndim`` corners of its cell in + the stored block of its patch (`_stored_block`), with the weights of mpifield's + linear kernels: ``(1 - f)`` and ``f`` per axis, ``f`` the marker's place in its + cell. The blocks of the patches with markers are laid end to end in one flat + buffer. Returns the markers in the domain, ``(flat index, weight)`` per corner, + ``(patch number, offset, storage)`` per block, and the buffer's size. + """ + import numpy as np + + inside = np.flatnonzero(found >= 0) + numbers = np.flatnonzero( + np.bincount(found[inside], minlength=len(self.patches)) + ) + patches = self.patches + ndim = self.ndim + blocks = [] + offset = 0 + first = np.zeros((len(patches), ndim), dtype=np.int64) + start = np.zeros(len(patches), dtype=np.int64) + strides = np.zeros((len(patches), ndim), dtype=np.int64) + spacing = np.ones((len(patches), ndim)) + for number in numbers.tolist(): + patch = patches[number] + array = patch.field(name) + layout = array.layout + storage = array.local_with_halos + blocks.append((number, offset, storage)) + start[number] = offset + first[number] = [ + lo + b0 - h + for (lo, _), (b0, _), h in zip( + patch.box, layout.index_bounds, layout.halo, strict=True + ) + ] + stride = 1 + for axis in range(ndim - 1, -1, -1): + strides[number, axis] = stride + stride *= storage.shape[axis] + spacing[number] = self.spacing(patch.level) + offset += storage.size + owner = found[inside] + origin = np.asarray(self.lower_bound, dtype=float) + # the flat index of each marker's lower corner, and the steps to the others + base = start - np.einsum("pa,pa->p", first, strides) + flat = base[owner] + steps, fraction = [], [] + for axis in range(ndim): + index = np.asarray(cell[axis])[inside] + step = strides[owner, axis] + flat += index * step + steps.append(step) + fraction.append( + (np.asarray(wrapped[axis])[inside] - origin[axis]) + * (1.0 / spacing)[owner, axis] + - index + ) + corners = [] + for corner in itertools.product((0, 1), repeat=ndim): + where = flat.copy() + weight = np.ones(inside.size) + for axis, up in enumerate(corner): + if up: + where += steps[axis] + weight *= fraction[axis] + else: + weight *= 1.0 - fraction[axis] + corners.append((where, weight)) + return inside, corners, blocks, offset + def _shape(self, name: str, splines: Any, what: str) -> Any: """The `mpifield.Splines` of ``splines`` (a degree or one), checked against the halo.""" from mpifield import splines as resolve @@ -1685,7 +1781,9 @@ def deposit( bilinear (cloud-in-cell) weights: the same weights as `CompositeNodes.deposit`, whose transposed interpolation the field gather is, and of - `interpolate`; mpifield's compiled kernels do the work. The values are + `interpolate`. These weights are added for the markers of all patches at + once (one ``bincount`` into a buffer of the blocks); a higher degree runs + mpifield's compiled kernels patch by patch. The values are charges, not a density. The markers must be on the ranks that `owner` gives (use `migrate`), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. @@ -1731,6 +1829,20 @@ def deposit( for patch in self.local_patches: patch.field(name).local_with_halos[...] = 0.0 patches = self.patches + if shape.degree == 1: # all patches in one pass over the markers + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + charges = charge[inside] + buffer = np.zeros(total) + for flat, weight in corners: + buffer += np.bincount(flat, weights=charges * weight, minlength=total) + for _, offset, storage in blocks: + storage += buffer[offset : offset + storage.size].reshape(storage.shape) + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return for number, chosen in _by_patch(found): start = time.perf_counter() storage, grid = self._patch_block(patches[number], name, shape.degree) @@ -1784,6 +1896,21 @@ def interpolate( ) values = np.zeros(flat[0].size) patches = self.patches + if weights.degree == 1: # all patches in one pass over the markers + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + buffer = np.empty(total) + for _, offset, storage in blocks: + buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) + gathered = np.zeros(inside.size) + for where, weight in corners: + gathered += weight * buffer[where] + values[inside] = gathered + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return values.reshape(shape) for number, chosen in _by_patch(found): start = time.perf_counter() storage, grid = self._patch_block(patches[number], name, weights.degree) diff --git a/src/patchwork/tests/unit/test_markers.py b/src/patchwork/tests/unit/test_markers.py index e850a94..24c3ca1 100644 --- a/src/patchwork/tests/unit/test_markers.py +++ b/src/patchwork/tests/unit/test_markers.py @@ -453,3 +453,42 @@ def test_the_node_grid_of_a_patch_holds_its_nodes() -> None: assert tuple(grid.num_gridpoints) == patch.node_shape assert grid.periodic == (False, False) assert grid.geometry == (i0 * dx, j0 * dy, dx, dy, *patch.node_shape, 0, 0) + + +@pytest.mark.parametrize("periodic", [(False, False), (True, False)]) +def test_one_pass_linear_deposit_and_gather_equal_the_kernels_patch_by_patch( + periodic, +) -> None: + from mpifield import splines + + mesh = AMRHierarchy(base_shape=(8, 8), periodic=periodic) + mesh.add_patch(1, ((4, 12), (4, 12)), ranks=0) + mesh.add_patch(2, ((10, 18), (8, 16)), ranks=0) + mesh.allocate_field("q", centering="node") + rng = np.random.default_rng(WORLD.Get_rank()) + x, y = rng.uniform(0, 1, (2, 2000)) + charge = rng.uniform(0.5, 1.5, x.size) + x, y, charge = mesh.migrate(x, y, charge, name="q") + mesh.deposit(x, y, charge, "q") + gathered = mesh.interpolate(x, y, "q") + # the same with mpifield's compiled kernels, one patch at a time + linear = splines(1) + flat, _ = mesh._points((x, y)) + found, _, wrapped = mesh._cells(flat) + expected_gather = np.zeros(x.size) + for patch in mesh.local_patches: + storage, grid = mesh._patch_block(patch, "q", 1) + reference = np.zeros_like(np.asarray(storage)) + number = mesh.patches.index(patch) + chosen = np.flatnonzero(found == number) + positions = np.array([w[chosen] for w in wrapped]) + linear.nodes.scatter_block( + positions, charge[chosen], reference[..., None], grid + ) + np.testing.assert_allclose(storage, reference, rtol=1e-12, atol=1e-12) + result = np.zeros((1, chosen.size)) + linear.nodes.gather_block( + positions, np.asarray(storage)[..., None], result, grid + ) + expected_gather[chosen] = result[0] + np.testing.assert_allclose(gathered, expected_gather, rtol=1e-12, atol=1e-12) From 9a9708d2d3f6877b0972173c7e2dcb6a5cfcfc3d Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 12:01:46 +0000 Subject: [PATCH 15/24] Results of the last per-patch changes, and the changelog. --- CHANGELOG.md | 10 ++++++++++ benchmarks/quadtree/RESULTS.md | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 490535a..94c24ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 136aabe..87925d2 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -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 From 9416ba5d45b743b7414a09c1d00e964c9ffdc88b Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 12:07:24 +0000 Subject: [PATCH 16/24] Types for pyright. --- src/patchwork/mesh/halos.py | 12 +++++++++--- src/patchwork/mesh/hierarchy.py | 8 ++++---- src/patchwork/mesh/regrid.py | 2 +- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index b9fce23..45ac958 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -674,7 +674,7 @@ def boxes(patches: Sequence[Patch]) -> np.ndarray: def touching(regions: np.ndarray, level: int) -> tuple[list[Patch], np.ndarray]: """The patches of ``level`` and which of them overlap each region.""" - candidates = hierarchy.patches_at_level(level) + 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): @@ -693,6 +693,8 @@ def touching(regions: np.ndarray, level: int) -> tuple[list[Patch], np.ndarray]: 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], @@ -702,10 +704,14 @@ def touching(regions: np.ndarray, level: int) -> tuple[list[Patch], np.ndarray]: for n, patch in enumerate(mine): key = ( _key(patch), - tuple(_key(same[m]) for m in np.flatnonzero(hit[n])), + 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])),) + key += ( + tuple( + _key(below[m]) for m in np.flatnonzero(under[n]).tolist() + ), + ) result[id(patch)] = key return result diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index cbbd753..6539818 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -1015,7 +1015,7 @@ def _rebuilt( self, boxes: Mapping[int, Sequence[IndexBox]], placement: Any, - cost: Mapping[int, Any] | None, + cost: Mapping[Any, Any] | None, fill_halos: bool, fields: Sequence[str] | None = None, ) -> AMRHierarchy: @@ -1054,7 +1054,7 @@ def _rebuilt( ranks = curve_ranks( boxes, size, - curve=new.placement, + curve=str(new.placement), ratio=self.refinement_ratio, load=load, weights=weights, @@ -1117,7 +1117,7 @@ def regrid( min_patch_size: int = 1, forbid: Any = None, placement: str | Callable[[int, IndexBox], Any] | None = None, - cost: Mapping[int, Any] | None = None, + cost: Mapping[Any, Any] | None = None, fill_halos: bool = False, fields: Sequence[str] | None = None, ) -> AMRHierarchy: @@ -1230,7 +1230,7 @@ def regrid( @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) def rebalance( self, - cost: Mapping[int, Any] | None = None, + cost: Mapping[Any, Any] | None = None, *, placement: str = "morton", fill_halos: bool = False, diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index f39e964..9e40821 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -883,7 +883,7 @@ def knapsack_ranks( def box_costs( hierarchy: AMRHierarchy, boxes: Mapping[int, Sequence[IndexBox]], - cost: Mapping[int, Any], + cost: Mapping[Any, Any], ) -> tuple[dict[int, list[float]], list[float]]: """The cost of each new box and of each rank's base patches. From cd0b5fffa74fcb3fcb40614738ac145ca9995452 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 14:35:44 +0000 Subject: [PATCH 17/24] perf: deposit and gather of every built-in spline degree over all patches in one compiled call. --- .../kernels/gather_blocks/__init__.py | 10 ++ .../gather_blocks/gather_blocks_numpy.py | 37 +++++ .../gather_blocks/gather_blocks_pyccel.py | 53 +++++++ .../kernels/scatter_blocks/__init__.py | 10 ++ .../scatter_blocks/scatter_blocks_numpy.py | 35 +++++ .../scatter_blocks/scatter_blocks_pyccel.py | 60 ++++++++ src/patchwork/mesh/hierarchy.py | 137 +++++++++--------- src/patchwork/tests/unit/test_markers.py | 15 +- 8 files changed, 284 insertions(+), 73 deletions(-) create mode 100644 src/patchwork/kernels/gather_blocks/__init__.py create mode 100644 src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py create mode 100644 src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py create mode 100644 src/patchwork/kernels/scatter_blocks/__init__.py create mode 100644 src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py create mode 100644 src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py diff --git a/src/patchwork/kernels/gather_blocks/__init__.py b/src/patchwork/kernels/gather_blocks/__init__.py new file mode 100644 index 0000000..c1ff470 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/__init__.py @@ -0,0 +1,10 @@ +"""The gather_blocks kernel: Pyccel and NumPy versions with the same arguments. + +``kernel(...)`` runs the Pyccel version, or the NumPy version if Pyccel is unavailable +(see ``cunumpy.kernels.set_host_kernel_implementation`` to choose). +""" + +from patchwork.kernels import KERNEL_PACKAGE + +# host kernels only: no CUDA version, so CuPy arrays fall back to the host one +kernel = KERNEL_PACKAGE.from_folder(__name__, missing_cuda="fallback") diff --git a/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py b/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py new file mode 100644 index 0000000..8b25b43 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py @@ -0,0 +1,37 @@ +"""The NumPy version of the ``gather_blocks`` kernel, run when Pyccel is unavailable. + +Same arguments and arithmetic as ``gather_blocks_pyccel.py``, vectorized over the +markers with mpifield's NumPy ``spline_cell``. +""" + +from __future__ import annotations + +import itertools + +import numpy as np +from mpifield.kernels.spline_cell import spline_cell + + +def gather_blocks( + rel: np.ndarray, + count: np.ndarray, + stride: np.ndarray, + base: np.ndarray, + degree: int, + buffer: np.ndarray, + result: np.ndarray, +) -> None: + """Write the gathered values of the markers to ``result``.""" + axes = [] + for a in range(rel.shape[0]): + nodes, weights = spline_cell(rel[a], count[a], False, degree) + axes.append([(k * stride[a], w) for k, w in zip(nodes, weights, strict=True)]) + total = np.zeros(result.shape) + for parts in itertools.product(*axes): + where = base.copy() + weight = np.ones(result.shape) + for at, w in parts: + where += at + weight = weight * w + total += weight * buffer[where] + result[...] = total diff --git a/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py b/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py new file mode 100644 index 0000000..5a91335 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py @@ -0,0 +1,53 @@ +"""B-spline gather of degree 0 to 3 from the blocks of many patches at once. + +The Pyccel version (CPU) of the ``gather_blocks`` kernel; ``gather_blocks_numpy.py`` +next to this file is the NumPy version, with the same arguments. Called by +`AMRHierarchy.interpolate`; the transpose of ``scatter_blocks`` (same stencils, see +there): ``result[i]`` is the weighted sum of the stencil nodes of marker ``i`` in the +flat ``buffer`` of the blocks. +""" + +import numpy as np +from mpifield.kernels.spline_cell_pyccel import spline_cell + + +def gather_blocks( + rel: "float[:,:]", + count: "int[:,:]", + stride: "int[:,:]", + base: "int[:]", + degree: int, + buffer: "float[:]", + result: "float[:]", +) -> None: + """Write the gathered values of the markers to ``result`` (see the module).""" + ndim = rel.shape[0] + node = np.zeros((3, 4), dtype=np.int64) + weight = np.zeros((3, 4), dtype=np.float64) + size = np.ones(3, dtype=np.int64) + for a in range(3): + node[a, 0] = 0 + weight[a, 0] = 1.0 + for a in range(ndim): + size[a] = degree + 1 + for i in range(rel.shape[1]): + for a in range(ndim): + spline_cell(rel[a, i], count[a, i], 0, degree, node[a, :], weight[a, :]) + total = 0.0 + for p in range(size[0]): + at_x = base[i] + node[0, p] * stride[0, i] + w_x = weight[0, p] + for q in range(size[1]): + at_y = at_x + w_y = w_x + if ndim > 1: + at_y = at_x + node[1, q] * stride[1, i] + w_y = w_x * weight[1, q] + for r in range(size[2]): + at = at_y + w = w_y + if ndim > 2: + at = at_y + node[2, r] * stride[2, i] + w = w_y * weight[2, r] + total += w * buffer[at] + result[i] = total diff --git a/src/patchwork/kernels/scatter_blocks/__init__.py b/src/patchwork/kernels/scatter_blocks/__init__.py new file mode 100644 index 0000000..4412bf5 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/__init__.py @@ -0,0 +1,10 @@ +"""The scatter_blocks kernel: Pyccel and NumPy versions with the same arguments. + +``kernel(...)`` runs the Pyccel version, or the NumPy version if Pyccel is unavailable +(see ``cunumpy.kernels.set_host_kernel_implementation`` to choose). +""" + +from patchwork.kernels import KERNEL_PACKAGE + +# host kernels only: no CUDA version, so CuPy arrays fall back to the host one +kernel = KERNEL_PACKAGE.from_folder(__name__, missing_cuda="fallback") diff --git a/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py b/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py new file mode 100644 index 0000000..e9c3e49 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py @@ -0,0 +1,35 @@ +"""The NumPy version of the ``scatter_blocks`` kernel, run when Pyccel is unavailable. + +Same arguments and arithmetic as ``scatter_blocks_pyccel.py``, vectorized over the +markers with mpifield's NumPy ``spline_cell``. +""" + +from __future__ import annotations + +import itertools + +import numpy as np +from mpifield.kernels.spline_cell import spline_cell + + +def scatter_blocks( + rel: np.ndarray, + count: np.ndarray, + stride: np.ndarray, + base: np.ndarray, + values: np.ndarray, + degree: int, + buffer: np.ndarray, +) -> None: + """Add the values of the markers to ``buffer``.""" + axes = [] + for a in range(rel.shape[0]): + nodes, weights = spline_cell(rel[a], count[a], False, degree) + axes.append([(k * stride[a], w) for k, w in zip(nodes, weights, strict=True)]) + for parts in itertools.product(*axes): + where = base.copy() + weight = values.copy() + for at, w in parts: + where += at + weight = weight * w + buffer += np.bincount(where, weights=weight, minlength=buffer.size) diff --git a/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py b/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py new file mode 100644 index 0000000..b1610c9 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py @@ -0,0 +1,60 @@ +"""B-spline deposit of degree 0 to 3 of marker values into the blocks of many patches at once. + +The Pyccel version (CPU) of the ``scatter_blocks`` kernel; ``scatter_blocks_numpy.py`` +next to this file is the NumPy version, with the same arguments. Called by +`AMRHierarchy.deposit`. + +The blocks of the patches lie end to end in one flat ``buffer``. Marker ``i`` deposits +``values[i]`` onto the ``degree + 1`` nodes of its stencil along each of the ``ndim`` +axes (``rel.shape[0]``, 1 to 3), found by mpifield's ``spline_cell`` from ``rel[a, i]``, +its position in nodes from the first node of its block, on a bounded axis of +``count[a, i]`` nodes (a stencil node past the edge is the edge node). The node ``k`` +along axis ``a`` is at ``base[i] + sum_a k_a * stride[a, i]`` in the buffer. Serial: +the sums are in the order of the markers. +""" + +import numpy as np +from mpifield.kernels.spline_cell_pyccel import spline_cell + + +def scatter_blocks( + rel: "float[:,:]", + count: "int[:,:]", + stride: "int[:,:]", + base: "int[:]", + values: "float[:]", + degree: int, + buffer: "float[:]", +) -> None: + """Add the values of the markers to ``buffer`` (see the module).""" + ndim = rel.shape[0] + node = np.zeros((3, 4), dtype=np.int64) + weight = np.zeros((3, 4), dtype=np.float64) + size = np.ones(3, dtype=np.int64) + for a in range(3): + node[a, 0] = 0 + weight[a, 0] = 1.0 + for a in range(ndim): + size[a] = degree + 1 + for i in range(rel.shape[1]): + value = values[i] + if value == 0.0: + continue + for a in range(ndim): + spline_cell(rel[a, i], count[a, i], 0, degree, node[a, :], weight[a, :]) + for p in range(size[0]): + at_x = base[i] + node[0, p] * stride[0, i] + w_x = weight[0, p] * value + for q in range(size[1]): + at_y = at_x + w_y = w_x + if ndim > 1: + at_y = at_x + node[1, q] * stride[1, i] + w_y = w_x * weight[1, q] + for r in range(size[2]): + at = at_y + w = w_y + if ndim > 2: + at = at_y + node[2, r] * stride[2, i] + w = w_y * weight[2, r] + buffer[at] += w diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 6539818..b26feb1 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -2,7 +2,6 @@ from __future__ import annotations -import itertools import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -98,6 +97,13 @@ def _gather_blocks( _GATHER_TAG = 7311 +def _built_in(shape: Any) -> bool: + """Whether ``shape`` is one of mpifield's built-in splines (degree 1 to 3).""" + from mpifield.splines import SPLINES + + return any(shape is built for degree, built in SPLINES.items() if 1 <= degree <= 3) + + def _share_time( times: dict, patches: Sequence[Any], owner: Any, seconds: float ) -> None: @@ -1659,79 +1665,74 @@ def _patch_block(self, patch: Patch, name: str, degree: int) -> tuple[Any, Any]: start = [f + lo for f, lo in zip(first, lower, strict=True)] return block, self._grid(patch, start, block.shape) - def _linear_corners( - self, found: Any, cell: tuple[Any, ...], wrapped: Any, name: str - ) -> tuple[Any, list[tuple[Any, Any]], list[tuple[int, int, Any]], int]: - """The cloud-in-cell corners of all markers at once, in one buffer of the blocks. - - Every marker in the domain reads or writes the ``2**ndim`` corners of its cell in - the stored block of its patch (`_stored_block`), with the weights of mpifield's - linear kernels: ``(1 - f)`` and ``f`` per axis, ``f`` the marker's place in its - cell. The blocks of the patches with markers are laid end to end in one flat - buffer. Returns the markers in the domain, ``(flat index, weight)`` per corner, - ``(patch number, offset, storage)`` per block, and the buffer's size. + def _block_markers( + self, found: Any, wrapped: Any, name: str, degree: int + ) -> tuple[Any, Any, Any, Any, Any, list[tuple[int, int, Any]], int]: + """The markers of all patches, placed in one flat buffer of their patches' blocks. + + The stored blocks (`_stored_block`) of the patches with markers lie end to end + in one buffer. A marker's stencil is on the block of `_patch_block`: the stored + block for degree 1, without the halo nodes outside the patch for higher degrees + (where mpifield's ``spline_cell`` folds a stencil onto the edge nodes). Returns + the markers in the domain; per marker and axis its position in nodes from the + first node of that block, the block's nodes and the buffer stride; per marker the + buffer index of the block's first node; ``(patch number, offset, storage)`` per + block; and the buffer's size: the arguments of the ``scatter_blocks`` and + ``gather_blocks`` kernels. """ import numpy as np - inside = np.flatnonzero(found >= 0) - numbers = np.flatnonzero( - np.bincount(found[inside], minlength=len(self.patches)) - ) patches = self.patches ndim = self.ndim + inside = np.flatnonzero(found >= 0) + numbers = np.flatnonzero(np.bincount(found[inside], minlength=len(patches))) blocks = [] offset = 0 - first = np.zeros((len(patches), ndim), dtype=np.int64) - start = np.zeros(len(patches), dtype=np.int64) + first = np.zeros((len(patches), ndim), dtype=np.int64) # level index + count = np.ones((len(patches), ndim), dtype=np.int64) strides = np.zeros((len(patches), ndim), dtype=np.int64) - spacing = np.ones((len(patches), ndim)) + start = np.zeros(len(patches), dtype=np.int64) + scale = np.ones((len(patches), ndim)) for number in numbers.tolist(): patch = patches[number] array = patch.field(name) layout = array.layout storage = array.local_with_halos blocks.append((number, offset, storage)) - start[number] = offset - first[number] = [ - lo + b0 - h - for (lo, _), (b0, _), h in zip( - patch.box, layout.index_bounds, layout.halo, strict=True - ) - ] stride = 1 for axis in range(ndim - 1, -1, -1): strides[number, axis] = stride stride *= storage.shape[axis] - spacing[number] = self.spacing(patch.level) + begin = offset + for axis in range(ndim): + stored = layout.index_bounds[axis][0] - layout.halo[axis] + lower, upper = 0, storage.shape[axis] + if degree > 1: # the block of `_patch_block` + lower = max(0, -stored) + upper = min(upper, patch.node_shape[axis] - stored) + first[number, axis] = patch.box[axis][0] + stored + lower + count[number, axis] = upper - lower + begin += lower * strides[number, axis] + start[number] = begin + scale[number] = 1.0 / np.asarray(self.spacing(patch.level), dtype=float) offset += storage.size owner = found[inside] origin = np.asarray(self.lower_bound, dtype=float) - # the flat index of each marker's lower corner, and the steps to the others - base = start - np.einsum("pa,pa->p", first, strides) - flat = base[owner] - steps, fraction = [], [] + rel = np.empty((ndim, inside.size)) for axis in range(ndim): - index = np.asarray(cell[axis])[inside] - step = strides[owner, axis] - flat += index * step - steps.append(step) - fraction.append( - (np.asarray(wrapped[axis])[inside] - origin[axis]) - * (1.0 / spacing)[owner, axis] - - index - ) - corners = [] - for corner in itertools.product((0, 1), repeat=ndim): - where = flat.copy() - weight = np.ones(inside.size) - for axis, up in enumerate(corner): - if up: - where += steps[axis] - weight *= fraction[axis] - else: - weight *= 1.0 - fraction[axis] - corners.append((where, weight)) - return inside, corners, blocks, offset + rel[axis] = (np.asarray(wrapped[axis])[inside] - origin[axis]) * scale[ + owner, axis + ] - first[owner, axis] + return ( + inside, + rel, + # copies, not views: the transpose of one column has a stride Pyccel rejects + count[owner].T.copy(), + strides[owner].T.copy(), + start[owner], + blocks, + offset, + ) def _shape(self, name: str, splines: Any, what: str) -> Any: """The `mpifield.Splines` of ``splines`` (a degree or one), checked against the halo.""" @@ -1781,9 +1782,10 @@ def deposit( bilinear (cloud-in-cell) weights: the same weights as `CompositeNodes.deposit`, whose transposed interpolation the field gather is, and of - `interpolate`. These weights are added for the markers of all patches at - once (one ``bincount`` into a buffer of the blocks); a higher degree runs - mpifield's compiled kernels patch by patch. The values are + `interpolate`. With mpifield's built-in splines the markers of all patches are + deposited in one compiled call (``scatter_blocks``, into a buffer of the + blocks, with mpifield's ``spline_cell``); another shape runs its own kernels + patch by patch. The values are charges, not a density. The markers must be on the ranks that `owner` gives (use `migrate`), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. @@ -1829,15 +1831,17 @@ def deposit( for patch in self.local_patches: patch.field(name).local_with_halos[...] = 0.0 patches = self.patches - if shape.degree == 1: # all patches in one pass over the markers + if _built_in(shape): # all patches in one compiled call + from patchwork.kernels.scatter_blocks import kernel as scatter_blocks + begin = time.perf_counter() - inside, corners, blocks, total = self._linear_corners( - found, cell, wrapped, name + inside, rel, count, stride, base, blocks, total = self._block_markers( + found, wrapped, name, shape.degree ) - charges = charge[inside] buffer = np.zeros(total) - for flat, weight in corners: - buffer += np.bincount(flat, weights=charges * weight, minlength=total) + scatter_blocks( + rel, count, stride, base, charge[inside], shape.degree, buffer + ) for _, offset, storage in blocks: storage += buffer[offset : offset + storage.size].reshape(storage.shape) if times is not None: @@ -1896,17 +1900,18 @@ def interpolate( ) values = np.zeros(flat[0].size) patches = self.patches - if weights.degree == 1: # all patches in one pass over the markers + if _built_in(weights): # all patches in one compiled call + from patchwork.kernels.gather_blocks import kernel as gather_blocks + begin = time.perf_counter() - inside, corners, blocks, total = self._linear_corners( - found, cell, wrapped, name + inside, rel, count, stride, base, blocks, total = self._block_markers( + found, wrapped, name, weights.degree ) buffer = np.empty(total) for _, offset, storage in blocks: buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) gathered = np.zeros(inside.size) - for where, weight in corners: - gathered += weight * buffer[where] + gather_blocks(rel, count, stride, base, weights.degree, buffer, gathered) values[inside] = gathered if times is not None: _share_time(times, patches, found[inside], time.perf_counter() - begin) diff --git a/src/patchwork/tests/unit/test_markers.py b/src/patchwork/tests/unit/test_markers.py index 24c3ca1..bb759ba 100644 --- a/src/patchwork/tests/unit/test_markers.py +++ b/src/patchwork/tests/unit/test_markers.py @@ -455,29 +455,30 @@ def test_the_node_grid_of_a_patch_holds_its_nodes() -> None: assert grid.geometry == (i0 * dx, j0 * dy, dx, dy, *patch.node_shape, 0, 0) +@pytest.mark.parametrize("degree", [1, 2, 3]) @pytest.mark.parametrize("periodic", [(False, False), (True, False)]) -def test_one_pass_linear_deposit_and_gather_equal_the_kernels_patch_by_patch( - periodic, +def test_one_pass_deposit_and_gather_equal_the_kernels_patch_by_patch( + periodic, degree ) -> None: from mpifield import splines mesh = AMRHierarchy(base_shape=(8, 8), periodic=periodic) mesh.add_patch(1, ((4, 12), (4, 12)), ranks=0) mesh.add_patch(2, ((10, 18), (8, 16)), ranks=0) - mesh.allocate_field("q", centering="node") + mesh.allocate_field("q", centering="node", halo=2) rng = np.random.default_rng(WORLD.Get_rank()) x, y = rng.uniform(0, 1, (2, 2000)) charge = rng.uniform(0.5, 1.5, x.size) x, y, charge = mesh.migrate(x, y, charge, name="q") - mesh.deposit(x, y, charge, "q") - gathered = mesh.interpolate(x, y, "q") + mesh.deposit(x, y, charge, "q", splines=degree) + gathered = mesh.interpolate(x, y, "q", splines=degree) # the same with mpifield's compiled kernels, one patch at a time - linear = splines(1) + linear = splines(degree) flat, _ = mesh._points((x, y)) found, _, wrapped = mesh._cells(flat) expected_gather = np.zeros(x.size) for patch in mesh.local_patches: - storage, grid = mesh._patch_block(patch, "q", 1) + storage, grid = mesh._patch_block(patch, "q", degree) reference = np.zeros_like(np.asarray(storage)) number = mesh.patches.index(patch) chosen = np.flatnonzero(found == number) From c1c3eebc59c673e014e8725e1f5327f38c11e958 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 14:53:46 +0000 Subject: [PATCH 18/24] Skip the block kernels on a rank without markers. --- src/patchwork/mesh/hierarchy.py | 12 ++++++++---- src/patchwork/tests/unit/test_markers.py | 10 ++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index b26feb1..134b65c 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -1839,9 +1839,10 @@ def deposit( found, wrapped, name, shape.degree ) buffer = np.zeros(total) - scatter_blocks( - rel, count, stride, base, charge[inside], shape.degree, buffer - ) + if inside.size: # Pyccel's slices refuse empty arrays + scatter_blocks( + rel, count, stride, base, charge[inside], shape.degree, buffer + ) for _, offset, storage in blocks: storage += buffer[offset : offset + storage.size].reshape(storage.shape) if times is not None: @@ -1911,7 +1912,10 @@ def interpolate( for _, offset, storage in blocks: buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) gathered = np.zeros(inside.size) - gather_blocks(rel, count, stride, base, weights.degree, buffer, gathered) + if inside.size: # Pyccel's slices refuse empty arrays + gather_blocks( + rel, count, stride, base, weights.degree, buffer, gathered + ) values[inside] = gathered if times is not None: _share_time(times, patches, found[inside], time.perf_counter() - begin) diff --git a/src/patchwork/tests/unit/test_markers.py b/src/patchwork/tests/unit/test_markers.py index bb759ba..2b55ccf 100644 --- a/src/patchwork/tests/unit/test_markers.py +++ b/src/patchwork/tests/unit/test_markers.py @@ -493,3 +493,13 @@ def test_one_pass_deposit_and_gather_equal_the_kernels_patch_by_patch( ) expected_gather[chosen] = result[0] np.testing.assert_allclose(gathered, expected_gather, rtol=1e-12, atol=1e-12) + + +@pytest.mark.parametrize("degree", [1, 2, 3]) +def test_a_rank_without_markers_deposits_and_gathers_nothing(degree) -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + mesh.allocate_field("q", centering="node", halo=2) + empty = np.zeros(0) + mesh.deposit(empty, empty, empty, "q", splines=degree) + assert mesh.interpolate(empty, empty, "q", splines=degree).size == 0 + assert all(not np.any(p.field("q").local) for p in mesh.local_patches) From f8e9d5749837c04a3a17783f5142c7c603f6d79d Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 14:57:51 +0000 Subject: [PATCH 19/24] perf: the accumulation schedule from the nodes of all local patches at once. --- src/patchwork/mesh/accumulate.py | 95 +++++++++++++++++++------------- 1 file changed, 56 insertions(+), 39 deletions(-) diff --git a/src/patchwork/mesh/accumulate.py b/src/patchwork/mesh/accumulate.py index cdae9a5..5038690 100644 --- a/src/patchwork/mesh/accumulate.py +++ b/src/patchwork/mesh/accumulate.py @@ -96,25 +96,36 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: members, replicated = blocks[number] if len(members) == 1 and not replicated: single[number] = members[0][0] - # per local patch: the storage of the nodes that move, and where each goes + # per local patch: the storage of the nodes that move, and where each goes; + # the nodes of all local patches at once, then split by patch self._moves: list[dict[str, Any]] = [] - for number, patch in enumerate(patches): - if not patch.is_local: - continue - array = patch.field(name) - node = np.meshgrid( - *(np.arange(b0, b1) for b0, b1 in array.layout.index_bounds), - indexing="ij", + local = [(n, p) for n, p in enumerate(patches) if p.is_local] + arrays = [patch.field(name) for _, patch in local] + if local: + numbers = np.array([n for n, _ in local], dtype=np.int64) + first = np.array( + [[b0 for b0, _ in a.layout.index_bounds] for a in arrays], + dtype=np.int64, + ).reshape(len(local), ndim) + shape = np.array( + [[b1 - b0 for b0, b1 in a.layout.index_bounds] for a in arrays], + dtype=np.int64, + ).reshape(len(local), ndim) + sizes_local = np.prod(shape, axis=1) + which = np.repeat(np.arange(len(local)), sizes_local) # local patch + rest = np.arange(which.size) - np.repeat( + np.cumsum(sizes_local) - sizes_local, sizes_local ) - index = [ - lower[number][axis] + node[axis] for axis in range(ndim) - ] # level indices - key = [ - (index[axis] * span[number]) % lattice[axis] - if periodic[axis] - else index[axis] * span[number] - for axis in range(ndim) - ] + node = [np.empty(0, dtype=np.int64)] * ndim # in the patch's indices + for axis in range(ndim - 1, -1, -1): + span_axis = shape[which, axis] + node[axis] = first[which, axis] + rest % span_axis + rest = rest // span_axis + number = numbers[which] + key = [] + for axis in range(ndim): + value = (lower[number, axis] + node[axis]) * span[number] + key.append(value % lattice[axis] if periodic[axis] else value) owner = table[tuple(key)].astype(np.int64) if (owner < 0).any(): raise RuntimeError( @@ -140,13 +151,12 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: moving = owner != number for axis in range(ndim): moving |= target[axis] != node[axis] - where = np.nonzero(moving) - owners = owner[where] - at = [values[where] for values in target] + chosen_all = np.flatnonzero(moving) + owners_all = owner[chosen_all] # an owner on one rank: that rank; else the rank whose block has the node - destination = single[owners] - several = np.flatnonzero(destination < 0) - for held, part in _by_patch(owners[several]): + destination_all = single[owners_all] + several = np.flatnonzero(destination_all < 0) + for held, part in _by_patch(owners_all[several]): chosen = several[part] members, replicated = blocks[held] if replicated: @@ -156,22 +166,29 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: ) for rank, bounds in members: inside = np.ones(chosen.size, dtype=bool) - for values, (a0, a1) in zip(at, bounds, strict=True): - inside &= (values[chosen] >= a0) & (values[chosen] < a1) - destination[chosen[inside]] = rank - halo = array.layout.halo - self._moves.append( - { - "patch": number, - "array": array, - "storage": tuple( - values + h for values, h in zip(where, halo, strict=True) - ), - "destination": destination, - "owner": owners.astype(np.int64), - "node": tuple(values.astype(np.int64) for values in at), - } - ) + for axis, (a0, a1) in enumerate(bounds): + values = target[axis][chosen_all[chosen]] + inside &= (values >= a0) & (values < a1) + destination_all[chosen[inside]] = rank + bounds_of = np.searchsorted(which[chosen_all], np.arange(len(local) + 1)) + for k, ((patch_number, _), array) in enumerate( + zip(local, arrays, strict=True) + ): + part = chosen_all[bounds_of[k] : bounds_of[k + 1]] + halo = array.layout.halo + self._moves.append( + { + "patch": patch_number, + "array": array, + "storage": tuple( + node[axis][part] - first[k, axis] + halo[axis] + for axis in range(ndim) + ), + "destination": destination_all[bounds_of[k] : bounds_of[k + 1]], + "owner": owner[part], + "node": tuple(target[axis][part] for axis in range(ndim)), + } + ) # where the received charge goes: the block of every local patch, as the # offset from a node's index in the patch to its place in the storage self._local: dict[int, tuple[Any, tuple[int, ...]]] = {} From 6bf4f9f1f20d3d538dcc43ecdf89375523a614e7 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 15:07:27 +0000 Subject: [PATCH 20/24] perf: cloud-in-cell deposit and gather by bincount again, the compiled block kernels for degrees 2 and 3. --- src/patchwork/mesh/hierarchy.py | 111 +++++++++++++++++++++++++++++++- 1 file changed, 108 insertions(+), 3 deletions(-) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 134b65c..16a9318 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -2,6 +2,7 @@ from __future__ import annotations +import itertools import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -1665,6 +1666,80 @@ def _patch_block(self, patch: Patch, name: str, degree: int) -> tuple[Any, Any]: start = [f + lo for f, lo in zip(first, lower, strict=True)] return block, self._grid(patch, start, block.shape) + def _linear_corners( + self, found: Any, cell: tuple[Any, ...], wrapped: Any, name: str + ) -> tuple[Any, list[tuple[Any, Any]], list[tuple[int, int, Any]], int]: + """The cloud-in-cell corners of all markers at once, in one buffer of the blocks. + + Every marker in the domain reads or writes the ``2**ndim`` corners of its cell in + the stored block of its patch (`_stored_block`), with the weights of mpifield's + linear kernels: ``(1 - f)`` and ``f`` per axis, ``f`` the marker's place in its + cell. The blocks of the patches with markers are laid end to end in one flat + buffer. Returns the markers in the domain, ``(flat index, weight)`` per corner, + ``(patch number, offset, storage)`` per block, and the buffer's size. + """ + import numpy as np + + inside = np.flatnonzero(found >= 0) + numbers = np.flatnonzero( + np.bincount(found[inside], minlength=len(self.patches)) + ) + patches = self.patches + ndim = self.ndim + blocks = [] + offset = 0 + first = np.zeros((len(patches), ndim), dtype=np.int64) + start = np.zeros(len(patches), dtype=np.int64) + strides = np.zeros((len(patches), ndim), dtype=np.int64) + spacing = np.ones((len(patches), ndim)) + for number in numbers.tolist(): + patch = patches[number] + array = patch.field(name) + layout = array.layout + storage = array.local_with_halos + blocks.append((number, offset, storage)) + start[number] = offset + first[number] = [ + lo + b0 - h + for (lo, _), (b0, _), h in zip( + patch.box, layout.index_bounds, layout.halo, strict=True + ) + ] + stride = 1 + for axis in range(ndim - 1, -1, -1): + strides[number, axis] = stride + stride *= storage.shape[axis] + spacing[number] = self.spacing(patch.level) + offset += storage.size + owner = found[inside] + origin = np.asarray(self.lower_bound, dtype=float) + # the flat index of each marker's lower corner, and the steps to the others + base = start - np.einsum("pa,pa->p", first, strides) + flat = base[owner] + steps, fraction = [], [] + for axis in range(ndim): + index = np.asarray(cell[axis])[inside] + step = strides[owner, axis] + flat += index * step + steps.append(step) + fraction.append( + (np.asarray(wrapped[axis])[inside] - origin[axis]) + * (1.0 / spacing)[owner, axis] + - index + ) + corners = [] + for corner in itertools.product((0, 1), repeat=ndim): + where = flat.copy() + weight = np.ones(inside.size) + for axis, up in enumerate(corner): + if up: + where += steps[axis] + weight *= fraction[axis] + else: + weight *= 1.0 - fraction[axis] + corners.append((where, weight)) + return inside, corners, blocks, offset + def _block_markers( self, found: Any, wrapped: Any, name: str, degree: int ) -> tuple[Any, Any, Any, Any, Any, list[tuple[int, int, Any]], int]: @@ -1783,9 +1858,10 @@ def deposit( `CompositeNodes.deposit`, whose transposed interpolation the field gather is, and of `interpolate`. With mpifield's built-in splines the markers of all patches are - deposited in one compiled call (``scatter_blocks``, into a buffer of the - blocks, with mpifield's ``spline_cell``); another shape runs its own kernels - patch by patch. The values are + deposited at once into a buffer of the blocks: the cloud-in-cell weights by + one ``bincount``, degrees 2 and 3 in one compiled call (``scatter_blocks``, + with mpifield's ``spline_cell``); another shape runs its own kernels patch by + patch. The values are charges, not a density. The markers must be on the ranks that `owner` gives (use `migrate`), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. @@ -1831,6 +1907,20 @@ def deposit( for patch in self.local_patches: patch.field(name).local_with_halos[...] = 0.0 patches = self.patches + if _built_in(shape) and shape.degree == 1: # all patches in one pass + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + charges = charge[inside] + buffer = np.zeros(total) + for flat, weight in corners: + buffer += np.bincount(flat, weights=charges * weight, minlength=total) + for _, offset, storage in blocks: + storage += buffer[offset : offset + storage.size].reshape(storage.shape) + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return if _built_in(shape): # all patches in one compiled call from patchwork.kernels.scatter_blocks import kernel as scatter_blocks @@ -1901,6 +1991,21 @@ def interpolate( ) values = np.zeros(flat[0].size) patches = self.patches + if _built_in(weights) and weights.degree == 1: # all patches in one pass + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + buffer = np.empty(total) + for _, offset, storage in blocks: + buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) + gathered = np.zeros(inside.size) + for where, weight in corners: + gathered += weight * buffer[where] + values[inside] = gathered + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return values.reshape(shape) if _built_in(weights): # all patches in one compiled call from patchwork.kernels.gather_blocks import kernel as gather_blocks From aaf96f0d7da9debc4235a6d07c6b50cf39d88d1d Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 15:07:54 +0000 Subject: [PATCH 21/24] Changelog: block kernels for degrees 2 and 3, vectorized accumulation schedule. --- CHANGELOG.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94c24ce..3f5088c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,9 +13,12 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). 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 +- `deposit` and `interpolate` add the markers of all patches in one pass into a buffer of the + blocks: cloud-in-cell by one `bincount`, the quadratic and cubic B-splines in one compiled + call (the new `scatter_blocks` and `gather_blocks` kernels, with mpifield's `spline_cell`; + 10-35% faster than mpifield's kernels patch by patch); other shapes keep their kernels per + patch. The `accumulate_halos` schedule is built from the nodes of all local patches at once + (68 to 11 ms on the quadtree benchmark's 8-cell blocks); 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. From bdb3d235946dd8bb603a3ece7ff9ec4576189c1a Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 15:09:58 +0000 Subject: [PATCH 22/24] Benchmark results of the block kernels and the accumulation schedule. --- benchmarks/quadtree/RESULTS.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 87925d2..317e9db 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -170,6 +170,36 @@ other at once. Serial, median of 3 runs, ms per step: 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). +## Higher spline degrees and the accumulation schedule (2026-11-25, final) + +Serial, with the solve, 3 repeats each, `devel` against the branch that deposits and +gathers the quadratic and cubic B-splines of all patches in one compiled call +(`scatter_blocks`, `gather_blocks`) and builds the `accumulate_halos` schedule from the +nodes of all local patches at once (times in ms per step): + +| mesh | | deposit | solver | halos | gather | total | +|---|---|---|---|---|---|---| +| cluster | before | 27.4 | 111.8 | 6.6 | 24.3 | 225 | +| | after | 30.9 | 120.4 | 6.6 | 26.4 | 242 | +| cluster, `max_patch_size=16` | before | 41.4 | 119.4 | 84.5 | 26.8 | 351 | +| | after | 38.9 | 125.7 | 92.9 | 30.1 | 378 | +| quadtree, block 8 | before | 65.0 | 108.3 | 101.2 | 27.7 | 465 | +| | after | 48.2 | 108.5 | 109.1 | 27.7 | 460 | +| quadtree, block 16 | before | 39.2 | 128.2 | 39.9 | 25.7 | 307 | +| | after | 34.8 | 130.6 | 38.7 | 26.6 | 305 | +| quadtree, block 32 | before | 33.5 | 212.5 | 17.8 | 25.1 | 355 | +| | after | 34.5 | 217.5 | 16.7 | 26.7 | 363 | + +- The benchmark deposits cloud-in-cell, which keeps its `bincount` path; what changes there + is the accumulation schedule: the deposit of blocks of 8 goes from 65 to 48 ms (the + schedule from 68 to 11 ms when built alone). The other differences are noise: the solver + setup, which neither branch touches, differs by up to 8% between the runs. +- With the quadratic and cubic B-splines (one rank, the 386 blocks of 8, 200 000 markers), + one compiled call over all patches against mpifield's kernels patch by patch: deposit + 58 → 50 ms (degree 2) and 60 → 61 ms (degree 3), gather 74 → 49 and 57 → 51 ms. For + cloud-in-cell the compiled call lost to the `bincount` (gather 24 → 38 ms), so it is + used for degrees 2 and 3 only. + ## Fixed on the way The regrid's transfer compared every new patch with every old one of its level, and copied From 98faeee5a6bd1d3564678e13d85db1b75fa05136 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 15:15:10 +0000 Subject: [PATCH 23/24] Pyodide: repeat counts as intp, and the Pyccel sources not imported. --- .github/workflows/pyodide.yml | 3 +++ src/patchwork/mesh/accumulate.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pyodide.yml b/.github/workflows/pyodide.yml index 0098dd0..b4e4948 100644 --- a/.github/workflows/pyodide.yml +++ b/.github/workflows/pyodide.yml @@ -13,3 +13,6 @@ on: jobs: pyodide: uses: max-models/starlight-theme/.github/workflows/pyodide.yml@v0 + with: + # the Pyccel sources: compiled, never imported (the browser runs the NumPy kernels) + skip: '_pyccel$' diff --git a/src/patchwork/mesh/accumulate.py b/src/patchwork/mesh/accumulate.py index 5038690..0a04148 100644 --- a/src/patchwork/mesh/accumulate.py +++ b/src/patchwork/mesh/accumulate.py @@ -111,7 +111,7 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: [[b1 - b0 for b0, b1 in a.layout.index_bounds] for a in arrays], dtype=np.int64, ).reshape(len(local), ndim) - sizes_local = np.prod(shape, axis=1) + sizes_local = np.prod(shape, axis=1).astype(np.intp) # np.repeat: intp which = np.repeat(np.arange(len(local)), sizes_local) # local patch rest = np.arange(which.size) - np.repeat( np.cumsum(sizes_local) - sizes_local, sizes_local From e0e4d0d67746118f5b2b319c653ce2a08cea14b1 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 25 Nov 2026 15:17:55 +0000 Subject: [PATCH 24/24] Lock cunumpy and mpiarray at their current devel. --- uv.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/uv.lock b/uv.lock index dc660dd..7cd00a3 100644 --- a/uv.lock +++ b/uv.lock @@ -890,7 +890,7 @@ toml = [ [[package]] name = "cunumpy" version = "0.8.0" -source = { git = "https://github.com/max-models/cunumpy?branch=devel#a25c7b31072823d31e0815f65efa0daa1212a403" } +source = { git = "https://github.com/max-models/cunumpy?branch=devel#e18126964f48342bfbf9bd7764914aa19c7ecebe" } dependencies = [ { name = "array-api-compat" }, { name = "maybempi" }, @@ -2301,7 +2301,7 @@ wheels = [ [[package]] name = "mpiarray" version = "0.2.1" -source = { git = "https://github.com/max-models/mpiarray?branch=devel#7d3490a566ebbc2489c5172d5cd09282fae87efe" } +source = { git = "https://github.com/max-models/mpiarray?branch=devel#59884298fd49826a07f0d2321c8c85f93965f388" } dependencies = [ { name = "cunumpy" }, { name = "maybempi" },