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
42 changes: 42 additions & 0 deletions experiments/nautilus_shell_geometry_signal/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Can the existing Nautilus bounds identify high-weight draws before evaluating the likelihood?

On the correlated 30D Gaussian, proximity to the centre of the learned ellipsoid identified 64–84% of held-out squared posterior weight in about 10% of fresh draws. This held across three independently learned sets of bounds. The existing neural ensemble’s margin captured 7–11% at the same selection rate. Only ellipsoid distance cleared the registered threshold for a proposal experiment. [Phase protocol](https://github.com/PyAutoLabs/autofit_profiling/issues/38).

| Seed | Score | Held-out draws | Selected | Recall of highest-weight 1% | Recall / random | Squared weight captured | Capture / random |
|---:|---|---:|---:|---:|---:|---:|---:|
| 1 | Ellipsoid | 624,250 | 9.88% | 79.87% | 8.08× | 84.06% | 8.53× |
| 2 | Ellipsoid | 548,800 | 10.02% | 82.71% | 8.26× | 83.41% | 8.38× |
| 3 | Ellipsoid | 780,300 | 9.93% | 66.35% | 6.69× | 64.32% | 6.48× |
| 1 | Neural | 624,250 | 9.93% | 9.03% | 0.91× | 11.05% | 1.11× |
| 2 | Neural | 548,800 | 10.01% | 7.59% | 0.76× | 7.13% | 0.71× |
| 3 | Neural | 780,300 | 9.97% | 9.66% | 0.97× | 11.15% | 1.12× |

Each random comparator samples the same expected number from each shell as that score selected on held-out data. The registered threshold was twice random on **both** metrics in **each** seed. The neural margin measures distance in score from a learned membership cutoff. These results assess its value for ranking points already drawn within shells. The native neural membership test remains in use. [Per-seed metrics and matched baselines](result.json).

## How the replay works

The three native checkpoints had each reached fresh-only ESS 10,000. We retained every fresh point after the stored exploration cutoff, split each shell in temporal order, set each score’s top-decile threshold from the first half, and applied it unchanged to the second. The frozen models came from exploration. The scoring functions take point coordinates and saved model parameters. Held-out likelihoods enter only to evaluate the rankings. [Independent 30D endpoints](../nautilus_30d_matched_ess/README.md) · [Earlier within-shell concentration diagnostic](../nautilus_shell_efficiency/README.md).

The ellipsoid score is negative squared radius in the enclosing ellipsoid’s native coordinates, taking the largest score across components. The neural score uses the largest native ensemble prediction minus its stored threshold among component ellipsoids containing the point. Points without a score rank last. At a cutoff tie each tied point receives its fractional inclusion probability. Each seed had 19 shells with a trained component and one initial shell without geometry. This initial shell contributed at the neutral 10% rate, including its 224,350 held-out draws in seed 3. All 60 shells and 1,953,350 held-out draws enter the table.

Tail recall counts the top 1% of held-out likelihoods within each shell, rounding the number up and splitting boundary ties. Each point in a shell has the same volume factor, so likelihood and posterior weight have the same rank there. To measure global squared-weight capture, give each held-out point weight proportional to its likelihood times native shell volume divided by that shell’s held-out count. The reported fraction is the share of the sum of **squared** weights, the denominator of importance-sampling ESS. A share of squared weight does not directly give a fraction of evidence or a runtime gain.

## Practical implication

The ellipsoid score warrants a bounded experiment that gives high-ranked points more likelihood evaluations while keeping a known, positive inclusion probability everywhere. Compare the reweighted estimate against native sampling on the same frozen bounds. Check analytic evidence, variance, ESS per likelihood call and wall time including scoring. Seed 3 is an important case because 35.68% of squared weight fell outside the selected subset. All measurements here used archived draws from one Gaussian fixture. Native sampling settings stay in production.

## Reproduction

Run the compact replay with NumPy and SciPy from the repository root.

```sh
python experiments/nautilus_shell_geometry_signal/analyze.py
```

To rebuild the [per-shell receipts](shells.json), use Python 3.11 or later, Nautilus 1.0.5, h5py and the three retained HDF5 files. The argument is a directory containing `seed1/checkpoint.hdf5`, `seed2/checkpoint.hdf5` and `seed3/checkpoint.hdf5`. Run with the original compatible scikit-learn environment for the archived networks.

```sh
OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 python experiments/nautilus_shell_geometry_signal/analyze.py --extract /path/to/checkpoints
```

Extraction checks all three SHA-256 identities against the earlier shell diagnostic and reconstructs native ESS, log evidence and row counts. An independent HDF5 calculation using the stored ellipsoid precision matrix, sorted cutoffs and direct linear weights reproduced the ellipsoid selection counts, tail hits and squared-weight capture for every shell. Native neural membership also agreed on 7,343 sampled point-component pairs. This local diagnostic belongs to the [canonical profiling producer task](https://github.com/PyAutoLabs/PyAutoPulse/blob/main/tasks/autofit_profiling_bootstrap.md).
202 changes: 202 additions & 0 deletions experiments/nautilus_shell_geometry_signal/analyze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""Replay frozen 30D bound scores on chronological held-out samples within each shell."""

import argparse
import hashlib
import json
import math
from pathlib import Path

import numpy as np
from scipy.special import logsumexp

HERE = Path(__file__).resolve().parent
EXPERIMENTS = HERE.parent
NAMES = ("ellipsoid", "neural")
CHUNK = 4096


def read(path):
return json.loads(path.read_text())


def cutoff(values, quota):
"""Choose a threshold and the inclusion probability of points tied there."""
index = len(values) - math.ceil(quota)
threshold = np.partition(values, index)[index]
above = np.count_nonzero(values > threshold)
tied = np.count_nonzero(values == threshold)
return threshold, (quota - above) / tied


def inclusion(values, threshold, tie_probability):
return (values > threshold).astype(float) + (values == threshold) * tie_probability


def bound_scores(points, children):
radius = np.full(len(points), -np.inf)
neural = np.full(len(points), -np.inf)
for child in children:
transformed = child.outer_bound.transform(points)
r2 = np.einsum("ij,ij->i", transformed, transformed)
radius = np.maximum(radius, -r2)
inside = r2 < 1.0
if child.emulator is not None and np.any(inside):
pred = child.emulator.predict(transformed[inside]) - child.score_predict_min
neural[inside] = np.maximum(neural[inside], pred)
if np.isnan(radius).any() or np.isnan(neural).any():
raise ValueError("Unusable model output")
return radius, neural


def shell_scores(dataset, start, children):
chunks = [
bound_scores(dataset[i : i + CHUNK], children) for i in range(start, len(dataset), CHUNK)
]
return {name: np.concatenate(parts) for name, parts in zip(NAMES, zip(*chunks), strict=True)}


def evaluate(scores, split, tail, squared):
threshold, tie = cutoff(scores[:split], split / 10)
chosen = inclusion(scores[split:], threshold, tie)
return {
"cutoff": float(threshold) if np.isfinite(threshold) else None,
"tie_probability": float(tie),
"selected": float(chosen.sum()),
"tail_selected": float(chosen @ tail),
"squared_weight_fraction": float(chosen @ squared),
}


def extract(path, source, expected):
import h5py
from nautilus.bounds import NeuralBound

with path.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != source["checkpoint_sha256"]:
raise ValueError(f"Unexpected checkpoint: {path}")
shells = []
full_first, full_second = [], []
with h5py.File(path, "r") as file:
g = file["sampler"]
a = g.attrs
if not a["_discard_exploration"] or a["n_like"] != expected["n_like"]:
raise ValueError("Wrong sampling stage or likelihood count")
for i, cut in enumerate(a["shell_end_exp"]):
points = g[f"points_{i}"]
log_l = g[f"log_l_{i}"][cut:]
n = len(log_l)
split = n // 2
if n != len(points) - cut or n != expected["fresh_samples_per_shell"][i] or n < 100:
raise ValueError("Shell rows do not reconcile")
b = file[f"bound_{i}"]
children = [
NeuralBound.read(b[f"neural_bound_{j}"])
for j in range(b.attrs.get("n_neural_bounds", 0))
]
scores = shell_scores(points, cut, children)
# Labels first enter the ranking evaluation here, after the frozen scores are computed.
test = log_l[split:]
tail_n = math.ceil(len(test) / 100)
tail = inclusion(test, *cutoff(test, tail_n))
log_second = logsumexp(2 * test)
squared = np.exp(2 * test - log_second)
volume = a["shell_log_v"][i]
full_first.append(logsumexp(log_l) + volume - np.log(n))
full_second.append(logsumexp(2 * log_l) + 2 * (volume - np.log(n)))
shells.append(
{
"shell": i,
"components": len(children),
"train_n": split,
"test_n": len(test),
"tail_n": tail_n,
"log_test_squared_mass": float(log_second + 2 * (volume - np.log(len(test)))),
"scores": {
name: evaluate(scores[name], split, tail, squared) for name in NAMES
},
}
)
logz = logsumexp(full_first)
ess = np.exp(2 * logz - logsumexp(full_second))
np.testing.assert_allclose([logz, ess], [expected["logZ"], expected["n_eff"]], rtol=1e-10)
return {"checkpoint_sha256": digest, "shells": shells}


def summarize(case):
shells = case["shells"]
weights = np.array([s["log_test_squared_mass"] for s in shells])
weights = np.exp(weights - logsumexp(weights))
sizes = np.array([s["test_n"] for s in shells])
tails = np.array([s["tail_n"] for s in shells])
results = {}
for name in NAMES:
rows = [s["scores"][name] for s in shells]
rates = np.array([r["selected"] for r in rows]) / sizes
capture = float(weights @ [r["squared_weight_fraction"] for r in rows])
neutral = float(weights @ rates)
tail_recall = sum(r["tail_selected"] for r in rows) / tails.sum()
tail_neutral = float(tails @ rates / tails.sum())
results[name] = {
"selected_pct": 100 * float(sizes @ rates / sizes.sum()),
"squared_capture_pct": 100 * capture,
"squared_random_pct": 100 * neutral,
"squared_lift": capture / neutral,
"tail_recall_pct": 100 * tail_recall,
"tail_random_pct": 100 * tail_neutral,
"tail_lift": tail_recall / tail_neutral,
"passes": bool(capture >= 2 * neutral and tail_recall >= 2 * tail_neutral),
}
return {
"train_n": sum(s["train_n"] for s in shells),
"test_n": int(sizes.sum()),
"shells": len(shells),
"scores": results,
}


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--extract", type=Path, help="raw PR #35 directory containing the three seed subdirectories"
)
args = parser.parse_args()
prior = read(EXPERIMENTS / "nautilus_shell_efficiency/moments.json")
endpoints = read(EXPERIMENTS / "nautilus_30d_matched_ess/result.json")["runs"]
if args.extract:
cases = {
r["stream"]: extract(
args.extract / r["stream"] / "checkpoint.hdf5",
prior["independent-" + r["stream"]],
r["result"]["final"],
)
for r in endpoints
}
output = cases
else:
cases = read(HERE / "shells.json")
if set(cases) != {r["stream"] for r in endpoints}:
raise ValueError("Missing held-out seed")
results = {}
for r in endpoints:
name = r["stream"]
if (
cases[name]["checkpoint_sha256"]
!= prior["independent-" + name]["checkpoint_sha256"]
):
raise ValueError("Checkpoint identity differs from PR #37")
result = summarize(cases[name])
if result["train_n"] + result["test_n"] != r["result"]["final"]["selected_samples"]:
raise ValueError("Missing fresh samples")
results[name] = result
output = {
"runs": results,
"advance": {
name: all(r["scores"][name]["passes"] for r in results.values()) for name in NAMES
},
}
print(json.dumps(output, indent=2, allow_nan=False))


if __name__ == "__main__":
main()
89 changes: 89 additions & 0 deletions experiments/nautilus_shell_geometry_signal/result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
{
"runs": {
"seed1": {
"train_n": 624250,
"test_n": 624250,
"shells": 20,
"scores": {
"ellipsoid": {
"selected_pct": 9.879695634761713,
"squared_capture_pct": 84.05902658259777,
"squared_random_pct": 9.857494959987289,
"squared_lift": 8.527422729994086,
"tail_recall_pct": 79.86555697823303,
"tail_random_pct": 9.87994559829557,
"tail_lift": 8.083602908907816,
"passes": true
},
"neural": {
"selected_pct": 9.932879455346416,
"squared_capture_pct": 11.047084257313006,
"squared_random_pct": 9.947234355605483,
"squared_lift": 1.1105684115191006,
"tail_recall_pct": 9.026888604353394,
"tail_random_pct": 9.932871072652992,
"tail_lift": 0.908789466643342,
"passes": false
}
}
},
"seed2": {
"train_n": 548800,
"test_n": 548800,
"shells": 20,
"scores": {
"ellipsoid": {
"selected_pct": 10.018586005830905,
"squared_capture_pct": 83.40574779639819,
"squared_random_pct": 9.952926827490076,
"squared_lift": 8.380022202718374,
"tail_recall_pct": 82.7052612415802,
"tail_random_pct": 10.018617807494053,
"tail_lift": 8.255156832084722,
"passes": true
},
"neural": {
"selected_pct": 10.00747084548105,
"squared_capture_pct": 7.127763798345288,
"squared_random_pct": 10.087888163843377,
"squared_lift": 0.7065664966323028,
"tail_recall_pct": 7.591480065537957,
"tail_random_pct": 10.007539796729997,
"tail_lift": 0.7585760556274284,
"passes": false
}
}
},
"seed3": {
"train_n": 780300,
"test_n": 780300,
"shells": 20,
"scores": {
"ellipsoid": {
"selected_pct": 9.92554145841343,
"squared_capture_pct": 64.31571519160082,
"squared_random_pct": 9.930587510096544,
"squared_lift": 6.476526703602409,
"tail_recall_pct": 66.35164553720067,
"tail_random_pct": 9.925271746474843,
"tail_lift": 6.685121297637696,
"passes": true
},
"neural": {
"selected_pct": 9.974881455850314,
"squared_capture_pct": 11.151038034828932,
"squared_random_pct": 10.000707692124918,
"squared_lift": 1.1150248940492327,
"tail_recall_pct": 9.660647970290682,
"tail_random_pct": 9.9750404795649,
"tail_lift": 0.9684820818603906,
"passes": false
}
}
}
},
"advance": {
"ellipsoid": true,
"neural": false
}
}
Loading
Loading