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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- `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.
- 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
`marker_counts` times what a marker costs against a cell; `rebalance(cost)` places the
patches of a hierarchy again by them and moves the fields.
- The halo geometry of every patch (its copies and interpolation weights) is kept on the
hierarchy and handed on by `regrid`: a patch with the same box and ranks and the same
patches within reach of its halo reuses it instead of finding it again.
- 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
Expand Down
3 changes: 2 additions & 1 deletion benchmarks/quadtree/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ markers: tag (`marker_tags`), regrid, migrate, deposit, build the solver, solve,
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).
`placement="morton"`, by cells and weighted by the markers (`cost`, a marker costing a
tenth of a cell), without the solve, which the LU backend does not distribute.

```sh
python benchmarks/quadtree/run.py --out /tmp/quadtree # serial, with the solve
Expand Down
90 changes: 53 additions & 37 deletions benchmarks/quadtree/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,57 +4,73 @@
`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.
largest. "kept" is the share of the patches of a regrid that were there before it. "tag"
counts the markers on one level more than it tags, for the cost of `morton, markers`.

## Serial, with the solve

With the halo geometry of kept patches reused (patchwork 10c; the numbers in brackets are
the halos without it, from the first run of this benchmark).

| 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 |
| cluster | 8 | 27,864 | 0% | 106.2 | 10.7 | 20.3 | 55.6 | 113.7 | 5.9 | 8.1 (4.7) | 30.1 | 351 |
| cluster, `max_patch_size=16` | 134 | 27,864 | 2% | 101.5 | 85.5 | 38.7 | 130.8 | 124.3 | 12.5 | 120.7 (100.0) | 74.6 | 689 |
| quadtree, block 8 | 386 | 24,714 | 92% | 105.6 | 284.7 | 65.1 | 229.2 | 184.0 | 23.9 | 273.7 (295.5) | 134.7 | 1301 |
| quadtree, block 16 | 121 | 30,925 | 91% | 100.0 | 66.6 | 37.2 | 113.7 | 130.8 | 11.4 | 78.2 (94.5) | 68.2 | 606 |
| quadtree, block 32 | 49 | 50,330 | 94% | 102.1 | 30.4 | 29.4 | 84.9 | 199.4 | 12.1 | 28.4 (43.0) | 50.9 | 538 |

## 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 |
`morton, markers` weighs the Morton cuts by `cost`: the markers of `marker_counts`, a marker
costing a tenth of a cell.

| mesh | placement | cells imbalance | markers imbalance | tag | regrid | migrate | deposit | halos | gather | total |
|---|---|---|---|---|---|---|---|---|---|---|
| cluster | balanced | 2.18 | 3.04 | 45.5 | 8.0 | 10.6 | 59.7 | 5.5 | 19.2 | 149 |
| cluster | morton | 2.19 | 3.04 | 46.4 | 9.8 | 10.9 | 62.1 | 5.6 | 23.6 | 159 |
| cluster | morton, markers | 2.19 | 3.04 | 46.7 | 9.5 | 10.1 | 53.1 | 5.6 | 19.8 | 145 |
| cluster, `max_patch_size=16` | balanced | 1.01 | 1.36 | 41.2 | 52.9 | 18.3 | 62.8 | 124.3 | 17.4 | 317 |
| cluster, `max_patch_size=16` | morton | 1.01 | 1.35 | 41.9 | 49.9 | 20.8 | 61.4 | 110.7 | 18.9 | 303 |
| cluster, `max_patch_size=16` | morton, markers | 1.11 | 1.22 | 40.5 | 55.3 | 19.3 | 60.7 | 128.7 | 17.2 | 322 |
| quadtree, block 8 | balanced | 1.00 | 1.31 | 40.8 | 215.3 | 28.7 | 92.6 | 395.5 | 23.4 | 796 |
| quadtree, block 8 | morton | 1.00 | 1.26 | 46.4 | 199.5 | 29.9 | 89.4 | 267.4 | 26.6 | 659 |
| quadtree, block 8 | morton, markers | 1.09 | 1.16 | 46.2 | 220.1 | 31.7 | 90.8 | 297.3 | 29.7 | 716 |
| quadtree, block 16 | balanced | 1.02 | 1.28 | 44.4 | 62.6 | 20.8 | 69.0 | 131.4 | 18.4 | 347 |
| quadtree, block 16 | morton | 1.02 | 1.35 | 46.9 | 63.2 | 27.2 | 63.2 | 105.0 | 20.5 | 326 |
| quadtree, block 16 | morton, markers | 1.13 | 1.24 | 48.6 | 67.4 | 21.0 | 68.1 | 104.0 | 18.0 | 327 |
| quadtree, block 32 | balanced | 1.02 | 1.28 | 42.6 | 23.3 | 16.4 | 58.0 | 44.9 | 13.9 | 199 |
| quadtree, block 32 | morton | 1.02 | 1.55 | 44.6 | 21.3 | 17.0 | 61.3 | 51.5 | 16.4 | 212 |
| quadtree, block 32 | morton, markers | 1.18 | 1.41 | 46.7 | 26.6 | 19.3 | 57.9 | 40.3 | 16.3 | 207 |

Imbalance: the largest cells per rank over the mean (the base level counted).
Imbalance: the largest cells (base level counted) or markers (after `migrate`) per rank over
the mean.

## 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`).
deposit and gather grow with the patches: 8 clusters take 351 ms per step, 386 blocks of 8
cells 1301 ms. At about the same number of patches the quadtree is as fast as clusters
(block 16, 121 patches: 606 ms; clusters cut to 16 cells, 134 patches: 689 ms).
- **Reusing the halo geometry of kept patches saves 7-34% of the halos** (block 8: 296 →
274 ms, block 16: 95 → 78 ms, block 32: 43 → 28 ms). Not more, for two reasons: about
a third of the patches still find their geometry again (kept patches whose neighbours or
coarse patches changed, and new ones), and building the `mpiarray.CopyPlan` of the
exchange from the copies is now the largest part (about 100 of 250 ms at 386 patches:
per-copy Python and a pickled `allgather`), and it is built for every new hierarchy. Next:
a cheaper `CopyPlan` in mpiarray (patchwork 8k). The clusters gain nothing, their patches are
recut every regrid, and pay a few ms for checking the signatures (8 clusters: 4.7 → 8.1 ms).
- **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.
clusters need; the solver setup grows with them (199 ms against 114 ms).
- **Morton placement**: on one node within the noise of `balanced` for most meshes (about
10% between repeats); the halos of blocks of 8 are faster with it (267 against 396 ms),
where the patches are small and many.
- **Weighing the cuts by the markers** (`morton, markers`) lowers the marker imbalance (blocks
of 8: 1.26 → 1.16, 16: 1.35 → 1.24, 32: 1.55 → 1.41, clusters cut to 16: 1.35 → 1.22) for a
higher cell imbalance (1.09-1.18), as asked. The step time does not change measurably on
four ranks: with 200,000 markers the deposit and gather take 60-120 ms against the cells'
halos and regrid. It pays where the markers dominate (many markers per cell, the push of a
real simulation, many nodes). The 7 clusters cannot be balanced by any cut (2.2, 3.0).

## Fixed on the way

Expand Down
29 changes: 24 additions & 5 deletions benchmarks/quadtree/bench_quadtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

- ``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``);
and ``--placement`` (``balanced`` or ``morton``, with ``--marker-cost`` the Morton cuts
weighted by the markers: `marker_counts` times the cost of a marker against a cell);
- ``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,
Expand Down Expand Up @@ -33,7 +34,7 @@
import scope_profiler as sp
from maybempi import MPI

from patchwork import AMRHierarchy, NodalPoisson, marker_tags
from patchwork import AMRHierarchy, NodalPoisson, marker_counts, marker_tags


def beam(rng, count: int, width: float, centre: tuple[float, float]):
Expand Down Expand Up @@ -67,6 +68,12 @@ def main() -> None:
parser.add_argument(
"--placement", choices=["balanced", "morton"], default="balanced"
)
parser.add_argument(
"--marker-cost",
type=float,
default=0.0,
help="what a marker costs against a cell: weighs the Morton cuts (with morton)",
)
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)
Expand Down Expand Up @@ -109,21 +116,30 @@ def markers(step: int):
**options,
)

kept, patches, cells = [], [], []
kept, patches, cells, held = [], [], [], []
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)
counts = marker_counts(mesh, x, y, levels=args.levels + 1)
tags = {
level: counts[level] > args.per_cell for level in range(args.levels)
}
weigh = {}
if args.marker_cost and args.placement == "morton":
weigh["cost"] = {
level: args.marker_cost * found for level, found in counts.items()
}
with sp.region("quadtree_bench.regrid"):
mesh = mesh.regrid(tags, **options)
mesh = mesh.regrid(tags, **options, **weigh)
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")
held.append(comm.allgather(mx.size))
with sp.region("quadtree_bench.deposit"):
mesh.deposit(mx, my, mq, "rho")
mesh.accumulate_halos("rho")
Expand Down Expand Up @@ -155,6 +171,9 @@ def markers(step: int):
"refined_cells": float(np.mean(cells)),
"kept": float(np.mean(kept)),
"load_imbalance": max(load) / (sum(load) / len(load)),
"marker_imbalance": float(
np.mean([max(h) / (sum(h) / len(h)) for h in held])
),
}
)
)
Expand Down
20 changes: 16 additions & 4 deletions benchmarks/quadtree/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
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``.
the load imbalance (largest cells per rank over the mean) and the marker imbalance (largest
markers per rank over the mean, after `migrate`). ``morton, markers`` weighs the Morton cuts
with the markers, a marker costing a tenth of a cell. Profiles are written to ``--out``.
"""

from __future__ import annotations
Expand All @@ -26,6 +28,13 @@
PROFILER = Path(sys.executable).with_name("scope-profiler")
PARTS = ("tag", "regrid", "migrate", "deposit", "solver", "solve", "halos", "gather")

#: the placements compared under MPI, and their arguments
PLACEMENTS = {
"balanced": ["--placement", "balanced"],
"morton": ["--placement", "morton"],
"morton, markers": ["--placement", "morton", "--marker-cost", "0.1"],
}

#: (label, arguments) of the meshes compared
MESHES = [
("cluster", ["--method", "cluster"]),
Expand Down Expand Up @@ -81,7 +90,7 @@ def main() -> 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"]
list(PLACEMENTS) if args.ranks > 1 else ["balanced"]
)
extra = list(bench) + ([] if args.ranks == 1 else ["--no-solve"])

Expand All @@ -92,6 +101,7 @@ def main() -> None:
"refined",
"kept",
"imbalance",
"markers",
*PARTS,
"total",
]
Expand All @@ -101,10 +111,11 @@ def main() -> None:
for placement in placements:
runs = []
for repeat in range(args.repeats):
name = f"{label.replace(', ', '_').replace(' ', '')}_{placement}_{args.ranks}_{repeat}.h5"
name = f"{label}_{placement}_{args.ranks}_{repeat}".replace(", ", "_")
name = name.replace(" ", "") + ".h5"
runs.append(
run_once(
[*arguments, "--placement", placement, *extra],
[*arguments, *PLACEMENTS[placement], *extra],
args.ranks,
args.out / name,
)
Expand All @@ -120,6 +131,7 @@ def main() -> None:
f"{mesh['refined_cells']:.0f}",
f"{mesh['kept']:.0%}",
f"{mesh['load_imbalance']:.2f}",
f"{mesh['marker_imbalance']:.2f}",
*(f"{times[part]:.1f}" if times[part] else "-" for part in PARTS),
f"{total:.1f}",
]
Expand Down
4 changes: 4 additions & 0 deletions src/patchwork/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
FluxRegister,
IndexBox,
Patch,
box_costs,
cluster,
function_tags,
graded_nodes,
gradient_tags,
marker_counts,
marker_tags,
morton_ranks,
plot_patches,
Expand Down Expand Up @@ -87,10 +89,12 @@
"PetscSystem",
"__version__",
"cell_body",
"box_costs",
"cluster",
"function_tags",
"graded_nodes",
"gradient_tags",
"marker_counts",
"marker_tags",
"morton_ranks",
"plot_patches",
Expand Down
4 changes: 4 additions & 0 deletions src/patchwork/mesh/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
from patchwork.mesh.plotting import plot_patches
from patchwork.mesh.reflux import FluxRegister
from patchwork.mesh.regrid import (
box_costs,
cluster,
function_tags,
gradient_tags,
marker_counts,
marker_tags,
morton_ranks,
quadtree_boxes,
Expand All @@ -25,10 +27,12 @@
"FluxRegister",
"IndexBox",
"Patch",
"box_costs",
"cluster",
"function_tags",
"graded_nodes",
"gradient_tags",
"marker_counts",
"marker_tags",
"morton_ranks",
"plot_patches",
Expand Down
Loading