diff --git a/CHANGELOG.md b/CHANGELOG.md index 658b7eb..c90a4d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- `regrid(..., fields=[...])`: the fields whose values are moved (default: all); the others + are allocated on the new hierarchy and zero. +- `CompositeNodes` finds the cells under finer patches from one coverage mask per level (it + compared every patch with every patch of the next level); the `accumulate_halos` schedule + takes the rank of a node's owner from a table; halo copies between two patches are kept + per pair across regrids; `in_domain` is a bounds check where the domain fills its box. - `deposit`, `interpolate`, `owner` and `migrate` group the markers by patch with one sort instead of a scan of all markers per patch, and `marker_counts` histograms only the finest level and sums it into the coarser ones: the quadtree benchmark's cycle 20-27% faster diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 12f7cf8..136aabe 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -105,6 +105,37 @@ Serial, median of 3 runs, ms per step: setup (183, mostly the composite node numbering) and the deposit (140, of which ~65 the schedule of `accumulate_halos`, built per hierarchy like the halos'). +## Node numbering, accumulation, halo pairs and `regrid(fields=...)` (2026-11-25, later) + +Against `devel` after the changes above. `CompositeNodes` finds the cells under finer +patches from one coverage mask per level instead of every patch against every patch of the +next level; the schedule of `accumulate_halos` takes the rank of a node's owner from a table +where the owner is on one rank; the halo copies between two patches of a level are kept per +pair; `in_domain` is a bounds check where the domain fills its box; and `regrid` takes +`fields`, the fields to move (the others are new and zero). Serial, median of 3 runs, ms per +step, total: + +| mesh | devel (all fields moved) | this, all fields moved | this, `fields=[]` | +|---|---|---|---| +| cluster | 241 | 245 | 225 (−7%) | +| cluster, `max_patch_size=16` | 496 | 495 | 430 (−13%) | +| quadtree, block 8 | 938 | 837 (−11%) | 632 (−33%) | +| quadtree, block 16 | 474 | 455 (−4%) | 388 (−18%) | +| quadtree, block 32 | 427 | 442 (within the noise) | 401 (−6%) | + +- With many patches the node numbering was quadratic: blocks of 8, solver setup 180 → + 111 ms (the numbering itself 143 → 24 ms); the rest of the setup is the assembly and the + LU factorisation, which do not depend on the patches. +- The deposit's accumulation schedule: 141 → 112 ms with blocks of 8. +- Not moving the fields that are computed again after the regrid (the charge, deposited; + the potential, solved for) leaves the regrid with the boxes and the new hierarchy: + blocks of 8, 253 → 84 ms; clusters, 14 → 3 ms. +- The halos did not get faster from the pair cache (195 → 186 ms with blocks of 8, within + the noise): what is left of their schedule is the `CopyPlan` (~65 ms), the coarse-to-fine + interpolation of the patches whose neighbourhood changed (~35 ms) and the signatures + (~33 ms). The next step there: keep the `CopyPlan` of the kept patches, or set up the + interpolation of all patches at once. + ## Fixed on the way The regrid's transfer compared every new patch with every old one of its level, and copied diff --git a/benchmarks/quadtree/bench_quadtree.py b/benchmarks/quadtree/bench_quadtree.py index 789696c..c94e3a0 100644 --- a/benchmarks/quadtree/bench_quadtree.py +++ b/benchmarks/quadtree/bench_quadtree.py @@ -82,6 +82,11 @@ def main() -> None: parser.add_argument("--steps", type=int, default=20) parser.add_argument("--speed", type=float, default=0.01, help="beam shift per step") parser.add_argument("--no-solve", dest="solve", action="store_false") + parser.add_argument( + "--move-fields", + action="store_true", + help="move the fields at every regrid (default: none, they are recomputed)", + ) parser.add_argument("--seed", type=int, default=0) args = parser.parse_args() @@ -93,6 +98,10 @@ def main() -> None: if args.method == "quadtree" else {"method": "cluster", "max_patch_size": args.max_patch_size} ) + if ( + not args.move_fields + ): # the charge is deposited again and the potential solved for + options["fields"] = [] mesh = AMRHierarchy( base_shape=(args.base, args.base), placement=args.placement, diff --git a/src/patchwork/mesh/accumulate.py b/src/patchwork/mesh/accumulate.py index 93cc9c9..cdae9a5 100644 --- a/src/patchwork/mesh/accumulate.py +++ b/src/patchwork/mesh/accumulate.py @@ -87,9 +87,15 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: axes.append(index % lattice[axis] if periodic[axis] else index) table[np.ix_(*axes)] = number - from patchwork.mesh.hierarchy import _gather_blocks + from patchwork.mesh.hierarchy import _by_patch, _gather_blocks blocks = hierarchy._schedule("blocks", name, _gather_blocks) + # the rank of every patch held by one rank (-1 for several) + single = np.full(len(patches), -1, dtype=np.int64) + for number in range(len(patches)): + members, replicated = blocks[number] + if len(members) == 1 and not replicated: + single[number] = members[0][0] # per local patch: the storage of the nodes that move, and where each goes self._moves: list[dict[str, Any]] = [] for number, patch in enumerate(patches): @@ -137,15 +143,17 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: where = np.nonzero(moving) owners = owner[where] at = [values[where] for values in target] - destination = np.empty(owners.size, dtype=np.int64) - for held in np.unique(owners): - members, replicated = blocks[int(held)] + # an owner on one rank: that rank; else the rank whose block has the node + destination = single[owners] + several = np.flatnonzero(destination < 0) + for held, part in _by_patch(owners[several]): + chosen = several[part] + members, replicated = blocks[held] if replicated: raise ValueError( f"field {name!r} is replicated (split=None) on the several ranks " f"of a patch: allocate it with split=0 to accumulate" ) - chosen = np.flatnonzero(owners == held) for rank, bounds in members: inside = np.ones(chosen.size, dtype=bool) for values, (a0, a1) in zip(at, bounds, strict=True): diff --git a/src/patchwork/mesh/halos.py b/src/patchwork/mesh/halos.py index 2ee124a..193da3a 100644 --- a/src/patchwork/mesh/halos.py +++ b/src/patchwork/mesh/halos.py @@ -120,6 +120,7 @@ def __init__(self, hierarchy: AMRHierarchy, nodal: bool) -> None: self.ratio = hierarchy.refinement_ratio self.periodic = hierarchy.periodic self._domains: dict[int, np.ndarray] = {} + self._wholes: dict[int, bool] = {} self._indices: dict[int, tuple[tuple[Patch, ...], _BoxIndex]] = {} def own(self, patch: Patch) -> Box: @@ -164,6 +165,12 @@ def _domain(self, level: int) -> np.ndarray: self._domains[level] = cells return self._domains[level] + def _whole(self, level: int) -> bool: + """Whether the domain fills the box of the level (no notch).""" + if level not in self._wholes: + self._wholes[level] = bool(self._domain(level).all()) + return self._wholes[level] + def in_domain(self, level: int, *index: np.ndarray) -> np.ndarray: """Whether points (level indices, possibly beyond the domain) are in it. @@ -172,6 +179,13 @@ def in_domain(self, level: int, *index: np.ndarray) -> np.ndarray: """ cells = self._domain(level) shape = cells.shape + if self._whole(level): # the domain fills its box: a bounds check + inside = np.ones(index[0].shape, dtype=bool) + top = 1 if self.nodal else 0 + for axis, values in enumerate(index): + if not self.periodic[axis]: + inside &= (values >= 0) & (values < shape[axis] + top) + return inside offsets = ( itertools.product((0, -1), repeat=len(index)) if self.nodal @@ -569,18 +583,25 @@ def _field(self, patch: Patch) -> Any: def _coarse_field(self, patch: Patch) -> Any: return patch.field(self._below) if patch.is_local else None - def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray: - """Copies from the patches of the same level; the halo points they cover.""" - own = points.own(patch) - width = self._width - extended = tuple((lo - width, hi + width) for lo, hi in own) - covered = np.zeros([hi - lo for lo, hi in extended], dtype=bool) - covered[(slice(width, -width),) * len(own)] = True - origin = tuple(lo for lo, _ in own) - for other in points.near(patch.level, extended): + def _pair( + self, points: _Points, patch: Patch, other: Patch, extended: Box + ) -> list[tuple]: + """The copies from ``other`` into the halo of ``patch`` (same level), found once. + + ``(source box, target box, covered slices)`` for every part, across periodic + faces too. They depend on the two boxes only, so they are kept by the pair + on the hierarchy and handed on by `AMRHierarchy.regrid`. + """ + key = (patch.level, patch.box, other.box) + found = self._pairs_known.get(key) + if found is None: + own = points.own(patch) + width = self._width + origin = tuple(lo for lo, _ in own) other_origin = tuple(lo for lo, _ in points.own(other)) + found = [] for shift in points.shifts(patch.level): - if other is patch and not any(shift): + if other.box == patch.box and not any(shift): continue theirs = _shift(points.own(other), shift) for frame in _frame(own, width): @@ -592,15 +613,25 @@ def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray tuple(-d - o for d, o in zip(shift, other_origin, strict=True)), ) target = _shift(part, tuple(-o for o in origin)) - copies.append( - (self._field(other), source, self._field(patch), target) + cover = tuple( + slice(s - e0, t - e0) + for (s, t), (e0, _) in zip(part, extended, strict=True) ) - covered[ - tuple( - slice(s - e0, t - e0) - for (s, t), (e0, _) in zip(part, extended, strict=True) - ) - ] = True + found.append((source, target, cover)) + self._pairs_used[key] = found + return found + + def _same_level(self, points: _Points, patch: Patch, copies: list) -> np.ndarray: + """Copies from the patches of the same level; the halo points they cover.""" + own = points.own(patch) + width = self._width + extended = tuple((lo - width, hi + width) for lo, hi in own) + covered = np.zeros([hi - lo for lo, hi in extended], dtype=bool) + covered[(slice(width, -width),) * len(own)] = True + for other in points.near(patch.level, extended): + for source, target, cover in self._pair(points, patch, other, extended): + copies.append((self._field(other), source, self._field(patch), target)) + covered[cover] = True return covered def _coarse_fine( @@ -770,6 +801,8 @@ def __init__( dtype = spec["dtype"] kind = ("halo", nodal, self._width, np.dtype(dtype).str, repr(spec["split"])) known = hierarchy._halo_records.get(kind, {}) + self._pairs_known = hierarchy._halo_records.get(("pairs", *kind), {}) + self._pairs_used: dict[tuple, list] = {} used: dict[tuple, _HaloRecord] = {} patches = {_key(patch): patch for patch in hierarchy.patches} for patch in hierarchy.patches if self._width else (): @@ -783,6 +816,11 @@ def __init__( self._bind(record, patch, patches, dtype) # keep the records of this mesh (all of them after a full build) hierarchy._halo_records[kind] = used if level is None else {**known, **used} + pairs = self._pairs_used + if level is not None: + pairs = {**self._pairs_known, **pairs} + hierarchy._halo_records[("pairs", *kind)] = pairs + del self._pairs_known, self._pairs_used self._plan = mpa.CopyPlan(self._copies, comm=hierarchy.comm) del self._copies diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 1a666f9..30ed0e3 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -997,6 +997,7 @@ def _rebuilt( placement: Any, cost: Mapping[int, Any] | None, fill_halos: bool, + fields: Sequence[str] | None = None, ) -> AMRHierarchy: """A hierarchy with this base and the refined ``boxes``, with the fields moved over.""" from patchwork.mesh.regrid import transfer @@ -1038,10 +1039,16 @@ def _rebuilt( for level in sorted(boxes): for box in sorted(boxes[level], key=lambda b: -_shared_cells(b, b)): new.add_patch(level, box) + moved = set(self._field_specs if fields is None else fields) + unknown = moved - set(self._field_specs) + if unknown: + raise KeyError(f"hierarchy has no field {sorted(unknown)[0]!r}") for name, spec in self._field_specs.items(): + new.allocate_field(name, **spec) + if name not in moved: + continue # allocated, zero if spec["conservative"]: self.restrict(name) - new.allocate_field(name, **spec) transfer(self, new, name) if fill_halos: for name in new.field_names: @@ -1085,6 +1092,7 @@ def regrid( placement: str | Callable[[int, IndexBox], Any] | None = None, cost: Mapping[int, Any] | None = None, fill_halos: bool = False, + fields: Sequence[str] | None = None, ) -> AMRHierarchy: """A new hierarchy with patches over the tagged cells, and the fields moved to it. @@ -1120,7 +1128,11 @@ def regrid( fine cells of a coarse cell keep its mean: its `integral` is the same before and after. Halos are not filled unless ``fill_halos`` (then `exchange_halos` runs for every field of the new - hierarchy). + hierarchy). ``fields`` names the fields whose values are moved + (default: all); the others are allocated on the new hierarchy and + zero, which saves the transfer of a field that is computed again + right after the regrid, such as a charge deposited from the markers + or a potential solved for. ``min_patch_size`` is the shortest side a patch may have, in cells of its own level (rounded up to whole cells of the level below): a patch @@ -1178,7 +1190,7 @@ def regrid( min_patch_size=min_patch_size, forbid=forbid, ) - return self._rebuilt(boxes, placement, cost, fill_halos) + return self._rebuilt(boxes, placement, cost, fill_halos, fields) @sp.profile("patchwork.rebalance", tags=PROFILE_TAGS) def rebalance( diff --git a/src/patchwork/spaces/nodes.py b/src/patchwork/spaces/nodes.py index d998f23..ea3ff64 100644 --- a/src/patchwork/spaces/nodes.py +++ b/src/patchwork/spaces/nodes.py @@ -370,20 +370,24 @@ def __init__(self, hierarchy: AMRHierarchy) -> None: self._spacing = np.asarray(hierarchy.spacing(finest), dtype=float) self._origin = np.asarray(hierarchy.lower_bound, dtype=float) + # the cells of every level under a finer patch (one may lie over several patches) + under = {} + for level in range(finest): + mask = np.zeros(hierarchy.level_shape(level), dtype=bool) + for child in hierarchy.patches_at_level(level + 1): + mask[tuple(slice(c0 // ratio, c1 // ratio) for c0, c1 in child.box)] = ( + True + ) + under[level] = mask lowers, spans, owners = [], [], [] for patch in hierarchy.patches: span = ratio ** (finest - patch.level) - covered = np.zeros(patch.shape, dtype=bool) - for child in hierarchy.patches_at_level(patch.level + 1): - # a finer patch may lie over several patches of this level - covered[ - tuple( - slice( - max(c0 // ratio, i0) - i0, max(min(c1 // ratio, i1) - i0, 0) - ) - for (c0, c1), (i0, i1) in zip(child.box, patch.box, strict=True) - ) - ] = True + if patch.level in under: + covered = under[patch.level][ + tuple(slice(i0, i1) for i0, i1 in patch.box) + ] + else: + covered = np.zeros(patch.shape, dtype=bool) index = np.nonzero(~covered) lowers.append( np.column_stack( diff --git a/src/patchwork/tests/unit/test_quadtree.py b/src/patchwork/tests/unit/test_quadtree.py index 95c9d33..61ad51b 100644 --- a/src/patchwork/tests/unit/test_quadtree.py +++ b/src/patchwork/tests/unit/test_quadtree.py @@ -462,3 +462,24 @@ def test_marker_counts_of_every_level_are_its_own_histogram(graded) -> None: edges = [mesh.node_positions(level, a) for a in range(2)] expected, _ = np.histogramdd(np.stack([x, y]).T, bins=edges) np.testing.assert_array_equal(found, WORLD.allreduce(expected)) + + +def test_regrid_moves_only_the_fields_asked_for() -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + mesh.allocate_field("u", centering="node") + mesh.allocate_field("rho", conservative=True) + for patch in mesh.local_patches: + patch.field("u").local[...] = 1.0 + patch.field("rho").local[...] = 2.0 + tags = function_tags(mesh, lambda x, y: x < 0.5, levels=1) + moved = mesh.regrid(tags, fields=["u"]) + assert moved.field_names == mesh.field_names + for patch in moved.local_patches: + assert np.all(patch.field("u").local == 1.0) + assert not np.any(patch.field("rho").local) + assert all( + np.all(p.field("rho").local == 2.0) + for p in mesh.regrid(tags, fields=None).local_patches + ) + with pytest.raises(KeyError, match="phi"): + mesh.regrid(tags, fields=["phi"])