diff --git a/README.md b/README.md index 790a43d8f..5a1d1c009 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ This repository is the single home for PyAutoLens performance measurement. It ex **What is profiled:** - **Likelihood functions** — imaging, interferometer, point-source, and datacube paths, across the MGE, pixelization, and Delaunay model compositions used in real science cases. +- **Mesh kernels** — full mapper-table profiling for Delaunay and Sibson natural-neighbour `DelaunayNN`, including static-cap scaling and split regularization. - **Simulators** — run-time tracking for the imaging, interferometer, point-source, cluster, group, and multi-plane simulators. - **Searches / samplers** — sampler-level profiling, starting with Nautilus. Other samplers (Dynesty, Emcee, BlackJAX, NumPyro, LBFGS, PocoMC) follow in later sweeps. @@ -136,6 +137,7 @@ auto-tables) live under `scripts/misc//`; dataset-agnostic tooling lives u | `quick_update/` · [README](./scripts/misc/quick_update/README.md) | Fast incremental re-profiling helpers. | | [`scripts/misc/jax_compile/`](./scripts/misc/jax_compile/README.md) | JAX/XLA **compile-time** profiling — trace / compile / first-call / steady split per likelihood × transform. *How long before this fit starts running?* | | [`scripts/misc/vram/`](./scripts/misc/vram/README.md) | GPU memory profiling + the per-cell vmap batch-size table for the A100. | +| [`scripts/misc/delaunay_nn/`](./scripts/misc/delaunay_nn/README.md) | DelaunayNN full-mapper runtime and fixed-shape cap scaling. | | [`scripts/misc/simulators/`](./scripts/misc/simulators/README.md) | Run-time tracking for the PyAutoLens simulators. | | [`scripts/misc/pipeline_resume/`](./scripts/misc/pipeline_resume/README.md) | SLaM pipeline resume overhead — the wall time a re-run pays per completed stage. | | [`instruments/`](./instruments/README.md) | Instrument presets (pixel scale, shape) that frame every result. | diff --git a/results/README.md b/results/README.md index 8d28d35b7..f9523dafc 100644 --- a/results/README.md +++ b/results/README.md @@ -14,6 +14,7 @@ packages; the dashboard tables in every README are rendered from this tree by | `searches/` | [`searches/`](../scripts/misc/searches/README.md) | Versioned sampler profiling summaries | | `pipeline_resume/` | [`pipeline_resume/`](../scripts/misc/pipeline_resume/README.md) | Versioned SLaM resume-overhead summaries (cold + resume run records) | | `quick_update/` | [`quick_update/`](../scripts/misc/quick_update/README.md) | Unversioned fast re-profiling snapshots (scratch tier) | +| `delaunay_nn/` | [`delaunay_nn/`](../scripts/misc/delaunay_nn/README.md) | Versioned full-mapper cap and runtime benchmarks | | `notes/` | humans + agents | Narrative findings and design notes (e.g. [`design_lock_in.md`](./notes/design_lock_in.md)) | | `baselines/` | campaign snapshots | Named, frozen baselines (e.g. `PreOptimizationTimes/`) — see below | diff --git a/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.json b/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.json new file mode 100644 index 000000000..9846df91a --- /dev/null +++ b/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.json @@ -0,0 +1,113 @@ +{ + "pyautolens_version": "2026.7.23.1", + "backend": "cpu", + "device": "cpu", + "mesh_points": 1200, + "queries": 15000, + "query_chunk": 256, + "repeats": 5, + "rows": [ + { + "name": "Delaunay", + "cap": null, + "compile_and_first_seconds": 0.3508444019998933, + "warm_median_seconds": 0.0667459289998078, + "warm_seconds": [ + 0.06326032399920223, + 0.0667459289998078, + 0.06692990099963936, + 0.0668505190005817, + 0.06327970300026209 + ], + "ratio_to_delaunay": 1.0 + }, + { + "name": "DelaunayNN cap 16", + "cap": 16, + "compile_and_first_seconds": 1.330291995999687, + "warm_median_seconds": 0.19231454999953712, + "warm_seconds": [ + 0.19774434400005703, + 0.20188686700021208, + 0.19175842699951318, + 0.19044281399965257, + 0.19231454999953712 + ], + "ratio_to_delaunay": 2.881292580407277, + "main_max_neighbors": 13, + "main_max_cavity": 11, + "split_max_neighbors": 11, + "split_max_cavity": 9, + "main_overflow_rows": 0, + "split_overflow_rows": 0, + "main_degenerate_rows": 0, + "split_degenerate_rows": 0 + }, + { + "name": "DelaunayNN cap 24", + "cap": 24, + "compile_and_first_seconds": 1.2141758490006396, + "warm_median_seconds": 0.23995153800024127, + "warm_seconds": [ + 0.23995153800024127, + 0.23690873500072485, + 0.23717795999982627, + 0.24465054699976463, + 0.24186520599960204 + ], + "ratio_to_delaunay": 3.5949988500561916, + "main_max_neighbors": 13, + "main_max_cavity": 11, + "split_max_neighbors": 11, + "split_max_cavity": 9, + "main_overflow_rows": 0, + "split_overflow_rows": 0, + "main_degenerate_rows": 0, + "split_degenerate_rows": 0 + }, + { + "name": "DelaunayNN cap 32", + "cap": 32, + "compile_and_first_seconds": 1.241680672000257, + "warm_median_seconds": 0.3176600659999167, + "warm_seconds": [ + 0.33976070000062464, + 0.32011838699963846, + 0.3176600659999167, + 0.30417247700006556, + 0.31641388699972595 + ], + "ratio_to_delaunay": 4.7592425599594455, + "main_max_neighbors": 13, + "main_max_cavity": 11, + "split_max_neighbors": 11, + "split_max_cavity": 9, + "main_overflow_rows": 0, + "split_overflow_rows": 0, + "main_degenerate_rows": 0, + "split_degenerate_rows": 0 + }, + { + "name": "DelaunayNN cap 64", + "cap": 64, + "compile_and_first_seconds": 1.5097327220000807, + "warm_median_seconds": 0.5624023139998826, + "warm_seconds": [ + 0.5624023139998826, + 0.5757860489993618, + 0.5676023759997406, + 0.4991818990001775, + 0.49036738100039656 + ], + "ratio_to_delaunay": 8.426016723828985, + "main_max_neighbors": 13, + "main_max_cavity": 11, + "split_max_neighbors": 11, + "split_max_cavity": 9, + "main_overflow_rows": 0, + "split_overflow_rows": 0, + "main_degenerate_rows": 0, + "split_degenerate_rows": 0 + } + ] +} diff --git a/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.png b/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.png new file mode 100644 index 000000000..21e1d09a4 Binary files /dev/null and b/results/delaunay_nn/delaunay_nn_benchmark_cpu_v2026.7.23.1.png differ diff --git a/results/notes/delaunay_nn_cap_audit.md b/results/notes/delaunay_nn_cap_audit.md new file mode 100644 index 000000000..f77c76ce1 --- /dev/null +++ b/results/notes/delaunay_nn_cap_audit.md @@ -0,0 +1,51 @@ +# DelaunayNN fixed-shape cap audit + +## Decision + +Keep both `DelaunayNN` static limits at **32**. Caps 16 and 24 are too low for +the tested lensing geometries; 64 roughly doubles the cap-32 geometry cost +without being required by the audit. + +## Correctness audit + +The workspace assertion +`scripts/misc/jax_assertions/delaunay_nn_caps.py` constructs a 1,200-vertex +Hilbert image mesh from an arc-like adapt image and ray-traces both that mesh +and 4,421 image pixels through 101 Isothermal + external-shear mass models. +The ensemble contains a 25-step local mass-model trajectory, 75 broad prior +draws, and a fixed stress geometry. It audits ordinary mapper queries and all +4,800 split-cross points used by split regularization. + +The untruncated cap-64 reference observed: + +| Quantity | Maximum | Rows above 16 | +|---|---:|---:| +| Main natural neighbours | 27 | 198 | +| Main cavity triangles | 25 | 107 | +| Split natural neighbours | 21 | 28 | +| Split cavity triangles | 19 | 12 | + +The main-neighbour 99th, 99.9th and 99.99th percentiles were 9, 14 and 22; +the corresponding split-neighbour percentiles were 9, 11 and 15. Thus 16 is +usually sufficient but fails in the tail—the precise failure mode that would +otherwise create rare NaN likelihood samples as the mass model changes. + +The worst geometry was rerun explicitly at caps 16, 24 and 32. Both 16 and 24 +reported fixed-shape overflow; 32 completed without main or split overflow. + +## Runtime trade-off + +The versioned local CPU benchmark uses 1,200 vertices, 15,000 data queries and +the full mapper path, including split regularization: + +| Mapper | Warm median | Relative to Delaunay | +|---|---:|---:| +| Barycentric Delaunay | 0.0667 s | 1.00× | +| DelaunayNN cap 16 | 0.1923 s | 2.88× | +| DelaunayNN cap 24 | 0.2400 s | 3.59× | +| DelaunayNN cap 32 | 0.3177 s | 4.76× | +| DelaunayNN cap 64 | 0.5624 s | 8.43× | + +These are local CPU measurements, not A100 results. The cap-32 choice is the +smallest tested static shape that covers the broad mass-model audit. The A100 +profile should be rerun before drawing sampler-throughput conclusions. diff --git a/scripts/misc/delaunay_nn/README.md b/scripts/misc/delaunay_nn/README.md new file mode 100644 index 000000000..a76127ea8 --- /dev/null +++ b/scripts/misc/delaunay_nn/README.md @@ -0,0 +1,35 @@ +# DelaunayNN profiling + +This profile isolates the full geometry cost of the Sibson natural-neighbour +mapper added as `mesh.DelaunayNN`. It times: + +- qhull connectivity and JAX point location; +- data-grid natural-neighbour weights; +- barycentric dual areas and split-cross coordinates; +- natural-neighbour weights for all split-regularization points. + +The comparison is therefore the complete mapper-table construction against +the equivalent barycentric `Delaunay` path, rather than an isolated +circumcircle kernel. + +Run the production-shaped CPU/GPU benchmark from the repository root: + +```bash +python scripts/misc/delaunay_nn/benchmark.py +``` + +Useful overrides: + +```bash +python scripts/misc/delaunay_nn/benchmark.py \ + --mesh-points 1500 --queries 20000 --caps 16 24 32 64 --repeats 10 +``` + +The script writes a versioned JSON and PNG pair under +`results/delaunay_nn/`. The cap sweep exposes the speed/headroom trade-off; +the separate workspace assertion +`scripts/misc/jax_assertions/delaunay_nn_caps.py` decides correctness using +actual Hilbert meshes ray-traced through a mass-model ensemble. + +The current cap decision and measured tail distributions are recorded in +[`results/notes/delaunay_nn_cap_audit.md`](../../../results/notes/delaunay_nn_cap_audit.md). diff --git a/scripts/misc/delaunay_nn/benchmark.py b/scripts/misc/delaunay_nn/benchmark.py new file mode 100644 index 000000000..fbe702918 --- /dev/null +++ b/scripts/misc/delaunay_nn/benchmark.py @@ -0,0 +1,208 @@ +"""Profile the full JAX DelaunayNN mapper across fixed-shape caps. + +This is a dataset-agnostic microbenchmark for the geometry that distinguishes +``DelaunayNN`` from barycentric ``Delaunay``. It includes data-query weights, +dual areas, split points and split-regularization weights, so the warm timing +is the cost paid by the mapper rather than an isolated Watson-weight kernel. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import time +from pathlib import Path + + +def _profiling_root() -> Path: + for parent in Path(__file__).resolve().parents: + if (parent / "ruff.toml").exists(): + return parent + raise RuntimeError("autolens_profiling root (ruff.toml) not found") + + +ROOT = _profiling_root() +sys.path.insert(0, str(ROOT)) +os.environ.setdefault("MPLBACKEND", "Agg") + +import autolens as al # noqa: E402 +import jax # noqa: E402 +import jax.numpy as jnp # noqa: E402 +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +from autoarray.inversion.mesh.interpolator.delaunay import jax_delaunay # noqa: E402 +from autoarray.inversion.mesh.interpolator.sibson import jax_delaunay_nn # noqa: E402 + +if os.environ.get("AUTOLENS_PROFILING_SMOKE") == "1": + print(f"[smoke] {__file__}: imports + module setup OK; exiting.") + raise SystemExit(0) + +jax.config.update("jax_enable_x64", True) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--mesh-points", type=int, default=1200) + parser.add_argument("--queries", type=int, default=15000) + parser.add_argument("--repeats", type=int, default=5) + parser.add_argument("--caps", type=int, nargs="+", default=[16, 24, 32, 64]) + parser.add_argument("--query-chunk", type=int, default=256) + parser.add_argument("--output-dir", type=Path, default=None) + return parser.parse_args() + + +def adaptive_mesh(count, rng): + """Production-shaped central source concentration plus boundary coverage.""" + blob_count = count // 2 + blob = rng.normal(size=(blob_count, 2)) * 0.15 + angle = rng.uniform(0.0, 2.0 * np.pi, size=count - blob_count) + radius = 1.0 + rng.normal(size=count - blob_count) * 0.12 + ring = np.stack([radius * np.cos(angle), radius * np.sin(angle)], axis=1) + return np.concatenate([blob, ring]) + + +def measure(function, points, queries, repeats): + jitted = jax.jit(function) + + start = time.perf_counter() + output = jitted(points, queries) + jax.block_until_ready(output) + compile_and_first = time.perf_counter() - start + + warm = [] + for _ in range(repeats): + start = time.perf_counter() + output = jitted(points, queries) + jax.block_until_ready(output) + warm.append(time.perf_counter() - start) + + return output, compile_and_first, float(np.median(warm)), warm + + +def slug(value): + return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") + + +args = parse_args() +rng = np.random.default_rng(4) +points = jnp.asarray(adaptive_mesh(args.mesh_points, rng)) +queries = jnp.asarray(adaptive_mesh(args.queries, rng)) + +baseline_output, baseline_compile, baseline_warm, baseline_runs = measure( + lambda mesh_points, query_points: jax_delaunay(mesh_points, query_points), + points, + queries, + args.repeats, +) + +rows = [ + { + "name": "Delaunay", + "cap": None, + "compile_and_first_seconds": baseline_compile, + "warm_median_seconds": baseline_warm, + "warm_seconds": baseline_runs, + "ratio_to_delaunay": 1.0, + } +] + +for cap in args.caps: + output, compile_and_first, warm_median, warm_runs = measure( + lambda mesh_points, query_points, fixed_cap=cap: jax_delaunay_nn( + mesh_points, + query_points, + max_cavity_triangles=fixed_cap, + max_neighbors=fixed_cap, + query_chunk=args.query_chunk, + ), + points, + queries, + args.repeats, + ) + + main_overflow = int(np.asarray(output[10]).sum()) + split_overflow = int(np.asarray(output[13]).sum()) + main_degenerate = int(np.asarray(output[11]).sum()) + split_degenerate = int(np.asarray(output[14]).sum()) + + rows.append( + { + "name": f"DelaunayNN cap {cap}", + "cap": cap, + "compile_and_first_seconds": compile_and_first, + "warm_median_seconds": warm_median, + "warm_seconds": warm_runs, + "ratio_to_delaunay": warm_median / baseline_warm, + "main_max_neighbors": int(np.asarray(output[3]).max()), + "main_max_cavity": int(np.asarray(output[9]).max()), + "split_max_neighbors": int(np.asarray(output[7]).max()), + "split_max_cavity": int(np.asarray(output[12]).max()), + "main_overflow_rows": main_overflow, + "split_overflow_rows": split_overflow, + "main_degenerate_rows": main_degenerate, + "split_degenerate_rows": split_degenerate, + } + ) + + if cap >= 32: + assert main_overflow == 0 + assert split_overflow == 0 + assert main_degenerate == 0 + assert split_degenerate == 0 + +device = jax.devices()[0] +device_label = getattr(device, "device_kind", str(device)) +backend = jax.default_backend() +version = getattr(al, "__version__", "unknown") +output_dir = args.output_dir or ROOT / "results" / "delaunay_nn" +output_dir.mkdir(parents=True, exist_ok=True) +stem = f"delaunay_nn_benchmark_{slug(backend)}_v{version}" +json_path = output_dir / f"{stem}.json" +png_path = output_dir / f"{stem}.png" + +payload = { + "pyautolens_version": version, + "backend": backend, + "device": device_label, + "mesh_points": args.mesh_points, + "queries": args.queries, + "query_chunk": args.query_chunk, + "repeats": args.repeats, + "rows": rows, +} +json_path.write_text(json.dumps(payload, indent=2) + "\n") + +labels = [row["name"] for row in rows] +warm_times = [row["warm_median_seconds"] for row in rows] +fig, axis = plt.subplots(figsize=(10, 5)) +bars = axis.bar(labels, warm_times, color=["#808080"] + ["#3B82F6"] * (len(rows) - 1)) +axis.set_ylabel("Warm full-mapper time (seconds)") +axis.set_title( + f"DelaunayNN fixed-shape cap cost\n{args.mesh_points} vertices × {args.queries} queries" +) +axis.tick_params(axis="x", rotation=25) +for bar, value in zip(bars, warm_times): + axis.text( + bar.get_x() + bar.get_width() / 2, + value, + f"{value:.3f}s", + ha="center", + va="bottom", + ) +fig.tight_layout() +fig.savefig(png_path, dpi=160) +plt.close(fig) + +print(f"device: {backend} / {device_label}") +print(f"shape: {args.mesh_points} mesh points x {args.queries} queries") +for row in rows: + print( + f"{row['name']}: warm={row['warm_median_seconds']:.6f}s, " + f"compile+first={row['compile_and_first_seconds']:.6f}s, " + f"ratio={row['ratio_to_delaunay']:.3f}x" + ) +print(f"wrote {json_path}") +print(f"wrote {png_path}")