diff --git a/scripts/profiling/__init__.py b/scripts/profiling/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/profiling/aggregator/README.md b/scripts/profiling/aggregator/README.md new file mode 100644 index 0000000..c7a4834 --- /dev/null +++ b/scripts/profiling/aggregator/README.md @@ -0,0 +1,16 @@ +# Aggregator profiling + +Tools to measure where `af.Aggregator` result-loading scales poorly (number of +results vs samples per result vs model size), using mock output folders written +through the real `DirectoryPaths` machinery — no sampler is ever run, so thousands +of results are fabricated in seconds. + +- `mock_results.py` — generate a mock result set (`--n-results/--n-samples/--n-gaussians/--zip`). +- `profile_aggregator.py` — time each loading pathway over a one-axis-at-a-time grid + (`--quick` for a fast pass, `--n-results-max 3000` for the science-scale case, + `--label before` to tag the JSON) and write a table + JSON under + `output/profiling_aggregator/results/`. + +Run both from the `autofit_workspace_test` root. Everything lands under `output/` +(gitignored). These scripts are profiling tools, not smoke tests — do not add them +to `smoke_tests.txt`. diff --git a/scripts/profiling/aggregator/__init__.py b/scripts/profiling/aggregator/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/scripts/profiling/aggregator/mock_results.py b/scripts/profiling/aggregator/mock_results.py new file mode 100644 index 0000000..19e94a6 --- /dev/null +++ b/scripts/profiling/aggregator/mock_results.py @@ -0,0 +1,238 @@ +""" +Profiling: Mock Aggregator Results +================================== + +Fabricates search-output directories that the real `af.Aggregator` accepts, without +running a non-linear search. + +One template result per (n_gaussians, n_samples) configuration is written through the +library's own `DirectoryPaths` machinery (`save_all` / `save_samples` / +`save_samples_summary`), so file formats always track the installed autofit. The +template is then stamped `n_results` times with `shutil.copytree`, which makes +thousands of mock results in seconds. + +Run from the `autofit_workspace_test` root, e.g.: + + python scripts/profiling/aggregator/mock_results.py --n-results 100 --n-samples 1000 --n-gaussians 5 +""" + +import argparse +import json +import shutil +import time +import zipfile +from pathlib import Path + +import numpy as np +from PIL import Image + +from autoconf import conf +import autofit as af +from autofit.non_linear.paths.directory import DirectoryPaths + +DEFAULT_ROOT = Path("output") / "profiling_aggregator" / "mock" + + +def model_from(n_gaussians: int) -> af.Collection: + """ + A model of `n_gaussians` `af.ex.Gaussian`s (3 free parameters each) with explicit + priors, so no prior config lookup is required. + """ + gaussians = {} + for i in range(n_gaussians): + gaussian = af.Model(af.ex.Gaussian) + gaussian.centre = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + gaussian.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + gaussian.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + gaussians[f"gaussian_{i}"] = gaussian + return af.Collection(**gaussians) + + +def samples_from(model, n_samples: int, seed: int = 1) -> af.SamplesNest: + """ + Random samples for the model. Parameter values are uniform draws in (0, 1) — the + numbers are immaterial for profiling, only the row/column counts matter. + """ + rng = np.random.default_rng(seed) + n_params = model.prior_count + + parameter_lists = rng.uniform(0.01, 0.99, size=(n_samples, n_params)).tolist() + log_likelihood_list = np.sort(rng.normal(-1000.0, 50.0, n_samples)).tolist() + log_prior_list = [0.0] * n_samples + weight = 1.0 / n_samples + weight_list = [weight] * n_samples + + sample_list = af.Sample.from_lists( + model=model, + parameter_lists=parameter_lists, + log_likelihood_list=log_likelihood_list, + log_prior_list=log_prior_list, + weight_list=weight_list, + ) + + return af.SamplesNest( + model=model, + sample_list=sample_list, + samples_info={ + "number_live_points": 50, + "log_evidence": -1000.0, + "total_samples": n_samples, + "total_accepted_samples": n_samples, + "total_iterations": n_samples, + "time": "1.0", + }, + ) + + +def write_template( + root: Path, + n_gaussians: int, + n_samples: int, + with_images: bool = True, + with_latent: bool = False, +) -> Path: + """ + Write one full search-output directory via the real paths machinery and return the + leaf directory (the one containing the `metadata` file). + """ + template_prefix = f"_template/g{n_gaussians}_s{n_samples}" + + conf.instance.push(new_path="config", output_path=str(root)) + + model = model_from(n_gaussians) + samples = samples_from(model=model, n_samples=n_samples) + search = af.DynestyStatic(name="fit") + + paths = DirectoryPaths(name="fit", path_prefix=template_prefix) + paths.model = model + paths.search = search + + if Path(paths.output_path).exists(): + shutil.rmtree(paths.output_path) + + paths.save_all(info={}) + paths.save_samples(samples=samples) + paths.save_samples_summary(samples_summary=samples.summary()) + if with_latent: + paths.save_latent_samples(latent_samples=samples) + paths.completed() + + if with_images: + image_path = paths.image_path + image = Image.new("RGB", (64, 64)) + for name in ("subplot_fit", "corner_pdf", "search_internal"): + image.save(image_path / f"{name}.png") + + return Path(paths.output_path) + + +def _zip_directory(directory: Path): + """ + Zip a result directory the way search output is zipped: contents at the archive + root, so `unzip_directory` re-extracts them into a sibling folder of the same name. + """ + with zipfile.ZipFile(directory.with_suffix(".zip"), "w") as f: + for path in directory.rglob("*"): + if path.is_file(): + f.write(path, path.relative_to(directory)) + shutil.rmtree(directory) + + +def stamp_results( + template_leaf: Path, + results_root: Path, + n_results: int, + zip_results: bool = False, +): + """ + Copy the template `n_results` times under `results_root`, giving each copy a unique + `dataset_name` metadata entry so results are distinguishable and queryable. + """ + for i in range(n_results): + dataset_name = f"dataset_{i:04d}" + destination = results_root / dataset_name / "fit" + shutil.copytree(template_leaf, destination) + with open(destination / "metadata", "a") as f: + f.write(f"\ndataset_name={dataset_name}") + if zip_results: + _zip_directory(destination) + + +def generate_mock_results( + root: Path = DEFAULT_ROOT, + n_results: int = 100, + n_samples: int = 1000, + n_gaussians: int = 5, + zip_results: bool = False, + with_images: bool = True, + with_latent: bool = False, + fresh: bool = False, +) -> Path: + """ + Generate a directory of `n_results` mock results and return it, ready for + `af.Aggregator.from_directory`. Skips regeneration when an identical set already + exists (recorded in a manifest file). + """ + root = Path(root) + config = { + "n_results": n_results, + "n_samples": n_samples, + "n_gaussians": n_gaussians, + "zip_results": zip_results, + "with_images": with_images, + "with_latent": with_latent, + } + tag = f"r{n_results}_s{n_samples}_g{n_gaussians}" + ("_zip" if zip_results else "") + results_root = root / tag + manifest_path = root / f"{tag}.manifest.json" + + if not fresh and manifest_path.exists() and results_root.exists(): + if json.loads(manifest_path.read_text()) == config: + return results_root + + if results_root.exists(): + shutil.rmtree(results_root) + + template_leaf = write_template( + root=root, + n_gaussians=n_gaussians, + n_samples=n_samples, + with_images=with_images, + with_latent=with_latent, + ) + stamp_results( + template_leaf=template_leaf, + results_root=results_root, + n_results=n_results, + zip_results=zip_results, + ) + + manifest_path.write_text(json.dumps(config)) + return results_root + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) + parser.add_argument("--n-results", type=int, default=100) + parser.add_argument("--n-samples", type=int, default=1000) + parser.add_argument("--n-gaussians", type=int, default=5) + parser.add_argument("--zip", action="store_true", dest="zip_results") + parser.add_argument("--latent", action="store_true", dest="with_latent") + parser.add_argument("--fresh", action="store_true") + args = parser.parse_args() + + start = time.perf_counter() + results_root = generate_mock_results( + root=args.root, + n_results=args.n_results, + n_samples=args.n_samples, + n_gaussians=args.n_gaussians, + zip_results=args.zip_results, + with_latent=args.with_latent, + fresh=args.fresh, + ) + print( + f"{args.n_results} mock results at {results_root} " + f"in {time.perf_counter() - start:.2f}s" + ) diff --git a/scripts/profiling/aggregator/profile_aggregator.py b/scripts/profiling/aggregator/profile_aggregator.py new file mode 100644 index 0000000..6e56ce9 --- /dev/null +++ b/scripts/profiling/aggregator/profile_aggregator.py @@ -0,0 +1,227 @@ +""" +Profiling: Aggregator Loading Pathways +====================================== + +Times each aggregator loading pathway separately over a grid of mock-result sets +(varying number of results, samples per result and model size one axis at a time), +so it is explicit which axis drives poor scaling. + +Stages timed per grid cell: + +- `generate`: building the mock results (not an aggregator cost; reported for context). +- `from_directory`: `af.Aggregator.from_directory` scan. +- `iterate`: iterating every `SearchOutput` (no file loads). +- `values_samples_summary`: `values("samples_summary")` — the lightweight summary path. +- `values_model`: `values("model")`. +- `values_samples`: `values("samples")` — full `samples.csv` parse per result. +- `query_dataset_name`: a metadata predicate query. +- `aggregate_csv`: `af.AggregateCSV` catalogue build (the csv_make workflow pattern). + +Run from the `autofit_workspace_test` root, e.g.: + + python scripts/profiling/aggregator/profile_aggregator.py --quick + +Results print as a table and are written as JSON under +`output/profiling_aggregator/results/`. +""" + +import argparse +import contextlib +import io +import json +import os +import shutil +import sys +import time +from collections import deque +from datetime import datetime +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) + +import autofit as af +from autofit.aggregator.aggregator import Aggregator +from mock_results import generate_mock_results + +RESULTS_PATH = Path("output") / "profiling_aggregator" / "results" + +# values("samples") holds every loaded Samples in memory (SearchOutput caches them), +# which OOMs at science scale — 3000 results x 1000 samples was killed at ~6.6 GB RSS. +# The samples stage is therefore timed on a capped slice; per-result cost extrapolates. +SAMPLES_STAGE_CAP = 500 + +BASE = {"n_results": 100, "n_samples": 1000, "n_gaussians": 5} +AXES = { + "n_results": [10, 100, 1000], + "n_samples": [100, 1000, 10000], + "n_gaussians": [1, 5, 15], +} +AXES_QUICK = { + "n_results": [10, 50], + "n_samples": [100, 1000], + "n_gaussians": [1, 5], +} + + +def grid_cells(axes: dict, base: dict) -> list: + """ + One cell per axis value, holding the other axes at the base configuration. + """ + cells = [] + for axis, values in axes.items(): + for value in values: + cell = dict(base) + cell[axis] = value + if cell not in cells: + cells.append(cell) + return cells + + +def timed(func) -> float: + """ + Wall-time a callable, swallowing its stdout (the aggregator prints progress + messages which would drown the table). + """ + with contextlib.redirect_stdout(io.StringIO()): + start = time.perf_counter() + func() + return time.perf_counter() - start + + +def profile_cell(cell: dict, zip_results: bool, keep: bool) -> dict: + timings = {} + + generate_start = time.perf_counter() + results_root = generate_mock_results(zip_results=zip_results, **cell) + timings["generate"] = time.perf_counter() - generate_start + + def fresh_agg(): + """ + A new Aggregator, so each stage is timed cold — SearchOutput caches model + and samples on the instance, which would otherwise let later stages ride + earlier stages' loads. + """ + with contextlib.redirect_stdout(io.StringIO()): + agg = Aggregator.from_directory(results_root) + assert len(agg) == cell["n_results"], ( + f"Aggregator found {len(agg)} results, expected {cell['n_results']}" + ) + return agg + + # Warm up one-off costs (imports triggered by the first summary/search load) so + # they don't pollute the first timed stage of the first cell. + warm = fresh_agg()[0] + _ = warm.samples_summary, warm.samples + + timings["from_directory"] = timed(lambda: Aggregator.from_directory(results_root)) + + agg = fresh_agg() + timings["iterate"] = timed(lambda: list(agg)) + + agg = fresh_agg() + timings["values_samples_summary"] = timed( + lambda: list(agg.values("samples_summary")) + ) + + agg = fresh_agg() + timings["values_model"] = timed(lambda: list(agg.values("model"))) + + with contextlib.redirect_stdout(io.StringIO()): + agg = fresh_agg()[:SAMPLES_STAGE_CAP] + samples_stage_results = len(agg) + timings["values_samples"] = timed( + lambda: deque(agg.values("samples"), maxlen=0) + ) + + agg = fresh_agg() + timings["query_dataset_name"] = timed( + lambda: agg.query(agg.dataset_name == "dataset_0000") + ) + + agg = fresh_agg() + + def aggregate_csv(): + agg_csv = af.AggregateCSV(agg) + agg_csv.add_variable("gaussian_0.centre") + agg_csv.add_variable("gaussian_0.sigma") + agg_csv.save(results_root.parent / "aggregate.csv") + + timings["aggregate_csv"] = timed(aggregate_csv) + + if not keep: + shutil.rmtree(results_root.parent) + + return { + **cell, + "zip": zip_results, + "samples_stage_results": samples_stage_results, + "timings": timings, + } + + +def print_table(rows: list): + stages = list(rows[0]["timings"]) + header = f"{'n_results':>9} {'n_samples':>9} {'n_gauss':>7} " + " ".join( + f"{stage:>22}" for stage in stages + ) + print("\nTimings in seconds (per-result milliseconds in brackets):\n") + print(header) + print("-" * len(header)) + for row in rows: + cells = [] + for stage in stages: + seconds = row["timings"][stage] + n = ( + row["samples_stage_results"] + if stage == "values_samples" + else row["n_results"] + ) + per_result_ms = 1000.0 * seconds / n + cells.append(f"{seconds:>12.3f} ({per_result_ms:>6.2f})") + print( + f"{row['n_results']:>9} {row['n_samples']:>9} {row['n_gaussians']:>7} " + + " ".join(cells) + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--quick", action="store_true", help="small grid, fast run") + parser.add_argument("--n-results-max", type=int, default=None) + parser.add_argument("--zip", action="store_true", dest="zip_results") + parser.add_argument("--keep", action="store_true", help="keep mock results on disk") + parser.add_argument("--label", type=str, default="", help="tag for the JSON output") + args = parser.parse_args() + + axes = dict(AXES_QUICK if args.quick else AXES) + base = dict(BASE) + if args.quick: + base = {"n_results": 50, "n_samples": 1000, "n_gaussians": 5} + if os.environ.get("PYAUTO_TEST_MODE"): + # Validation sweeps (run_all_scripts.sh) only smoke-check that the harness + # works — profile a single tiny cell instead of a real grid. + axes = {"n_results": [5]} + base = {"n_results": 5, "n_samples": 50, "n_gaussians": 1} + if args.n_results_max is not None: + axes["n_results"] = axes["n_results"] + [args.n_results_max] + + rows = [] + for cell in grid_cells(axes=axes, base=base): + print(f"profiling {cell} ...", flush=True) + rows.append(profile_cell(cell, zip_results=args.zip_results, keep=args.keep)) + + print_table(rows) + + RESULTS_PATH.mkdir(parents=True, exist_ok=True) + label = f"_{args.label}" if args.label else "" + output_file = ( + RESULTS_PATH + / f"profile_{datetime.now().strftime('%Y%m%d_%H%M%S')}{label}.json" + ) + output_file.write_text( + json.dumps( + {"autofit_version": af.__version__, "rows": rows}, + indent=2, + ) + ) + print(f"\nJSON written to {output_file}")