diff --git a/CHANGELOG.md b/CHANGELOG.md index c90a4d7..94c24ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- Placement along a Hilbert curve (`placement="hilbert"`, cunumpy's `hilbert_encode`) next to + the Morton curve: `morton_ranks` is now `curve_ranks(..., curve="morton" | "hilbert")`. + `placement="balanced"` takes `cost` too, cut by `knapsack_ranks` (the largest cost first to + the least loaded rank). `cost` may also map a patch `(level, box)` to a measured cost, which + `deposit(..., times=...)` and `interpolate(..., times=...)` collect per patch; + `rebalance(cost, placement=...)` places by any of them. +- The cloud-in-cell `deposit` and `interpolate` add the markers of all patches in one pass + (one `bincount` into a buffer of the blocks; higher B-spline degrees keep mpifield's kernels + per patch); a marker's owner comes from a table where its patch is on one rank; the halo + signatures test all patches of a level at once. - `regrid(..., fields=[...])`: the fields whose values are moved (default: all); the others are allocated on the new hierarchy and zero. - `CompositeNodes` finds the cells under finer patches from one coverage mask per level (it @@ -33,7 +43,7 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). with clusters, but all patches have one size and a regrid keeps most of them. Tutorial "Quadtree patches". - `placement="morton"`: `regrid` puts the patches on the ranks along a Morton curve - (`morton_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs + (`curve_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs of about equal cells with the base level's cells counted. - Morton cuts weighted by cost: `regrid(..., placement="morton", cost=...)` weighs every patch by its cells plus the cost of its leaf cells (`box_costs`), e.g. the markers of diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 136aabe..87925d2 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -136,6 +136,40 @@ step, total: (~33 ms). The next step there: keep the `CopyPlan` of the kept patches, or set up the interpolation of all patches at once. +## One gather per array, markers in one pass (2026-11-25, last) + +Against `devel` (with `regrid(fields=[])` on both sides): mpiarray's `CopyPlan` packs and +unpacks with one gather and one scatter per array (flat storage indices found when the plan +is built) and lays out its pieces with array operations; the cloud-in-cell deposit and +gather add the markers of all patches in one pass (`bincount` into a buffer of the blocks, +equal to mpifield's kernels to 1e-12); a marker's owner rank comes from a table where its +patch is on one rank; and the halo signatures test all patches of a level against each +other at once. Serial, median of 3 runs, ms per step: + +| mesh | | tag | regrid | migrate | deposit | solver | solve | halos | gather | total | +|---|---|---|---|---|---|---|---|---|---|---| +| cluster | before | 35.2 | 2.8 | 17.1 | 25.9 | 107.7 | 6.3 | 8.2 | 25.0 | 228 | +| | after | 35.1 | 2.7 | 9.6 | 25.2 | 108.4 | 6.1 | 6.0 | 24.0 | 217 (−5%) | +| cluster, `max_patch_size=16` | before | 35.7 | 18.5 | 30.3 | 69.1 | 122.9 | 12.6 | 108.5 | 52.5 | 450 | +| | after | 38.3 | 19.4 | 11.9 | 43.9 | 118.5 | 12.8 | 83.7 | 27.0 | 356 (−21%) | +| quadtree, block 8 | before | 36.3 | 88.0 | 34.8 | 106.6 | 108.9 | 21.7 | 193.4 | 70.7 | 661 | +| | after | 36.9 | 93.6 | 14.7 | 69.5 | 110.9 | 22.3 | 108.3 | 29.4 | 486 (−26%) | +| quadtree, block 16 | before | 37.4 | 15.2 | 31.8 | 68.5 | 133.5 | 12.4 | 62.2 | 54.6 | 416 | +| | after | 35.5 | 14.5 | 11.4 | 39.9 | 131.5 | 12.0 | 37.5 | 25.8 | 308 (−26%) | +| quadtree, block 32 | before | 36.2 | 6.2 | 26.3 | 52.1 | 205.8 | 12.7 | 23.5 | 43.4 | 406 | +| | after | 37.3 | 6.7 | 10.8 | 34.3 | 210.2 | 13.0 | 16.9 | 25.3 | 355 (−13%) | + +- The `CopyPlan` of the halos of 392 patches (4422 copies) builds in 23 ms (43 before) and + executes in 0.7 ms (10 before); the halos of blocks of 8 take 108 ms per step, from 193. +- Gather 71 → 29 ms and deposit 107 → 70 ms with blocks of 8; migrate about halves + everywhere (the owner check). +- Since the first run of this benchmark (1263 ms per step with blocks of 8, all fields + moved), the cycle on blocks of 8 is 2.6 times faster; the clusters' 327 ms are now 217. +- What is left with blocks of 8: the solver setup (111 ms: assembly and LU, which do not + depend on the patches), the halos (108: the interpolation records of the patches whose + neighbourhood changed, one per patch, and their copies), the regrid (94: the boxes and + the new hierarchy) and the deposit (70, of which the `accumulate_halos` schedule ~35). + ## Fixed on the way The regrid's transfer compared every new patch with every old one of its level, and copied diff --git a/src/patchwork/__init__.py b/src/patchwork/__init__.py index d40902b..51177af 100644 --- a/src/patchwork/__init__.py +++ b/src/patchwork/__init__.py @@ -16,12 +16,13 @@ Patch, box_costs, cluster, + curve_ranks, function_tags, graded_nodes, gradient_tags, + knapsack_ranks, marker_counts, marker_tags, - morton_ranks, plot_patches, quadtree_boxes, ) @@ -91,12 +92,13 @@ "cell_body", "box_costs", "cluster", + "curve_ranks", "function_tags", "graded_nodes", "gradient_tags", + "knapsack_ranks", "marker_counts", "marker_tags", - "morton_ranks", "plot_patches", "quadtree_boxes", "solve_nodal_poisson", diff --git a/src/patchwork/mesh/__init__.py b/src/patchwork/mesh/__init__.py index 0db5ce8..56e2ff7 100644 --- a/src/patchwork/mesh/__init__.py +++ b/src/patchwork/mesh/__init__.py @@ -14,11 +14,12 @@ from patchwork.mesh.regrid import ( box_costs, cluster, + curve_ranks, function_tags, gradient_tags, + knapsack_ranks, marker_counts, marker_tags, - morton_ranks, quadtree_boxes, ) @@ -29,12 +30,13 @@ "Patch", "box_costs", "cluster", + "curve_ranks", "function_tags", "graded_nodes", "gradient_tags", + "knapsack_ranks", "marker_counts", "marker_tags", - "morton_ranks", "plot_patches", "quadtree_boxes", ] diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 193da3a..45ac958 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -30,6 +30,8 @@ from methodcard import ConvergenceProblem, method if TYPE_CHECKING: + from collections.abc import Sequence + from patchwork.mesh.hierarchy import AMRHierarchy, Patch Box = tuple[tuple[int, int], ...] @@ -542,19 +544,6 @@ def _key(patch: Patch) -> tuple: return (patch.level, patch.box, patch.ranks) -def _within(points: _Points, level: int, box: Box) -> tuple: - """The keys of the patches of ``level`` that overlap ``box`` or one of its periodic images.""" - shifts = points.shifts(level) - return tuple( - _key(other) - for other in points.near(level, box) - if any( - _overlap(box, _shift(points.own(other), shift)) is not None - for shift in shifts - ) - ) - - class _HaloRecord: """The halo geometry of one patch, its fields named by patch keys. @@ -663,22 +652,68 @@ def _coarse_fine( if interpolation is not None: self._interpolations.append(interpolation) - def _signature(self, points: _Points, patch: Patch) -> tuple: - """What a patch's halo geometry depends on: itself and the patches within reach. + def _signatures(self, points: _Points) -> dict[int, tuple]: + """What every patch's halo geometry depends on: itself and the patches within reach. - The patches of its level that may overlap its halo, and those of the level - below that may hold the coarse points of its interpolation, each as - ``(level, box, ranks)``. + The patches of its level that overlap its halo, and those of the level + below that may hold the coarse points of its interpolation (a margin of + one coarse cell and the stencil's), each as ``(level, box, ranks)``, in the + order of the patches. All patches of a level are tested against all of + the level and the one below at once, periodic images included. Keyed by + ``id`` of the patch. """ - own = points.own(patch) + hierarchy = self._hierarchy width = self._width - extended = tuple((lo - width, hi + width) for lo, hi in own) - same = _within(points, patch.level, extended) - if patch.level == 0: - return (_key(patch), same) ratio = points.ratio - coarse = tuple((lo // ratio - 1, -(-hi // ratio) + 2) for lo, hi in extended) - return (_key(patch), same, _within(points, patch.level - 1, coarse)) + result: dict[int, tuple] = {} + + def boxes(patches: Sequence[Patch]) -> np.ndarray: + return np.array([points.own(p) for p in patches], dtype=np.int64).reshape( + len(patches), hierarchy.ndim, 2 + ) + + def touching(regions: np.ndarray, level: int) -> tuple[list[Patch], np.ndarray]: + """The patches of ``level`` and which of them overlap each region.""" + candidates = list(hierarchy.patches_at_level(level)) + theirs = boxes(candidates) + hit = np.zeros((regions.shape[0], theirs.shape[0]), dtype=bool) + for shift in points.shifts(level): + moved = theirs + np.asarray(shift, dtype=np.int64)[None, :, None] + lower = np.maximum(regions[:, None, :, 0], moved[None, :, :, 0]) + upper = np.minimum(regions[:, None, :, 1], moved[None, :, :, 1]) + hit |= np.all(lower < upper, axis=-1) + return candidates, hit + + for level in range(hierarchy.max_level + 1): + if self._level is not None and level != self._level: + continue + mine = hierarchy.patches_at_level(level) + if not mine: + continue + own = boxes(mine) + extended = own + np.array([-width, width], dtype=np.int64) + same, hit = touching(extended, level) + below: list[Patch] = [] + under = np.zeros((len(mine), 0), dtype=bool) + if level > 0: + coarse = np.stack( + [extended[..., 0] // ratio - 1, -(-extended[..., 1] // ratio) + 2], + axis=-1, + ) + below, under = touching(coarse, level - 1) + for n, patch in enumerate(mine): + key = ( + _key(patch), + tuple(_key(same[m]) for m in np.flatnonzero(hit[n]).tolist()), + ) + if level > 0: + key += ( + tuple( + _key(below[m]) for m in np.flatnonzero(under[n]).tolist() + ), + ) + result[id(patch)] = key + return result def _record(self, points: _Points, patch: Patch, dtype: Any) -> _HaloRecord: """The halo geometry of one patch, with its fields as patch keys.""" @@ -805,10 +840,11 @@ def __init__( self._pairs_used: dict[tuple, list] = {} used: dict[tuple, _HaloRecord] = {} patches = {_key(patch): patch for patch in hierarchy.patches} + signatures = self._signatures(points) if self._width else {} for patch in hierarchy.patches if self._width else (): if level is not None and patch.level != level: continue - signature = self._signature(points, patch) + signature = signatures[id(patch)] record = known.get(signature) if record is None: record = self._record(points, patch, dtype) diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 30ed0e3..6539818 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -2,6 +2,8 @@ from __future__ import annotations +import itertools +import time from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -89,10 +91,27 @@ def _gather_blocks( return result +#: The placements a hierarchy takes by name (besides a function of the patch). +_PLACEMENTS = ("all", "balanced", "morton", "hilbert") + #: Tag of the messages that carry a gathered patch field to another rank. _GATHER_TAG = 7311 +def _share_time( + times: dict, patches: Sequence[Any], owner: Any, seconds: float +) -> None: + """Add ``seconds`` spent on markers of several patches to ``times``, split by markers.""" + import numpy as np + + if not owner.size: + return + numbers, counts = np.unique(owner, return_counts=True) + for number, count in zip(numbers.tolist(), counts.tolist(), strict=True): + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + seconds * count / owner.size + + def _by_patch(found: Any) -> Iterator[tuple[int, Any]]: """The markers of each patch: ``(patch number, their indices)``, in the order of the patches. @@ -319,16 +338,17 @@ class AMRHierarchy: on several, over which mpiarray splits its fields. ``placement`` says where a patch goes that is added without ``ranks``: ``"all"`` puts it on every rank, ``"balanced"`` on the one rank that holds the fewest cells so - far, ``"morton"`` along a Morton (Z-order) curve when `regrid` places the - patches (`morton_ranks`: the patches of all levels in the order of the - curve, cut into runs of about equal cells with the base level counted, - one run per rank, so that neighbouring patches and the patches over them - tend to share a rank; a patch added by `add_patch` goes where + far, ``"morton"`` or ``"hilbert"`` along that space-filling curve when + `regrid` places the patches (`curve_ranks`: the patches of all levels in + the order of the curve, cut into runs of about equal cells with the base + level counted, one run per rank, so that neighbouring patches and the + patches over them tend to share a rank; the Hilbert curve has no jumps, so + its runs are more compact; a patch added by `add_patch` goes where ``"balanced"`` would put it), or a function ``placement(level, box)`` that returns the ranks (as ``ranks`` of `add_patch` takes them). With ``max_cells_per_rank``, a ``"balanced"`` patch with more cells than that is split over as many of the least loaded ranks as it needs (at most all of - them); a ``"morton"`` patch stays on one rank. + them); a patch placed along a curve stays on one rank. The domain is the rectangle of ``base_shape`` cells, or with ``base_boxes`` the union of those boxes of base cells: an L, a T, a rectangle with a notch. @@ -503,10 +523,10 @@ def __init__( ) self.geometry = geometry self.comm = mpa.default_comm() if comm is None else comm - if not callable(placement) and placement not in ("all", "balanced", "morton"): + if not callable(placement) and placement not in _PLACEMENTS: raise ValueError( - "placement must be 'all', 'balanced', 'morton' or a function, " - f"got {placement!r}" + f"placement must be one of {', '.join(map(repr, _PLACEMENTS))} " + f"or a function, got {placement!r}" ) if max_cells_per_rank is not None and int(max_cells_per_rank) < 1: raise ValueError("max_cells_per_rank must be at least 1") @@ -995,7 +1015,7 @@ def _rebuilt( self, boxes: Mapping[int, Sequence[IndexBox]], placement: Any, - cost: Mapping[int, Any] | None, + cost: Mapping[Any, Any] | None, fill_halos: bool, fields: Sequence[str] | None = None, ) -> AMRHierarchy: @@ -1019,19 +1039,26 @@ def _rebuilt( geometry=self.geometry, axis_nodes=self.axis_nodes, ) - if new.placement == "morton": - from patchwork.mesh.regrid import box_costs, morton_ranks + if new.placement in ("morton", "hilbert") or ( + new.placement == "balanced" and cost is not None + ): + from patchwork.mesh.regrid import box_costs, curve_ranks, knapsack_ranks weights, load = None, list(new.cells_on_rank) # the base level if cost is not None: weights, load = box_costs(new, boxes, cost) - ranks = morton_ranks( - boxes, - self.comm.Get_size(), - ratio=self.refinement_ratio, - load=load, - weights=weights, - ) + size = self.comm.Get_size() + if new.placement == "balanced": + ranks = knapsack_ranks(boxes, size, load=load, weights=weights) + else: + ranks = curve_ranks( + boxes, + size, + curve=str(new.placement), + ratio=self.refinement_ratio, + load=load, + weights=weights, + ) for level in sorted(boxes): for box, rank in zip(boxes[level], ranks[level], strict=True): new.add_patch(level, box, ranks=rank) @@ -1090,7 +1117,7 @@ def regrid( min_patch_size: int = 1, forbid: Any = None, placement: str | Callable[[int, IndexBox], Any] | None = None, - cost: Mapping[int, Any] | None = None, + cost: Mapping[Any, Any] | None = None, fill_halos: bool = False, fields: Sequence[str] | None = None, ) -> AMRHierarchy: @@ -1145,24 +1172,32 @@ def regrid( is used for every refined level. Tags that would need a forbidden cell are dropped, as are those that would need patches too close to it. - New patches are placed by ``placement`` (default: this hierarchy's), - the largest first, or along a Morton curve with ``"morton"``. With - ``"morton"``, ``cost`` weighs the patches by more than their cells: a - mapping from a level to a per-cell cost of that level's shape, in units - of one cell (the markers of `marker_counts` times what a marker costs - against a cell), counted in the patch where the cell is a leaf - (`box_costs`), so that a rank with a dense beam gets fewer cells. Collective over ``comm``; this hierarchy is left as + New patches are placed by ``placement`` (default: this hierarchy's): + the largest first with ``"balanced"``, or along a space-filling curve + with ``"morton"`` or ``"hilbert"``. With these three, ``cost`` weighs + the patches by more than their cells (`box_costs`): a mapping from a + level to a per-cell cost of that level's shape, in units of one cell + (the markers of `marker_counts` times what a marker costs against a + cell), counted in the patch where the cell is a leaf, or a mapping from + a patch ``(level, box)`` to a measured cost (``deposit(..., + times=...)``). ``"balanced"`` with a cost is the greedy knapsack + (`knapsack_ranks`): the most even, without locality. Collective over ``comm``; this hierarchy is left as it is, except for the restriction of conservative fields. """ from patchwork.mesh.regrid import combine_tags, new_boxes, quadtree_boxes if method not in ("cluster", "quadtree"): raise ValueError(f"method must be 'cluster' or 'quadtree', got {method!r}") - if ( - cost is not None - and (self.placement if placement is None else placement) != "morton" + if cost is not None and ( + self.placement if placement is None else placement + ) not in ( + "balanced", + "morton", + "hilbert", ): - raise ValueError("cost weighs the patches of placement='morton' only") + raise ValueError( + "cost weighs the patches of placement 'balanced', 'morton' or 'hilbert'" + ) if method == "quadtree" and max_patch_size is not None: raise ValueError( "max_patch_size does not apply to method='quadtree': " @@ -1194,22 +1229,34 @@ def regrid( @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) def rebalance( - self, cost: Mapping[int, Any] | None = None, *, fill_halos: bool = False + self, + cost: Mapping[Any, Any] | None = None, + *, + placement: str = "morton", + fill_halos: bool = False, ) -> AMRHierarchy: - """The same patches placed again along the Morton curve, by ``cost``; fields moved. - - Every refined patch goes to a rank by `morton_ranks`, weighed by its - cells plus the ``cost`` of its leaf cells as in `regrid` (`box_costs`; - without ``cost`` by its cells). The base level stays where it is. Every - field is copied to the patches' new ranks; send the markers after them - with `migrate`. The new hierarchy places its regrids along the curve as - well (``placement="morton"``). Collective over ``comm``. + """The same patches placed again by ``cost``; fields moved. + + Every refined patch goes to a rank along a space-filling curve + (``placement`` ``"morton"`` or ``"hilbert"``, `curve_ranks`) or by the + greedy knapsack (``"balanced"``, `knapsack_ranks`), weighed by its cells + plus the ``cost`` of its leaf cells, or by measured costs per patch, as + in `regrid` (`box_costs`; without ``cost`` by its cells). The base + level stays where it is. Every field is copied to the patches' new + ranks; send the markers after them with `migrate`. The new hierarchy + places its regrids the same way. Collective over ``comm``. """ + if placement not in ("balanced", "morton", "hilbert"): + raise ValueError( + f"rebalance places by 'balanced', 'morton' or 'hilbert', got {placement!r}" + ) boxes = { level: [patch.box for patch in self.patches_at_level(level)] for level in range(1, self.max_level + 1) } - return self._rebuilt(boxes, "morton", cost, fill_halos) + if placement == "balanced" and cost is None: + cost = {} # by cells: the knapsack, not the order of add_patch + return self._rebuilt(boxes, placement, cost, fill_halos) def integral(self, name: str) -> float: """The integral of field ``name`` over the domain, from the finest values. @@ -1430,8 +1477,15 @@ def _owners(self, found: Any, cell: tuple[Any, ...], name: str) -> Any: blocks = self._schedule("blocks", name, _gather_blocks) patches = self.patches - result = np.full(found.shape, -1, dtype=np.int64) - for number, chosen in _by_patch(found): + # a patch on one rank: that rank, for all its markers at once + single = np.full(len(patches) + 1, -1, dtype=np.int64) + for number, (members, replicated) in blocks.items(): + if len(members) == 1 and not replicated: + single[number] = members[0][0] + result = single[found] # -1 (outside the domain) picks the last entry + several = np.flatnonzero((result < 0) & (found >= 0)) + for number, part in _by_patch(found[several]): + chosen = several[part] members, replicated = blocks[number] if replicated: raise ValueError( @@ -1605,6 +1659,80 @@ def _patch_block(self, patch: Patch, name: str, degree: int) -> tuple[Any, Any]: start = [f + lo for f, lo in zip(first, lower, strict=True)] return block, self._grid(patch, start, block.shape) + def _linear_corners( + self, found: Any, cell: tuple[Any, ...], wrapped: Any, name: str + ) -> tuple[Any, list[tuple[Any, Any]], list[tuple[int, int, Any]], int]: + """The cloud-in-cell corners of all markers at once, in one buffer of the blocks. + + Every marker in the domain reads or writes the ``2**ndim`` corners of its cell in + the stored block of its patch (`_stored_block`), with the weights of mpifield's + linear kernels: ``(1 - f)`` and ``f`` per axis, ``f`` the marker's place in its + cell. The blocks of the patches with markers are laid end to end in one flat + buffer. Returns the markers in the domain, ``(flat index, weight)`` per corner, + ``(patch number, offset, storage)`` per block, and the buffer's size. + """ + import numpy as np + + inside = np.flatnonzero(found >= 0) + numbers = np.flatnonzero( + np.bincount(found[inside], minlength=len(self.patches)) + ) + patches = self.patches + ndim = self.ndim + blocks = [] + offset = 0 + first = np.zeros((len(patches), ndim), dtype=np.int64) + start = np.zeros(len(patches), dtype=np.int64) + strides = np.zeros((len(patches), ndim), dtype=np.int64) + spacing = np.ones((len(patches), ndim)) + for number in numbers.tolist(): + patch = patches[number] + array = patch.field(name) + layout = array.layout + storage = array.local_with_halos + blocks.append((number, offset, storage)) + start[number] = offset + first[number] = [ + lo + b0 - h + for (lo, _), (b0, _), h in zip( + patch.box, layout.index_bounds, layout.halo, strict=True + ) + ] + stride = 1 + for axis in range(ndim - 1, -1, -1): + strides[number, axis] = stride + stride *= storage.shape[axis] + spacing[number] = self.spacing(patch.level) + offset += storage.size + owner = found[inside] + origin = np.asarray(self.lower_bound, dtype=float) + # the flat index of each marker's lower corner, and the steps to the others + base = start - np.einsum("pa,pa->p", first, strides) + flat = base[owner] + steps, fraction = [], [] + for axis in range(ndim): + index = np.asarray(cell[axis])[inside] + step = strides[owner, axis] + flat += index * step + steps.append(step) + fraction.append( + (np.asarray(wrapped[axis])[inside] - origin[axis]) + * (1.0 / spacing)[owner, axis] + - index + ) + corners = [] + for corner in itertools.product((0, 1), repeat=ndim): + where = flat.copy() + weight = np.ones(inside.size) + for axis, up in enumerate(corner): + if up: + where += steps[axis] + weight *= fraction[axis] + else: + weight *= 1.0 - fraction[axis] + corners.append((where, weight)) + return inside, corners, blocks, offset + def _shape(self, name: str, splines: Any, what: str) -> Any: """The `mpifield.Splines` of ``splines`` (a degree or one), checked against the halo.""" from mpifield import splines as resolve @@ -1643,6 +1771,7 @@ def deposit( name: str | None = None, reset: bool = True, splines: Any = 1, + times: dict | None = None, ) -> None: """Deposit the charge of markers on the node-centered field ``name``, patch by patch. @@ -1652,7 +1781,9 @@ def deposit( bilinear (cloud-in-cell) weights: the same weights as `CompositeNodes.deposit`, whose transposed interpolation the field gather is, and of - `interpolate`; mpifield's compiled kernels do the work. The values are + `interpolate`. These weights are added for the markers of all patches at + once (one ``bincount`` into a buffer of the blocks); a higher degree runs + mpifield's compiled kernels patch by patch. The values are charges, not a density. The markers must be on the ranks that `owner` gives (use `migrate`), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. @@ -1667,6 +1798,10 @@ def deposit( ``mpifield.splines(p).halo`` nodes (2 from degree 2 on). Where the stencil would reach past the edge of the marker's patch it folds onto the patch's edge nodes, so the total is kept; such charge stays on the patch. + + ``times``, a dict, collects the seconds spent on the markers of every + patch, added to the value of its ``(level, box)``: costs measured on + this rank, for `regrid` and `rebalance` (sum them over the ranks first). """ import numpy as np @@ -1694,17 +1829,39 @@ def deposit( for patch in self.local_patches: patch.field(name).local_with_halos[...] = 0.0 patches = self.patches + if shape.degree == 1: # all patches in one pass over the markers + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + charges = charge[inside] + buffer = np.zeros(total) + for flat, weight in corners: + buffer += np.bincount(flat, weights=charges * weight, minlength=total) + for _, offset, storage in blocks: + storage += buffer[offset : offset + storage.size].reshape(storage.shape) + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return for number, chosen in _by_patch(found): + start = time.perf_counter() storage, grid = self._patch_block(patches[number], name, shape.degree) positions = np.array([w[chosen] for w in wrapped]) # the kernels take the nodes component-last: a view with one component shape.nodes.scatter_block( positions, charge[chosen], storage[..., None], grid ) + if times is not None: + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + time.perf_counter() - start @sp.profile("patchwork.interpolate", tags=PROFILE_TAGS) def interpolate( - self, *arguments: Any, name: str | None = None, splines: Any = 1 + self, + *arguments: Any, + name: str | None = None, + splines: Any = 1, + times: dict | None = None, ) -> Any: """Interpolate the node-centered field ``name`` at markers, each in its own patch. @@ -1721,6 +1878,8 @@ def interpolate( ``splines`` is the B-spline degree of the weights (1, 2 or 3) or an `mpifield.Splines`, as for `deposit`, whose transpose this is for the same degree, the fold at the patch edges included. + + ``times`` collects the seconds spent per patch, as in `deposit`. """ import numpy as np @@ -1737,12 +1896,31 @@ def interpolate( ) values = np.zeros(flat[0].size) patches = self.patches + if weights.degree == 1: # all patches in one pass over the markers + begin = time.perf_counter() + inside, corners, blocks, total = self._linear_corners( + found, cell, wrapped, name + ) + buffer = np.empty(total) + for _, offset, storage in blocks: + buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) + gathered = np.zeros(inside.size) + for where, weight in corners: + gathered += weight * buffer[where] + values[inside] = gathered + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return values.reshape(shape) for number, chosen in _by_patch(found): + start = time.perf_counter() storage, grid = self._patch_block(patches[number], name, weights.degree) positions = np.array([w[chosen] for w in wrapped]) result = np.zeros((1, chosen.size)) weights.nodes.gather_block(positions, storage[..., None], result, grid) values[chosen] = result[0] + if times is not None: + key = (patches[number].level, patches[number].box) + times[key] = times.get(key, 0.0) + time.perf_counter() - start return values.reshape(shape) @sp.profile("patchwork.accumulate_halos", tags=PROFILE_TAGS) diff --git a/src/patchwork/mesh/regrid.py b/src/patchwork/mesh/regrid.py index 92f434d..9e40821 100644 --- a/src/patchwork/mesh/regrid.py +++ b/src/patchwork/mesh/regrid.py @@ -738,44 +738,79 @@ def quadtree_boxes( return boxes +def _curve_keys(items: list[tuple], ratio: int, curve: str) -> list[int]: + """The key of every ``(level, n, box)`` on a curve: its lower corner in finest cells.""" + top = max(level for level, _, _ in items) + corners = np.array( + [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], + dtype=np.uint64, + ) + if corners.shape[1] == 1: # 1D: the curve is the axis + return corners.reshape(-1).tolist() + if curve == "morton": + return xp.algorithms.morton_encode(*corners.T).tolist() + levels = max(1, int(corners.max()).bit_length()) + return xp.algorithms.hilbert_encode(*corners.T, levels=levels).tolist() + + +def _costs( + boxes: Mapping[int, Sequence[IndexBox]], + items: list[tuple], + weights: Mapping[int, Sequence[float]] | None, +) -> list[float]: + """The cost of every item: its cells, or its weight.""" + if weights is None: + return [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] + for level in boxes: + if len(weights[level]) != len(boxes[level]): + raise ValueError(f"weights of level {level} need one value per box") + return [float(weights[level][n]) for level, n, _ in items] + + @method( equations={ - "key": r"k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}", - "ranks": r"\text{along the curve, rank } q \text{ takes boxes while } w_q + |B|/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B |B|\Big)", + "morton": r"k(B) = \sum_{b} \sum_{d=0}^{D-1} \mathrm{bit}_b\big(r^{L - \ell}\, i_d\big)\, 2^{bD + d} \quad \text{(the lower corner } \mathbf i \text{ of } B \text{ on level } \ell\text{, in cells of the finest level } L\text{)}", + "hilbert": r"k(B) = H\big(r^{L - \ell}\, \mathbf i\big), \quad H \text{ the Hilbert index (Skilling's construction): consecutive keys are neighbouring cells}", + "ranks": r"\text{along the curve, rank } q \text{ takes boxes while } w_q + c_B/2 \le T, \quad T = \frac{1}{R}\Big(\sum_q w_q^{0} + \sum_B c_B\Big)", }, assumptions=( "the patches of all refined levels on one curve, a coarse patch before the finer ones at the same corner, so that a patch and the patches over it tend to share a rank", - "the load a rank already has (the base level) counts: such a rank takes fewer patches", + "the cost $c_B$ of a box is its cells, or its weight (`box_costs`); the load a rank already has (the base level) counts", "a patch stays on one rank", ), references=( "[Morton, IBM technical report (1966)](https://dominoweb.draco.res.ibm.com/reports/Morton1966.pdf)", + "[Skilling, AIP Conf. Proc. 707, 381 (2004)](https://doi.org/10.1063/1.1751381)", "[Burstedde, Wilcox and Ghattas, SIAM J. Sci. Comput. 33, 1103 (2011)](https://doi.org/10.1137/100791634)", ), ) -def morton_ranks( +def curve_ranks( boxes: Mapping[int, Sequence[IndexBox]], size: int, *, + curve: str = "morton", ratio: int = 2, load: Sequence[float] | None = None, weights: Mapping[int, Sequence[float]] | None = None, ) -> dict[int, list[int]]: - """The rank of each box: the boxes of all levels along a Morton curve, cut into ``size`` runs. - - ``boxes`` maps a level to its boxes. Every box gets the Morton (Z-order) - key of its lower corner in cells of the finest level, so that boxes close - in space are close on the curve whatever their level, and a box comes - before the finer boxes at the same corner. Walking the curve, a rank takes - boxes until its cells, with the ``load`` it already has (the cells of the - base level, say), reach an equal share of all cells; then the next rank - goes on. ``weights`` (per level, one per box) replaces the cells of a box - by its cost, in the units of ``load``: with `box_costs`, the cells plus the - markers on them. Returns, per level, the ranks in the order of + """The rank of each box: the boxes of all levels along a space-filling curve, cut into ``size`` runs. + + ``boxes`` maps a level to its boxes. Every box gets the key of its lower + corner, in cells of the finest level, on the ``curve``: ``"morton"`` (the + Z-order curve) or ``"hilbert"`` (without the Z's jumps, so that the run of + a rank is more compact). Boxes close in space are close on the curve + whatever their level, and a box comes before the finer boxes at the same + corner. Walking the curve, a rank takes boxes until its cost, with the + ``load`` it already has (the cells of the base level, say), reaches an equal + share of all costs; then the next rank goes on. The cost of a box is its + cells, or ``weights`` (per level, one per box, in the units of ``load``; + see `box_costs`). Returns, per level, the ranks in the order of ``boxes[level]``. """ if size < 1: raise ValueError(f"size must be at least 1, got {size}") + if curve not in ("morton", "hilbert"): + raise ValueError(f"curve must be 'morton' or 'hilbert', got {curve!r}") loads = [0.0] * size if load is None else [float(w) for w in load] if len(loads) != size: raise ValueError(f"load needs {size} values, got {len(loads)}") @@ -785,25 +820,11 @@ def morton_ranks( result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} if not items: return result - top = max(level for level, _, _ in items) - corners = np.array( - [[lo * ratio ** (top - level) for lo, _ in box] for level, _, box in items], - dtype=np.uint64, - ) - if corners.shape[1] > 1: - keys = xp.algorithms.morton_encode(*corners.T) # 2D and 3D - else: # 1D: the curve is the axis - keys = corners.reshape(-1) - if weights is None: - costs = [float(np.prod([hi - lo for lo, hi in box])) for _, _, box in items] - else: - for level in boxes: - if len(weights[level]) != len(boxes[level]): - raise ValueError(f"weights of level {level} need one value per box") - costs = [float(weights[level][n]) for level, n, _ in items] + keys = _curve_keys(items, ratio, curve) + costs = _costs(boxes, items, weights) share = (sum(loads) + sum(costs)) / size rank = 0 - for k in sorted(range(len(items)), key=lambda k: (int(keys[k]), items[k][0])): + for k in sorted(range(len(items)), key=lambda k: (keys[k], items[k][0])): while rank < size - 1 and loads[rank] + costs[k] / 2 > share: rank += 1 level, n, _ = items[k] @@ -812,21 +833,99 @@ def morton_ranks( return result +@method( + equations={ + "greedy": r"c_{B_1} \ge c_{B_2} \ge \dots, \qquad r(B_k) = \arg\min_q w_q \text{ (the lowest such rank)}, \quad w_{r(B_k)} \mathrel{+}= c_{B_k}", + }, + assumptions=( + "the greedy (longest processing time first) solution of the knapsack-like partition: the largest cost at most 4/3 of the best possible", + "no locality: neighbouring patches may land on any ranks", + ), + references=( + "[Graham, SIAM J. Appl. Math. 17, 416 (1969)](https://doi.org/10.1137/0117039)", + ), +) +def knapsack_ranks( + boxes: Mapping[int, Sequence[IndexBox]], + size: int, + *, + load: Sequence[float] | None = None, + weights: Mapping[int, Sequence[float]] | None = None, +) -> dict[int, list[int]]: + """The rank of each box: the largest cost first, each to the rank with the least so far. + + The greedy solution of cutting the boxes into ``size`` sets of equal cost, + what ``placement="balanced"`` does with cells, here with the ``weights`` of + `box_costs` and the ``load`` the ranks already have. Balances better than a + curve, but neighbouring boxes may land on different ranks. Returns, per + level, the ranks in the order of ``boxes[level]``. + """ + if size < 1: + raise ValueError(f"size must be at least 1, got {size}") + loads = [0.0] * size if load is None else [float(w) for w in load] + if len(loads) != size: + raise ValueError(f"load needs {size} values, got {len(loads)}") + items = [ + (level, n, box) for level in sorted(boxes) for n, box in enumerate(boxes[level]) + ] + result: dict[int, list[int]] = {level: [0] * len(boxes[level]) for level in boxes} + costs = _costs(boxes, items, weights) + for k in sorted( + range(len(items)), key=lambda k: (-costs[k], items[k][0], items[k][2]) + ): + rank = min(range(size), key=lambda q: (loads[q], q)) + level, n, _ = items[k] + result[level][n] = rank + loads[rank] += costs[k] + return result + + def box_costs( hierarchy: AMRHierarchy, boxes: Mapping[int, Sequence[IndexBox]], - cost: Mapping[int, Any], + cost: Mapping[Any, Any], ) -> tuple[dict[int, list[float]], list[float]]: - """The cost of each new box and of each rank's base patches: cells plus the cost of the leaf cells. - - ``cost`` maps a level to a per-cell cost of that level's shape, in units of - one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a cell; - a missing level costs nothing beyond its cells). A cell's cost goes to the - box where it is a leaf, not covered by a finer box, since that is where its - markers deposit and gather. ``hierarchy`` holds the base level (the patches - of level 0 with their ranks). Returns the weights of ``boxes`` per level and - the load of every rank from the base level, for `morton_ranks`. + """The cost of each new box and of each rank's base patches. + + ``cost`` is one of two things: + + - a mapping from a level to a per-cell cost of that level's shape, in units + of one cell (``0.5 * marker_counts(...)[level]`` if a marker costs half a + cell; a missing level costs nothing beyond its cells): a box costs its + cells plus the cost of its leaf cells, the cells no finer box covers, + since that is where their markers deposit and gather; + - a mapping from a patch, ``(level, box)``, to its cost, e.g. the seconds + measured with ``deposit(..., times=...)`` and ``interpolate(..., + times=...)``: a box costs its own value, and a box without one the mean + cost per cell of those that have one. + + ``hierarchy`` holds the base level (the patches of level 0 with their + ranks). Returns the weights of ``boxes`` per level and the load of every + rank from the base level, for `curve_ranks` and `knapsack_ranks`. """ + if any(isinstance(key, tuple) for key in cost): + measured = { + (int(level), tuple(tuple(side) for side in box)): float(value) + for (level, box), value in cost.items() + } + cells = sum(float(np.prod([hi - lo for lo, hi in box])) for _, box in measured) + per_cell = sum(measured.values()) / cells if cells else 0.0 + + def measured_weight(level: int, box: IndexBox) -> float: + found = measured.get((level, box)) + if found is not None: + return found + return per_cell * float(np.prod([hi - lo for lo, hi in box])) + + weights = { + level: [measured_weight(level, box) for box in boxes[level]] + for level in boxes + } + load = [0.0] * hierarchy.comm.Get_size() + for patch in hierarchy.patches_at_level(0): + for rank in patch.ranks: + load[rank] += measured_weight(0, patch.box) / len(patch.ranks) + return weights, load ratio = hierarchy.refinement_ratio top = max(boxes, default=0) leaf_cost = {} diff --git a/src/patchwork/tests/unit/test_markers.py b/src/patchwork/tests/unit/test_markers.py index e850a94..24c3ca1 100644 --- a/src/patchwork/tests/unit/test_markers.py +++ b/src/patchwork/tests/unit/test_markers.py @@ -453,3 +453,42 @@ def test_the_node_grid_of_a_patch_holds_its_nodes() -> None: assert tuple(grid.num_gridpoints) == patch.node_shape assert grid.periodic == (False, False) assert grid.geometry == (i0 * dx, j0 * dy, dx, dy, *patch.node_shape, 0, 0) + + +@pytest.mark.parametrize("periodic", [(False, False), (True, False)]) +def test_one_pass_linear_deposit_and_gather_equal_the_kernels_patch_by_patch( + periodic, +) -> None: + from mpifield import splines + + mesh = AMRHierarchy(base_shape=(8, 8), periodic=periodic) + mesh.add_patch(1, ((4, 12), (4, 12)), ranks=0) + mesh.add_patch(2, ((10, 18), (8, 16)), ranks=0) + mesh.allocate_field("q", centering="node") + rng = np.random.default_rng(WORLD.Get_rank()) + x, y = rng.uniform(0, 1, (2, 2000)) + charge = rng.uniform(0.5, 1.5, x.size) + x, y, charge = mesh.migrate(x, y, charge, name="q") + mesh.deposit(x, y, charge, "q") + gathered = mesh.interpolate(x, y, "q") + # the same with mpifield's compiled kernels, one patch at a time + linear = splines(1) + flat, _ = mesh._points((x, y)) + found, _, wrapped = mesh._cells(flat) + expected_gather = np.zeros(x.size) + for patch in mesh.local_patches: + storage, grid = mesh._patch_block(patch, "q", 1) + reference = np.zeros_like(np.asarray(storage)) + number = mesh.patches.index(patch) + chosen = np.flatnonzero(found == number) + positions = np.array([w[chosen] for w in wrapped]) + linear.nodes.scatter_block( + positions, charge[chosen], reference[..., None], grid + ) + np.testing.assert_allclose(storage, reference, rtol=1e-12, atol=1e-12) + result = np.zeros((1, chosen.size)) + linear.nodes.gather_block( + positions, np.asarray(storage)[..., None], result, grid + ) + expected_gather[chosen] = result[0] + np.testing.assert_allclose(gathered, expected_gather, rtol=1e-12, atol=1e-12) diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 61ad51b..7e0d984 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -11,9 +11,9 @@ from patchwork import ( AMRHierarchy, + curve_ranks, function_tags, marker_tags, - morton_ranks, quadtree_boxes, ) from patchwork.mesh.regrid import combine_tags @@ -223,28 +223,28 @@ def test_quadtree_adds_no_level_where_every_cell_is_forbidden() -> None: assert new.max_level == 0 -def test_morton_ranks_follow_the_z_curve_with_equal_cells() -> None: +def test_curve_ranks_follow_the_z_curve_with_equal_cells() -> None: # sixteen 2 x 2 blocks of a 8 x 8 level: the Z curve visits the quadrants in turn boxes = [ ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(4) for j in range(4) ] - ranks = morton_ranks({1: boxes}, 4)[1] + ranks = curve_ranks({1: boxes}, 4)[1] for box, rank in zip(boxes, ranks, strict=True): (i0, _), (j0, _) = box assert rank == (i0 >= 4) + 2 * (j0 >= 4) # the first axis is the lowest bit # a rank that holds the base already takes fewer patches - loaded = morton_ranks({1: boxes}, 2, load=[32, 0])[1] + loaded = curve_ranks({1: boxes}, 2, load=[32, 0])[1] assert loaded.count(0) == 4 and loaded.count(1) == 12 # a patch and the finer patch over it are neighbours on the curve levels = {1: [((0, 4), (0, 4)), ((4, 8), (4, 8))], 2: [((0, 4), (0, 4))]} - assert morton_ranks(levels, 2) == {1: [0, 1], 2: [0]} - assert morton_ranks({1: boxes}, 1)[1] == [0] * 16 - assert morton_ranks({}, 3) == {} - assert morton_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D + assert curve_ranks(levels, 2) == {1: [0, 1], 2: [0]} + assert curve_ranks({1: boxes}, 1)[1] == [0] * 16 + assert curve_ranks({}, 3) == {} + assert curve_ranks({1: [((0, 4),), ((4, 8),)]}, 2) == {1: [0, 1]} # 1D with pytest.raises(ValueError, match="size"): - morton_ranks({1: boxes}, 0) + curve_ranks({1: boxes}, 0) with pytest.raises(ValueError, match="load"): - morton_ranks({1: boxes}, 2, load=[1.0]) + curve_ranks({1: boxes}, 2, load=[1.0]) def test_regrid_places_the_blocks_along_the_morton_curve() -> None: @@ -255,7 +255,7 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: assert new.placement == "morton" boxes = {level: [p.box for p in new.patches_at_level(level)] for level in (1, 2)} base = AMRHierarchy(base_shape=(16, 16), placement="morton").cells_on_rank - expected = morton_ranks(boxes, SIZE, load=base) + expected = curve_ranks(boxes, SIZE, load=base) for level in (1, 2): patches = new.patches_at_level(level) assert [p.ranks for p in patches] == [(r,) for r in expected[level]] @@ -268,7 +268,7 @@ def test_regrid_places_the_blocks_along_the_morton_curve() -> None: added = again.add_patch(3, ((40, 48), (40, 48))) assert len(added.ranks) == 1 with pytest.raises(ValueError, match="morton"): - AMRHierarchy(base_shape=(4, 4), placement="hilbert") + AMRHierarchy(base_shape=(4, 4), placement="peano") @pytest.mark.parametrize("centering", ["node", "cell"]) @@ -338,12 +338,12 @@ def test_marker_weights_move_the_cuts_of_the_morton_curve() -> None: boxes = { 1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(4)] } # four boxes of 4 cells - assert morton_ranks(boxes, 2) == {1: [0, 0, 1, 1]} + assert curve_ranks(boxes, 2) == {1: [0, 0, 1, 1]} # the first box costs as much as the other three: it gets a rank to itself heavy = {1: [12.0, 4.0, 4.0, 4.0]} - assert morton_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} + assert curve_ranks(boxes, 2, weights=heavy) == {1: [0, 1, 1, 1]} with pytest.raises(ValueError, match="weights"): - morton_ranks(boxes, 2, weights={1: [1.0]}) + curve_ranks(boxes, 2, weights={1: [1.0]}) mesh = AMRHierarchy(base_shape=(8, 8)) rank = WORLD.Get_rank() @@ -430,7 +430,7 @@ def plane(x, y): for level in range(1, mesh.max_level + 1) } weights, load = box_costs(moved, boxes, cost) - expected = morton_ranks(boxes, SIZE, load=load, weights=weights) + expected = curve_ranks(boxes, SIZE, load=load, weights=weights) for level in boxes: ranks = [p.ranks for p in moved.patches_at_level(level)] assert ranks == [(r,) for r in expected[level]] @@ -483,3 +483,96 @@ def test_regrid_moves_only_the_fields_asked_for() -> None: ) with pytest.raises(KeyError, match="phi"): mesh.regrid(tags, fields=["phi"]) + + +def test_hilbert_runs_are_contiguous_and_balanced() -> None: + from patchwork import curve_ranks + + boxes = [ + ((2 * i, 2 * i + 2), (2 * j, 2 * j + 2)) for i in range(8) for j in range(8) + ] + ranks = curve_ranks({1: boxes}, 3, curve="hilbert")[1] + assert sorted(set(ranks)) == [0, 1, 2] + counts = [ranks.count(r) for r in range(3)] + assert max(counts) - min(counts) <= 1 + # every rank's boxes are connected through shared faces: the curve has no jumps + for rank in range(3): + mine = { + (b[0][0] // 2, b[1][0] // 2) + for b, r in zip(boxes, ranks, strict=True) + if r == rank + } + seen, todo = set(), [next(iter(mine))] + while todo: + cell = todo.pop() + if cell in seen: + continue + seen.add(cell) + i, j = cell + todo += [ + c for c in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)) if c in mine + ] + assert seen == mine + with pytest.raises(ValueError, match="curve"): + curve_ranks({1: boxes}, 3, curve="peano") + + +def test_knapsack_balances_the_weights() -> None: + from patchwork import knapsack_ranks + + boxes = {1: [((2 * i, 2 * i + 2), (0, 2)) for i in range(6)]} + weights = {1: [7.0, 5.0, 4.0, 3.0, 3.0, 2.0]} + ranks = knapsack_ranks(boxes, 2, weights=weights)[1] + load = [ + sum(w for w, r in zip(weights[1], ranks, strict=True) if r == q) + for q in range(2) + ] + assert sorted(load) == [12.0, 12.0] + assert knapsack_ranks(boxes, 2, load=[100.0, 0.0])[1] == [1] * 6 + with pytest.raises(ValueError, match="load"): + knapsack_ranks(boxes, 2, load=[1.0]) + with pytest.raises(ValueError, match="size"): + knapsack_ranks(boxes, 0) + + +def test_measured_times_per_patch_weigh_the_placement() -> None: + from patchwork import box_costs + + mesh = AMRHierarchy(base_shape=(16, 16), placement="hilbert") + mesh.allocate_field("rho", centering="node") + mesh = mesh.regrid( + function_tags(mesh, ring, levels=1), method="quadtree", block_size=8 + ) + rng = np.random.default_rng(WORLD.Get_rank()) + x, y = rng.uniform(0.2, 0.4, (2, 500)) + q = np.ones(x.size) + mx, my, mq = mesh.migrate(x, y, q, name="rho") + times: dict = {} + mesh.deposit(mx, my, mq, "rho", times=times) + mesh.interpolate(mx, my, "rho", times=times) + # a rank may hold no markers: count over all ranks (and fail on all of them) + assert WORLD.allreduce(len(times)) > 0 + assert all(value >= 0.0 for value in times.values()) + assert all( + (level, box) in {(p.level, p.box) for p in mesh.patches} for level, box in times + ) + # a patch with a cost gets it, one without the mean per cell + boxes = {1: [p.box for p in mesh.patches_at_level(1)]} + known = boxes[1][0] + weights, load = box_costs(mesh, boxes, {(1, known): 640.0}) + assert weights[1][0] == 640.0 + assert np.allclose(weights[1][1:], 640.0 / 64 * 64) + moved = mesh.rebalance( + {(p.level, p.box): float(n) for n, p in enumerate(mesh.patches)} + ) + assert moved.placement == "morton" + for placement in ("balanced", "hilbert"): + again = mesh.rebalance(placement=placement) + assert [(p.level, p.box) for p in again.patches] == [ + (p.level, p.box) for p in mesh.patches + ] + assert again.placement == placement + with pytest.raises(ValueError, match="rebalance"): + mesh.rebalance(placement="all") + with pytest.raises(ValueError, match="cost weighs"): + AMRHierarchy(base_shape=(4, 4)).regrid({0: np.ones((4, 4), bool)}, cost={}) diff --git a/tutorials/13_quadtree_patches.ipynb b/tutorials/13_quadtree_patches.ipynb index 470002a..e0d6c26 100644 --- a/tutorials/13_quadtree_patches.ipynb +++ b/tutorials/13_quadtree_patches.ipynb @@ -4,20 +4,7 @@ "cell_type": "markdown", "id": "0", "metadata": {}, - "source": [ - "# Quadtree patches\n", - "\n", - "`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\n", - "tagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n", - "[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\n", - "aligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\n", - "the blocks of a level are the children of those of the level below, so the patches are the\n", - "nodes of a quadtree (an octree in 3D), all of one size.\n", - "\n", - "Both give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\n", - "solvers work on either. They differ in how many patches there are, how many cells are\n", - "refined, and how much the mesh changes when the tags change a little." - ] + "source": "# Quadtree patches\n\n`regrid` places patches in one of two ways. The default, `method=\"cluster\"`, covers the\ntagged cells with few rectangles fitted to them (the Berger-Rigoutsos algorithm, see\n[Regridding](/patchwork/examples/06-regridding/)). `method=\"quadtree\"` cuts every level into\naligned square blocks of `block_size` cells and makes a patch of each block that holds a tag:\nthe blocks of a level are the children of those of the level below, so the patches are the\nnodes of a quadtree (an octree in 3D), all of one size.\n\nBoth give an ordinary hierarchy: halos, regridding of the fields, markers, deposits and the\nsolvers work on either. They differ in how many patches there are, how many cells are\nrefined, and how much the mesh changes when the tags change a little." }, { "cell_type": "code", @@ -42,11 +29,7 @@ "cell_type": "markdown", "id": "2", "metadata": {}, - "source": [ - "## Clusters and blocks\n", - "\n", - "The same tags, a ring refined by three levels, placed both ways:" - ] + "source": "## Clusters and blocks\n\nThe same tags, a ring refined by three levels, placed both ways:" }, { "cell_type": "code", @@ -91,19 +74,7 @@ "cell_type": "markdown", "id": "4", "metadata": {}, - "source": [ - "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\n", - "blocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\n", - "size for every patch, and patches that are easy to share out between ranks.\n", - "\n", - "## The blocks form a tree\n", - "\n", - "A block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n", - "(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\n", - "exactly one block of the level below, its parent, and each parent has four children. Where a\n", - "block is refined, the level below is refined around it as well, with a margin of `nesting`\n", - "cells, so neighbouring blocks differ by at most one level: the tree is balanced." - ] + "source": "The clusters follow the ring closely with few, unequal rectangles. The quadtree refines whole\nblocks, so it covers more cells, but every patch is a square of 16 x 16 cells: one kernel\nsize for every patch, and patches that are easy to share out between ranks.\n\n## The blocks form a tree\n\nA block of level $k + 1$ is `block_size` cells of its level wide, half a block of level $k$\n(refinement ratio 2), and its corners are on multiples of `block_size`. So each block lies in\nexactly one block of the level below, its parent, and each parent has four children. Where a\nblock is refined, the level below is refined around it as well, with a margin of `nesting`\ncells, so neighbouring blocks differ by at most one level: the tree is balanced." }, { "cell_type": "code", @@ -129,18 +100,7 @@ "cell_type": "markdown", "id": "6", "metadata": {}, - "source": [ - "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\n", - "it may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n", - "\n", - "## Refining by the number of markers\n", - "\n", - "`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\n", - "particle tree stops splitting a box when it holds few enough particles; regridding with these\n", - "tags stops refining where the cells hold few enough markers. The markers are counted over all\n", - "ranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\n", - "background:" - ] + "source": "A block at the edge of the domain or of a forbidden region (`forbid`) is cut to the cells\nit may cover, so a patch can be narrower than `block_size` there, as in the notch of an L.\n\n## Refining by the number of markers\n\n`marker_tags` tags the cells that hold more than `per_cell` markers, on every level. A\nparticle tree stops splitting a box when it holds few enough particles; regridding with these\ntags stops refining where the cells hold few enough markers. The markers are counted over all\nranks, so each rank passes its own. Here a dense beam and a wider cloud on a uniform\nbackground:" }, { "cell_type": "code", @@ -190,10 +150,7 @@ "cell_type": "markdown", "id": "8", "metadata": {}, - "source": [ - "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\n", - "potential (grounded faces)." - ] + "source": "The mesh is a hierarchy like any other: deposit the markers' charge on it and solve for the\npotential (grounded faces)." }, { "cell_type": "code", @@ -218,15 +175,7 @@ "cell_type": "markdown", "id": "10", "metadata": {}, - "source": [ - "## Following a moving beam\n", - "\n", - "The beam moves to the right, and the mesh is regridded after every step. Between two regrids\n", - "the clusters are recut wherever the tags change, even by a few cells, while the quadtree\n", - "adds and removes blocks only where the beam has come or gone and keeps the others as they\n", - "are: the same patches, on the same ranks, with their fields copied rather than\n", - "interpolated. Kept patches are grey, new ones red:" - ] + "source": "## Following a moving beam\n\nThe beam moves to the right, and the mesh is regridded after every step. Between two regrids\nthe clusters are recut wherever the tags change, even by a few cells, while the quadtree\nadds and removes blocks only where the beam has come or gone and keeps the others as they\nare: the same patches, on the same ranks, with their fields copied rather than\ninterpolated. Kept patches are grey, new ones red:" }, { "cell_type": "code", @@ -289,16 +238,7 @@ "cell_type": "markdown", "id": "12", "metadata": {}, - "source": [ - "## Placing the blocks on ranks\n", - "\n", - "Under MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n", - "(Z-order) curve (`morton_ranks`): the patches of all levels in the order of the curve, keyed\n", - "by their lower corner in cells of the finest level, cut into runs of about equal cells, the\n", - "base level's cells counted. Neighbouring patches, and a patch and the patches over it, then\n", - "tend to share a rank, which saves messages between ranks. Here the ranks four processes would\n", - "give the patches of the beam's mesh:" - ] + "source": "## Placing the blocks on ranks\n\nUnder MPI, `placement=\"morton\"` puts the patches of a regrid on the ranks along a Morton\n(Z-order) curve (`curve_ranks`): the patches of all levels in the order of the curve, keyed\nby their lower corner in cells of the finest level, cut into runs of about equal cells, the\nbase level's cells counted. Neighbouring patches, and a patch and the patches over it, then\ntend to share a rank, which saves messages between ranks. Here the ranks four processes would\ngive the patches of the beam's mesh:" }, { "cell_type": "code", @@ -307,7 +247,7 @@ "metadata": {}, "outputs": [], "source": [ - "from patchwork import box_costs, marker_counts, morton_ranks\n", + "from patchwork import box_costs, curve_ranks, marker_counts\n", "\n", "boxes = {\n", " level: [patch.box for patch in mesh.patches_at_level(level)]\n", @@ -350,7 +290,7 @@ "cells = {\n", " level: [np.prod([hi - lo for lo, hi in b]) for b in boxes[level]] for level in boxes\n", "}\n", - "ranks = morton_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", + "ranks = curve_ranks(boxes, 4, load=[1024, 0, 0, 0]) # the base level on rank 0\n", "draw_ranks(ranks, f\"cells per rank: {per_rank(ranks, cells, 1024)}\")" ] }, @@ -358,15 +298,7 @@ "cell_type": "markdown", "id": "14", "metadata": {}, - "source": [ - "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\n", - "the markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\n", - "its cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\n", - "patch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n", - "`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\n", - "hierarchy again by them and moves the fields (send the markers after them with `migrate`).\n", - "The ranks with the beam now get fewer cells and about the same cost:" - ] + "source": "Equal cells are not equal work in a particle code: the ranks with the beam hold most of\nthe markers. With `cost`, `regrid(..., placement=\"morton\", cost=...)` weighs every patch by\nits cells plus the cost of its leaf cells (a cell's markers deposit and gather on the finest\npatch over it), here the counts of `marker_counts` at a tenth of a cell per marker.\n`box_costs` gives these weights, and `rebalance(cost)` places the patches of an existing\nhierarchy again by them and moves the fields (send the markers after them with `migrate`).\nThe ranks with the beam now get fewer cells and about the same cost:" }, { "cell_type": "code", @@ -378,7 +310,7 @@ "counts = marker_counts(mesh, x, y, levels=mesh.max_level + 1)\n", "cost = {level: 0.1 * found for level, found in counts.items()}\n", "weights, (base,) = box_costs(mesh, boxes, cost) # one rank here: the base's cost\n", - "weighted = morton_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", + "weighted = curve_ranks(boxes, 4, load=[base, 0, 0, 0], weights=weights)\n", "print(\"cells per rank:\", per_rank(weighted, cells, 1024))\n", "print(\"cost per rank, by cells: \", per_rank(ranks, weights, base))\n", "print(\"cost per rank, by markers: \", per_rank(weighted, weights, base))\n", @@ -389,23 +321,7 @@ "cell_type": "markdown", "id": "16", "metadata": {}, - "source": [ - "The few new blocks far from the beam come from the uniform background: its count per cell\n", - "fluctuates around `per_cell` there, so a block or two switches on or off. With fewer\n", - "markers per cell than `per_cell` in the background they would not appear.\n", - "\n", - "## Which one to use\n", - "\n", - "- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n", - " change slowly and the per-patch overhead matters.\n", - "- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n", - " and a regrid leaves most of them untouched: the choice when the tags change every few\n", - " steps, as with markers that move, and for spreading many equal patches over ranks\n", - " (`placement=\"balanced\"`).\n", - "\n", - "`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\n", - "many patches; large blocks give few patches and refine more cells." - ] + "source": "The few new blocks far from the beam come from the uniform background: its count per cell\nfluctuates around `per_cell` there, so a block or two switches on or off. With fewer\nmarkers per cell than `per_cell` in the background they would not appear.\n\n## Which one to use\n\n- `\"cluster\"` refines the fewest cells with the fewest patches: the choice when the tags\n change slowly and the per-patch overhead matters.\n- `\"quadtree\"` refines more cells, in more and smaller patches, but they are all of one size\n and a regrid leaves most of them untouched: the choice when the tags change every few\n steps, as with markers that move, and for spreading many equal patches over ranks\n (`placement=\"balanced\"`).\n\n`block_size` sets the balance: small blocks follow the tags as closely as clusters do, with\nmany patches; large blocks give few patches and refine more cells." } ], "metadata": {