From b601d24ba4a87b433f604b05b69142786a6eb429 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 14:43:46 +0000 Subject: [PATCH 1/2] Compare native and scalar weight updates across complete fits --- .../nautilus_weight_whole_fit/compare_fits.py | 218 ++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 experiments/nautilus_weight_whole_fit/compare_fits.py diff --git a/experiments/nautilus_weight_whole_fit/compare_fits.py b/experiments/nautilus_weight_whole_fit/compare_fits.py new file mode 100644 index 0000000..25c5d88 --- /dev/null +++ b/experiments/nautilus_weight_whole_fit/compare_fits.py @@ -0,0 +1,218 @@ +"""Paired whole native fits for the retained-array scalar weight candidate.""" + +import argparse +import hashlib +import importlib.util +import json +import os +import platform +import signal +import subprocess +import sys +import time +from contextlib import contextmanager +from importlib.metadata import version +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts/misc")) +from profiling.nautilus_resources import atomic_json, supervise + +BASELINE_SHA = "081a2bda9a61e24e2c82663b6b4711461e86ddd924c8e81ba5bf66daad573286" +REFERENCE_SHA = "24f24946e38c2a4c1875f8c1d7aa8199c9d4ce89a87e170b1557f362e6b5ae36" +CANDIDATE_SHA = "965c8cd737f52049761facf7523627f7d1f35803afd2d383bfb41d2f40d1c96c" +ORDER = ("native", "candidate", "candidate", "native") +THREADS = dict.fromkeys( + ( + "OPENBLAS_NUM_THREADS", + "OMP_NUM_THREADS", + "MKL_NUM_THREADS", + "BLIS_NUM_THREADS", + "NUMEXPR_NUM_THREADS", + ), + "1", +) + + +def verified(path, expected): + data = path.read_bytes() + if hashlib.sha256(data).hexdigest() != expected: + raise ValueError(f"Unexpected SHA-256 for {path.name}") + return data + + +def load_module(path, expected, name): + verified(path, expected) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def reference(directory): + return json.loads(verified(directory / "result.json", REFERENCE_SHA)) + + +@contextmanager +def solver(variant, candidate): + import nautilus + from nautilus.bounds import basic + + calls = [] + with TemporaryDirectory() as tmp: + kernel = basic.minimum_volume_enclosing_ellipsoid + if variant == "candidate": + module = candidate.load_candidate(Path(nautilus.__file__).parent, Path(tmp)) + kernel = module.minimum_volume_enclosing_ellipsoid + + def counted(points, *args, **kwargs): + calls.append(points.shape) + return kernel(points, *args, **kwargs) + + with patch.object(basic, "minimum_volume_enclosing_ellipsoid", counted): + yield calls + + +def check_native_checkpoint(base, directory, expected): + from nautilus import Sampler + from profiling.nautilus_target import CorrelatedGaussianTarget + + path = directory / "checkpoint.hdf5" + if not path.is_file(): + raise FileNotFoundError(path) + + def forbidden(*args, **kwargs): + raise ValueError("Native checkpoint reopening attempted a likelihood evaluation") + + restored = Sampler( + CorrelatedGaussianTarget.prior, + forbidden, + pool=None, + filepath=str(path), + **base.CONFIG.constructor(), + ) + if base.signature(restored, restored.posterior()) != expected: + raise ValueError("Unpatched native checkpoint result differs") + + +def child(directory, baseline_dir, variant): + base = load_module(baseline_dir / "run.py", BASELINE_SHA, "whole_fit_baseline") + candidate = load_module( + ROOT / "experiments/nautilus_ellipsoid_weight_update/compare.py", + CANDIDATE_SHA, + "weight_candidate", + ) + ref = reference(baseline_dir) + expected = ref["runs"][0]["science"] + with solver(variant, candidate) as calls: + base.one_fit(directory, "control") + fit = json.loads((directory / "fit.json").read_text()) + if fit["science"] != expected or not fit["checkpoint_reopen_equal"]: + raise ValueError("Whole-fit science differs from the frozen native control") + traced = ref["runs"][1]["builds"] + if len(calls) != sum(b["calls"]["ellipsoid"] for b in traced): + raise ValueError("Unexpected number of enclosing-ellipsoid calls") + check_native_checkpoint(base, directory, expected) + fit.update(variant=variant, solver_call_shapes=calls, native_reopen_equal=True) + atomic_json(directory / "verified.json", fit) + + +def run(output, baseline_dir): + ref = reference(baseline_dir) + verified(baseline_dir / "run.py", BASELINE_SHA) + candidate = ROOT / "experiments/nautilus_ellipsoid_weight_update/compare.py" + verified(candidate, CANDIDATE_SHA) + versions = {name: version(name) for name in ref["versions"]} + if versions != ref["versions"] or platform.python_version() != ref["python"]: + raise ValueError("Runtime differs from the registered whole-fit versions") + output.mkdir(parents=True, exist_ok=False) + receipt = output / "result.json" + state = { + "status": "running", + "baseline_sha256": BASELINE_SHA, + "reference_sha256": REFERENCE_SHA, + "candidate_loader_sha256": CANDIDATE_SHA, + "nautilus_source_sha256": ref["nautilus_source_sha256"], + "driver_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "configuration": ref["configuration"], + "versions": versions, + "python": platform.python_version(), + "platform": platform.platform(), + "limits": ref["limits"], + "runs": [], + "unrun": list(ORDER), + } + atomic_json(receipt, state) + started = time.monotonic() + try: + for i, variant in enumerate(ORDER, 1): + directory = output / f"{i}-{variant}" + directory.mkdir() + row = {"case": directory.name, "variant": variant, "load_average": os.getloadavg()} + state["runs"].append(row) + remaining = state["limits"]["total_s"] - (time.monotonic() - started) + if remaining <= 0: + raise TimeoutError("Aggregate allowance exhausted") + with (directory / "run.log").open("w") as log: + proc = subprocess.Popen( + [ + sys.executable, + __file__, + str(directory), + str(baseline_dir), + "--child", + variant, + ], + env={**os.environ, **THREADS}, + start_new_session=True, + stdout=log, + stderr=subprocess.STDOUT, + ) + state["unrun"].pop(0) + row["supervision"] = supervise( + proc, + min(state["limits"]["child_s"], remaining), + state["limits"]["group_mib"] * 1024**2, + ) + if row["supervision"]["returncode"] != 0: + raise RuntimeError(f"{directory.name} failed; see its log and supervisor receipt") + row.update(json.loads((directory / "verified.json").read_text())) + shapes = row.pop("solver_call_shapes") + row["solver_call_count"] = len(shapes) + row["solver_shapes_sha256"] = hashlib.sha256(json.dumps(shapes).encode()).hexdigest() + if row["solver_shapes_sha256"] != state["runs"][0]["solver_shapes_sha256"]: + raise ValueError(f"{directory.name} solver input shape sequence differs") + if time.monotonic() - started > state["limits"]["total_s"]: + raise TimeoutError("Aggregate allowance exhausted") + row["status"] = "success" + atomic_json(receipt, state) + state["status"] = "complete" + except BaseException as error: + state.update(status="halted", reason=f"{type(error).__name__}: {error}") + if state["runs"] and "status" not in state["runs"][-1]: + state["runs"][-1]["status"] = "failed" + raise + finally: + state["elapsed_s"] = time.monotonic() - started + atomic_json(receipt, state) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path, help="Fresh output directory") + parser.add_argument( + "baseline_dir", type=Path, help="Pinned whole-fit experiment directory from PR #21" + ) + parser.add_argument("--child", choices=("native", "candidate"), help=argparse.SUPPRESS) + args = parser.parse_args() + if args.child: + child(args.output, args.baseline_dir, args.child) + else: + + def interrupted(signum, frame): + raise SystemExit(128 + signum) + + signal.signal(signal.SIGTERM, interrupted) + run(args.output, args.baseline_dir) From b10c0b142adeaf486109b30fe1052aabc6d0c898 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 24 Nov 2026 14:48:18 +0000 Subject: [PATCH 2/2] Record exact whole-fit parity and opposing timing effects --- .../nautilus_weight_whole_fit/README.md | 32 ++ .../nautilus_weight_whole_fit/result.json | 274 ++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 experiments/nautilus_weight_whole_fit/README.md create mode 100644 experiments/nautilus_weight_whole_fit/result.json diff --git a/experiments/nautilus_weight_whole_fit/README.md b/experiments/nautilus_weight_whole_fit/README.md new file mode 100644 index 0000000..e5262a5 --- /dev/null +++ b/experiments/nautilus_weight_whole_fit/README.md @@ -0,0 +1,32 @@ +# Scalar weight updates preserved the posterior. Whole-fit timing was inconclusive + +On the 10D seed-2 fixture, the scalar update was 4.1% slower than native when it ran second and 15.2% faster when it ran first. Both comparisons passed exact scientific parity. The pair effects changed sign, so the registered decision rule leaves the end-to-end speed benefit unresolved. [All four fit receipts](result.json) + +| Run order | Native fit | Candidate fit | Candidate wall-time change relative to native | +|---|---:|---:|---:| +| 1. Native then candidate | 41.48 s | 43.17 s | +4.1% | +| 2. Candidate then native | 45.08 s | 38.22 s | −15.2% | + +Every fit made **101 enclosing-ellipsoid calls** with the same ordered sequence of input shapes, and **23,500 likelihood evaluations**. The ordered posterior hash (`919674e04195da25f5d6646743b2ce8aa0089fc5642e7cda523dd72991eae260`), log evidence (-12.37447679), ESS (10038.50761), 12 shells and exploration flags matched the frozen native reference exactly. All four checkpoints reopened under unmodified Nautilus with the same scientific signature and zero additional likelihood evaluations. The four cases completed in 174.7 s on the shared WSL2 laptop, with a maximum sampled process-group RSS of 161.5 MiB. + +The native controls themselves differed by 3.60 s. This small pilot cannot attribute the variation to execution order or a specific hardware cause. [PR #23](https://github.com/PyAutoLabs/autofit_profiling/pull/23) measured a consistent direction for the isolated outer-bound reconstruction on retained inputs. The whole-fit result does not support changing the production solver. If development continues, the next discriminating experiment is a pre-registered paired comparison on a quieter CPU allocation with multiple seeds and separate kernel and total-fit timings. The present study made no allocation or campaign request. + +## What was timed + +Each fresh process used Nautilus 1.0.5, 400 live points, four native neural networks, batches of 100 and an ESS target of 10,000. The 10D correlated Gaussian, seed 2, discarded exploration samples, one numerical thread and native checkpoints match the original native experiment. The timed interval starts before constructing `Sampler` and ends after materializing its ordered posterior. It includes checkpoint writes. Imports, loading the experimental solver, result hashing and checkpoint verification occur outside the clock. Both variants count invocations through the same lightweight wrapper. The candidate replaces the enclosing-ellipsoid routine only for that process and restores the original callable afterward. + +The native–candidate–candidate–native order produces one pair in each direction. Positive reductions mean the candidate completed sooner. The decision rule gives an inconclusive timing result when the pair signs disagree. Repeated fits use the same seed to check numerical parity and control workload variation. They supply no cross-seed reliability estimate. + +The supervisor limited each fresh process group to 180 seconds and 4096 MiB. The four-fit limit was 720 seconds. Any incomplete fit, cap or science mismatch stops the next case. The compact receipt retains the science values, solver call count and ordered shape digest, times and supervision. The four checkpoints and child logs are in the retained raw output. + +## Reproduce + +Use Linux and the exact Python and dependency versions in [result.json](result.json). This branch contains the [candidate loader](../nautilus_ellipsoid_weight_update/compare.py). The runner also verifies two files from the pinned [whole-fit reference directory](https://github.com/PyAutoLabs/autofit_profiling/tree/d8709a7d536a61f278a311b67ac99ea66f61702f/experiments/nautilus_whole_fit_geometry), `run.py` and `result.json`. Pass their directory in a local checkout of that revision as the second argument. + +```sh +python experiments/nautilus_weight_whole_fit/compare_fits.py \ + output/whole-fit-weight-pilot \ + /path/to/baseline-checkout/experiments/nautilus_whole_fit_geometry +``` + +Use a fresh output directory. The trial is an off-board CPU engineering experiment tracked by [issue #24](https://github.com/PyAutoLabs/autofit_profiling/issues/24). diff --git a/experiments/nautilus_weight_whole_fit/result.json b/experiments/nautilus_weight_whole_fit/result.json new file mode 100644 index 0000000..bca9df8 --- /dev/null +++ b/experiments/nautilus_weight_whole_fit/result.json @@ -0,0 +1,274 @@ +{ + "status": "complete", + "baseline_sha256": "081a2bda9a61e24e2c82663b6b4711461e86ddd924c8e81ba5bf66daad573286", + "reference_sha256": "24f24946e38c2a4c1875f8c1d7aa8199c9d4ce89a87e170b1557f362e6b5ae36", + "candidate_loader_sha256": "965c8cd737f52049761facf7523627f7d1f35803afd2d383bfb41d2f40d1c96c", + "nautilus_source_sha256": "61e91f8fb85cf4a38877cd1c65bb0b111589bde77f5f74acb22a90f3ff2ec45c", + "driver_sha256": "89b0bc640dbca3fe6f2eb835c82359832d201813d1e4a9ca29cc54b9ada5267a", + "configuration": { + "constructor": { + "n_dim": 10, + "n_live": 400, + "n_update": 400, + "n_points_min": 60, + "n_like_new_bound": 4000, + "enlarge_per_dim": 1.1, + "split_threshold": 100, + "n_networks": 4, + "n_batch": 100, + "vectorized": false, + "seed": 2 + }, + "stopping": { + "f_live": 0.01, + "n_shell": 1, + "n_eff": 10000, + "discard_exploration": true, + "verbose": false + } + }, + "versions": { + "nautilus-sampler": "1.0.5", + "numpy": "1.26.4", + "scipy": "1.15.3", + "scikit-learn": "1.7.2", + "h5py": "3.10.0", + "threadpoolctl": "3.6.0", + "joblib": "1.5.2" + }, + "python": "3.10.12", + "platform": "Linux-6.18.58.1-microsoft-standard-WSL2-x86_64-with-glibc2.35", + "limits": { + "child_s": 180, + "group_mib": 4096, + "total_s": 720 + }, + "runs": [ + { + "case": "1-native", + "variant": "native", + "load_average": [ + 1.7109375, + 3.484375, + 2.76611328125 + ], + "supervision": { + "returncode": 0, + "termination_reason": null, + "sampled_group_peak_rss_bytes": 165105664, + "memory_limit_bytes": 4294967296, + "rss_sample_interval_s": 0.05, + "rss_note": "process group sum; shared pages may repeat; sub-interval spikes may be missed" + }, + "science": { + "posterior_sha256": "919674e04195da25f5d6646743b2ce8aa0089fc5642e7cda523dd72991eae260", + "n_like": 23500, + "ess": 10038.507608002912, + "log_z": -12.37447679148005, + "shells": 12, + "explored": true, + "discard_exploration": true + }, + "checkpoint_reopen_equal": true, + "native_threads": [ + { + "internal_api": "openblas", + "version": "0.3.23.dev", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openblas", + "version": "0.3.28", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openmp", + "version": null, + "num_threads": 1, + "architecture": null + } + ], + "fit_s": 41.47792679899794, + "constructor_s": 0.00022622599863098003, + "sampling_s": 41.452542333001475, + "posterior_s": 0.025158239997836063, + "builds": [], + "native_reopen_equal": true, + "solver_call_count": 101, + "solver_shapes_sha256": "3020cb4d7bdc3f6abfd50232171553596107f044e6d9c9380c67dbf6e3146b2f", + "status": "success" + }, + { + "case": "2-candidate", + "variant": "candidate", + "load_average": [ + 2.13916015625, + 3.35205078125, + 2.75537109375 + ], + "supervision": { + "returncode": 0, + "termination_reason": null, + "sampled_group_peak_rss_bytes": 167063552, + "memory_limit_bytes": 4294967296, + "rss_sample_interval_s": 0.05, + "rss_note": "process group sum; shared pages may repeat; sub-interval spikes may be missed" + }, + "science": { + "posterior_sha256": "919674e04195da25f5d6646743b2ce8aa0089fc5642e7cda523dd72991eae260", + "n_like": 23500, + "ess": 10038.507608002912, + "log_z": -12.37447679148005, + "shells": 12, + "explored": true, + "discard_exploration": true + }, + "checkpoint_reopen_equal": true, + "native_threads": [ + { + "internal_api": "openblas", + "version": "0.3.23.dev", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openblas", + "version": "0.3.28", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openmp", + "version": null, + "num_threads": 1, + "architecture": null + } + ], + "fit_s": 43.16674992600019, + "constructor_s": 0.00018324000120628625, + "sampling_s": 43.13465697499851, + "posterior_s": 0.031909711000480456, + "builds": [], + "native_reopen_equal": true, + "solver_call_count": 101, + "solver_shapes_sha256": "3020cb4d7bdc3f6abfd50232171553596107f044e6d9c9380c67dbf6e3146b2f", + "status": "success" + }, + { + "case": "3-candidate", + "variant": "candidate", + "load_average": [ + 2.568359375, + 3.28759765625, + 2.76171875 + ], + "supervision": { + "returncode": 0, + "termination_reason": null, + "sampled_group_peak_rss_bytes": 169304064, + "memory_limit_bytes": 4294967296, + "rss_sample_interval_s": 0.05, + "rss_note": "process group sum; shared pages may repeat; sub-interval spikes may be missed" + }, + "science": { + "posterior_sha256": "919674e04195da25f5d6646743b2ce8aa0089fc5642e7cda523dd72991eae260", + "n_like": 23500, + "ess": 10038.507608002912, + "log_z": -12.37447679148005, + "shells": 12, + "explored": true, + "discard_exploration": true + }, + "checkpoint_reopen_equal": true, + "native_threads": [ + { + "internal_api": "openblas", + "version": "0.3.23.dev", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openblas", + "version": "0.3.28", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openmp", + "version": null, + "num_threads": 1, + "architecture": null + } + ], + "fit_s": 38.219748180999886, + "constructor_s": 0.0002622360007080715, + "sampling_s": 38.18582509100088, + "posterior_s": 0.03366085399829899, + "builds": [], + "native_reopen_equal": true, + "solver_call_count": 101, + "solver_shapes_sha256": "3020cb4d7bdc3f6abfd50232171553596107f044e6d9c9380c67dbf6e3146b2f", + "status": "success" + }, + { + "case": "4-native", + "variant": "native", + "load_average": [ + 2.724609375, + 3.23486328125, + 2.7666015625 + ], + "supervision": { + "returncode": 0, + "termination_reason": null, + "sampled_group_peak_rss_bytes": 167489536, + "memory_limit_bytes": 4294967296, + "rss_sample_interval_s": 0.05, + "rss_note": "process group sum; shared pages may repeat; sub-interval spikes may be missed" + }, + "science": { + "posterior_sha256": "919674e04195da25f5d6646743b2ce8aa0089fc5642e7cda523dd72991eae260", + "n_like": 23500, + "ess": 10038.507608002912, + "log_z": -12.37447679148005, + "shells": 12, + "explored": true, + "discard_exploration": true + }, + "checkpoint_reopen_equal": true, + "native_threads": [ + { + "internal_api": "openblas", + "version": "0.3.23.dev", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openblas", + "version": "0.3.28", + "num_threads": 1, + "architecture": "Haswell" + }, + { + "internal_api": "openmp", + "version": null, + "num_threads": 1, + "architecture": null + } + ], + "fit_s": 45.08070869999938, + "constructor_s": 0.00035569399915402755, + "sampling_s": 45.051428241000394, + "posterior_s": 0.028924764999828767, + "builds": [], + "native_reopen_equal": true, + "solver_call_count": 101, + "solver_shapes_sha256": "3020cb4d7bdc3f6abfd50232171553596107f044e6d9c9380c67dbf6e3146b2f", + "status": "success" + } + ], + "unrun": [], + "elapsed_s": 174.66293823900196 +} \ No newline at end of file