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
40 changes: 40 additions & 0 deletions experiments/nautilus_shell_efficiency/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Why fresh-sample efficiency falls at 30 dimensions

On the saved seed-0 path at fresh-only ESS 10,000, the correlated Gaussian needed 1.17 likelihood calls per effective sample at 5D, 1.64 at 10D and 98.02 at 30D. In the three independently explored 30D fits the cost was 109.73–156.04. A few large weights within each shell dominate the ESS denominator. In the independent fits the highest-weight 1% of draws in each shell together contributed 94.85–95.61% of total squared posterior weight. [Registered phase 0b diagnostic](https://github.com/PyAutoLabs/autofit_profiling/issues/36).

| Dimension and exploration | Earlier calls | Fresh calls | Fresh ESS | Calls per ESS | Top 1% share of squared weight | Hindsight saving | Split-half saving |
|---|---:|---:|---:|---:|---:|---:|---:|
| 5D / saved seed 0 | 4,600 | 11,700 | 10,020.8 | 1.17 | 4.31% | 0.1651% | +0.05% |
| 10D / saved seed 0 | 6,400 | 16,500 | 10,062.2 | 1.64 | 12.99% | 0.1279% | -0.06% |
| 30D / saved seed 0 | 34,100 | 980,300 | 10,001.1 | 98.02 | 94.05% | 0.0060% | -9.48% |
| 30D / seed-0 bounds, resample 1 | 34,100 | 636,100 | 10,000.7 | 63.61 | 92.52% | 0.0015% | -12.55% |
| 30D / seed-0 bounds, resample 2 | 34,100 | 835,600 | 10,001.7 | 83.55 | 93.79% | 0.0007% | -17.36% |
| 30D / independent seed 1 | 33,700 | 1,248,500 | 10,000.1 | 124.85 | 94.98% | 0.0012% | -10.09% |
| 30D / independent seed 2 | 34,600 | 1,097,600 | 10,003.0 | 109.73 | 94.85% | 0.0005% | -15.36% |
| 30D / independent seed 3 | 34,200 | 1,560,600 | 10,001.0 | 156.04 | 95.61% | 0.0003% | -8.48% |

Earlier calls are total native calls minus fresh rows. They are excluded from the fresh-sample cost. The three rows using seed-0 bounds share one exploration. The final three use different learned bounds. The 5D and 10D rows each cover a single exploration. These are direct native CPU runs on the analytic fixture. [Original 5D/10D records](../nautilus_30d_diagnostics/evidence/attempts.json) · [Seed-0 30D continuations](../nautilus_30d_evidence_check/result.json) · [Independent 30D endpoints](../nautilus_30d_matched_ess/result.json).

## What the allocation comparison measures

Kish ESS is the square of the sum of the weights divided by the sum of squared weights. To measure concentration, take the largest likelihoods within each shell (round 1% up to a whole draw), weight them by the same shell factor as the other rows, and sum their squared weights across shells. These shares describe the ESS denominator. They do not measure posterior probability or rejected proposals.

Let a shell have estimated volume V, likelihood mean m, second raw likelihood moment s, and fraction p of the fresh likelihood calls. Under fixed shell volumes and moments, evidence is Z = Σ V m. Predicted fresh calls per ESS are Σ(V² s / p) / Z². For equal cost per call the continuous minimum occurs at p proportional to V √s. This follows directly from Cauchy–Schwarz. Native per-shell minimums, integer batches, changes in volume estimates and the cost of acquiring the moments are omitted from the optimum. These assumptions make it an optimistic retrospective comparison of allocation on these shells.

We reconstructed each historical ESS and log evidence using the complete fresh sections of all shells. The hindsight calculation then uses those same rows to find the optimum allocation. Across all six 30D rows the predicted saving is at most 0.0061%. This near-agreement is consistent with native Nautilus already directing later draws toward shells with large contributions to the ESS denominator. These endpoints leave open the gains from changing the proposal distribution, learned geometry or the number of calls needed to learn those bounds.

As a sensitivity check, estimate allocation proportions from the first half of each shell and score both that allocation and the observed proportions on the second half. Both use the final recorded shell volumes. The native proportions also reflect adaptation to the full run. This calculation tests sensitivity to the observed likelihood moments. A live allocation change would require a separate experiment. The early-half allocation predicts 8.48–17.36% more calls per ESS across the six 30D cases. A negative saving denotes an increase.

## Decision

Retain native shell allocation for this fixture. A candidate worth testing is a better proposal *within* a learned shell. A bounded next diagnostic can use retained positions to ask whether quantities available before evaluating the likelihood (for example, distance in the bound geometry) identify where the high weights occur on held-out draws. Any later proposal change needs its own support, importance-weight and evidence checks. No algorithm change or new campaign was made here. Wider phase 0b remains open.

## Reproduction

Run the following command with NumPy and SciPy from a checkout containing the three source receipts. The compact input contains counts and sums of likelihoods and squared likelihoods in log space, plus the top-tail sum for each shell. All eight cases are required. [Compact inputs and source hashes](moments.json) · [Per-case numbers](result.json).

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

To re-extract the input use Python 3.11 or later with h5py and pass `--extract PATH_MAP.json`. Map each case key in moments.json to its retained HDF5 checkpoint. Extraction reads only the arrays past each stored exploration cutoff, checks native shell counts, volumes, mean likelihoods, ESS and the aggregate phase receipt, and records the checkpoint hash. The two earlier low-dimensional files still carry the historical false discard flag. Their fresh-only shell summaries and explicit cutoff counts reconcile; neither source file was modified. [Canonical profiling task](https://github.com/PyAutoLabs/PyAutoPulse/blob/main/tasks/autofit_profiling_bootstrap.md).
174 changes: 174 additions & 0 deletions experiments/nautilus_shell_efficiency/analyze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
"""Extract shell likelihood moments, or replay the compact phase 0b receipts."""

import argparse
import hashlib
import json
from pathlib import Path

import numpy as np
from scipy.special import logsumexp

HERE = Path(__file__).resolve().parent
EXPERIMENTS = HERE.parent


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


def expected_runs():
prior = read(EXPERIMENTS / "nautilus_30d_diagnostics/evidence/attempts.json")
for row in prior["attempts"]:
if row["case"] in ("evidence-d5-rsaved", "evidence-d10-rsaved"):
yield row["case"], row["child"]["fresh_only"]
for exp, prefix in (
("nautilus_30d_evidence_check", "conditional"),
("nautilus_30d_matched_ess", "independent"),
):
for row in read(EXPERIMENTS / exp / "result.json")["runs"]:
yield prefix + "-" + row["stream"], row["result"]["final"]


def moment(ll):
return {"n": len(ll), "log_sum": float(logsumexp(ll)), "log_sum_sq": float(logsumexp(2 * ll))}


def extract(path, expected):
import h5py

with path.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
shells = []
with h5py.File(path, "r") as checkpoint:
group = checkpoint["sampler"]
a = group.attrs
if int(a["n_like"]) != expected["n_like"]:
raise ValueError("Wrong checkpoint call count")
np.testing.assert_allclose(a["shell_log_v"], expected["shell_log_v"], rtol=0, atol=1e-12)
for i, cut in enumerate(a["shell_end_exp"]):
ll = group[f"log_l_{i}"][cut:]
n = len(ll)
if n < 100 or n != expected["fresh_samples_per_shell"][i] or n != a["shell_n"][i]:
raise ValueError("Fresh sample count disagrees with phase receipt")
full = moment(ll)
np.testing.assert_allclose(
full["log_sum"] - np.log(n), a["shell_log_l"][i], atol=1e-10, rtol=0
)
np.testing.assert_allclose(
np.exp(2 * full["log_sum"] - full["log_sum_sq"]), a["shell_n_eff"][i], rtol=1e-10
)
k = (n + 99) // 100
top = np.partition(ll, n - k)[-k:]
shells.append(
{
"log_v": float(a["shell_log_v"][i]),
"top_n": k,
"top_log_sum_sq": float(logsumexp(2 * top)),
"first": moment(ll[: n // 2]),
"last": moment(ll[n // 2 :]),
}
)
return {
"checkpoint_sha256": digest,
"persisted_discard_flag": bool(a["_discard_exploration"]),
"shells": shells,
}


def moments(shells, part):
counts, first, second = [], [], []
for shell in shells:
m = [shell["first"], shell["last"]] if part == "full" else [shell[part]]
n = sum(x["n"] for x in m)
counts.append(n)
first.append(logsumexp([x["log_sum"] for x in m]) - np.log(n))
second.append(logsumexp([x["log_sum_sq"] for x in m]) - np.log(n))
return np.array(counts), np.array(first), np.array(second)


def allocation(log_v, log_second):
# Cauchy-Schwarz minimizer of sum(V_h^2 E[L_h^2] / p_h).
log_share = log_v + 0.5 * log_second
return log_share - logsumexp(log_share)


def cost(log_v, log_first, log_second, log_share):
log_z = logsumexp(log_v + log_first)
return float(np.exp(logsumexp(2 * log_v + log_second - log_share) - 2 * log_z))


def analyze(run, expected):
shells = run["shells"]
log_v = np.array([s["log_v"] for s in shells])
n, first, second = moments(shells, "full")
if n.tolist() != expected["fresh_samples_per_shell"]:
raise ValueError("Shell counts changed")
np.testing.assert_allclose(log_v, expected["shell_log_v"], rtol=0, atol=1e-12)
log_z = logsumexp(log_v + first)
observed = cost(log_v, first, second, np.log(n / n.sum()))
ess = float(n.sum() / observed)
np.testing.assert_allclose([log_z, ess], [expected["logZ"], expected["n_eff"]], rtol=1e-11)
if n.sum() != expected["selected_samples"]:
raise ValueError("Total selected samples changed")
optimum = cost(log_v, first, second, allocation(log_v, second))
if optimum > observed + 1e-9:
raise ValueError("Optimum worse than feasible reference")
_, _, first_half_second = moments(shells, "first")
last_n, last_first, last_second = moments(shells, "last")
historical = cost(log_v, last_first, last_second, np.log(last_n / last_n.sum()))
predicted = cost(log_v, last_first, last_second, allocation(log_v, first_half_second))
# Each row in a shell has unnormalized posterior weight V_h * L / n_h.
top = np.array([shell["top_log_sum_sq"] for shell in shells])
top_sq = logsumexp(2 * (log_v - np.log(n)) + top)
all_sq = logsumexp(2 * log_v + second - np.log(n))
concentration = float(100 * np.exp(top_sq - all_sq))
if not 0 <= concentration <= 100:
raise ValueError("Invalid squared-weight share")
return {
"fresh_calls": int(n.sum()),
"earlier_calls": expected["n_like"] - int(n.sum()),
"ess": ess,
"logZ": float(log_z),
"logZ_error": expected["logZ_error"],
"calls_per_ess": observed,
"top_count": sum(shell["top_n"] for shell in shells),
"top_squared_weight_pct": concentration,
"optimal_calls_per_ess": optimum,
"same_data_saving_pct": 100 * (1 - optimum / observed),
"held_out_native_calls_per_ess": historical,
"held_out_predicted_calls_per_ess": predicted,
"held_out_saving_pct": 100 * (1 - predicted / historical),
}


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--extract",
type=Path,
metavar="PATH_MAP",
help="JSON mapping case names to original local checkpoints",
)
args = parser.parse_args()
expected = dict(expected_runs())
if args.extract:
paths = read(args.extract)
if paths.keys() != expected.keys():
raise ValueError("Incomplete checkpoint map")
inputs = {k: extract(Path(paths[k]), v) for k, v in expected.items()}
for k, v in expected.items():
analyze(inputs[k], v)
print(json.dumps(inputs, indent=2, allow_nan=False))
else:
inputs = read(HERE / "moments.json")
if inputs.keys() != expected.keys():
raise ValueError("Incomplete moment set")
print(
json.dumps(
{k: analyze(inputs[k], v) for k, v in expected.items()}, indent=2, allow_nan=False
)
)


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