Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
789c5ca
Quadtree regridding: patches as the blocks of a balanced quadtree, an…
max-models Nov 25, 2026
b7b1d5b
docs: README.md as quarto renders it.
max-models Nov 25, 2026
e74d2d8
feat: Morton placement, a cheaper regrid transfer, and the quadtree b…
max-models Nov 25, 2026
5666903
Docstrings of the quadtree benchmark.
max-models Nov 25, 2026
8ae5cdc
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
7e60256
Morton placement over all levels, with the base level's load counted.
max-models Nov 25, 2026
6ad46a7
Quadtree benchmark results, Morton placement in the tutorial and the …
max-models Nov 25, 2026
dc62af1
feat: reuse the halo geometry of kept patches, and Morton cuts weight…
max-models Nov 25, 2026
8e21a5e
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
6638fee
feat: rebalance by cost, and the benchmark of halo reuse and marker-w…
max-models Nov 25, 2026
82ff47a
perf: markers grouped by patch with one sort, and marker counts from …
max-models Nov 25, 2026
478050a
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
74312f8
Benchmark warm-up, and the per-patch costs before and after.
max-models Nov 25, 2026
f5ed73c
perf: coverage per level for the node numbering, halo copies per pair…
max-models Nov 25, 2026
ff1a0b6
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
8ac2cc8
Results of the node numbering, accumulation and fields changes.
max-models Nov 25, 2026
44b2d18
feat: Hilbert placement, knapsack with cost, measured costs per patch.
max-models Nov 25, 2026
4f3b1bd
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
d718326
perf: linear deposit and gather over all patches at once, owners by t…
max-models Nov 25, 2026
9a9708d
Results of the last per-patch changes, and the changelog.
max-models Nov 25, 2026
9416ba5
Types for pyright.
max-models Nov 25, 2026
cd0b5ff
perf: deposit and gather of every built-in spline degree over all pat…
max-models Nov 25, 2026
73545e1
Merge the merged branch (its changes are in devel).
max-models Nov 25, 2026
c1c3eeb
Skip the block kernels on a rank without markers.
max-models Nov 25, 2026
f8e9d57
perf: the accumulation schedule from the nodes of all local patches a…
max-models Nov 25, 2026
6bf4f9f
perf: cloud-in-cell deposit and gather by bincount again, the compile…
max-models Nov 25, 2026
aaf96f0
Changelog: block kernels for degrees 2 and 3, vectorized accumulation…
max-models Nov 25, 2026
bdb3d23
Benchmark results of the block kernels and the accumulation schedule.
max-models Nov 25, 2026
98faeee
Pyodide: repeat counts as intp, and the Pyccel sources not imported.
max-models Nov 25, 2026
e0e4d0d
Lock cunumpy and mpiarray at their current devel.
max-models Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/pyodide.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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$'
9 changes: 6 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 30 additions & 0 deletions benchmarks/quadtree/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/patchwork/kernels/gather_blocks/__init__.py
Original file line number Diff line number Diff line change
@@ -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")
37 changes: 37 additions & 0 deletions src/patchwork/kernels/gather_blocks/gather_blocks_numpy.py
Original file line number Diff line number Diff line change
@@ -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
53 changes: 53 additions & 0 deletions src/patchwork/kernels/gather_blocks/gather_blocks_pyccel.py
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions src/patchwork/kernels/scatter_blocks/__init__.py
Original file line number Diff line number Diff line change
@@ -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")
35 changes: 35 additions & 0 deletions src/patchwork/kernels/scatter_blocks/scatter_blocks_numpy.py
Original file line number Diff line number Diff line change
@@ -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)
60 changes: 60 additions & 0 deletions src/patchwork/kernels/scatter_blocks/scatter_blocks_pyccel.py
Original file line number Diff line number Diff line change
@@ -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
95 changes: 56 additions & 39 deletions src/patchwork/mesh/accumulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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:
Expand All @@ -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, ...]]] = {}
Expand Down
Loading
Loading