diff --git a/experiments/nautilus_compact_array/README.md b/experiments/nautilus_compact_array/README.md new file mode 100644 index 0000000..655f34c --- /dev/null +++ b/experiments/nautilus_compact_array/README.md @@ -0,0 +1,26 @@ +# Compact corner plotting experiment + +The array renderer reduced full replay time in both completed pairs while producing byte-identical PNGs. Five cases completed; the host-load guard stopped the final candidate case. The third baseline is unpaired and is excluded from every speedup summary. + +| Pair | Backend | Process (s) | Wrapped output (s) | Corner plot (s) | Peak RSS (MiB) | +|---|---|---:|---:|---:|---:| +| 1 | baseline | 149.01 | 133.36 | 102.38 | 535.1 | +| 1 | candidate | 73.68 | 62.51 | 37.54 | 534.9 | +| 2 | candidate | 83.31 | 69.96 | 43.94 | 534.6 | +| 2 | baseline | 111.93 | 101.07 | 73.25 | 534.7 | +| 3 | baseline | 112.30 | 102.54 | 79.47 | 535.3 | + +Completed-pair process ratios (baseline / candidate): 2.022x, 1.344x. +The median/range in summary.json use only those two pairs. Timing variation is material; this is exploratory evidence and does not justify changing the default. + +All five cases retained all 33,984 weighted samples, the native count of 34,100, unchanged posterior/checkpoint hashes, zero sampler likelihood calls and exactly one separately authorized final-summary timing call. Both matched pairs have identical PNG bytes. The canvas remains 12x12 inches at 100 dpi with every cross-parameter panel and unchanged typography. + +Aggregate elapsed time: 535.88s, including preflight, against 1800s. Every completed child stayed within 240s/4096 MiB. Memory is sampled process-group RSS; brief spikes can be missed. The start guard uses one-minute host load <=2 for the eight-CPU affinity. The precise failing host snapshot was not persisted. No automatic retry followed it. + +The first attempt stopped before any child because the activation omitted auxiliary package metadata paths. No installed dependency changed. The corrected attempt was explicitly approved; both attempts and all raw data remain retained. + +Measured library: e57611dc6; producer: 3bce28c; baseline: bdb7af0e9. A later library guard sends non-string labels back to pandas; the measured string-label drawing path is unchanged. See summary.json for complete frozen source/package identities. + +[Library PR](https://github.com/PyAutoLabs/PyAutoFit/pull/1764) · [Experiment PR](https://github.com/PyAutoLabs/autofit_profiling/pull/14). Outside Pulse. Default backend remains anesthetic; merge remains human. This does not resolve 30D evidence accuracy or complete the wider phase 0b. + +![Measured compact corner plot](compact_corner.png) diff --git a/experiments/nautilus_compact_array/compact_corner.png b/experiments/nautilus_compact_array/compact_corner.png new file mode 100644 index 0000000..f68bbb1 Binary files /dev/null and b/experiments/nautilus_compact_array/compact_corner.png differ diff --git a/experiments/nautilus_compact_array/summary.json b/experiments/nautilus_compact_array/summary.json new file mode 100644 index 0000000..04e3c43 --- /dev/null +++ b/experiments/nautilus_compact_array/summary.json @@ -0,0 +1,420 @@ +{ + "status": "halted", + "reason": "RuntimeError: host load exceeds guard", + "spent_s": 535.8790144850027, + "protocol": "nautilus-compact-array-experiment@1", + "limits": { + "timeout_s": 240, + "memory_mib": 4096, + "budget_s": 1800 + }, + "measured_environments": { + "baseline": { + "sources": { + "PyAutoFit": { + "revision": "bdb7af0e9c339ad07850679fd6ac168aacc7d18c", + "code_sha256": "9e566e1b1a259e279d2eaa86319556a78561183b347ac8835793a315d980ad75" + }, + "PyAutoNerves": { + "revision": "9b204c90c2ce05c5bb0cf3e9800ed13f005c6c56", + "code_sha256": "560c9250eb0d7f8f56b3d4d21f22b9e556e93fd0eba92b5b33860b903a2f3f0b" + }, + "producer": { + "revision": "3bce28c878733ef8a861dffa6535fbaa2c4d9a7d", + "code_sha256": "14ef7de24ca6fcf99faad192c5787ee9623d41e77617250ce28f2956082b99ca" + } + }, + "nautilus_source_sha256": "61e91f8fb85cf4a38877cd1c65bb0b111589bde77f5f74acb22a90f3ff2ec45c", + "packages": { + "numpy": "2.5.4", + "scipy": "1.17.1", + "scikit-learn": "1.9.1", + "h5py": "3.16.0", + "nautilus-sampler": "1.0.5", + "jax": "0.11.2", + "jaxlib": "0.11.2", + "threadpoolctl": "3.8.0" + }, + "distribution_versions": { + "autofit": "9999.0.0.dev0", + "autonerves": "9999.0.0.dev0", + "autoarray": "9999.0.0.dev0", + "autogalaxy": "9999.0.0.dev0", + "autolens": "9999.0.0.dev0", + "networkx": "3.1", + "jsonpickle": "4.1.4", + "dynesty": "2.1.5", + "array-api-compat": "1.16.0", + "pyparsing": "3.3.3", + "pillow": "13.0.0", + "psutil": "6.1.0", + "cycler": "0.12.1", + "emcee": "3.1.6", + "jaxlib": "0.11.2", + "pure_eval": "0.2.4", + "six": "1.17.0", + "imagesize": "2.0.1", + "mypy_extensions": "1.2.0", + "joblib": "1.6.0", + "snowballstemmer": "3.1.1", + "urllib3": "2.8.0", + "prompt_toolkit": "3.0.53", + "nautilus-sampler": "1.0.5", + "ml_dtypes": "0.6.0", + "Pygments": "2.21.0", + "babel": "2.18.0", + "pluggy": "1.7.0", + "MarkupSafe": "3.0.4", + "traitlets": "5.16.1", + "roman-numerals": "4.1.0", + "corner": "2.2.2", + "typing_extensions": "4.16.0", + "sphinxcontrib-devhelp": "2.0.0", + "dill": "0.4.1", + "asttokens": "3.0.2", + "sphinxcontrib-serializinghtml": "2.0.0", + "optax": "0.2.8", + "matplotlib-inline": "0.2.2", + "threadpoolctl": "3.8.0", + "ipython": "9.12.0", + "ruff": "0.17.4", + "Sphinx": "9.1.1", + "typing-inspect": "0.9.0", + "jedi": "0.20.1", + "certifi": "2026.10.23", + "wheel": "0.48.0", + "parso": "0.8.7", + "contourpy": "1.4.0", + "anesthetic": "2.16.0", + "alabaster": "1.0.0", + "pyvis": "0.3.2", + "charset-normalizer": "3.5.2", + "numpydoc": "1.11.0", + "gprof2dot": "2021.2.21", + "timeout-decorator": "0.5.0", + "absl-py": "2.5.1", + "ipython_pygments_lexers": "1.1.1", + "fonttools": "4.68.0", + "sphinxcontrib-qthelp": "2.0.0", + "PyYAML": "6.0.3", + "sphinxcontrib-applehelp": "2.0.0", + "iniconfig": "2.3.1", + "sphinxcontrib-jsmath": "2.0.0", + "executing": "2.3.0", + "numpy": "2.5.4", + "sphinxcontrib-htmlhelp": "2.1.0", + "decorator": "5.3.1", + "xxhash": "3.4.1", + "jax": "0.11.2", + "scipy": "1.17.1", + "Jinja2": "3.1.6", + "pandas": "3.0.6", + "stack-data": "0.6.3", + "kiwisolver": "1.5.1", + "python-dateutil": "4.0.0", + "packaging": "26.3", + "cloudpickle": "3.1.2", + "opt_einsum": "3.4.0", + "scikit-learn": "1.9.1", + "jaxnnls": "1.0.1", + "pexpect": "4.9.0", + "requests": "2.34.2", + "h5py": "3.16.0", + "ptyprocess": "0.7.0", + "greenlet": "3.5.6", + "docutils": "0.22.4", + "tzdata": "2026.6", + "wcwidth": "0.9.4", + "idna": "3.20", + "astunparse": "1.6.3", + "SQLAlchemy": "2.0.57", + "pytest": "9.2.0", + "narwhals": "2.28.0", + "matplotlib": "3.11.2" + }, + "python": "3.12.10 (main, Apr 9 2025, 08:55:05) [GCC 11.4.0]", + "host": "DESKTOP-H143S82", + "platform": "Linux-6.18.58.1-microsoft-standard-WSL2-x86_64-with-glibc2.35", + "affinity": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "thread_env": { + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1" + } + }, + "candidate": { + "sources": { + "PyAutoFit": { + "revision": "e57611dc6934e92b8a04367d6e40be408a90b6b8", + "code_sha256": "e8aaf9113c3d5eea57ea42ff93c50b8c6bdb0139ea7478cd7a73fb3861d29736" + }, + "PyAutoNerves": { + "revision": "9b204c90c2ce05c5bb0cf3e9800ed13f005c6c56", + "code_sha256": "560c9250eb0d7f8f56b3d4d21f22b9e556e93fd0eba92b5b33860b903a2f3f0b" + }, + "producer": { + "revision": "3bce28c878733ef8a861dffa6535fbaa2c4d9a7d", + "code_sha256": "14ef7de24ca6fcf99faad192c5787ee9623d41e77617250ce28f2956082b99ca" + } + }, + "nautilus_source_sha256": "61e91f8fb85cf4a38877cd1c65bb0b111589bde77f5f74acb22a90f3ff2ec45c", + "packages": { + "numpy": "2.5.4", + "scipy": "1.17.1", + "scikit-learn": "1.9.1", + "h5py": "3.16.0", + "nautilus-sampler": "1.0.5", + "jax": "0.11.2", + "jaxlib": "0.11.2", + "threadpoolctl": "3.8.0" + }, + "distribution_versions": { + "autofit": "9999.0.0.dev0", + "autonerves": "9999.0.0.dev0", + "autoarray": "9999.0.0.dev0", + "autogalaxy": "9999.0.0.dev0", + "autolens": "9999.0.0.dev0", + "networkx": "3.1", + "jsonpickle": "4.1.4", + "dynesty": "2.1.5", + "array-api-compat": "1.16.0", + "pyparsing": "3.3.3", + "pillow": "13.0.0", + "psutil": "6.1.0", + "cycler": "0.12.1", + "emcee": "3.1.6", + "jaxlib": "0.11.2", + "pure_eval": "0.2.4", + "six": "1.17.0", + "imagesize": "2.0.1", + "mypy_extensions": "1.2.0", + "joblib": "1.6.0", + "snowballstemmer": "3.1.1", + "urllib3": "2.8.0", + "prompt_toolkit": "3.0.53", + "nautilus-sampler": "1.0.5", + "ml_dtypes": "0.6.0", + "Pygments": "2.21.0", + "babel": "2.18.0", + "pluggy": "1.7.0", + "MarkupSafe": "3.0.4", + "traitlets": "5.16.1", + "roman-numerals": "4.1.0", + "corner": "2.2.2", + "typing_extensions": "4.16.0", + "sphinxcontrib-devhelp": "2.0.0", + "dill": "0.4.1", + "asttokens": "3.0.2", + "sphinxcontrib-serializinghtml": "2.0.0", + "optax": "0.2.8", + "matplotlib-inline": "0.2.2", + "threadpoolctl": "3.8.0", + "ipython": "9.12.0", + "ruff": "0.17.4", + "Sphinx": "9.1.1", + "typing-inspect": "0.9.0", + "jedi": "0.20.1", + "certifi": "2026.10.23", + "wheel": "0.48.0", + "parso": "0.8.7", + "contourpy": "1.4.0", + "anesthetic": "2.16.0", + "alabaster": "1.0.0", + "pyvis": "0.3.2", + "charset-normalizer": "3.5.2", + "numpydoc": "1.11.0", + "gprof2dot": "2021.2.21", + "timeout-decorator": "0.5.0", + "absl-py": "2.5.1", + "ipython_pygments_lexers": "1.1.1", + "fonttools": "4.68.0", + "sphinxcontrib-qthelp": "2.0.0", + "PyYAML": "6.0.3", + "sphinxcontrib-applehelp": "2.0.0", + "iniconfig": "2.3.1", + "sphinxcontrib-jsmath": "2.0.0", + "executing": "2.3.0", + "numpy": "2.5.4", + "sphinxcontrib-htmlhelp": "2.1.0", + "decorator": "5.3.1", + "xxhash": "3.4.1", + "jax": "0.11.2", + "scipy": "1.17.1", + "Jinja2": "3.1.6", + "pandas": "3.0.6", + "stack-data": "0.6.3", + "kiwisolver": "1.5.1", + "python-dateutil": "4.0.0", + "packaging": "26.3", + "cloudpickle": "3.1.2", + "opt_einsum": "3.4.0", + "scikit-learn": "1.9.1", + "jaxnnls": "1.0.1", + "pexpect": "4.9.0", + "requests": "2.34.2", + "h5py": "3.16.0", + "ptyprocess": "0.7.0", + "greenlet": "3.5.6", + "docutils": "0.22.4", + "tzdata": "2026.6", + "wcwidth": "0.9.4", + "idna": "3.20", + "astunparse": "1.6.3", + "SQLAlchemy": "2.0.57", + "pytest": "9.2.0", + "narwhals": "2.28.0", + "matplotlib": "3.11.2" + }, + "python": "3.12.10 (main, Apr 9 2025, 08:55:05) [GCC 11.4.0]", + "host": "DESKTOP-H143S82", + "platform": "Linux-6.18.58.1-microsoft-standard-WSL2-x86_64-with-glibc2.35", + "affinity": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "thread_env": { + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1" + } + } + }, + "plan_sha256": "179d705337d96dab5faf4d2e04b755efd57802120f0516ba0c970236e2b315a0", + "rows": [ + { + "case": "pair-1-baseline", + "pair": 1, + "backend": "baseline", + "process_s": 149.0125159340023, + "wrapper_s": 133.35539624900048, + "plot_s": 102.37780540400126, + "png_export_s": 23.92417515899797, + "axes_s": 6.026391900002636, + "peak_rss_mib": 535.1171875, + "png_sha256": "fd3be1c8a96cebc800b89b1d7c161a319d35ca6ac48ad0f23f2640553d9f9bb9", + "checkpoint_sha256": "4ceaaa063547ebf9a03d3f16c8c7cf376b965cf079e4a228f91ad9a00846172c", + "posterior_sha256": "a4234203f31abb988319385b0a5d92f0f57fbc10dbf23e0715e5906e146d499a", + "new_sampler_calls": 0, + "summary_timing_calls": 1 + }, + { + "case": "pair-1-candidate", + "pair": 1, + "backend": "candidate", + "process_s": 73.67767932300194, + "wrapper_s": 62.51083860700237, + "plot_s": 37.5353184279993, + "png_export_s": 18.808281887002522, + "axes_s": 8.145461078001972, + "peak_rss_mib": 534.87890625, + "png_sha256": "fd3be1c8a96cebc800b89b1d7c161a319d35ca6ac48ad0f23f2640553d9f9bb9", + "checkpoint_sha256": "4ceaaa063547ebf9a03d3f16c8c7cf376b965cf079e4a228f91ad9a00846172c", + "posterior_sha256": "a4234203f31abb988319385b0a5d92f0f57fbc10dbf23e0715e5906e146d499a", + "new_sampler_calls": 0, + "summary_timing_calls": 1 + }, + { + "case": "pair-2-candidate", + "pair": 2, + "backend": "candidate", + "process_s": 83.30664087600235, + "wrapper_s": 69.95747389399912, + "plot_s": 43.941108405000705, + "png_export_s": 27.394552567002393, + "axes_s": 5.507749349999358, + "peak_rss_mib": 534.640625, + "png_sha256": "fd3be1c8a96cebc800b89b1d7c161a319d35ca6ac48ad0f23f2640553d9f9bb9", + "checkpoint_sha256": "4ceaaa063547ebf9a03d3f16c8c7cf376b965cf079e4a228f91ad9a00846172c", + "posterior_sha256": "a4234203f31abb988319385b0a5d92f0f57fbc10dbf23e0715e5906e146d499a", + "new_sampler_calls": 0, + "summary_timing_calls": 1 + }, + { + "case": "pair-2-baseline", + "pair": 2, + "backend": "baseline", + "process_s": 111.92577019199962, + "wrapper_s": 101.07498074100295, + "plot_s": 73.25124941300237, + "png_export_s": 19.578193344998, + "axes_s": 6.076578799002164, + "peak_rss_mib": 534.68359375, + "png_sha256": "fd3be1c8a96cebc800b89b1d7c161a319d35ca6ac48ad0f23f2640553d9f9bb9", + "checkpoint_sha256": "4ceaaa063547ebf9a03d3f16c8c7cf376b965cf079e4a228f91ad9a00846172c", + "posterior_sha256": "a4234203f31abb988319385b0a5d92f0f57fbc10dbf23e0715e5906e146d499a", + "new_sampler_calls": 0, + "summary_timing_calls": 1 + }, + { + "case": "pair-3-baseline", + "pair": 3, + "backend": "baseline", + "process_s": 112.29937400999916, + "wrapper_s": 102.5415643760025, + "plot_s": 79.4737175170012, + "png_export_s": 17.815724185002182, + "axes_s": 6.7777833600011945, + "peak_rss_mib": 535.2734375, + "png_sha256": "fd3be1c8a96cebc800b89b1d7c161a319d35ca6ac48ad0f23f2640553d9f9bb9", + "checkpoint_sha256": "4ceaaa063547ebf9a03d3f16c8c7cf376b965cf079e4a228f91ad9a00846172c", + "posterior_sha256": "a4234203f31abb988319385b0a5d92f0f57fbc10dbf23e0715e5906e146d499a", + "new_sampler_calls": 0, + "summary_timing_calls": 1 + } + ], + "pairs": [ + { + "pair": 1, + "process_speedup": 2.0224919854048804, + "wrapper_speedup": 2.133316385137444, + "plot_speedup": 2.7275059781465183 + }, + { + "pair": 2, + "process_speedup": 1.3435395907823888, + "wrapper_speedup": 1.4448060387965644, + "plot_speedup": 1.6670323547110621 + } + ], + "unrun": [ + "pair-3-candidate" + ], + "interpretation": "exploratory paired output replays, not sampler or statistical-efficiency speedups", + "process_speedup": { + "median": 1.6830157880936345, + "minimum": 1.3435395907823888, + "maximum": 2.0224919854048804, + "complete_pairs": 2 + }, + "retained_preflight_failure": { + "status": "halted", + "attempts": [], + "unrun": [ + 0, + 1, + 2, + 3, + 4, + 5 + ], + "reason": "ValueError: environment changed: ['distribution_versions']", + "spent_s": 2.144871865002642 + } +} diff --git a/scripts/analytic_gaussian/nautilus/compact_benchmark.py b/scripts/analytic_gaussian/nautilus/compact_benchmark.py new file mode 100644 index 0000000..d41d950 --- /dev/null +++ b/scripts/analytic_gaussian/nautilus/compact_benchmark.py @@ -0,0 +1,302 @@ +"""One bounded, off-Pulse AB/BA/AB comparison; never retries a stopped run.""" + +import argparse +import contextlib +import copy +import functools +import json +import os +import shutil +import signal +import subprocess +import sys +import time +import traceback +from pathlib import Path + +ROOT = next(p for p in Path(__file__).resolve().parents if (p / "ruff.toml").exists()) +sys.path.insert(0, str(ROOT / "scripts/misc")) +from profiling.nautilus_campaign import environment_key, host_snapshot +from profiling.nautilus_diagnostics import ( + StageLog, + assert_environment, + check_inputs, + estimate, + output_replay, + runtime_identity, + sha256, + stage_summary, +) +from profiling.nautilus_diagnostics import ( + validate_plan as validate_input_plan, +) +from profiling.nautilus_manifest import fingerprint, source_pins +from profiling.nautilus_resources import atomic_json, memory_available, supervise + +LIMITS = {"timeout_s": 240, "memory_mib": 4096, "budget_s": 1800} +ORDER = ["baseline", "candidate", "candidate", "baseline", "baseline", "candidate"] +PROTOCOL = "nautilus-compact-array-experiment@1" + + +def metadata_paths(pythonpath): + """Retain the original activation's auxiliary distribution visibility. + + These are not imported by PyAutoFit. Their egg-info was nevertheless part + of the archived full inventory. Keep that inventory check exact, without + admitting a second PyAutoFit/PyAutoNerves tree into a measured child. + """ + names = {"PyAutoArray", "PyAutoGalaxy", "PyAutoLens", "PyAutoCTI"} + return [p for p in pythonpath.split(os.pathsep) if p and Path(p).name in names] + + +def validate(plan): + if plan["sha256"] != fingerprint({k: v for k, v in plan.items() if k != "sha256"}): + raise ValueError("frozen plan changed") + if plan["protocol"] != PROTOCOL or plan["limits"] != LIMITS: + raise ValueError("unapproved protocol or limits") + if [c["backend"] for c in plan["cases"]] != ORDER: + raise ValueError("unapproved case order") + for index, case in enumerate(plan["cases"]): + if ( + case["id"] != f"pair-{index // 2 + 1}-{ORDER[index]}" + or case["arm"] != "output" + or case["original_n_like"] != 34100 + or case["dimension"] != 30 + or case["summary_timing_call_limit"] != 1 + or case["original_selected_samples"] != 33984 + or case.get("attribution", False) + or case["plot_policy"] + != {"name": "thirty-small", "indices": list(range(30)), "figsize": [12, 12], "dpi": 100} + ): + raise ValueError("unapproved case policy") + + +def prepare(input_plan, baseline_fit): + from nautilus import Sampler + from profiling.nautilus_baseline import git_identity, provenance + from profiling.nautilus_manifest import RunConfig + from profiling.nautilus_plot_comparison import font_cache + from profiling.nautilus_target import CorrelatedGaussianTarget + + old = json.loads(input_plan.read_text()) + validate_input_plan(old) + if old["scope"] != "plot-attribution": + raise ValueError("expected the frozen original attribution input") + check_inputs(old) + actual = provenance() + baseline_source = git_identity(baseline_fit) + if baseline_source["dirty"] or any(s["dirty"] for s in actual["sources"].values()): + raise ValueError("all measured sources must be committed and clean") + candidate = environment_key(actual) + baseline = copy.deepcopy(candidate) + baseline["sources"]["PyAutoFit"] = source_pins({"PyAutoFit": baseline_source})["PyAutoFit"] + assert_environment(runtime_identity(baseline), runtime_identity(old["environment"])) + template = copy.deepcopy(old["cases"][0]) + template.pop("attribution", None) + target = CorrelatedGaussianTarget(30) + sampler = Sampler( + target.prior, + target, + filepath=template["checkpoint"], + **RunConfig(dimension=30, n_live=400, trace=False).constructor(), + ) + restored = estimate(sampler, target) + if ( + restored["posterior_sha256"] != template["original_posterior_sha256"] + or fingerprint(target.truth()) != template["target_sha256"] + ): + raise ValueError("saved posterior/target differs") + plan = { + "protocol": PROTOCOL, + "limits": LIMITS, + "font_cache": font_cache(), + "environments": {"baseline": baseline, "candidate": candidate}, + "source_roots": { + "baseline": str(baseline_fit.resolve()), + "candidate": actual["sources"]["PyAutoFit"]["root"], + "nerves": actual["sources"]["PyAutoNerves"]["root"], + }, + "metadata_pythonpath": metadata_paths(os.environ.get("PYTHONPATH", "")), + "input_plan": str(input_plan.resolve()), + "input_plan_sha256": sha256(input_plan), + "cases": [ + {**template, "id": f"pair-{i // 2 + 1}-{backend}", "backend": backend} + for i, backend in enumerate(ORDER) + ], + } + plan["sha256"] = fingerprint(plan) + validate(plan) + return plan + + +def child(plan, case, directory): + from profiling.nautilus_baseline import provenance + from profiling.nautilus_plot_comparison import font_cache, replaced + from profiling.nautilus_target import CorrelatedGaussianTarget + + validate(plan) + check_inputs(plan) + expected = plan["environments"][case["backend"]] + assert_environment(environment_key(provenance()), expected) + if font_cache() != plan["font_cache"]: + raise ValueError("font cache changed") + target = CorrelatedGaussianTarget(30) + if fingerprint(target.truth()) != case["target_sha256"]: + raise ValueError("target changed") + checkpoint = directory / "checkpoint.hdf5" + shutil.copyfile(case["checkpoint"], checkpoint) + log = StageLog(directory / "stages.jsonl") + adapter_calls = [] + with contextlib.ExitStack() as stack: + if case["backend"] == "candidate": + from autofit.non_linear.plot import compact_corner, nest_plotters + + original = nest_plotters.corner_anesthetic + + def array_corner(*args, **kwargs): + return original(*args, compact_backend="array", **kwargs) + + stack.enter_context(replaced(nest_plotters, "corner_anesthetic", array_corner)) + draw = compact_corner.draw + + @functools.wraps(draw) + def witnessed(*args, **kwargs): + adapter_calls.append(True) + with log.stage("array_posterior_plotting"): + return draw(*args, **kwargs) + + stack.enter_context(replaced(compact_corner, "draw", witnessed)) + result = output_replay(case, checkpoint, target, directory, log) + if len(adapter_calls) != (case["backend"] == "candidate"): + raise ValueError("candidate unexpectedly fell back") + if sha256(checkpoint) != case["checkpoint_sha256"]: + raise ValueError("replay changed copied checkpoint") + assert_environment(environment_key(provenance()), expected) + check_inputs(plan) + return {"status": "success", "adapter_calls": len(adapter_calls), **result} + + +def run(input_plan, baseline_fit, root): + start = time.monotonic() + root.mkdir(parents=True, exist_ok=False) + state = {"status": "running", "attempts": [], "unrun": list(range(6))} + atomic_json(root / "state.json", state) + try: + plan = prepare(input_plan, baseline_fit) + atomic_json(root / "plan.json", plan) + state["preflight_s"] = time.monotonic() - start + for case in plan["cases"]: + if time.monotonic() - start + LIMITS["timeout_s"] > LIMITS["budget_s"]: + raise RuntimeError("aggregate budget exhausted") + snapshot = host_snapshot() + if memory_available() < 2 * LIMITS["memory_mib"] * 1024**2: + raise RuntimeError("insufficient safe host memory") + if snapshot["load"][0] > max(1.0, len(snapshot["affinity"]) / 4): + raise RuntimeError("host load exceeds guard") + check_inputs(plan) + directory = root / case["id"] + directory.mkdir() + row = {"case": case["id"], "status": "running", "host": snapshot} + state["attempts"].append(row) + atomic_json(root / "state.json", state) + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join( + [plan["source_roots"][case["backend"]], plan["source_roots"]["nerves"]] + + plan["metadata_pythonpath"] + ) + with (directory / "run.log").open("w") as output: + tick = time.monotonic() + process = subprocess.Popen( + [ + sys.executable, + str(Path(__file__).resolve()), + "child", + "--plan", + str(root / "plan.json"), + "--case", + case["id"], + "--output", + str(directory), + ], + env=env, + stdout=output, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + supervision = supervise( + process, LIMITS["timeout_s"], LIMITS["memory_mib"] * 1024**2 + ) + row.update( + process_wall_s=time.monotonic() - tick, + supervision=supervision, + stages=stage_summary(directory / "stages.jsonl"), + ) + receipt = directory / "child.json" + if receipt.exists(): + row["child"] = json.loads(receipt.read_text()) + row["status"] = supervision["termination_reason"] or ( + "success" + if supervision["returncode"] == 0 + and row.get("child", {}).get("status") == "success" + else "error" + ) + check_inputs(plan) + atomic_json(directory / "result.json", row) + if row["status"] != "success": + raise RuntimeError(f"{case['id']}: {row['status']}") + if len(state["attempts"]) % 2 == 0: + a, b = state["attempts"][-2:] + if a["child"]["plot"]["png"]["sha256"] != b["child"]["plot"]["png"]["sha256"]: + raise ValueError("paired PNGs differ; exact parity required") + state["spent_s"] = time.monotonic() - start + atomic_json(root / "state.json", state) + print(f"{case['id']}: {row['process_wall_s']:.2f}s", flush=True) + state["status"] = "complete" + except BaseException as error: + state.update(status="halted", reason=f"{type(error).__name__}: {error}") + traceback.print_exc() + finally: + state["spent_s"] = time.monotonic() - start + state["unrun"] = list(range(len(state["attempts"]), 6)) + atomic_json(root / "state.json", state) + return 0 if state["status"] == "complete" else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("run", "child")) + parser.add_argument("--input-plan", type=Path) + parser.add_argument("--baseline-fit", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--plan", type=Path) + parser.add_argument("--case") + args = parser.parse_args() + + def interrupted(signum, frame): + raise KeyboardInterrupt(f"signal {signum}") + + signal.signal(signal.SIGTERM, interrupted) + signal.signal(signal.SIGHUP, interrupted) + for key in ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + ): + os.environ[key] = "1" + os.environ["MPLBACKEND"] = "Agg" + if args.command == "run": + return run(args.input_plan, args.baseline_fit, args.output.resolve()) + plan = json.loads(args.plan.read_text()) + case = next(c for c in plan["cases"] if c["id"] == args.case) + try: + result = child(plan, case, args.output.resolve()) + except Exception as error: + traceback.print_exc() + result = {"status": "error", "error": f"{type(error).__name__}: {error}"} + atomic_json(args.output / "child.json", result) + return 0 if result["status"] == "success" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/analytic_gaussian/nautilus/compact_report.py b/scripts/analytic_gaussian/nautilus/compact_report.py new file mode 100644 index 0000000..657ad12 --- /dev/null +++ b/scripts/analytic_gaussian/nautilus/compact_report.py @@ -0,0 +1,174 @@ +"""Export compact plotting evidence without admitting an unmatched timing arm.""" + +import argparse +import hashlib +import json +import shutil +import statistics +from pathlib import Path + + +def digest(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def pairs(rows): + grouped = {} + for row in rows: + grouped.setdefault(row["pair"], {})[row["backend"]] = row + result = [] + for number, arms in sorted(grouped.items()): + if set(arms) != {"baseline", "candidate"}: + continue + a, b = arms["baseline"], arms["candidate"] + if a["png_sha256"] != b["png_sha256"]: + raise ValueError("paired images differ") + result.append( + { + "pair": number, + "process_speedup": a["process_s"] / b["process_s"], + "wrapper_speedup": a["wrapper_s"] / b["wrapper_s"], + "plot_speedup": a["plot_s"] / b["plot_s"], + } + ) + return result + + +def report(root, destination): + state = json.loads((root / "state.json").read_text()) + plan = json.loads((root / "plan.json").read_text()) + rows = [] + for attempt in state["attempts"]: + if attempt["status"] != "success": + continue + case = next(c for c in plan["cases"] if c["id"] == attempt["case"]) + child = attempt["child"] + if ( + child["new_sampler_likelihood_calls"] != 0 + or child["summary_timing_calls"] != 1 + or child["posterior"]["posterior_sha256"] != case["original_posterior_sha256"] + ): + raise ValueError("sampling/summary invariant differs") + for path in (Path(case["checkpoint"]), root / case["id"] / "checkpoint.hdf5"): + if digest(path) != case["checkpoint_sha256"]: + raise ValueError("checkpoint bytes changed") + png = child["plot"]["png"] + if digest(root / case["id"] / png["path"]) != png["sha256"]: + raise ValueError("PNG bytes changed") + + stage_seconds = {} + for stage in attempt["stages"]["completed"]: + name = stage["stage"] + stage_seconds[name] = stage_seconds.get(name, 0.0) + stage["wall_s"] + rows.append( + { + "case": case["id"], + "pair": int(case["id"].split("-")[1]), + "backend": case["backend"], + "process_s": attempt["process_wall_s"], + "wrapper_s": stage_seconds["wrapped_replay"], + "plot_s": stage_seconds["search_corner"], + "png_export_s": stage_seconds["png_export"], + "axes_s": stage_seconds["axes_construction"], + "peak_rss_mib": attempt["supervision"]["sampled_group_peak_rss_bytes"] / 1024**2, + "png_sha256": png["sha256"], + "checkpoint_sha256": case["checkpoint_sha256"], + "posterior_sha256": case["original_posterior_sha256"], + "new_sampler_calls": 0, + "summary_timing_calls": 1, + } + ) + paired = pairs(rows) + summary = { + "status": state["status"], + "reason": state.get("reason"), + "spent_s": state["spent_s"], + "protocol": plan["protocol"], + "limits": plan["limits"], + "measured_environments": plan["environments"], + "plan_sha256": plan["sha256"], + "rows": rows, + "pairs": paired, + "unrun": [plan["cases"][i]["id"] for i in state["unrun"]], + "interpretation": "exploratory paired output replays, not sampler or statistical-efficiency speedups", + } + if paired: + values = [p["process_speedup"] for p in paired] + summary["process_speedup"] = { + "median": statistics.median(values), + "minimum": min(values), + "maximum": max(values), + "complete_pairs": len(values), + } + previous = root.parent / "compact-array-01/state.json" + if previous.exists(): + summary["retained_preflight_failure"] = json.loads(previous.read_text()) + destination.mkdir(parents=True, exist_ok=False) + (destination / "summary.json").write_text(json.dumps(summary, indent=2) + "\n") + image_case = next(c for c in plan["cases"] if c["backend"] == "candidate") + attempt = next(r for r in state["attempts"] if r["case"] == image_case["id"]) + shutil.copyfile( + root / image_case["id"] / attempt["child"]["plot"]["png"]["path"], + destination / "compact_corner.png", + ) + lines = [ + "# Compact corner plotting experiment", + "", + "The array renderer reduced full replay time in both completed pairs while producing byte-identical PNGs. " + "Five cases completed; the host-load guard stopped the final candidate case. " + "The third baseline is unpaired and is excluded from every speedup summary.", + "", + "| Pair | Backend | Process (s) | Wrapped output (s) | Corner plot (s) | Peak RSS (MiB) |", + "|---|---|---:|---:|---:|---:|", + ] + for row in rows: + lines.append( + f"| {row['pair']} | {row['backend']} | {row['process_s']:.2f} | " + f"{row['wrapper_s']:.2f} | {row['plot_s']:.2f} | {row['peak_rss_mib']:.1f} |" + ) + lines.extend( + [ + "", + "Completed-pair process ratios (baseline / candidate): " + + ", ".join(f"{p['process_speedup']:.3f}x" for p in paired) + + ".", + "The median/range in summary.json use only those two pairs. Timing variation is material; " + "this is exploratory evidence and does not justify changing the default.", + "", + "All five cases retained all 33,984 weighted samples, the native count of 34,100, unchanged " + "posterior/checkpoint hashes, zero sampler likelihood calls and exactly one separately authorized " + "final-summary timing call. Both matched pairs have identical PNG bytes. " + "The canvas remains 12x12 inches at 100 dpi with every cross-parameter panel and unchanged typography.", + "", + f"Aggregate elapsed time: {state['spent_s']:.2f}s, including preflight, against 1800s. " + "Every completed child stayed within 240s/4096 MiB. Memory is sampled process-group RSS; " + "brief spikes can be missed. The start guard uses one-minute host load <=2 for the eight-CPU affinity. " + "The precise failing host snapshot was not persisted. No automatic retry followed it.", + "", + "The first attempt stopped before any child because the activation omitted auxiliary package " + "metadata paths. No installed dependency changed. The corrected attempt was explicitly approved; " + "both attempts and all raw data remain retained.", + "", + "Measured library: e57611dc6; producer: 3bce28c; baseline: bdb7af0e9. " + "A later library guard sends non-string labels back to pandas; the measured string-label drawing path " + "is unchanged. See summary.json for complete frozen source/package identities.", + "", + "[Library PR](https://github.com/PyAutoLabs/PyAutoFit/pull/1764) · " + "[Experiment PR](https://github.com/PyAutoLabs/autofit_profiling/pull/14). " + "Outside Pulse. Default backend remains anesthetic; merge remains human. " + "This does not resolve 30D evidence accuracy or complete the wider phase 0b.", + "", + "![Measured compact corner plot](compact_corner.png)", + "", + ] + ) + (destination / "README.md").write_text("\n".join(lines)) + return summary + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("destination", type=Path) + args = parser.parse_args() + report(args.root, args.destination) diff --git a/scripts/misc/test/test_nautilus_compact_benchmark.py b/scripts/misc/test/test_nautilus_compact_benchmark.py new file mode 100644 index 0000000..a019177 --- /dev/null +++ b/scripts/misc/test/test_nautilus_compact_benchmark.py @@ -0,0 +1,101 @@ +"""Admission rejects enlarged budgets, sampling, thinning and reordered pairs.""" + +import copy +import importlib.util +from pathlib import Path + +import pytest +from profiling.nautilus_manifest import fingerprint + +SOURCE = Path(__file__).resolve().parents[2] / "analytic_gaussian/nautilus/compact_benchmark.py" +spec = importlib.util.spec_from_file_location("compact_benchmark", SOURCE) +benchmark = importlib.util.module_from_spec(spec) +spec.loader.exec_module(benchmark) + + +def plan(): + result = { + "protocol": benchmark.PROTOCOL, + "limits": benchmark.LIMITS.copy(), + "cases": [ + { + "id": f"pair-{i // 2 + 1}-{backend}", + "backend": backend, + "arm": "output", + "dimension": 30, + "original_n_like": 34100, + "summary_timing_call_limit": 1, + "original_selected_samples": 33984, + "plot_policy": { + "name": "thirty-small", + "indices": list(range(30)), + "figsize": [12, 12], + "dpi": 100, + }, + } + for i, backend in enumerate(benchmark.ORDER) + ], + } + result["sha256"] = fingerprint(result) + return result + + +@pytest.mark.parametrize( + "change", ["budget", "order", "sample", "timing", "plot", "sampling", "hash"] +) +def test_scope_change_rejected(change): + p = plan() + benchmark.validate(p) + if change == "budget": + p["limits"]["budget_s"] += 1 + elif change == "order": + p["cases"].reverse() + elif change == "sample": + p["cases"][0]["original_selected_samples"] -= 1 + elif change == "timing": + p["cases"][0]["summary_timing_call_limit"] += 1 + elif change == "plot": + p["cases"][0]["plot_policy"]["indices"] = [0, 1] + elif change == "sampling": + p["cases"][0]["arm"] = "evidence" + else: + p["sha256"] = "bad" + if change != "hash": + p["sha256"] = fingerprint({k: v for k, v in p.items() if k != "sha256"}) + with pytest.raises(ValueError): + benchmark.validate(p) + + +def test_one_shot_directory_cannot_be_reused(tmp_path): + root = tmp_path / "run" + root.mkdir() + with pytest.raises(FileExistsError): + benchmark.run(None, None, root) + + +def test_auxiliary_metadata_paths_never_reintroduce_library_roots(tmp_path): + names = ["PyAutoFit", "PyAutoNerves", "PyAutoArray", "PyAutoGalaxy", "PyAutoLens", "unknown"] + paths = [str(tmp_path / name) for name in names] + assert benchmark.metadata_paths(benchmark.os.pathsep.join(paths)) == paths[2:5] + + +def test_report_excludes_unmatched_baseline_and_checks_image_identity(): + spec = importlib.util.spec_from_file_location( + "compact_report", SOURCE.with_name("compact_report.py") + ) + report = importlib.util.module_from_spec(spec) + spec.loader.exec_module(report) + a = { + "pair": 1, + "backend": "baseline", + "png_sha256": "same", + "process_s": 100, + "wrapper_s": 80, + "plot_s": 60, + } + b = {**a, "backend": "candidate", "process_s": 50, "wrapper_s": 40, "plot_s": 30} + unmatched = {**a, "pair": 3} + result = report.pairs([a, b, unmatched]) + assert result == [{"pair": 1, "process_speedup": 2, "wrapper_speedup": 2, "plot_speedup": 2}] + with pytest.raises(ValueError, match="images differ"): + report.pairs([a, {**b, "png_sha256": "different"}])