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
45 changes: 45 additions & 0 deletions experiments/nautilus_bound_cadence/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Nautilus bound-update cadence on complete PyAutoFit fits

This local pilot compares the native interval of 200 with an interval of 400 at 200 live points and four neural networks. Each row is a pair of complete fits. The two fixtures share the same simulated 100-pixel Gaussian-profile data. The second uses a signed centre and evaluates the profile at its absolute value. Its positive and negative modes have exactly equal prior and posterior mass and its evidence equals that of the first fixture. [Registered comparison and decision rules](https://github.com/PyAutoLabs/autofit_profiling/issues/26).

## Paired results

Values in paired columns run from default to doubled interval. A positive wall reduction means the doubled interval finished sooner. Peak columns give the first sampler evaluation within one log-likelihood unit of the independently fitted maximum. The symmetric rows show positive / negative peaks.

| Fixture | Seed | Wall (s) | Reduction | Bound builds | Evaluations | Default peak calls | Doubled peak calls |
|---|---:|---:|---:|---:|---:|---:|---:|
| profile | 1 | 60.64 → 39.58 | 34.7% | 26 → 18 | 7,500 → 9,300 | 4278 | 6020 |
| profile | 2 | 53.55 → 39.89 | 25.5% | 28 → 19 | 7,400 → 9,200 | 4043 | 5608 |
| symmetric | 1 | 98.98 → 68.11 | 31.2% | 25 → 18 | 7,700 → 9,300 | 4737 / 4740 | 6235 / 5561 |
| symmetric | 2 | 94.12 → 63.61 | 32.4% | 26 → 18 | 7,500 → 9,300 | 5136 / 4427 | 6047 / 5486 |

| Fixture | Seed | Arm | Training (s) | Geometry (s) | Log evidence | ESS | Positive-mode mass |
|---|---:|---|---:|---:|---:|---:|---:|
| profile | 1 | default | 22.76 | 10.38 | -57.5115 | 1301 | — |
| profile | 1 | doubled | 16.66 | 8.13 | -57.4934 | 1451 | — |
| profile | 2 | doubled | 15.58 | 7.96 | -57.4815 | 1570 | — |
| profile | 2 | default | 22.69 | 10.11 | -57.4743 | 1381 | — |
| symmetric | 1 | doubled | 35.53 | 10.36 | -57.4991 | 1563 | 0.490 |
| symmetric | 1 | default | 51.47 | 14.94 | -57.4734 | 1416 | 0.520 |
| symmetric | 2 | default | 46.75 | 14.00 | -57.4966 | 1405 | 0.496 |
| symmetric | 2 | doubled | 33.96 | 9.70 | -57.4785 | 1650 | 0.501 |

## Decision

The doubled interval finished sooner in 4 of four pairs. In 3 pairs at least one peak took over 25% more evaluations to reach. The registered pilot decision is **keep the native default**. All eight runs recovered the expected peaks and met the evidence tolerance. Both symmetric seeds met the mode-mass gate in both arms. Every pair met the folded posterior-mean gate.

For the Gaussian profile the doubled interval required 1,800 extra evaluations for each seed. Dividing the paired wall saving by those extra calls gives about 11.7 ms and 7.6 ms per additional evaluation respectively. In a simple serial cost model, adding that much work to every likelihood call would use up the observed savings. This extrapolation assumes the sampling path and other costs stay fixed. Lensing fits and batched GPU execution need their own measurements.

## Method and reproduction

Each case ran in a fresh local WSL process on an Intel Core i9-10885H with one sampler core, one numerical thread, NumPy, batch 100, native checkpointing, normal PyAutoFit output and target ESS 500. Seeds 1 and 2 were paired within each fixture. The runner reversed arm order between seeds and between fixtures. Wall is the elapsed time of the full search.fit call. Training and geometry are timed by the existing exclusive component wrappers. The count and discovery metrics cover sampler evaluations only. Reaching the threshold counts the position within the batch. Elapsed seconds to the threshold were outside the timing protocol.

Least squares gave a peak log likelihood of −38.17109. Tensor quadrature over all three uniform prior ranges gave log evidence −57.45410 at orders 32 and 48. The signed prior folds exactly onto the original positive prior. Posterior checks use normalized sample weights, sign mass and marginal means after folding the centre. The two seeds form a bounded engineering pilot. The symmetric control has two equal peaks and leaves recovery of faint secondary modes on observational data open.

The eight fits ran with [driver revision b8c5549](https://github.com/PyAutoLabs/autofit_profiling/blob/b8c5549171304ef0d333808c880cc82ee36cd2eb/experiments/nautilus_bound_cadence/compare.py). The runner requires the PyAutoFit and PyAutoNerves checkouts and dependency versions in [the receipt](result.json) on the Python import path. From the producer checkout run the following command with a fresh output path. The supervisor caps each child at 300 seconds and writes the ordered results, gates and individual fit logs under that path.

```sh
python experiments/nautilus_bound_cadence/compare.py output/bound_cadence_pilot
```

The comparison is an off-board experiment under the [canonical profiling producer task](https://github.com/PyAutoLabs/PyAutoPulse/blob/main/tasks/autofit_profiling_bootstrap.md). [Application breakdown](https://github.com/PyAutoLabs/autofit_profiling/blob/e64e3a7e5c8f9d9b3e4aba3fded2c0ea04b09dbf/results/gaussian_x1/nautilus/breakdown.json).
272 changes: 272 additions & 0 deletions experiments/nautilus_bound_cadence/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
"""Paired search.fit comparisons for issue #26. Run from a fresh output directory."""

import argparse
import json
import os
import platform
import subprocess
import sys
import time
from pathlib import Path
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts" / "gaussian_x1" / "nautilus"))

import numpy as np
import search_fit_breakdown as baseline
from nautilus import Sampler
from scipy.optimize import least_squares
from scipy.special import logsumexp

THREAD_VARS = ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "BLIS_NUM_THREADS")
ARMS = ("default", "doubled")
FIXTURES = ("profile", "symmetric")


def reference(dataset):
"""Integrate the uniform prior by tensor quadrature, refined around the fitted peak."""
x, data, noise = dataset

def residual(params):
return (data - baseline.Gaussian(*params).model_data_from(x)) / noise

fit = least_squares(residual, [50, 25, 10], bounds=([0, 0, 1e-8], [100, 50, 50]))
widths = np.sqrt(np.diag(np.linalg.inv(fit.jac.T @ fit.jac)))
log_evidences = []
for order in (16, 32, 48):
nodes, weights = np.polynomial.legendre.leggauss(order)
axes = []
for peak, width, upper in zip(fit.x, widths, (100, 50, 50)):
edges = np.unique(
np.clip([0, peak - 12 * width, peak, peak + 12 * width, upper], 0, upper)
)
grid, mass = [], []
for lo, hi in zip(edges[:-1], edges[1:]):
grid.extend((hi + lo + (hi - lo) * nodes) / 2)
mass.extend(weights * (hi - lo) / (2 * upper))
axes.append((np.asarray(grid), np.asarray(mass)))
(centres, wc), (amps, wa), (sigmas, ws) = axes
parts = []
for centre, w in zip(centres, wc):
basis = np.exp(-0.5 * ((x - centre) / sigmas[:, None]) ** 2) / (
sigmas[:, None] * np.sqrt(2 * np.pi)
)
residuals = (data - amps[:, None, None] * basis) / noise
ll = -0.5 * np.sum(residuals**2, axis=-1)
parts.append(np.log(w) + logsumexp(ll, b=wa[:, None] * ws))
log_evidences.append(float(logsumexp(parts)))
if abs(log_evidences[-1] - log_evidences[-2]) > 0.001:
raise RuntimeError("Evidence quadrature failed to converge")
return {
"best_log_likelihood": -fit.cost,
"maximum": fit.x.tolist(),
"orders": [16, 32, 48],
"log_evidences": log_evidences,
}


class SignedGaussian(baseline.Gaussian):
"""Identical positive- and negative-centre peaks under a uniform signed prior."""

def model_data_from(self, xvalues):
return baseline.Gaussian(abs(self.centre), self.normalization, self.sigma).model_data_from(
xvalues
)


def run_one(directory, fixture, arm, seed, ref):
if (directory / "output").exists():
raise FileExistsError("Each child needs a fresh output directory")
baseline.af.conf.instance.push(new_path=ROOT / "config", output_path=directory / "output")
model = baseline.make_model()
if fixture == "symmetric":
model = baseline.af.Model(
SignedGaussian,
normalization=model.normalization,
sigma=model.sigma,
centre=baseline.af.UniformPrior(lower_limit=-100, upper_limit=100),
)
names = list(model.parameter_names)
centre_index = names.index("centre")
search = baseline.af.Nautilus(
name="cadence",
verbose=False,
n_live=200,
n_networks=4,
number_of_cores=1,
seed=seed,
n_update=None if arm == "default" else 400,
)
analysis = baseline.AnalysisGaussianX1(*baseline.make_dataset())
trace = {"calls": 0, "peak_calls": {}, "native": {}}
timer = baseline.ExclusiveTimer()
restore = baseline.instrument(timer)
evaluate = Sampler.evaluate_likelihood
threshold = ref["best_log_likelihood"] - 1.0

def observed(sampler, points):
result = evaluate(sampler, points)
if not trace["native"]:
trace["native"] = {
"n_update": int(sampler.n_update),
"n_batch": int(sampler.n_batch),
"n_networks": int(sampler.n_networks),
"n_live": int(sampler.n_live),
}
for index in np.flatnonzero(np.asarray(result[0]) >= threshold):
sign = (
"negative"
if fixture == "symmetric" and points[index, centre_index] < 0.5
else "positive"
)
trace["peak_calls"].setdefault(sign, trace["calls"] + int(index) + 1)
trace["calls"] += len(points)
return result

try:
with patch.object(Sampler, "evaluate_likelihood", observed):
start = time.perf_counter()
result = search.fit(model=model, analysis=analysis)
wall = time.perf_counter() - start
finally:
restore()
samples = result.samples
weights = np.array(samples.weight_list)
weights /= weights.sum()
params = np.asarray(samples.parameter_lists)
positive_mass = float(weights[params[:, centre_index] > 0].sum())
params[:, centre_index] = abs(params[:, centre_index])
mean = weights @ params
std = np.sqrt(weights @ (params - mean) ** 2)
expected_interval = 200 if arm == "default" else 400
if (
trace["native"]["n_update"] != expected_interval
or trace["calls"] != samples.samples_info["total_samples"]
):
raise RuntimeError("Sampler cadence or evaluation accounting mismatch")
return {
"fixture": fixture,
"arm": arm,
"seed": seed,
"wall_s": wall,
**trace,
"bounds": timer.counts["bound_geometry"],
"training_s": timer.totals["nn_training"],
"geometry_s": timer.totals["bound_geometry"],
"log_evidence": float(samples.log_evidence),
"max_log_likelihood": float(max(samples.log_likelihood_list)),
"ess": float(1 / (weights @ weights)),
"parameter_names": names,
"folded_mean": mean.tolist(),
"folded_std": std.tolist(),
"positive_mass": positive_mass,
}


def compare(base, candidate, ref):
modes = ("positive", "negative") if base["fixture"] == "symmetric" else ("positive",)
checks = {}
for row in (base, candidate):
arm = row["arm"]
checks[f"{arm}_evidence"] = abs(row["log_evidence"] - ref["log_evidences"][-1]) <= 0.5
checks[f"{arm}_peaks"] = all(mode in row["peak_calls"] for mode in modes)
if len(modes) == 2:
checks[f"{arm}_mode_mass"] = 0.35 <= row["positive_mass"] <= 0.65
checks["peak_discovery"] = all(
mode in base["peak_calls"]
and mode in candidate["peak_calls"]
and candidate["peak_calls"][mode] <= base["peak_calls"][mode] * 1.25
for mode in modes
)
# Prior creation order can differ between models. Compare within each fixture by name.
delta = (np.asarray(candidate["folded_mean"]) - base["folded_mean"]) / base["folded_std"]
checks["folded_means"] = bool(np.all(abs(delta) <= 0.3))
return {
"fixture": base["fixture"],
"seed": base["seed"],
"checks": checks,
"mean_shifts_in_baseline_sd": delta.tolist(),
"wall_reduction_pct": 100 * (1 - candidate["wall_s"] / base["wall_s"]),
}


def write(path, obj):
path.write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n")


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
parser.add_argument("--case", nargs=3, metavar=("FIXTURE", "ARM", "SEED"))
args = parser.parse_args()
directory = args.directory.resolve()
if args.case:
fixture, arm, seed = args.case
ref = json.loads((directory.parent / "reference.json").read_text())
write(directory / "case.json", run_one(directory, fixture, arm, int(seed), ref))
return
directory.mkdir(parents=True, exist_ok=False)
ref = reference(baseline.make_dataset())
write(directory / "reference.json", ref)
plan = [
(fixture, seed, arm)
for i, fixture in enumerate(FIXTURES)
for seed in (1, 2)
for arm in (ARMS if (i + seed) % 2 else ARMS[::-1])
]
software, release, dirty = baseline.software()
receipt = {
"reference": ref,
"software": software,
"release": release,
"dirty_library": dirty,
"python": platform.python_version(),
"threads": 1,
"plan": plan,
"runs": [],
"pairs": [],
"status": "running",
}
for fixture, seed, arm in plan:
case = directory / f"{fixture}-{seed}-{arm}"
case.mkdir()
cmd = [
sys.executable,
str(Path(__file__).resolve()),
str(case),
"--case",
fixture,
arm,
str(seed),
]
try:
with (case / "fit.log").open("w") as log:
subprocess.run(
cmd,
env={**os.environ, **dict.fromkeys(THREAD_VARS, "1")},
stdout=log,
stderr=subprocess.STDOUT,
timeout=300,
check=True,
)
except (subprocess.SubprocessError, OSError) as error:
receipt.update(status="incomplete", failure=str(error), failed_case=case.name)
write(directory / "result.json", receipt)
raise
row = json.loads((case / "case.json").read_text())
receipt["runs"].append(row)
print(case.name, round(row["wall_s"], 2), flush=True)
if len(receipt["runs"]) % 2 == 0:
pair = {r["arm"]: r for r in receipt["runs"][-2:]}
receipt["pairs"].append(compare(pair["default"], pair["doubled"], ref))
write(directory / "result.json", receipt)
passed = all(
p["wall_reduction_pct"] > 0 and all(p["checks"].values()) for p in receipt["pairs"]
)
receipt.update(status="complete", pilot_win=passed)
write(directory / "result.json", receipt)


if __name__ == "__main__":
main()
Loading
Loading