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
52 changes: 52 additions & 0 deletions experiments/nautilus_ellipsoid_weight_update/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Scalar weight updates in Nautilus ellipsoid fitting

Updating a single weight by index reduced the wall time to reconstruct eleven retained outer bounds in every paired block, with a **median reduction of 14.4%**. The 57 native ellipsoid calls captured in preflight returned bitwise-identical centers and matrices under the candidate. [Full timing and parity receipt](result.json)

## Candidate

Nautilus 1.0.5 updates every weight after choosing point `j`. Its native expression makes an integer index array and a Boolean mask for each accepted update.

```python
u = u * (1 - a) + a * (np.arange(n_points) == j)
```

The candidate performs the same scaling in the existing weight array and adds the increment at the chosen index.

```python
u *= 1 - a
u[j] += a
```

The weights are local to the solver. The replacement preserves the selected point, iteration order, and the matrix and covariance calculations. The harness validates the native source hash and substitutes only this expression in a temporary copy. The production library and fitted neural models remain as measured in the earlier experiments.

## Matched timing

Each row sums one call to the native outer mixture constructor per retained bound, using the eleven 400 × 10 arrays from RAL job 415196, seed 2. Forward and reverse blocks alternate. Each individual bound sees the candidate run first in three blocks and second in three. Wall and process CPU measurements enclose construction only. Parity checks and JSON writes occur outside the timers.

| Block | Native wall (s) | Candidate wall (s) | Wall reduction | Process CPU reduction |
|---|---:|---:|---:|---:|
| 1 | 3.287 | 2.781 | 15.4% | 15.3% |
| 2 | 3.577 | 2.882 | 19.4% | 19.4% |
| 3 | 3.839 | 2.862 | 25.5% | 24.7% |
| 4 | 3.788 | 3.281 | 13.4% | 13.4% |
| 5 | 4.547 | 4.474 | 1.6% | 1.6% |
| 6 | 5.981 | 5.808 | 2.9% | 4.5% |

Median process CPU fell 14.4%. Summing all six blocks gives an 11.7% reduction in wall time. Both variants slowed substantially in the final two blocks on the shared WSL2 laptop, where their differences narrowed. The six blocks repeat the same inputs and provide no independent-seed evidence.

## Numerical checks and scope

In preflight the harness records the shape, dtype and SHA-256 of each solver input and each of its three outputs. It compares the full ordered sequence for both variants, and checks each input again after return. The first two outer bounds made 20 and 19 calls; the next nine made two each. Every preflight and timed final geometry had identical dimension masks, membership on retained points, log volume and available ellipsoid matrices and center relative to the native reconstruction. The preflight also checked the original checkpoint using the tolerances from [PR #19](https://github.com/PyAutoLabs/autofit_profiling/pull/19). Random generator state was preserved.

These 57 calls cover the outer mixture constructor. [Whole-fit attribution](https://github.com/PyAutoLabs/autofit_profiling/pull/21) found 101 ellipsoid calls across all bound-building paths and 18.6–19.1% of fit time in the routine. The remaining calls have a different input mix. The next test is a direct native-versus-candidate whole-fit comparison with checkpoint reopening and exact ordered posterior, evidence, ESS, shell and likelihood-count parity. The present experiment provides no end-to-end timing or production default change.

## Reproduction

Use the extracted job 415196 pilot directory and the prerequisite [replay instructions and package pins](../nautilus_bound_geometry/README.md). The committed receipt records the numerical libraries, thread counts and measured harness hash. From the producer root:

```sh
python experiments/nautilus_ellipsoid_weight_update/compare.py \
/path/to/parent-cpu-diagnostics-ral-01/pilot output/ellipsoid-weight-comparison
```

Choose a fresh output directory. A parity or input failure leaves a halted receipt with any previously recorded progress. This off-board experiment belongs to [issue #22](https://github.com/PyAutoLabs/autofit_profiling/issues/22).
181 changes: 181 additions & 0 deletions experiments/nautilus_ellipsoid_weight_update/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
"""Paired ablation of the one-hot weight update in the pinned Nautilus MVEE solver."""

import argparse
import hashlib
import importlib.util
import json
import platform
import sys
from importlib.metadata import distribution, version
from pathlib import Path
from tempfile import TemporaryDirectory
from time import perf_counter_ns, process_time_ns
from unittest.mock import patch

import numpy as np
from threadpoolctl import threadpool_info, threadpool_limits

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "experiments/nautilus_bound_geometry"))
sys.path.insert(0, str(ROOT / "scripts/misc"))
from profiling.nautilus_resources import atomic_json
from replay import CHECKPOINT_SHA, SOURCE_SHA, check_geometry, load_basic, load_inputs

ORIGINAL = " u = u * (1 - a) + a * (np.arange(n_points) == j)"
REPLACEMENT = " u *= 1 - a\n u[j] += a"
BLOCKS = 6


def load_candidate(source, directory):
text = (source / "bounds/basic.py").read_text()
if text.count(ORIGINAL) != 1:
raise ValueError("Expected exactly one native weight update")
path = directory / "basic_candidate.py"
path.write_text(text.replace(ORIGINAL, REPLACEMENT))
spec = importlib.util.spec_from_file_location("mvee_candidate", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def identity(array):
return {
"shape": list(array.shape),
"dtype": array.dtype.str,
"sha256": hashlib.sha256(array.tobytes(order="C")).hexdigest(),
}


def geometry(bound, points):
result = {
"mask": identity(bound.dim_cube),
"membership": identity(bound.contains(points)),
"log_volume": identity(np.asarray(bound.log_v)),
}
if bound.ellipsoid is not None:
for field in ("c", "A", "B", "B_inv"):
result[field] = identity(getattr(bound.ellipsoid, field))
return result


def construct(module, points, rng):
return module.UnitCubeEllipsoidMixture.compute(points, enlarge_per_dim=1.1, rng=rng)


def preflight(module, points, expected):
calls = []
kernel = module.minimum_volume_enclosing_ellipsoid

def record(array, *args, **kwargs):
before = identity(array)
output = kernel(array, *args, **kwargs)
if before != identity(array):
raise ValueError("Solver modified its input")
calls.append({"input": before, "outputs": [identity(x) for x in output]})
return output

rng = np.random.default_rng(2)
state = rng.bit_generator.state
with patch.object(module, "minimum_volume_enclosing_ellipsoid", record):
bound = construct(module, points, rng)
if state != rng.bit_generator.state:
raise ValueError("Solver consumed random draws")
check_geometry(bound, expected, points)
return calls, geometry(bound, points)


def run(inputs, native, candidate, state, receipt):
modules = {"native": native, "candidate": candidate}
reference = {}
for ordinal, (points, expected) in inputs.items():
points.setflags(write=False)
state["current"] = {"phase": "parity", "ordinal": ordinal}
calls, signature = preflight(native, points, expected)
other_calls, other_signature = preflight(candidate, points, expected)
if calls != other_calls or signature != other_signature:
raise ValueError(f"Bitwise solver or bound parity failed at bound {ordinal}")
reference[ordinal] = signature
state["parity"].append(
{
"ordinal": ordinal,
"call_count": len(calls),
"call_sequence_sha256": hashlib.sha256(
json.dumps(calls, sort_keys=True).encode()
).hexdigest(),
}
)
atomic_json(receipt, state)
if sum(row["call_count"] for row in state["parity"]) != 57:
raise ValueError("Incomplete retained solver path")

for block in range(BLOCKS):
ordinals = list(inputs) if block % 2 == 0 else list(reversed(inputs))
for ordinal in ordinals:
order = list(modules) if (block + ordinal) % 2 else list(reversed(modules))
points, _ = inputs[ordinal]
for name in order:
state["current"] = {"block": block + 1, "ordinal": ordinal, "variant": name}
rng = np.random.default_rng(2)
rng_before = rng.bit_generator.state
cpu = process_time_ns()
wall = perf_counter_ns()
bound = construct(modules[name], points, rng)
elapsed = perf_counter_ns() - wall
cpu_elapsed = process_time_ns() - cpu
if (
rng.bit_generator.state != rng_before
or geometry(bound, points) != reference[ordinal]
):
raise ValueError(f"Timed geometry differs at bound {ordinal}")
state["timings"].append(
{**state["current"], "wall_ns": elapsed, "cpu_ns": cpu_elapsed}
)
atomic_json(receipt, state)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("pilot", type=Path, help="Retained job 415196 pilot directory")
parser.add_argument("output", type=Path, help="Fresh directory for result.json")
parser.add_argument("--nautilus-source", type=Path, help="Pinned nautilus package directory")
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=False)
receipt = args.output / "result.json"
state = {
"status": "running",
"source_sha256": SOURCE_SHA,
"checkpoint_sha256": CHECKPOINT_SHA,
"harness_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"versions": {name: version(name) for name in ("numpy", "scipy", "h5py", "threadpoolctl")},
"python": platform.python_version(),
"platform": platform.platform(),
"parity": [],
"timings": [],
}
atomic_json(receipt, state)
try:
source = args.nautilus_source or Path(
distribution("nautilus-sampler").locate_file("nautilus")
)
native = load_basic(source)
inputs, _ = load_inputs(args.pilot, native)
with TemporaryDirectory() as tmp, threadpool_limits(1):
candidate = load_candidate(source, Path(tmp))
state["threads"] = [
{k: lib.get(k) for k in ("internal_api", "version", "num_threads", "architecture")}
for lib in threadpool_info()
]
if any(lib["num_threads"] != 1 for lib in state["threads"]):
raise RuntimeError("Numerical thread limit was not applied")
run(inputs, native, candidate, state, receipt)
state.pop("current", None)
state["status"] = "complete"
except BaseException as error:
state.update(status="halted", reason=f"{type(error).__name__}: {error}")
raise
finally:
atomic_json(receipt, state)


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