Skip to content

refactor(ep): cut per-factor-search wrapper overhead (dynesty single pass, EP visuals off, mapper fast path) #1642

Closed

Description

@Jammy2211

Overview

Every EP factor update is a full autofit non-linear search. On the ep_toy_gaussian hierarchical toy a 1-parameter Dynesty factor search takes 2.45 s, of which only 1.47 s is dynesty and 0.98 s is autofit wrapper overhead: a redundant second run_nested pass (13 %), per-search corner/model-fit/data plots (23 %), instance_from_vector at 57 % of the likelihood callback, and scipy.stats.norm.cdf in truncated-normal message maths. This task cuts those costs (~2x on the toy, ~15-20 min saved per 1000-search N=50 EP repeat) while keeping ordinary non-EP fits behaviour-preserving.

Plan

  • Fix Dynesty finished-detection so a converged first pass is recognised (no second perform_update + checkpoint restore + no-op run_nested).
  • Swap scipy.stats.norm.cdf for scipy.special.ndtr in the truncated-normal message maths, and make manage_quick_update return early when quick updates are disabled.
  • Let EP factor searches skip per-search visuals by default (new config key), drawing before-fit visuals only for the first search of each factor.
  • Mapper fast path: frozen-cached prior tuple and instance plan on the model hot path.
  • Measure each PR on the toy (run_nested count, per-search wall, parent moments under a seeded harness); full test_autofit serially each time.
  • Ship as three PRs from one worktree/issue: PR 1 = steps 1+2 (output-identical, small), PR 2 = step 3 (adds a config key, changes EP default output), PR 3 = step 4 (shared hot path, supervised review).
  • Nautilus has the same double-run shape but needs a different fix (iterations_from counts posterior samples, not likelihood calls) — filed as a separate Mind draft, not done here.
  • Witness correction: the prompt's 1e-6 same-seed moment check is unreachable as written (dynesty gets no rstate; Laplace refine uses global np.random) — the harness seeds both, see detailed plan.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary, only)

Branch Survey

Repository Current Branch Dirty?
./fit/PyAutoFit main @ a736840 clean

No other active.md claim on PyAutoFit; worktree_check_conflict clean.

Suggested branch: feature/ep-factor-search-overhead
Worktree root: ~/Code/PyAutoLabs-wt/ep-factor-search-overhead/ (created by start_library)

Implementation Steps

PR 1a — Dynesty finished-detection

File: autofit/non_linear/search/nest/dynesty/search/abstract.py, run_search_internal (~413-459). Dynesty stops on its own criterion iff the run consumed no more calls than the maxcall=iterations budget it was handed. Replace the tail:

iterations_after_run = np.sum(search_internal.results.ncall)
if isinstance(self.paths, NullPaths):
    return True
if self.maxcall is not None and iterations_after_run >= self.maxcall:
    return True                                    # global cap
if iterations > 0 and iterations_after_run - total_iterations <= iterations:
    return True                                    # dynesty stopped itself under budget
return total_iterations == iterations_after_run    # legacy no-progress criterion

Default iterations_per_full_update: 1e99 → every converged run finishes in one pass; a finite cadence still loops through perform_update. Resume path unchanged. Test mode (maxcall=1) finishes after one pass. Update the docstring.

Tests in test_autofit/non_linear/search/nest/test_dynesty.py: fake sampler → converged first pass finished; chunk-limited (cadence 50, 51+ calls) not finished; global maxcall finished; real dynesty static+dynamic on a 1-param af.ex.Gaussian (nlive 20) wrapping run_nested with a counter → exactly one call and zero during_analysis=True updates; finite-cadence patched fake → 3 runs, 2 intermediate updates.

PR 1b — ndtr swap + quick-update early return

  • autofit/messages/truncated_normal.py: norm.cdf → scipy.special.ndtr in log_partition (~60), kl (~350), _normal_gradient_hessian_from (~426); reuse _norm_cdf from autofit/mapper/prior/_erf_helpers.py, binding ndtr/ndtri once at module level there for the numpy branch. Keep log(ndtr(b) - ndtr(a)) (bit-identical to scipy's norm._cdf). Do not touch truncnorm.stats. Test test_autofit/messages/test_truncated_normal.py::test__ndtr_swap_bit_identical over a grid of mean/sigma/limits incl. infinite limits vs scipy.stats.norm.
  • autofit/non_linear/fitness.py manage_quick_update (~652): early return when iterations_per_quick_update is None or >= 1e90. Move ITERATIONS_NEVER into fitness.py and re-export from abstract_search.py (multi_start_gradient/search.py imports it there). Check test_quick_update_parameter_types.py:73 (quick_update_count == 1) and test_quick_update_invalid_instance.py still hold or adjust them deliberately.
  • Keep the per-search gc.collect() (abstract_search.py:~684): fix(ep): release each factor search's internals so JAX executables are collectable #1634's release relies on cycle collection.

PR 2 — EP factor searches skip per-search visuals

  • Config: autofit/config/general.yaml under output: add visualize_ep_factor_searches: false (True → each EP factor search draws its own corner/fit visuals and redraws before-fit visuals; False → only the first search per factor draws before-fit visuals, none draw per-search visuals).
  • autofit/non_linear/search/abstract_search.py: class attrs _visualize_fit = True, _visualize_before_fit = True on NonLinearSearch. In optimise (~321), before self.fit: read the key; _visualize_fit = on, _visualize_before_fit = on or number == 0 (number = self.optimisation_counter[factor.name]); reset both in finally. pre_fit_output (~762): gate visualize_before_fit/_combined on self._visualize_before_fit. _updater sets self._search_updater.visualization_enabled = self._visualize_fit.
  • autofit/non_linear/search/updater.py: SearchUpdater(visualization_enabled=True); visualize() returns immediately when False. Samples, summary, and EPOptimiser's own Visualise (graph.png etc.) unchanged.
  • Tests: new test_autofit/graphical/test_ep_factor_search_visuals.py (two AnalysisFactors with a recording Visualizer, named DynestyStatic small nlive/maxcall, optimise(..., paths=DirectoryPaths, max_steps=2)): default → zero visualize/plot_results, visualize_before_fit once per factor, graph.info/graph.png/ep_history present; key True → per-search calls happen. Add test__visualize__disabled_skips_all to test_autofit/non_linear/search/test_updater.py.
  • PR body flag: users lose per-factor model_fit.png by default under EP (intended).

PR 3 — Mapper fast path (behaviour-preserving)

Model is frozen for the whole _fit; frozen_cache (autofit/mapper/model.py:30) already invalidates on unfreeze()/__setstate__.

  • autofit/mapper/prior_model/abstract.py instance_from_vector (~990): @frozen_cache _vector_priors() = tuple of priors from prior_tuples_ordered_by_id; length check, arguments = dict(zip(priors, vector)) (JAX-tracer safe).
  • autofit/mapper/prior_model/prior_model.py _instance_for_arguments (~483): @frozen_cache _instance_plan() returning attribute_arguments, tuple-prior / child-model / prior lists, deferred flag, class-type flags and statically-filtered post-construction candidates; keep the per-call hasattr(result, key) check. Unfrozen models fall through unchanged.
  • abstract.py instance_for_arguments (~1818): test self._assertions before reading conf.instance["general"]["test"]["exception_override"].
  • Test: new test_autofit/mapper/test_instance_from_vector_frozen.py parametrised over Model(Gaussian), nested Collection, shared priors, tuple priors, deferred argument, Constants, assertions (must raise FitException identically); 50 random vectors: frozen vs unfrozen results equal attribute-by-attribute incl. types.

Measurement harness (scratch, not shipped) + witness correction

ep_toy_gaussian copy at N=5, max_steps=3, nlive=100: count run_nested calls, per-search wall, ep_history.csv flags, parent moments. The prompt's "moments within 1e-6 of a same-seed control" is unreachable as written — dynesty never receives an rstate (falls back to OS entropy) and Laplace refine draws from global np.random. The harness seeds np.random per factor search keyed on (factor name, counter) and patches dynesty.dynesty.get_random_generator to a PCG64(np.random.randint(2**32)); with that, before/after moments are compared at 1e-6 for PR 1 and PR 3 (output-identical), and for PR 2 the check is flags + moments within 0.1 σ across 3 seeds. run_nested count must be exactly one per converged search after PR 1.

Verification

  • After each PR: python -m pytest test_autofit/ -p no:xdist serially; PR CI legs 3.12/3.13/nojax + docs green; autofit_workspace smoke.
  • Harness numbers posted here per PR: run_nested calls (15/15), per-search wall (target ≤ 1.5 s after PR 1+2), moments vs control.

Key Files

  • autofit/non_linear/search/nest/dynesty/search/abstract.py — finished-detection
  • autofit/messages/truncated_normal.py, autofit/mapper/prior/_erf_helpers.py — ndtr swap
  • autofit/non_linear/fitness.py — manage_quick_update early return, ITERATIONS_NEVER
  • autofit/non_linear/search/abstract_search.py, autofit/non_linear/search/updater.py, autofit/config/general.yaml — EP visuals switch
  • autofit/mapper/prior_model/abstract.py, autofit/mapper/prior_model/prior_model.py, autofit/mapper/model.py — mapper fast path

Original Prompt

Click to expand starting prompt

EP: cut the per-factor-search wrapper overhead (redundant second run_nested pass, per-search plots, instance_from_vector fast path)

Type: refactor
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • graphical-ep
    Difficulty: medium
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Witness: on the ep_toy_gaussian N=5, max_steps=3 toy, run_nested is called once per Dynesty factor search (15 calls for 15 searches, not 30) and per-search wall drops from ~2.45 s to <= 1.5 s at identical parent moments (mean and sigma within 1e-6 of a control run with the same seeds), with the full test_autofit suite green run serially.
    Review-minutes: 5
    Unattended: ready
    Epic: graphical-ep
    Filed: 2026-09-24

Why

Every EP factor update is a full autofit non-linear search. On the
ep_toy_gaussian #1405 collapse toy (PyAutoCortex
projects/ep_toy_gaussian.md) a 1-parameter Dynesty factor search spends
about as much time in the autofit wrapper as in the sampler. A 1000-search
N=50 repeat carries ~15-20 min of pure overhead; best case on the toy is ~2x.

Profile (2026-09-24, laptop, PyAutoFit at the RAL mirror a736840, N=5,
max_steps=3, 15 factor searches, cProfile total 109 s; files in
ep_factor_search_wrapper_overhead_assets/):

  • Per search 2.45 s = ~1.47 s dynesty run_nested + ~0.98 s autofit wrapper
    (plots, a redundant second run_nested pass, samples writes).
  • Redundant second run_nested pass (~5.5 s / 13 %). 30 run_nested
    calls for 15 searches. run_search_internal
    (autofit/non_linear/search/nest/dynesty/search/abstract.py:413-455)
    returns finished = total_iterations == iterations_after_run, which is
    never true on a first pass that converges, so every search does a full
    perform_update(during_analysis=True) + checkpoint restore + a no-op second
    run_nested.
  • Per-search visuals. corner_anesthetic + model_fit.png 7.7 s / 18 %;
    data.png redrawn every search 2.3 s / 5 % although the data never changes.
  • instance_from_vector (autofit/mapper/prior_model/abstract.py:990)
    is 57 % of fitness.call, i.e. ~25-30 % of run_nested for a 1-parameter
    model: autofit/mapper/model.py:30 cache 486k calls,
    autofit/mapper/prior_model/attribute_pair.py wrapper 481k calls,
    prior_model.py:483 _instance_for_arguments 2.7 s tottime.
  • truncated_normal.log_partition / kl call scipy.stats.norm.cdf
    18.6k times / 3.45 s — use scipy.special.ndtr / log_ndtr.
  • manage_quick_update 1.8 s while quick-update is disabled (61k calls).
  • gc.collect per search 75 ms (1.78 s over 15).

What (phases)

  1. Dynesty finished-detection fix so a converged first pass is recognised
    and the second perform_update + checkpoint restore + run_nested is
    skipped; unit test that counts run_nested calls (mock the sampler) and
    asserts one per converged search.
  2. EP factor searches skip per-search visuals — a config switch, default
    off under EP (corner/model_fit per search), and data.png drawn once per
    analysis rather than per search.
  3. Mapper fast path for fixed-structure models in instance_from_vector
    (precompute the prior-to-attribute map once per model; bypass the
    cache / attribute_pair wrappers on the hot path).
  4. ndtr swap in autofit/messages/truncated_normal.py (and
    mapper/prior/_erf_helpers.py if it pays) — scipy.special.ndtr /
    log_ndtr in place of scipy.stats.norm.cdf. Also look at the disabled
    manage_quick_update early-out and the per-search gc.collect.

Each phase should be measured on the same toy (per-search wall, run_nested
call count, parent moments against a same-seed control).

Side observation (reproducibility)

Three runs of ep_repeat.py --repeat 0 gave parent means 51.86 / 51.33 /
51.61: the repeat seed does not make EP reproducible at a736840. Known cause
— the Laplace refine draws from global np.random and depends on variable-id
ordering (PyAutoFit#1352). The witness's "same seeds" control therefore needs
the global RNG seeded (or the #1352 fix) before the 1e-6 moment comparison is
meaningful; if it cannot be made deterministic, compare moments across
matched repeats within their spread and say so.

Links

  • Campaign ledger: draft/research/graphical_ep/ep_campaign.md (row 1b; phase 6 epic 2, EP profiling)
  • Sibling: draft/refactor/autofit/ep_analysis_level_compile_cache.md (the JAX recompile per factor search)
  • EMFILE fix that preceded this profile: PyAutoFit#1632 (dynesty single-core no pool), fix(ep): release each factor search's internals so JAX executables are collectable #1634 (release factor search internals)
  • Evidence: ep_factor_search_wrapper_overhead_assets/ep_profile_report.txt, ep_pstats_cumulative.txt, ep_pstats_tottime.txt (paths shortened: SP/ = site-packages, PyAutoFit/, STDLIB/, SCRATCH/ = the profiling scratch dir)

Activity

  1. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    PR 1 progress (1a Dynesty finished-detection + 1b ndtr / quick-update early return)

    Committed on feature/ep-factor-search-overhead, not pushed yet:

    • 0e2c09748 fix(dynesty): recognise a converged first pass as finished
    • 16789050a perf(ep): ndtr in truncated-normal message maths; skip disabled quick updates

    Harness (ep_toy_gaussian copy, N=5, max_steps=3, nlive=100, rwalk, seeded)

    The baseline and the modified runs were interleaved (ABAB) on the same laptop at similar load. Baseline source is git archive a73684012.

    baseline a736840 after 1678905
    run_nested calls (15 factor searches) 30 15
    intermediate perform_update(during_analysis=True) 15 (4.9 s / 5.3 s total) 0
    per-search wall (search.fit, mean) 1.93 s / 2.21 s 1.57 s / 1.83 s (about −0.37 s, −18 %)
    EP run total 34.2 s / 38.7 s 26.9 s / 30.9 s
    parent mean 51.04323159176496 ± 4.782755146060134 identical (bit-for-bit)
    parent sigma 9.907461162327577 ± 3.8431304013282555 identical (bit-for-bit)
    centre moments (5 × mean/std) — max abs diff 0.0
    ep_history flags SUCCESS 26, NO_CHANGE 15, BAD_PROJECTION 10 identical

    The harness gives the same answer on repeat runs: two baseline runs and two modified runs each agree to 0.0. Per-call (sum(ncall), logz) is identical in every search. The 1e-6 moment check therefore passes exactly, without reseeding around perform_update.

    Harness determinism: what it took. Seeding numpy and patching dynesty's get_random_generator were not enough on their own. The first search still differed between runs, because autofit's InitializerPrior draws the initial live points with stdlib random (random.random / random.uniform in mapper/prior_model/abstract.py and non_linear/initializer.py). The harness now does four things:

    • It seeds np.random and random at the start of each factor search, keyed on crc32(factor name, optimisation counter), by hooking NonLinearSearch.optimise.
    • It seeds the same way before each LaplaceOptimiser.optimise, keyed on (factor, call index).
    • It patches dynesty.dynesty.get_random_generator(None) (and dynesty.utils) to return Generator(PCG64(np.random.randint(2**32))). Seeded calls pass through unchanged.
    • It sets PYTHONHASHSEED=0 as a precaution. I did not test whether this is needed.

    Dynesty 2.1.5 semantics verified (probe script, 1-D Gaussian, nlive=20)

    • In Sampler.sample(), the per-run counter ncall = 0 resets on every run_nested. It stops only when ncall > maxcall (strictly above), and the check runs at the top of each iteration. Budget-stopped runs: counter 325 at maxcall 300, counter 52 at maxcall 50.
    • sum(results.ncall) grows by at least the counter. The first run adds nlive on top (1641 = 1621 + 20, from initial/added live points, nc=1 each). A resumed chunk adds exactly the counter (309).
    • A static sampler that has already converged, run again, uses 0 calls.
    • DynamicNestedSampler.run_nested compares maxcall against its running total. A second run after a budget stop uses 0 calls. This PR does not change that: the finite-cadence dynamic path still ends through the legacy criterion, exactly as before.

    Criterion shipped (run_search_internal), checked in order: NullPaths → finished; global maxcall set and sum(ncall) >= maxcall → finished; iterations > 0 and sum(ncall)_after - sum(ncall)_before <= iterations → finished (dynesty stopped itself under budget); otherwise the legacy check (no new calls) decides. One known conservative case: a converged first chunk at a finite cadence whose counter is ≤ cadence but counter + nlive > cadence gets the old extra no-op pass. The result is the same; there is no behaviour regression.

    Tests

    • test_dynesty.py has 5 new tests (6 cases, since the real-dynesty test is parametrized over static and dynamic): fake converged / chunk-limited / global maxcall; a finite-cadence _fit loop (3 runs, 2 intermediate updates); real dynesty static and dynamic, each with exactly one run_nested and no during_analysis=True update. All of them fail on the old code, checked by swapping the file.
    • test__ndtr_swap_bit_identical: 72 grid cases, including infinite limits, with exact equality against scipy.stats.norm.cdf for _norm_cdf, log_partition, _normal_gradient_hessian_from and kl.
    • test__disabled_cadence_returns_before_any_bookkeeping (1e99 and 1e100) fails on the old code. No existing test asserted quick_update_count == 1 under 1e99, so nothing else had to change.
    • Full suite, run serially (pytest test_autofit -p no:xdist -x): 2881 passed, 2 skipped.
  2. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    PR 2 (EP factor searches skip per-search visuals): committed locally

    Commit 1cd4a5b85 is on feature/ep-factor-search-overhead-p2, stacked on PR 1 16789050a. It is not pushed yet.

    Change. There is a new config key, general.yaml -> output -> visualize_ep_factor_searches: false. With the default, EP factor searches no longer run analysis.visualize/visualize_combined/plot_results, and only the first search of each factor draws before-fit visuals. Samples, summaries and the EP optimiser's own graph.info/graph.png/ep_history.csv are unchanged. The key is read with .get(..., False), so user configs that predate it keep working. Users lose per-factor model-fit and corner images by default under EP. This is intended; setting the key to true restores them.

    Harness (n5_profile, repeat 0, max_steps 3, nlive 100, seeded). The machine was shared with another session's profiling job (load average ~6), so the PR 1 head was re-run interleaved as a load-matched control. Per-search wall time is optimise_wall_mean:

    run autofit run_nested per-search wall (s) moments max diff vs PR 1 flags
    PR 1 reference (quiet machine, earlier) 1678905 15 1.575 – S26 / NC15 / F0 / BP10 / E0
    PR 1 (loaded) ×3 1678905 15 3.52 / 4.12 / 2.01 – same
    PR 2 (loaded) ×3, interleaved pf_p2 15 2.61 / 2.77 / 1.54 0.0 same
    PR 2 other runs (loaded) pf_p2 15 2.71 / 2.24 0.0 same
    • Per-search wall is 26–37 % lower than PR 1 in each load-matched pair. The committed-sha run hit 1.54 s against 2.01 s for the PR 1 run straight after it. The ≤ 1.5 s target was not met in absolute terms, but only because every run here was on a loaded machine.
    • The moments are bit-identical to PR 1 across 5 PR 2 runs. Skipping the plots did not consume any global RNG, so the planned 0.1σ allowance was not needed.
    • Output tree (--keep-output): graph.png, graph_factors.png and mean_field_evolution.png are at the EP root. Under dataset_*/optimization_* the only images are dataset_*/optimization_0/image/data.png, the first search's before-fit visual, which the plan keeps. There are no PNGs under optimization_1/optimization_2 and no corner or fit images anywhere.

    Tests

    • New test_autofit/graphical/test_ep_factor_search_visuals.py, with 3 tests:
      • With the default key, a two-factor EP run with a named DynestyStatic makes 0 visualize calls and 0 plot_results calls, and calls visualize_before_fit once per factor. graph.info, graph.png and ep_history.csv are present.
      • With the key set to true, every factor search draws per-search visuals.
      • The visual switches are back to True after optimise.
    • test_updater.py::test__visualize__disabled_skips_all is added.
    • The new tests fail (red) on PR 1 source, as expected.
    • Graphical and search directories, run serially: 646 passed, 1 skipped.
    • Full suite, run serially: 2885 passed, 2 skipped.
  3. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created: PR 1 of 3

    PR: #1643 (pending-release, open and awaiting a human /prm; not merged)

    • 0e2c09748 fix(dynesty): a converged first pass is now recognised as finished, so a converged search runs run_nested once with no intermediate perform_update or checkpoint restore.
    • 16789050a perf(ep): ndtr in the truncated-normal message maths (bit-identical results); disabled quick updates now return before any bookkeeping.

    API changes: no public signature changes. ITERATIONS_NEVER moved to autofit.non_linear.fitness and is still re-exported from abstract_search. The behaviour changes are listed in the PR.
    Workspace impact: (iii) none. The autofit workspace smoke passed (8/8 scripts, 2/2 notebooks), so no workspace follow-up is needed for PR 1.

    Next: a human /prm on #1643 once CI is green. PR 2 (EP visuals) and PR 3 (mapper fast path) follow under this issue.

    Heart RED override (development only)

    This PR is opened under the PyAutoBrain/AUTONOMY.md "Human override for Heart RED (development only)". It is a development-shipping override only. It does not claim to fix Heart, and Heart remains RED for release purposes. Merge still needs a separate explicit human /prm with every required check green.

    • Authorisation (live human, 2026-09-24, Claude Code CLI session): the human selected "Yes, override and open PR 1" to the question authorising the development-only Heart RED override for PR 1 of refactor(ep): cut per-factor-search wrapper overhead (dynesty single pass, EP visuals off, mapper fast path) #1642.
    • Exact current RED reasons (pyauto-heart readiness --json, verdict red, score 45, ts 2026-09-24T15:11:12.973142+00:00):
      1. release validation FAILED (stage integrate)
      2. workspace validation not passing (4 failed, cloud#35579888156: autolens notebooks/cluster/modeling.ipynb, autolens notebooks/weak/a2744.ipynb, autolens scripts/cluster/modeling.py, +1 more)
      3. manifest drift: hub organism blurb (organs present) — 7 mismatch(es) vs PyAutoMind/repos.yaml
    • Branch gates passed: full serial test_autofit 2881 passed / 2 skipped on head 1678905; autofit workspace smoke 8/8 scripts + 2/2 notebooks; PyAutoFit main CI green; downstream workspace impact (iii) none.
    • Permitted scope: commit, push, and opening this pending-release PR. No merge, release or release rehearsal, and no bypassing of tests, checks or branch protection.
  4. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created: PR 2 of 3

    PR: #1644 (pending-release, stacked on #1643 with base feature/ep-factor-search-overhead; retarget to main after #1643 merges; open and awaiting a human /prm; not merged)

    • 1cd4a5b85 perf(ep): EP factor searches skip per-search visuals by default. New key general.yaml -> output -> visualize_ep_factor_searches: false; only the first search of each factor draws before-fit visuals; SearchUpdater(visualization_enabled) gates per-search visuals.

    API changes: no incompatible signature changes. Behaviour change: EP factor searches no longer write per-search corner/model-fit images or redraw before-fit visuals after the first search (opt back in with the config key). The NSS live-visual path and ordinary search.fit are unchanged. SearchUpdater gains a visualization_enabled=True keyword.
    Workspace impact: (iii) none. No hits for the new key or attributes in the workspaces, HowToFit or the array/galaxy/lens libraries.

    Next: a human /prm on #1643, then retarget #1644 to main and /prm it once CI is green. PR 3 (mapper fast path) is in progress on feature/ep-factor-search-overhead-p3.

    Heart RED override (development only)

    This PR is opened under the PyAutoBrain/AUTONOMY.md "Human override for Heart RED (development only)". It is a development-shipping override only. It does not claim to fix Heart, and Heart remains RED for release purposes. Merge still needs a separate explicit human /prm with every required check green.

    • Authorisation (live human, 2026-09-24, Claude Code CLI session): asked "Does your override extend to opening PR 2 now as a stacked PR (base = PR 1 branch, retargeted to main after PR 1 merges), and PR 3 the same way once it is green?", the human selected "Yes, same override for PR 2 and PR 3".
    • Exact current RED reasons (pyauto-heart readiness --json, verdict red, score 45, ts 2026-09-24T15:11:12.973142+00:00):
      1. release validation FAILED (stage integrate)
      2. workspace validation not passing (4 failed, cloud#35579888156: autolens notebooks/cluster/modeling.ipynb, autolens notebooks/weak/a2744.ipynb, autolens scripts/cluster/modeling.py, +1 more)
      3. manifest drift: hub organism blurb (organs present) — 7 mismatch(es) vs PyAutoMind/repos.yaml
    • Branch gates passed: full serial test_autofit 2885 passed / 2 skipped on head 1cd4a5b; the new EP-visuals tests are red on PR 1 source; EP harness moments bit-identical to PR 1 (evidence: refactor(ep): cut per-factor-search wrapper overhead (dynesty single pass, EP visuals off, mapper fast path) #1642 (comment)); downstream workspace impact (iii) none.
    • Permitted scope: commit, push, and opening this stacked pending-release PR. No merge, release or release rehearsal, and no bypassing of tests, checks or branch protection.
  5. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    PR 3 — Mapper fast path: committed (local, not pushed)

    Commit b3deab4a7 on feature/ep-factor-search-overhead-p3 (stacked on PR 2 head 1cd4a5b85).

    • (a) AbstractPriorModel._vector_priors(): a @frozen_cache tuple of the id-ordered priors, which instance_from_vector zips with the vector.
    • (b) Model._instance_plan(): a @frozen_cache of the value-independent structure of _instance_for_arguments, replayed by _instance_for_arguments_frozen.
    • (c) instance_for_arguments checks the model's own _assertions before reading the exception_override config.

    Unfrozen models take the unchanged path. The existing frozen_cache is reset on unfreeze()/__setstate__ and left out of pickles.

    Micro-benchmark: 20k frozen instance_from_vector calls, ABAB ×3, medians

    model PR 2 (µs/call) PR 3 (µs/call) speed-up
    af.Model(af.ex.Gaussian) 21.27 3.68 5.8×
    3-Gaussian af.Collection 58.83 12.81 4.6×

    EP harness: n5_profile, --max-steps 3 --nlive 100

    run autofit per-search wall (s) run_nested moments vs PR 2
    ab4_p2ref_1 PR 2 0.871 15 —
    ab4_p3_1 PR 3 0.909 15 0.0
    ab4_p2ref_2 PR 2 1.091 15 0.0
    ab4_p3_2 PR 3 1.019 15 0.0
    p3_after1 PR 3 0.973 15 0.0 (vs p2_after1 / ab3_p2)
    • Flags are identical: SUCCESS 26, NO_CHANGE 15, BAD_PROJECTION 10.
    • The per-search wall difference is within run-to-run noise. Under cProfile, instance_from_vector is called about 62k times per run, and its cumulative time drops from 5.84 s to 1.31 s. Without the profiler that is about 1 s saved per run, roughly 7% of search time, which is smaller than the noise between wall-clock runs.

    Tests

    • New test_autofit/mapper/test_instance_from_vector_frozen.py (10 tests): frozen and unfrozen models give identical instances across several model shapes. A deliberate mutation to the code was caught by these tests.
    • test_autofit/mapper + test_autofit/non_linear: 1828 passed, 1 skipped.
    • Full test_autofit: 2895 passed, 2 skipped.
    • A frozen model pickles and unpickles after use. jax.jit and jax.grad through instance_from_vector work (gradient is non-zero).
  6. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created: PR 3 of 3

    PR: #1645 (pending-release, stacked on #1644 with base feature/ep-factor-search-overhead-p2; retarget to main after #1644 merges; open and awaiting a human /prm; not merged)

    • b3deab4a7 perf(mapper): frozen-cached prior tuple and instance plan on the instance_from_vector hot path. _vector_priors() and Model._instance_plan() are @frozen_cached and used only for frozen models. The model's own assertions are checked before the exception_override config is read. Frozen instance_from_vector is 5.8× faster for Model(Gaussian) and 4.6× for a 3-Gaussian Collection. On the toy harness the EP per-search wall change is within noise (about 1 s per run, roughly 7 %).

    API changes: none public. Behaviour is preserved: the caches exist only for frozen models, the unfrozen path is unchanged, EP moments are bit-identical to PR 2, and pickle, jax.jit and jax.grad are verified.
    Workspace impact: (iii) none. No downstream subclass overrides or calls _instance_for_arguments / instance_for_arguments / _vector_priors / _instance_plan (PyAutoArray, PyAutoGalaxy, PyAutoLens, autofit_workspace*, HowToFit).

    Smoke (covers the PR 2 + PR 3 stack): pyauto-heart smoke autofit on a bundle whose PyAutoFit is the PR 3 head (b3deab4, which contains PR 2's 1cd4a5b): 8/8 scripts and 2/2 notebooks PASS. autofit was imported from the PR 3 worktree. PR 2's ship did not run the smoke, so this also covers #1644.

    Next: a human /prm on #1643, then retarget #1644 to main and /prm it, then retarget #1645 to main and /prm it, each once CI is green.

    Heart RED override (development only)

    This PR is opened under the PyAutoBrain/AUTONOMY.md "Human override for Heart RED (development only)". It is a development-shipping override only. It does not claim to fix Heart, and Heart remains RED for release purposes. Merge still needs a separate explicit human /prm with every required check green.

    • Authorisation (live human, 2026-09-24, Claude Code CLI session): asked "Does your override extend to opening PR 2 now as a stacked PR (base = PR 1 branch, retargeted to main after PR 1 merges), and PR 3 the same way once it is green?", the human selected "Yes, same override for PR 2 and PR 3".
    • Exact current RED reasons (pyauto-heart readiness --json, verdict red, score 45, ts 2026-09-24T15:11:12.973142+00:00):
      1. release validation FAILED (stage integrate)
      2. workspace validation not passing (4 failed, cloud#35579888156: autolens notebooks/cluster/modeling.ipynb, autolens notebooks/weak/a2744.ipynb, autolens scripts/cluster/modeling.py, +1 more)
      3. manifest drift: hub organism blurb (organs present) — 7 mismatch(es) vs PyAutoMind/repos.yaml
    • Branch gates passed: full serial test_autofit 2895 passed / 2 skipped on head b3deab4; the 10 new frozen-path tests pass, and they caught a deliberate mutation; EP harness moments bit-identical to PR 2 (evidence: refactor(ep): cut per-factor-search wrapper overhead (dynesty single pass, EP visuals off, mapper fast path) #1642 (comment)); autofit workspace smoke on the stacked PR 2 + PR 3 head passed (8/8 scripts, 2/2 notebooks); downstream workspace impact (iii) none.
    • Permitted scope: commit, push, and opening this stacked pending-release PR. No merge, release or release rehearsal, and no bypassing of tests, checks or branch protection.
  7. added 3 commits that reference this issue on Sep 24, 2026
  8. Jammy2211 commented on Sep 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    All three PRs for this issue were merged into main on 2026-09-24. CI was green on every leg. They were merged under the human's Heart RED override, which is recorded on each PR.

    PR Merge What changed
    #1643 71c096d46 Dynesty now finishes a converged search in one run_nested pass (no intermediate perform_update or second pass). The truncated-normal EP maths calls scipy.special.ndtr directly, and manage_quick_update returns early when quick updates are disabled.
    #1644 aff2f3686 EP factor searches no longer draw per-search visuals by default. Set output.visualize_ep_factor_searches: true in general.yaml to turn them back on.
    #1645 dd9fbe0aa Frozen models cache the prior tuple and the instance plan used by instance_from_vector.

    Outcome on the seeded ep_toy_gaussian harness (N=5, max_steps=3, nlive=100):

    • Wall time per factor search fell from 2.45 s to about 0.9–1.0 s.
    • run_nested calls per EP run fell from 30 to 15.
    • The frozen mapper is 4.6–5.8x faster per call (21.3 → 3.7 µs for a single Gaussian, 58.8 → 12.8 µs for a 3-Gaussian collection). This helps every search with a cheap likelihood, not only EP.
    • The answer is unchanged. Centre moments are bit-identical across all three PRs (max abs diff 0.0; the witness bar was 1e-6), and the ep_history flags are identical.

    The witness was corrected during the task: the harness has to be fully seeded, including stdlib random for InitializerPrior, before identical moments can be compared at all.

    Pending release. These changes are merged but not yet published to PyPI.

    Follow-up (left as a Mind draft): draft/bug/autofit/nautilus_converged_run_double_pass.md.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions