Skip to content

refactor: A4a decompose NonLinearSearch (TestModeBypass, EP adapter, runtime settings, paths capabilities) - #1685

Merged
Jammy2211 merged 4 commits into
mainfrom
feature/search-ext-a4-decompose
Oct 14, 2026
Merged

Jammy2211 merged 4 commits into
mainfrom
feature/search-ext-a4-decompose

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Summary

Search-extensibility phase A4a (PR 1 of 3, stacked: this → feature/search-ext-a4-seed → feature/search-ext-a4-family-bases). Decomposes NonLinearSearch: abstract_search.py goes from 2,102 to 584 lines with no change to identifiers, search.json, serialized constructor-argument sets or the public API. FitLifecycle is deliberately not extracted (D22, deferred to A5). Issue #1684 is closed by PR 3.

What changed, by sub-step

  1. Paths capabilities + paths_from (d3835e50c). AbstractPaths.has_timer / supports_checkpointing (Null: False/False; Database: False/True; Directory and sub-directory paths: True/True) replace the isinstance(NullPaths/DatabasePaths) checks in the updater timer, start_resume_fit, and the Dynesty/Nautilus checkpoint and iteration paths. autofit.non_linear.paths.paths_from(name, path_prefix, unique_tag, session, paths) is the paths factory that __init__ used inline.
  2. SearchFactorOptimiser (ee8d99139), in autofit/graphical/expectation_propagation/search_factor_optimiser.py and re-exported from autofit.graphical.expectation_propagation. It holds the old optimise body unchanged: the release_search_internal call (RAL 342410 comment kept), the fresh SubDirectoryPaths for each step that makes the cached updater rebuild itself, the EP visual switches, the log_norm evidence, and the check_factor_search_cores refusal. NonLinearSearch.optimise is now a one-line delegate, and NonLinearSearch is still an AbstractFactorOptimiser.
  3. SearchRuntimeSettings (956e4958b, search/runtime.py). This is a frozen dataclass holding the general.yaml reads made once at construction: update cadences, HPC override, background/live updates, the force-overwrite flags and silence. It is applied as the same instance attributes as before, so search.json is unchanged. The module also holds warn_if_threads_unpinned, configure_handler, check_cores, warn_deprecated_jax_knob, log_fit_start and quick_update_message; abstract_search re-exports the old names.
  4. Decomposition (d37280e2b):
    • TestModeBypass (search/test_mode_bypass.py) holds the level 2/3 bypass, the deterministic valid-point search, the level-1 rejected-sample repair (repair_reduced_samples) and build_fake_samples. The bypass and the real fit both end in the one NonLinearSearch.finalize_result(samples, ...): make_result, then save_results(_combined), unfreeze, then _complete_fit.
    • Generic apply_test_mode is driven by the declared test_mode_budget (dotted keys reach members, e.g. convergence.window). It runs once from a post-init hook, _SearchMeta.__call__ → _post_init, after the outermost __init__ returns. The eight if is_test_mode(): self.apply_test_mode() tails and the five plain-assignment overrides (Emcee, Zeus, Dynesty, Nautilus, NSS) are gone. BlackJAXNUTS and SMC keep their overrides because they cap rather than assign (min(num_chains, 2), min(num_particles, 16)).
    • BFGS/LBFGS gain test_mode_budget = {"maxiter": 10}. At level 1 they used to run the full maxiter=15000. The registry and docs/searches/index.rst are regenerated to match.
    • The runtime gates (whole-graph backend agreement, REQUIRED gate, x64, trace preflight) move from start_resume_fit into preflight.check_runtime_gates. They still run after the bypass return.
    • The remaining method groups move to __init__-less bases of NonLinearSearch in their own modules. These are execution.py (the run(ctx) bridge _run_bridge, make_fitness, start points, pools, _SearchMeta), internal_state.py (archive/resume state, the samples-conversion path) and updates.py (cached SearchUpdater, perform_update / perform_visualization, the update schedule).
    • The legacy pool shims make_pool, make_sneaky_pool and the number_of_cores accessor stay, with docstrings marked deprecated until A5. SneakyPool stays as PoolFactory.sneaky.

Invariants (report §3.2)

# Invariant Evidence
1 Public class names / af. exports unchanged; SearchFactorOptimiser added to autofit.graphical.expectation_propagation
2 Identifier hashes golden table (test_conformance.py::test_identifier_golden, all 15) passes; a scripted dump of str(Identifier(cls())) and hash_list for all 15 is byte-identical to main 8437a3b
3 search.json, serialized constructor-argument sets af.to_dict(cls()) and autonerves.dictable.get_arguments(cls) for all 15 identical to main (the new bases define no __init__, so the __bases__ walk adds nothing); test_search_json_round_trip passes
4 On-disk layout / filenames unchanged (no paths or checkpoint filename touched)
5 samples_info["class_path"] unchanged (no Samples class moved)
6 #1493 clipper tripwire test_nested_samplers_have_no_clipper, test_clipper_forks_mle_identifier pass
7 NonLinearSearch is an AbstractFactorOptimiser new test_search_is_still_a_factor_optimiser
8 External subclasses method surface unchanged (overrides and monkeypatching of perform_update, samples_via_internal_from, _fit, ... still resolve on the search)
9 Result one class untouched

Witness

  • wc -l autofit/non_linear/search/abstract_search.py: 2102 → 584 (guarded by test_decomposition.py::test_abstract_search_is_at_most_600_lines).
  • BFGS at test-mode level 1 runs a reduced maxiter: test_bfgs_runs_a_reduced_maxiter_at_test_mode_1 (maxiter == 10, BFGS and LBFGS), and 15000 outside test mode.
  • 2-step EP with MockSearch: test_autofit/graphical/test_search_factor_optimiser.py. Every factor gets optimization_0 and optimization_1 with fresh paths. The cached updater is rebuilt for each new paths object (updater._paths is search.paths). The visual switches are set for each step and restored afterwards. release_search_internal is called on every step's result.
  • TestBypass*, test_updater.py, test_autofit/graphical/* pass.

Tests

  • Full suite, serial (python -m pytest test_autofit -q): 3603 passed, 1 skipped, 4 xfailed (main baseline: 3579 passed / 1 skipped / 4 xfailed; +24 new tests).
  • unittest-nojax emulation (a sitecustomize blocking jax/jaxlib/blackjax/optax, find_spec → None): 3298 passed, 170 skipped, 2 xfailed.
  • Sphinx: 30 warnings (≤30, all pre-existing kinds). docs/_generate_searches.py --check is clean after regenerating (BFGS/LBFGS budget column).
  • Workspace smoke (pyauto-heart smoke autofit autolens, worktree source): autofit_workspace 8/8 scripts + 2/2 notebooks, autolens_workspace 41/41 scripts + 2/2 notebooks pass.
  • autofit_workspace_test scripts/searches + scripts/graphical (32 scripts): 25/32 pass at PYAUTO_TEST_MODE=1, 23/32 at =2. Every failure also fails on main 8437a3b with the same harness. They are real-search assertions not meant for test mode (BlackJAXNUTS divergences, MultiStart accuracy/resurrect/NaN-counter checks, analytic_gaussian* parity, and at level 2 NSS log_evidence_error and ep_parity), so none is a regression.
  • Note: running only a subset of the suite (non_linear/search + graphical + database/identifier) shows 5 order-dependent failures (graphical/info/test_output.py, test_global.py, test_identifiers.py::test_unique_tag). The same subset fails identically on main, and the full serial suite is green.

Decisions taken

  • Mixin modules rather than delegating collaborators for the groups that are not lifecycle. With FitLifecycle deferred (D22), the lifecycle plus constructor alone is about 450 lines, so ≤600 needed the rest out of the file. The new bases keep the whole method surface on the search, so subclass overrides and tests that monkeypatch NonLinearSearch.<method> still work, and none defines __init__, so dictable.get_arguments is unchanged (verified for all 15). The real collaborators are TestModeBypass, SearchFactorOptimiser, SearchRuntimeSettings, paths_from and PoolFactory.
  • Lifecycle docstrings condensed (fit, pre_fit_output, start_resume_fit, result_via_completed_fit). Content is kept and the verbose parameter blocks are trimmed.
  • EP visual switches stay on the search (_visualize_fit, _visualize_before_fit). The adapter sets and restores them. Tests and the updater read them there, and StaticSearch doubles rely on the class defaults.
  • Generic reduction semantics = assignment. BlackJAXNUTS and SMC keep apply_test_mode overrides for their min(...) caps, so a user's smaller num_chains / num_particles is not raised. Drawer keeps an empty budget, because its initializer already draws test-mode samples, and changing total_draws would re-key its test-mode output.
  • DatabasePaths.supports_checkpointing = True. This keeps the Dynesty/Nautilus checkpoint and iteration behaviour for database paths, where previously only NullPaths was excluded. has_timer is False for Null and Database, exactly as the two old isinstance checks.
  • The samples_from fallback warning now logs under autofit.non_linear.search.internal_state; test_conformance_backend.py follows it. Tests patching TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS now patch search.test_mode_bypass. test_make_fitness.py's single-construction-site scan now names execution.py.
  • The JAX-device start-of-fit log line now comes from search/runtime.py's logger.

Companion changes required

None for this PR.

🤖 Generated with Claude Code

Jammy2211 and others added 4 commits October 14, 2026 11:31
…paths_from

Replace the isinstance(NullPaths/DatabasePaths) checks in the updater timer and
the Dynesty/Nautilus checkpoint paths with paths capability flags; paths_from
builds a search's paths from name/path_prefix/session.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ical/expectation_propagation

Moves NonLinearSearch.optimise's body verbatim (release_search_internal, the
per-step SubDirectoryPaths that invalidates the cached updater, the EP visual
switches) and re-exports it from autofit.graphical.expectation_propagation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ode hook, mixin modules)

- TestModeBypass (search/test_mode_bypass.py): the level 2/3 bypass and the level 1
  rejected-sample repair; bypass and real fit share finalize_result(samples).
- Generic apply_test_mode from test_mode_budget, run once by a post-init hook
  (_SearchMeta.__call__); the per-search tails and plain overrides are removed.
  BFGS/LBFGS gain test_mode_budget={'maxiter': 10}.
- optimise delegates to SearchFactorOptimiser; __init__ uses paths_from and
  SearchRuntimeSettings; the runtime gates move to preflight.check_runtime_gates.
- The run(ctx) bridge, Fitness, start points and pools (execution.py), the
  archive/resume/samples path (internal_state.py) and the updater/schedule
  (updates.py) move to __init__-less bases of NonLinearSearch.
- abstract_search.py: 2102 -> 584 lines.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant