Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
allowed cells. `quadtree_boxes` gives the boxes on their own. More cells are refined than
with clusters, but all patches have one size and a regrid keeps most of them. Tutorial
"Quadtree patches".
- `placement="morton"`: `regrid` puts the patches on the ranks along a Morton curve
(`morton_ranks`), all levels on one curve keyed in cells of the finest level, cut into runs
of about equal cells with the base level's cells counted.
- Benchmark `benchmarks/quadtree`: clusters against quadtree blocks in a particle-in-cell
cycle, serially and under MPI with both placements (`RESULTS.md`).
- `marker_tags(hierarchy, x, y, per_cell=..., levels=...)`: tag the cells that hold more than
`per_cell` markers, counted over all ranks.
- Graded axes: `AMRHierarchy(axis_nodes=...)` takes, per axis, `None` (uniform) or the
Expand Down
16 changes: 16 additions & 0 deletions benchmarks/quadtree/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Quadtree patches against clustered ones

`bench_quadtree.py` runs a particle-in-cell cycle on a mesh that follows a moving beam of
markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve, exchange
the halos and gather, each a scope-profiler region. `run.py` runs it for clustered patches
(`method="cluster"`, with and without `max_patch_size`) and quadtree blocks of 8, 16 and 32
cells, and prints a table; under MPI it compares `placement="balanced"` with
`placement="morton"` (without the solve, which the LU backend does not distribute).

```sh
python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve
python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid
python benchmarks/quadtree/run.py --out /tmp/quadtree --steps 40 --base 128 # any option of bench_quadtree.py
```

`RESULTS.md` has the numbers of the last run.
65 changes: 65 additions & 0 deletions benchmarks/quadtree/RESULTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Results

2026-11-25, a cloud container with 4 cores (Intel Xeon, 2.1 GHz), one thread per rank,
`bench_quadtree.py` defaults: a 64 x 64 base, 3 levels, 200,000 markers (four fifths in a
Gaussian beam of width 0.06 moving by 0.01 per step), `per_cell=20`, 20 timed steps. Times
are the median of 3 runs of the mean ms per step; under MPI on the rank where the part is
largest. "kept" is the share of the patches of a regrid that were there before it.

## Serial, with the solve

| mesh | patches | refined cells | kept | tag | regrid | migrate | deposit | solver | solve | halos | gather | total |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| cluster | 8 | 27,864 | 0% | 73.9 | 10.3 | 22.0 | 57.8 | 114.1 | 6.2 | 4.7 | 31.2 | 320 |
| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 73.2 | 98.6 | 43.6 | 132.7 | 133.8 | 13.1 | 100.0 | 78.2 | 673 |
| quadtree, block 8 | 386 | 24,714 | 92% | 70.6 | 277.0 | 64.9 | 231.4 | 179.7 | 23.4 | 295.5 | 131.4 | 1274 |
| quadtree, block 16 | 121 | 30,925 | 91% | 72.4 | 75.3 | 40.0 | 126.4 | 135.1 | 12.4 | 94.5 | 74.6 | 631 |
| quadtree, block 32 | 49 | 50,330 | 94% | 72.3 | 26.0 | 31.2 | 88.6 | 204.6 | 13.0 | 43.0 | 53.5 | 532 |

## 4 ranks, without the solve

| mesh | placement | imbalance | tag | regrid | migrate | deposit | halos | gather | total |
|---|---|---|---|---|---|---|---|---|---|
| cluster | balanced | 2.18 | 30.6 | 7.5 | 13.3 | 59.9 | 4.4 | 18.8 | 135 |
| cluster | morton | 2.19 | 32.0 | 7.6 | 12.4 | 57.5 | 4.8 | 23.0 | 137 |
| cluster, `max_patch_size=16` | balanced | 1.01 | 24.2 | 51.7 | 19.1 | 53.9 | 97.5 | 15.8 | 262 |
| cluster, `max_patch_size=16` | morton | 1.01 | 29.9 | 46.3 | 18.4 | 61.7 | 101.4 | 20.1 | 278 |
| quadtree, block 8 | balanced | 1.00 | 27.5 | 214.2 | 32.2 | 91.2 | 296.3 | 24.8 | 686 |
| quadtree, block 8 | morton | 1.00 | 30.7 | 189.0 | 30.9 | 95.9 | 273.5 | 25.3 | 645 |
| quadtree, block 16 | balanced | 1.02 | 24.6 | 39.4 | 17.8 | 60.5 | 96.6 | 16.6 | 256 |
| quadtree, block 16 | morton | 1.02 | 27.4 | 47.1 | 19.6 | 56.8 | 95.9 | 18.1 | 265 |
| quadtree, block 32 | balanced | 1.02 | 29.3 | 24.6 | 18.0 | 58.1 | 47.1 | 15.5 | 193 |
| quadtree, block 32 | morton | 1.02 | 25.5 | 17.3 | 14.5 | 49.7 | 36.3 | 15.2 | 158 |

Imbalance: the largest cells per rank over the mean (the base level counted).

## What they say

- **The cost follows the number of patches, not how they are placed.** Regrid, halos,
deposit and gather grow with the patches: 8 clusters take 320 ms per step, 386 blocks of 8
cells 1274 ms. At about the same number of patches the quadtree is as fast as clusters
(block 16, 121 patches: 631 ms; clusters cut to 16 cells, 134 patches: 673 ms), its
regrid a little faster since most of its patches are copied, not interpolated.
- **What the quadtree keeps is not reused yet.** 91-94% of its patches survive a regrid,
but the hierarchy is new, so the halo schedules (`build_schedule`, most of "halos"), the
composite node numbering and the solver are built again from scratch. Reusing them for
kept patches is where the quadtree could win; picnic's solver already reuses the grids and
probed operators of kept boxes (see picnic's `adaptive_rebuild_cost.py --method quadtree`).
- **Large blocks refine many cells**: blocks of 32 cover 50,330 cells for the 27,864 the
clusters need; the solver setup grows with them (205 ms against 114 ms).
- **Morton and balanced placement are within the noise on one node** (about 10% between
repeats). Morton keeps neighbouring patches and the patches over them on one rank, which
saves messages between nodes; within a node the messages are cheap and the halo time is
the schedule, built in Python. The few large clusters cannot be balanced by either (2.2).
- On four ranks tagging and gathering take about half as long as serially, but the deposit
does not get faster (58 ms serially, 50-96 ms on the slowest rank): the placements balance
cells, and the beam's patches hold most markers. Marker-weighted cuts of the Morton curve
are patchwork step 8e.

## Fixed on the way

The regrid's transfer compared every new patch with every old one of its level, and copied
the nodes a new patch shares with its old neighbours although an old patch with the same box
already had them. With the bin index of the halo schedules and without the copies that a
later one overwrites, the regrid of the 386-block mesh went from 866 ms to 277 ms per step
(serial), with the same values.
164 changes: 164 additions & 0 deletions benchmarks/quadtree/bench_quadtree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
r"""Quadtree patches against clustered ones in a particle-in-cell cycle.

A beam of markers (a Gaussian of width ``--width``, ``--markers`` of them, on a uniform
background) moves across the unit square on a ``--base`` x ``--base`` base, and every step

- ``tag``: `marker_tags` (more than ``--per-cell`` markers per cell, ``--levels`` levels);
- ``regrid``: `regrid` with ``--method`` (``cluster`` or ``quadtree`` with ``--block-size``)
and ``--placement`` (``balanced`` or ``morton``);
- ``migrate``, ``deposit``: the markers to their patches' ranks, cloud-in-cell deposit and
`accumulate_halos`;
- ``solver``, ``solve``: a new `NodalPoisson` on the new mesh and its solve (serial only,
or with ``--solve`` where the LU backend is enough);
- ``halos``: `exchange_halos` of the potential (or of the charge without a solve);
- ``gather``: `interpolate` at the markers.

Each part is a scope-profiler region (``quadtree_bench.<part>``); run with

scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py --method quadtree
mpiexec -n 4 scope-profiler run -o prof.h5 benchmarks/quadtree/bench_quadtree.py \\
--placement morton --no-solve

and read the times with ``scope-profiler inspect prof.h5 --sort total``. Rank 0 also prints
one JSON line with the mesh: patches, refined cells, the share of patches a regrid keeps,
and the cells per rank.
"""

from __future__ import annotations

import argparse
import json

import numpy as np
import scope_profiler as sp
from maybempi import MPI

from patchwork import AMRHierarchy, NodalPoisson, marker_tags


def beam(rng, count: int, width: float, centre: tuple[float, float]):
"""Markers of a Gaussian beam on a uniform background (a fifth of them), in the unit square."""
dense = count * 4 // 5
x = np.concatenate(
[rng.normal(centre[0], width, dense), rng.uniform(0, 1, count - dense)]
)
y = np.concatenate(
[rng.normal(centre[1], width, dense), rng.uniform(0, 1, count - dense)]
)
inside = (x > 0) & (x < 1) & (y > 0) & (y < 1)
return x[inside], y[inside]


def refined_cells(mesh) -> int:
"""The cells of the patches above the base level."""
return sum(
int(np.prod([hi - lo for lo, hi in patch.box]))
for patch in mesh.patches
if patch.level
)


def main() -> None:
"""Run the cycle and print the mesh of the run as one JSON line."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--method", choices=["cluster", "quadtree"], default="quadtree")
parser.add_argument("--block-size", type=int, default=16)
parser.add_argument("--max-patch-size", type=int, default=None)
parser.add_argument(
"--placement", choices=["balanced", "morton"], default="balanced"
)
parser.add_argument("--base", type=int, default=64)
parser.add_argument("--levels", type=int, default=3)
parser.add_argument("--markers", type=int, default=200_000)
parser.add_argument("--per-cell", type=float, default=20.0)
parser.add_argument("--width", type=float, default=0.06)
parser.add_argument("--steps", type=int, default=20)
parser.add_argument("--speed", type=float, default=0.01, help="beam shift per step")
parser.add_argument("--no-solve", dest="solve", action="store_false")
parser.add_argument("--seed", type=int, default=0)
args = parser.parse_args()

comm = MPI.COMM_WORLD
rank, size = comm.Get_rank(), comm.Get_size()
rng = np.random.default_rng(args.seed + rank)
options = (
{"method": "quadtree", "block_size": args.block_size}
if args.method == "quadtree"
else {"method": "cluster", "max_patch_size": args.max_patch_size}
)
mesh = AMRHierarchy(
base_shape=(args.base, args.base),
placement=args.placement,
comm=comm,
)
mesh.allocate_field("rho", centering="node")
if args.solve:
mesh.allocate_field("phi", centering="node")

def markers(step: int):
x, y = beam(
rng, args.markers // size, args.width, (0.25 + args.speed * step, 0.5)
)
return x, y, np.full(x.size, 1.0 / args.markers)

# build the levels on the first beam, one level per regrid, untimed
x, y, q = markers(0)
for _ in range(args.levels):
mesh = mesh.regrid(
marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels),
**options,
)

kept, patches, cells = [], [], []
previous = {(p.level, p.box) for p in mesh.patches if p.level}
for step in range(1, args.steps + 1):
x, y, q = markers(step)
with sp.region("quadtree_bench.tag"):
tags = marker_tags(mesh, x, y, per_cell=args.per_cell, levels=args.levels)
with sp.region("quadtree_bench.regrid"):
mesh = mesh.regrid(tags, **options)
boxes = {(p.level, p.box) for p in mesh.patches if p.level}
kept.append(len(boxes & previous) / max(len(boxes), 1))
previous = boxes
patches.append(len(boxes))
cells.append(refined_cells(mesh))
with sp.region("quadtree_bench.migrate"):
mx, my, mq = mesh.migrate(x, y, q, name="rho")
with sp.region("quadtree_bench.deposit"):
mesh.deposit(mx, my, mq, "rho")
mesh.accumulate_halos("rho")
field = "rho"
if args.solve:
with sp.region("quadtree_bench.solver"):
solver = NodalPoisson(mesh)
with sp.region("quadtree_bench.solve"):
density = solver.nodes.from_patches("rho") / solver.nodes.volumes
solver.solve(density, potential="phi")
field = "phi"
with sp.region("quadtree_bench.halos"):
mesh.exchange_halos(field)
with sp.region("quadtree_bench.gather"):
mesh.interpolate(mx, my, field)

load = mesh.cells_on_rank
if rank == 0:
print(
json.dumps(
{
"method": args.method,
"block_size": args.block_size
if args.method == "quadtree"
else None,
"placement": args.placement,
"ranks": size,
"patches": float(np.mean(patches)),
"refined_cells": float(np.mean(cells)),
"kept": float(np.mean(kept)),
"load_imbalance": max(load) / (sum(load) / len(load)),
}
)
)


if __name__ == "__main__":
main()
130 changes: 130 additions & 0 deletions benchmarks/quadtree/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Run `bench_quadtree.py` for several meshes and placements and print a table of the times.

python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve
python benchmarks/quadtree/run.py --out /tmp/quadtree --ranks 4 # halos, deposit, regrid

Every configuration runs ``--repeats`` times under ``scope-profiler run``; the table gives
the median over the repeats of the mean time per step of each region (ms; under MPI on the
rank where it is largest), and the mesh of
the JSON line of the run: patches, refined cells, the share of patches a regrid keeps and
the load imbalance (largest cells per rank over the mean). Profiles are written to ``--out``.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).parent
BENCH = HERE / "bench_quadtree.py"
PROFILER = Path(sys.executable).with_name("scope-profiler")
PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather")

#: (label, arguments) of the meshes compared
MESHES = [
("cluster", ["--method", "cluster"]),
("cluster, max 16", ["--method", "cluster", "--max-patch-size", "16"]),
("quadtree 8", ["--method", "quadtree", "--block-size", "8"]),
("quadtree 16", ["--method", "quadtree", "--block-size", "16"]),
("quadtree 32", ["--method", "quadtree", "--block-size", "32"]),
]


def run_once(arguments: list[str], ranks: int, output: Path) -> tuple[dict, dict]:
"""One profiled run: the JSON line of the mesh and the mean ms per step of each part."""
command = [str(PROFILER), "run", "-o", str(output), str(BENCH), *arguments]
if ranks > 1:
command = ["mpiexec", "-n", str(ranks), "--oversubscribe", *command]
env = os.environ | {
"OMPI_ALLOW_RUN_AS_ROOT": "1",
"OMPI_ALLOW_RUN_AS_ROOT_CONFIRM": "1",
"OMP_NUM_THREADS": "1",
}
result = subprocess.run(
command, capture_output=True, text=True, env=env, check=True
)
mesh = next(
json.loads(line)
for line in result.stdout.splitlines()
if line.startswith("{") and '"method"' in line
)
times: dict[str, float] = {}
for rank in range(ranks): # the slowest rank's mean per step of each part
inspected = subprocess.run(
[str(PROFILER), "inspect", str(output), "--json", "--top", "50"]
+ (["--ranks", str(rank)] if ranks > 1 else []),
capture_output=True,
text=True,
check=True,
)
for region in json.loads(inspected.stdout)["regions"]["items"]:
name = region["name"]
if name.startswith("quadtree_bench."):
part = name.split(".", 1)[1]
times[part] = max(times.get(part, 0.0), 1e3 * region["avg"])
return mesh, times


def main() -> None:
"""Run every configuration and print the table."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--ranks", type=int, default=1)
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--placements", nargs="+", default=None)
args, bench = parser.parse_known_args()
args.out.mkdir(parents=True, exist_ok=True)
placements = args.placements or (
["balanced", "morton"] if args.ranks > 1 else ["balanced"]
)
extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"])

header = [
"mesh",
"placement",
"patches",
"refined",
"kept",
"imbalance",
*PARTS,
"total",
]
print("| " + " | ".join(header) + " |")
print("|" + "---|" * len(header))
for label, arguments in MESHES:
for placement in placements:
runs = []
for repeat in range(args.repeats):
name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5"
runs.append(
run_once(
[*arguments, "--placement", placement, *extra],
args.ranks,
args.out / name,
)
)
mesh = runs[0][0]
times = {
part: float(np.median([t.get(part, 0.0) for _, t in runs]))
for part in PARTS
}
total = sum(times.values())
cells = [
f"{mesh['patches']:.0f}",
f"{mesh['refined_cells']:.0f}",
f"{mesh['kept']:.0%}",
f"{mesh['load_imbalance']:.2f}",
*(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS),
f"{total:.1f}",
]
print(f"| {label} | {placement} | " + " | ".join(cells) + " |", flush=True)


if __name__ == "__main__":
main()
Loading