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/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/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/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py new file mode 100644 index 0000000..7113df3 --- /dev/null +++ b/benchmarks/quadtree/bench_quadtree.py @@ -0,0 +1,164 @@ +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 + +- ``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: + """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 + if patch.level + ) + + +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) + 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..4bd7d42 --- /dev/null +++ b/benchmarks/quadtree/run.py @@ -0,0 +1,130 @@ +"""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; 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``. +""" + +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 + ) + 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 + + +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) + 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..044aa1e 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -299,10 +299,16 @@ 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 (`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 + 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 +483,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 +1053,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 +1108,22 @@ 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 + + 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): + 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) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index cb48c0d..81a5df6 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,70 @@ def quadtree_boxes( return boxes +@method( + equations={ + "key": r"k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}", + "ranks": r"\text{along the curve, rank } q \text{ takes boxes while } w_q + |B|/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B |B|\Big)", + }, + assumptions=( + "the patches of all refined levels on one curve, a coarse patch before the finer ones at the same corner, so that a patch and the patches over it tend to share a rank", + "the load a rank already has (the base level) counts: such a rank takes fewer patches", + "a patch stays on one rank", + ), + references=( + "[Morton, IBM technical report (1966)](https://dominoweb.draco.res.ibm.com/reports/Morton1966.pdf)", + "[Burstedde, Wilcox and Ghattas, SIAM J. Sci. Comput. 33, 1103 (2011)](https://doi.org/10.1137/100791634)", + ), +) +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}") + 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) + 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) def transfer(old: AMRHierarchy, new: AMRHierarchy, name: str) -> None: """Fill field ``name`` of ``new`` from ``old``, level by level (collective). @@ -743,9 +808,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 +824,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..8c5d2fd 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,51 @@ 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({1: boxes}, 4)[1] + for box, rank in zip(boxes, ranks, strict=True): + (i0, _), (j0, _) = box + assert rank == (i0 >= 4) + 2 * (j0 >= 4) # the first axis is the lowest bit + # a rank that holds the base already takes fewer patches + loaded = morton_ranks({1: boxes}, 2, load=[32, 0])[1] + 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({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: + 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" + 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) + 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" + 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") 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",