diff --git a/.github/workflows/pyodide.yml b/.github/workflows/pyodide.yml index 0098dd0..b4e4948 100644 --- a/.github/workflows/pyodide.yml +++ b/.github/workflows/pyodide.yml @@ -13,3 +13,6 @@ on: jobs: pyodide: uses: max-models/starlight-theme/.github/workflows/pyodide.yml@v0 + with: + # the Pyccel sources: compiled, never imported (the browser runs the NumPy kernels) + skip: '_pyccel$' diff --git a/CHANGELOG.md b/CHANGELOG.md index 94c24ce..3f5088c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,9 +13,12 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). the least loaded rank). `cost` may also map a patch `(level, box)` to a measured cost, which `deposit(..., times=...)` and `interpolate(..., times=...)` collect per patch; `rebalance(cost, placement=...)` places by any of them. -- The cloud-in-cell `deposit` and `interpolate` add the markers of all patches in one pass - (one `bincount` into a buffer of the blocks; higher B-spline degrees keep mpifield's kernels - per patch); a marker's owner comes from a table where its patch is on one rank; the halo +- `deposit` and `interpolate` add the markers of all patches in one pass into a buffer of the + blocks: cloud-in-cell by one `bincount`, the quadratic and cubic B-splines in one compiled + call (the new `scatter_blocks` and `gather_blocks` kernels, with mpifield's `spline_cell`; + 10-35% faster than mpifield's kernels patch by patch); other shapes keep their kernels per + patch. The `accumulate_halos` schedule is built from the nodes of all local patches at once + (68 to 11 ms on the quadtree benchmark's 8-cell blocks); a marker's owner comes from a table where its patch is on one rank; the halo signatures test all patches of a level at once. - `regrid(..., fields=[...])`: the fields whose values are moved (default: all); the others are allocated on the new hierarchy and zero. diff --git a/benchmarks/quadtree/RESULTS.md b/benchmarks/quadtree/RESULTS.md index 87925d2..317e9db 100644 --- a/benchmarks/quadtree/RESULTS.md +++ b/benchmarks/quadtree/RESULTS.md @@ -170,6 +170,36 @@ other at once. Serial, median of 3 runs, ms per step: neighbourhood changed, one per patch, and their copies), the regrid (94: the boxes and the new hierarchy) and the deposit (70, of which the `accumulate_halos` schedule ~35). +## Higher spline degrees and the accumulation schedule (2026-11-25, final) + +Serial, with the solve, 3 repeats each, `devel` against the branch that deposits and +gathers the quadratic and cubic B-splines of all patches in one compiled call +(`scatter_blocks`, `gather_blocks`) and builds the `accumulate_halos` schedule from the +nodes of all local patches at once (times in ms per step): + +| mesh | | deposit | solver | halos | gather | total | +|---|---|---|---|---|---|---| +| cluster | before | 27.4 | 111.8 | 6.6 | 24.3 | 225 | +| | after | 30.9 | 120.4 | 6.6 | 26.4 | 242 | +| cluster, `max_patch_size=16` | before | 41.4 | 119.4 | 84.5 | 26.8 | 351 | +| | after | 38.9 | 125.7 | 92.9 | 30.1 | 378 | +| quadtree, block 8 | before | 65.0 | 108.3 | 101.2 | 27.7 | 465 | +| | after | 48.2 | 108.5 | 109.1 | 27.7 | 460 | +| quadtree, block 16 | before | 39.2 | 128.2 | 39.9 | 25.7 | 307 | +| | after | 34.8 | 130.6 | 38.7 | 26.6 | 305 | +| quadtree, block 32 | before | 33.5 | 212.5 | 17.8 | 25.1 | 355 | +| | after | 34.5 | 217.5 | 16.7 | 26.7 | 363 | + +- The benchmark deposits cloud-in-cell, which keeps its `bincount` path; what changes there + is the accumulation schedule: the deposit of blocks of 8 goes from 65 to 48 ms (the + schedule from 68 to 11 ms when built alone). The other differences are noise: the solver + setup, which neither branch touches, differs by up to 8% between the runs. +- With the quadratic and cubic B-splines (one rank, the 386 blocks of 8, 200 000 markers), + one compiled call over all patches against mpifield's kernels patch by patch: deposit + 58 → 50 ms (degree 2) and 60 → 61 ms (degree 3), gather 74 → 49 and 57 → 51 ms. For + cloud-in-cell the compiled call lost to the `bincount` (gather 24 → 38 ms), so it is + used for degrees 2 and 3 only. + ## Fixed on the way The regrid's transfer compared every new patch with every old one of its level, and copied diff --git a/src/patchwork/kernels/gather_blocks/__init__.py b/src/patchwork/kernels/gather_blocks/__init__.py new file mode 100644 index 0000000..c1ff470 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/__init__.py @@ -0,0 +1,10 @@ +"""The gather_blocks kernel: Pyccel and NumPy versions with the same arguments. + +``kernel(...)`` runs the Pyccel version, or the NumPy version if Pyccel is unavailable +(see ``cunumpy.kernels.set_host_kernel_implementation`` to choose). +""" + +from patchwork.kernels import KERNEL_PACKAGE + +# host kernels only: no CUDA version, so CuPy arrays fall back to the host one +kernel = KERNEL_PACKAGE.from_folder(__name__, missing_cuda="fallback") diff --git a/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py b/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py new file mode 100644 index 0000000..8b25b43 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py @@ -0,0 +1,37 @@ +"""The NumPy version of the ``gather_blocks`` kernel, run when Pyccel is unavailable. + +Same arguments and arithmetic as ``gather_blocks_pyccel.py``, vectorized over the +markers with mpifield's NumPy ``spline_cell``. +""" + +from __future__ import annotations + +import itertools + +import numpy as np +from mpifield.kernels.spline_cell import spline_cell + + +def gather_blocks( + rel: np.ndarray, + count: np.ndarray, + stride: np.ndarray, + base: np.ndarray, + degree: int, + buffer: np.ndarray, + result: np.ndarray, +) -> None: + """Write the gathered values of the markers to ``result``.""" + axes = [] + for a in range(rel.shape[0]): + nodes, weights = spline_cell(rel[a], count[a], False, degree) + axes.append([(k * stride[a], w) for k, w in zip(nodes, weights, strict=True)]) + total = np.zeros(result.shape) + for parts in itertools.product(*axes): + where = base.copy() + weight = np.ones(result.shape) + for at, w in parts: + where += at + weight = weight * w + total += weight * buffer[where] + result[...] = total diff --git a/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py b/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py new file mode 100644 index 0000000..5a91335 --- /dev/null +++ b/src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py @@ -0,0 +1,53 @@ +"""B-spline gather of degree 0 to 3 from the blocks of many patches at once. + +The Pyccel version (CPU) of the ``gather_blocks`` kernel; ``gather_blocks_numpy.py`` +next to this file is the NumPy version, with the same arguments. Called by +`AMRHierarchy.interpolate`; the transpose of ``scatter_blocks`` (same stencils, see +there): ``result[i]`` is the weighted sum of the stencil nodes of marker ``i`` in the +flat ``buffer`` of the blocks. +""" + +import numpy as np +from mpifield.kernels.spline_cell_pyccel import spline_cell + + +def gather_blocks( + rel: "float[:,:]", + count: "int[:,:]", + stride: "int[:,:]", + base: "int[:]", + degree: int, + buffer: "float[:]", + result: "float[:]", +) -> None: + """Write the gathered values of the markers to ``result`` (see the module).""" + ndim = rel.shape[0] + node = np.zeros((3, 4), dtype=np.int64) + weight = np.zeros((3, 4), dtype=np.float64) + size = np.ones(3, dtype=np.int64) + for a in range(3): + node[a, 0] = 0 + weight[a, 0] = 1.0 + for a in range(ndim): + size[a] = degree + 1 + for i in range(rel.shape[1]): + for a in range(ndim): + spline_cell(rel[a, i], count[a, i], 0, degree, node[a, :], weight[a, :]) + total = 0.0 + for p in range(size[0]): + at_x = base[i] + node[0, p] * stride[0, i] + w_x = weight[0, p] + for q in range(size[1]): + at_y = at_x + w_y = w_x + if ndim > 1: + at_y = at_x + node[1, q] * stride[1, i] + w_y = w_x * weight[1, q] + for r in range(size[2]): + at = at_y + w = w_y + if ndim > 2: + at = at_y + node[2, r] * stride[2, i] + w = w_y * weight[2, r] + total += w * buffer[at] + result[i] = total diff --git a/src/patchwork/kernels/scatter_blocks/__init__.py b/src/patchwork/kernels/scatter_blocks/__init__.py new file mode 100644 index 0000000..4412bf5 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/__init__.py @@ -0,0 +1,10 @@ +"""The scatter_blocks kernel: Pyccel and NumPy versions with the same arguments. + +``kernel(...)`` runs the Pyccel version, or the NumPy version if Pyccel is unavailable +(see ``cunumpy.kernels.set_host_kernel_implementation`` to choose). +""" + +from patchwork.kernels import KERNEL_PACKAGE + +# host kernels only: no CUDA version, so CuPy arrays fall back to the host one +kernel = KERNEL_PACKAGE.from_folder(__name__, missing_cuda="fallback") diff --git a/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py b/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py new file mode 100644 index 0000000..e9c3e49 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py @@ -0,0 +1,35 @@ +"""The NumPy version of the ``scatter_blocks`` kernel, run when Pyccel is unavailable. + +Same arguments and arithmetic as ``scatter_blocks_pyccel.py``, vectorized over the +markers with mpifield's NumPy ``spline_cell``. +""" + +from __future__ import annotations + +import itertools + +import numpy as np +from mpifield.kernels.spline_cell import spline_cell + + +def scatter_blocks( + rel: np.ndarray, + count: np.ndarray, + stride: np.ndarray, + base: np.ndarray, + values: np.ndarray, + degree: int, + buffer: np.ndarray, +) -> None: + """Add the values of the markers to ``buffer``.""" + axes = [] + for a in range(rel.shape[0]): + nodes, weights = spline_cell(rel[a], count[a], False, degree) + axes.append([(k * stride[a], w) for k, w in zip(nodes, weights, strict=True)]) + for parts in itertools.product(*axes): + where = base.copy() + weight = values.copy() + for at, w in parts: + where += at + weight = weight * w + buffer += np.bincount(where, weights=weight, minlength=buffer.size) diff --git a/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py b/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py new file mode 100644 index 0000000..b1610c9 --- /dev/null +++ b/src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py @@ -0,0 +1,60 @@ +"""B-spline deposit of degree 0 to 3 of marker values into the blocks of many patches at once. + +The Pyccel version (CPU) of the ``scatter_blocks`` kernel; ``scatter_blocks_numpy.py`` +next to this file is the NumPy version, with the same arguments. Called by +`AMRHierarchy.deposit`. + +The blocks of the patches lie end to end in one flat ``buffer``. Marker ``i`` deposits +``values[i]`` onto the ``degree + 1`` nodes of its stencil along each of the ``ndim`` +axes (``rel.shape[0]``, 1 to 3), found by mpifield's ``spline_cell`` from ``rel[a, i]``, +its position in nodes from the first node of its block, on a bounded axis of +``count[a, i]`` nodes (a stencil node past the edge is the edge node). The node ``k`` +along axis ``a`` is at ``base[i] + sum_a k_a * stride[a, i]`` in the buffer. Serial: +the sums are in the order of the markers. +""" + +import numpy as np +from mpifield.kernels.spline_cell_pyccel import spline_cell + + +def scatter_blocks( + rel: "float[:,:]", + count: "int[:,:]", + stride: "int[:,:]", + base: "int[:]", + values: "float[:]", + degree: int, + buffer: "float[:]", +) -> None: + """Add the values of the markers to ``buffer`` (see the module).""" + ndim = rel.shape[0] + node = np.zeros((3, 4), dtype=np.int64) + weight = np.zeros((3, 4), dtype=np.float64) + size = np.ones(3, dtype=np.int64) + for a in range(3): + node[a, 0] = 0 + weight[a, 0] = 1.0 + for a in range(ndim): + size[a] = degree + 1 + for i in range(rel.shape[1]): + value = values[i] + if value == 0.0: + continue + for a in range(ndim): + spline_cell(rel[a, i], count[a, i], 0, degree, node[a, :], weight[a, :]) + for p in range(size[0]): + at_x = base[i] + node[0, p] * stride[0, i] + w_x = weight[0, p] * value + for q in range(size[1]): + at_y = at_x + w_y = w_x + if ndim > 1: + at_y = at_x + node[1, q] * stride[1, i] + w_y = w_x * weight[1, q] + for r in range(size[2]): + at = at_y + w = w_y + if ndim > 2: + at = at_y + node[2, r] * stride[2, i] + w = w_y * weight[2, r] + buffer[at] += w diff --git a/src/patchwork/mesh/accumulate.py b/src/patchwork/mesh/accumulate.py index cdae9a5..0a04148 100644 --- a/src/patchwork/mesh/accumulate.py +++ b/src/patchwork/mesh/accumulate.py @@ -96,25 +96,36 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: members, replicated = blocks[number] if len(members) == 1 and not replicated: single[number] = members[0][0] - # per local patch: the storage of the nodes that move, and where each goes + # per local patch: the storage of the nodes that move, and where each goes; + # the nodes of all local patches at once, then split by patch self._moves: list[dict[str, Any]] = [] - for number, patch in enumerate(patches): - if not patch.is_local: - continue - array = patch.field(name) - node = np.meshgrid( - *(np.arange(b0, b1) for b0, b1 in array.layout.index_bounds), - indexing="ij", + local = [(n, p) for n, p in enumerate(patches) if p.is_local] + arrays = [patch.field(name) for _, patch in local] + if local: + numbers = np.array([n for n, _ in local], dtype=np.int64) + first = np.array( + [[b0 for b0, _ in a.layout.index_bounds] for a in arrays], + dtype=np.int64, + ).reshape(len(local), ndim) + shape = np.array( + [[b1 - b0 for b0, b1 in a.layout.index_bounds] for a in arrays], + dtype=np.int64, + ).reshape(len(local), ndim) + sizes_local = np.prod(shape, axis=1).astype(np.intp) # np.repeat: intp + which = np.repeat(np.arange(len(local)), sizes_local) # local patch + rest = np.arange(which.size) - np.repeat( + np.cumsum(sizes_local) - sizes_local, sizes_local ) - index = [ - lower[number][axis] + node[axis] for axis in range(ndim) - ] # level indices - key = [ - (index[axis] * span[number]) % lattice[axis] - if periodic[axis] - else index[axis] * span[number] - for axis in range(ndim) - ] + node = [np.empty(0, dtype=np.int64)] * ndim # in the patch's indices + for axis in range(ndim - 1, -1, -1): + span_axis = shape[which, axis] + node[axis] = first[which, axis] + rest % span_axis + rest = rest // span_axis + number = numbers[which] + key = [] + for axis in range(ndim): + value = (lower[number, axis] + node[axis]) * span[number] + key.append(value % lattice[axis] if periodic[axis] else value) owner = table[tuple(key)].astype(np.int64) if (owner < 0).any(): raise RuntimeError( @@ -140,13 +151,12 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: moving = owner != number for axis in range(ndim): moving |= target[axis] != node[axis] - where = np.nonzero(moving) - owners = owner[where] - at = [values[where] for values in target] + chosen_all = np.flatnonzero(moving) + owners_all = owner[chosen_all] # an owner on one rank: that rank; else the rank whose block has the node - destination = single[owners] - several = np.flatnonzero(destination < 0) - for held, part in _by_patch(owners[several]): + destination_all = single[owners_all] + several = np.flatnonzero(destination_all < 0) + for held, part in _by_patch(owners_all[several]): chosen = several[part] members, replicated = blocks[held] if replicated: @@ -156,22 +166,29 @@ def __init__(self, hierarchy: AMRHierarchy, name: str) -> None: ) for rank, bounds in members: inside = np.ones(chosen.size, dtype=bool) - for values, (a0, a1) in zip(at, bounds, strict=True): - inside &= (values[chosen] >= a0) & (values[chosen] < a1) - destination[chosen[inside]] = rank - halo = array.layout.halo - self._moves.append( - { - "patch": number, - "array": array, - "storage": tuple( - values + h for values, h in zip(where, halo, strict=True) - ), - "destination": destination, - "owner": owners.astype(np.int64), - "node": tuple(values.astype(np.int64) for values in at), - } - ) + for axis, (a0, a1) in enumerate(bounds): + values = target[axis][chosen_all[chosen]] + inside &= (values >= a0) & (values < a1) + destination_all[chosen[inside]] = rank + bounds_of = np.searchsorted(which[chosen_all], np.arange(len(local) + 1)) + for k, ((patch_number, _), array) in enumerate( + zip(local, arrays, strict=True) + ): + part = chosen_all[bounds_of[k] : bounds_of[k + 1]] + halo = array.layout.halo + self._moves.append( + { + "patch": patch_number, + "array": array, + "storage": tuple( + node[axis][part] - first[k, axis] + halo[axis] + for axis in range(ndim) + ), + "destination": destination_all[bounds_of[k] : bounds_of[k + 1]], + "owner": owner[part], + "node": tuple(target[axis][part] for axis in range(ndim)), + } + ) # where the received charge goes: the block of every local patch, as the # offset from a node's index in the patch to its place in the storage self._local: dict[int, tuple[Any, tuple[int, ...]]] = {} diff --git a/src/patchwork/mesh/hierarchy.py b/src/patchwork/mesh/hierarchy.py index 6539818..16a9318 100644 --- a/src/patchwork/mesh/hierarchy.py +++ b/src/patchwork/mesh/hierarchy.py @@ -98,6 +98,13 @@ def _gather_blocks( _GATHER_TAG = 7311 +def _built_in(shape: Any) -> bool: + """Whether ``shape`` is one of mpifield's built-in splines (degree 1 to 3).""" + from mpifield.splines import SPLINES + + return any(shape is built for degree, built in SPLINES.items() if 1 <= degree <= 3) + + def _share_time( times: dict, patches: Sequence[Any], owner: Any, seconds: float ) -> None: @@ -1733,6 +1740,75 @@ def _linear_corners( corners.append((where, weight)) return inside, corners, blocks, offset + def _block_markers( + self, found: Any, wrapped: Any, name: str, degree: int + ) -> tuple[Any, Any, Any, Any, Any, list[tuple[int, int, Any]], int]: + """The markers of all patches, placed in one flat buffer of their patches' blocks. + + The stored blocks (`_stored_block`) of the patches with markers lie end to end + in one buffer. A marker's stencil is on the block of `_patch_block`: the stored + block for degree 1, without the halo nodes outside the patch for higher degrees + (where mpifield's ``spline_cell`` folds a stencil onto the edge nodes). Returns + the markers in the domain; per marker and axis its position in nodes from the + first node of that block, the block's nodes and the buffer stride; per marker the + buffer index of the block's first node; ``(patch number, offset, storage)`` per + block; and the buffer's size: the arguments of the ``scatter_blocks`` and + ``gather_blocks`` kernels. + """ + import numpy as np + + patches = self.patches + ndim = self.ndim + inside = np.flatnonzero(found >= 0) + numbers = np.flatnonzero(np.bincount(found[inside], minlength=len(patches))) + blocks = [] + offset = 0 + first = np.zeros((len(patches), ndim), dtype=np.int64) # level index + count = np.ones((len(patches), ndim), dtype=np.int64) + strides = np.zeros((len(patches), ndim), dtype=np.int64) + start = np.zeros(len(patches), dtype=np.int64) + scale = np.ones((len(patches), ndim)) + for number in numbers.tolist(): + patch = patches[number] + array = patch.field(name) + layout = array.layout + storage = array.local_with_halos + blocks.append((number, offset, storage)) + stride = 1 + for axis in range(ndim - 1, -1, -1): + strides[number, axis] = stride + stride *= storage.shape[axis] + begin = offset + for axis in range(ndim): + stored = layout.index_bounds[axis][0] - layout.halo[axis] + lower, upper = 0, storage.shape[axis] + if degree > 1: # the block of `_patch_block` + lower = max(0, -stored) + upper = min(upper, patch.node_shape[axis] - stored) + first[number, axis] = patch.box[axis][0] + stored + lower + count[number, axis] = upper - lower + begin += lower * strides[number, axis] + start[number] = begin + scale[number] = 1.0 / np.asarray(self.spacing(patch.level), dtype=float) + offset += storage.size + owner = found[inside] + origin = np.asarray(self.lower_bound, dtype=float) + rel = np.empty((ndim, inside.size)) + for axis in range(ndim): + rel[axis] = (np.asarray(wrapped[axis])[inside] - origin[axis]) * scale[ + owner, axis + ] - first[owner, axis] + return ( + inside, + rel, + # copies, not views: the transpose of one column has a stride Pyccel rejects + count[owner].T.copy(), + strides[owner].T.copy(), + start[owner], + blocks, + offset, + ) + def _shape(self, name: str, splines: Any, what: str) -> Any: """The `mpifield.Splines` of ``splines`` (a degree or one), checked against the halo.""" from mpifield import splines as resolve @@ -1781,9 +1857,11 @@ def deposit( bilinear (cloud-in-cell) weights: the same weights as `CompositeNodes.deposit`, whose transposed interpolation the field gather is, and of - `interpolate`. These weights are added for the markers of all patches at - once (one ``bincount`` into a buffer of the blocks); a higher degree runs - mpifield's compiled kernels patch by patch. The values are + `interpolate`. With mpifield's built-in splines the markers of all patches are + deposited at once into a buffer of the blocks: the cloud-in-cell weights by + one ``bincount``, degrees 2 and 3 in one compiled call (``scatter_blocks``, + with mpifield's ``spline_cell``); another shape runs its own kernels patch by + patch. The values are charges, not a density. The markers must be on the ranks that `owner` gives (use `migrate`), so that the corners fall in the block or its halo, and the field needs a halo of at least one node. @@ -1829,7 +1907,7 @@ def deposit( for patch in self.local_patches: patch.field(name).local_with_halos[...] = 0.0 patches = self.patches - if shape.degree == 1: # all patches in one pass over the markers + if _built_in(shape) and shape.degree == 1: # all patches in one pass begin = time.perf_counter() inside, corners, blocks, total = self._linear_corners( found, cell, wrapped, name @@ -1843,6 +1921,23 @@ def deposit( if times is not None: _share_time(times, patches, found[inside], time.perf_counter() - begin) return + if _built_in(shape): # all patches in one compiled call + from patchwork.kernels.scatter_blocks import kernel as scatter_blocks + + begin = time.perf_counter() + inside, rel, count, stride, base, blocks, total = self._block_markers( + found, wrapped, name, shape.degree + ) + buffer = np.zeros(total) + if inside.size: # Pyccel's slices refuse empty arrays + scatter_blocks( + rel, count, stride, base, charge[inside], shape.degree, buffer + ) + for _, offset, storage in blocks: + storage += buffer[offset : offset + storage.size].reshape(storage.shape) + if times is not None: + _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) @@ -1896,7 +1991,7 @@ def interpolate( ) values = np.zeros(flat[0].size) patches = self.patches - if weights.degree == 1: # all patches in one pass over the markers + if _built_in(weights) and weights.degree == 1: # all patches in one pass begin = time.perf_counter() inside, corners, blocks, total = self._linear_corners( found, cell, wrapped, name @@ -1911,6 +2006,25 @@ def interpolate( if times is not None: _share_time(times, patches, found[inside], time.perf_counter() - begin) return values.reshape(shape) + if _built_in(weights): # all patches in one compiled call + from patchwork.kernels.gather_blocks import kernel as gather_blocks + + begin = time.perf_counter() + inside, rel, count, stride, base, blocks, total = self._block_markers( + found, wrapped, name, weights.degree + ) + buffer = np.empty(total) + for _, offset, storage in blocks: + buffer[offset : offset + storage.size] = np.asarray(storage).reshape(-1) + gathered = np.zeros(inside.size) + if inside.size: # Pyccel's slices refuse empty arrays + gather_blocks( + rel, count, stride, base, weights.degree, buffer, gathered + ) + values[inside] = gathered + if times is not None: + _share_time(times, patches, found[inside], time.perf_counter() - begin) + return values.reshape(shape) for number, chosen in _by_patch(found): start = time.perf_counter() storage, grid = self._patch_block(patches[number], name, weights.degree) diff --git a/src/patchwork/tests/unit/test_markers.py b/src/patchwork/tests/unit/test_markers.py index 24c3ca1..2b55ccf 100644 --- a/src/patchwork/tests/unit/test_markers.py +++ b/src/patchwork/tests/unit/test_markers.py @@ -455,29 +455,30 @@ def test_the_node_grid_of_a_patch_holds_its_nodes() -> None: assert grid.geometry == (i0 * dx, j0 * dy, dx, dy, *patch.node_shape, 0, 0) +@pytest.mark.parametrize("degree", [1, 2, 3]) @pytest.mark.parametrize("periodic", [(False, False), (True, False)]) -def test_one_pass_linear_deposit_and_gather_equal_the_kernels_patch_by_patch( - periodic, +def test_one_pass_deposit_and_gather_equal_the_kernels_patch_by_patch( + periodic, degree ) -> None: from mpifield import splines mesh = AMRHierarchy(base_shape=(8, 8), periodic=periodic) mesh.add_patch(1, ((4, 12), (4, 12)), ranks=0) mesh.add_patch(2, ((10, 18), (8, 16)), ranks=0) - mesh.allocate_field("q", centering="node") + mesh.allocate_field("q", centering="node", halo=2) rng = np.random.default_rng(WORLD.Get_rank()) x, y = rng.uniform(0, 1, (2, 2000)) charge = rng.uniform(0.5, 1.5, x.size) x, y, charge = mesh.migrate(x, y, charge, name="q") - mesh.deposit(x, y, charge, "q") - gathered = mesh.interpolate(x, y, "q") + mesh.deposit(x, y, charge, "q", splines=degree) + gathered = mesh.interpolate(x, y, "q", splines=degree) # the same with mpifield's compiled kernels, one patch at a time - linear = splines(1) + linear = splines(degree) flat, _ = mesh._points((x, y)) found, _, wrapped = mesh._cells(flat) expected_gather = np.zeros(x.size) for patch in mesh.local_patches: - storage, grid = mesh._patch_block(patch, "q", 1) + storage, grid = mesh._patch_block(patch, "q", degree) reference = np.zeros_like(np.asarray(storage)) number = mesh.patches.index(patch) chosen = np.flatnonzero(found == number) @@ -492,3 +493,13 @@ def test_one_pass_linear_deposit_and_gather_equal_the_kernels_patch_by_patch( ) expected_gather[chosen] = result[0] np.testing.assert_allclose(gathered, expected_gather, rtol=1e-12, atol=1e-12) + + +@pytest.mark.parametrize("degree", [1, 2, 3]) +def test_a_rank_without_markers_deposits_and_gathers_nothing(degree) -> None: + mesh = AMRHierarchy(base_shape=(8, 8)) + mesh.allocate_field("q", centering="node", halo=2) + empty = np.zeros(0) + mesh.deposit(empty, empty, empty, "q", splines=degree) + assert mesh.interpolate(empty, empty, "q", splines=degree).size == 0 + assert all(not np.any(p.field("q").local) for p in mesh.local_patches) diff --git a/uv.lock b/uv.lock index dc660dd..7cd00a3 100644 --- a/uv.lock +++ b/uv.lock @@ -890,7 +890,7 @@ toml = [ [[package]] name = "cunumpy" version = "0.8.0" -source = { git = "https://github.com/max-models/cunumpy?branch=devel#a25c7b31072823d31e0815f65efa0daa1212a403" } +source = { git = "https://github.com/max-models/cunumpy?branch=devel#e18126964f48342bfbf9bd7764914aa19c7ecebe" } dependencies = [ { name = "array-api-compat" }, { name = "maybempi" }, @@ -2301,7 +2301,7 @@ wheels = [ [[package]] name = "mpiarray" version = "0.2.1" -source = { git = "https://github.com/max-models/mpiarray?branch=devel#7d3490a566ebbc2489c5172d5cd09282fae87efe" } +source = { git = "https://github.com/max-models/mpiarray?branch=devel#59884298fd49826a07f0d2321c8c85f93965f388" } dependencies = [ { name = "cunumpy" }, { name = "maybempi" },