From 789c5ca83b0fd0881c7fe9b92328fbc5caebade0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:01:20 +0000 Subject: [PATCH 01/10] 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/10] 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/10] 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/10] 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/10] 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/10] 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/10] 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/10] 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/10] 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/10] 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