From 81de70d002ef5e3bc152602049e3d81efb1e63cc Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 14 Oct 2026 16:02:45 +0100 Subject: [PATCH 1/2] refactor: close the run(ctx) framework, ship the new-search template (search-ext A5 PR 4) - Delete the legacy pool shims of the _fit contract (make_pool, make_sneaky_pool and their one-core decorator check_cores); PoolFactory is the only pool source (SneakyPool stays, via PoolFactory.sneaky). An external search that still overrides _fit keeps working through self._pools(analysis). - Unknown-kwarg guard: warn (never raise) only for keywords no __init__ in the MRO names; use_jax_vmap=None, which SettingsSearch.search_dict hands every search, is no longer reported for searches without it. - autofit/non_linear/search/_template/search.py: a runnable template search whose module docstring states the run(ctx) contract and the six PyAutoFit touch points; test_template_search.py runs both conformance layers on a renamed copy (template_toy_search.ToyHillClimb, 158 lines). - docs/design/run_ctx.md revision 4; FitLifecycle not introduced (D22). Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/parallel/pool.py | 6 +- .../non_linear/search/_template/__init__.py | 0 autofit/non_linear/search/_template/search.py | 198 ++++++++++++++++++ autofit/non_linear/search/abstract_search.py | 10 +- autofit/non_linear/search/execution.py | 32 +-- autofit/non_linear/search/fit_context.py | 7 +- autofit/non_linear/search/runtime.py | 60 +++++- autofit/non_linear/search/seed.py | 5 +- docs/design/run_ctx.md | 43 ++++ .../non_linear/search/template_toy_search.py | 158 ++++++++++++++ .../non_linear/search/test_abstract_search.py | 49 +++++ .../non_linear/search/test_template_search.py | 126 +++++++++++ 12 files changed, 641 insertions(+), 53 deletions(-) create mode 100644 autofit/non_linear/search/_template/__init__.py create mode 100644 autofit/non_linear/search/_template/search.py create mode 100644 test_autofit/non_linear/search/template_toy_search.py create mode 100644 test_autofit/non_linear/search/test_template_search.py diff --git a/autofit/non_linear/parallel/pool.py b/autofit/non_linear/parallel/pool.py index 05d5fb101..9a6b295f0 100644 --- a/autofit/non_linear/parallel/pool.py +++ b/autofit/non_linear/parallel/pool.py @@ -134,9 +134,9 @@ def __init__(self, search, analysis=None): The pools one fit of ``search`` may use, with the JAX fork rule applied once. Built by ``NonLinearSearch`` once per fit, after the test-mode bypass and the - fail-fast gates, and reached by a ``run(ctx)`` search as ``ctx.pool`` and by a - legacy ``_fit`` through ``make_pool`` / ``make_sneaky_pool`` / ``number_of_cores`` - of the fit's factory. + fail-fast gates, and reached by a ``run(ctx)`` search as ``ctx.pool`` (and by an + external search that still overrides ``_fit`` as ``self._pools(analysis)``). It + is the only pool source of a search: every pool a fit uses comes from here. Parameters ---------- diff --git a/autofit/non_linear/search/_template/__init__.py b/autofit/non_linear/search/_template/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/autofit/non_linear/search/_template/search.py b/autofit/non_linear/search/_template/search.py new file mode 100644 index 000000000..3e9e8d36f --- /dev/null +++ b/autofit/non_linear/search/_template/search.py @@ -0,0 +1,198 @@ +""" +The template for a new non-linear search (search-extensibility phase A5). + +Copy this file to ``autofit/non_linear/search///search.py``, rename +``TemplateSearch``, replace the hill-climbing loop in ``run`` with your backend and +fill in the class attributes. The search below is complete and runnable: a random-walk +hill climber that keeps every point it visits. A copy of it, +``test_autofit/non_linear/search/template_toy_search.py``, passes both layers of the +search conformance suite (``test_template_search.py``). + +The contract (``docs/design/run_ctx.md``) +----------------------------------------- +A search implements three things and declares the rest: + +1. **Class attributes**: the static capabilities (``autofit.non_linear.search.capabilities``: + ``jax_use``, ``gradient``, ``batched``, ``posterior_kind``, ``objective_target``, + ``invalid_value``, ``resumable``, ``test_mode_budget``, ...), the ``samples_cls`` the + samples are built as, the ``checkpointer`` / ``resume_state`` archive strategy + (``autofit.non_linear.checkpoint``; the default archives a dill) and + ``__identifier_fields__``, the constructor arguments that change the result and so + key the output folder. Every constructor argument is stored as ``self.``, + because ``search.json`` reads them back. +2. ``run(self, ctx) -> internal``: the backend loop. ``ctx`` (``FitContext``) gives + the objective (``ctx.objective(kind)`` / ``ctx.fitness``), pools (``ctx.pool``; + never build one yourself), start points (``ctx.start_points(n)``), randomness + (``ctx.rng``, a ``SeedSequence`` of the search's ``seed``; ``ctx.rng.spawn(k)``), + the resume state (``ctx.resume``), the update cadence (``ctx.schedule``) and the + mid-run update (``ctx.update(internal)``). ``run`` never builds a ``Fitness``, a + pool or an initializer, never reads ``PYAUTO_TEST_MODE`` (level 1 is already applied + from ``test_mode_budget``), never calls ``perform_update`` and never writes + ``.completed``. It returns the backend's internal state, which is archived and + read back by ``raw_samples_from``. +3. ``raw_samples_from(self, model, internal) -> RawSamples``: the parameters, the log + likelihoods or log posteriors and the weights of the internal state, plus the + ``samples_info`` entries (``info_from``). + +The six touch points of a new search in PyAutoFit +------------------------------------------------- +1. the search file (this template); +2. its registry entry (``autofit/non_linear/search/registry.py``), which generates the + capability matrix, API page and citations (``python docs/_generate_searches.py``); +3. the export line in ``autofit/__init__.py``; +4. a unit test (and a roster entry in ``test_autofit/non_linear/search/conformance_roster.py``); +5. an integration script, ``autofit_workspace_test/scripts/searches/.py``; +6. a section in ``autofit_workspace/scripts/searches/``. +""" + +from __future__ import annotations + +from typing import Optional + +import numpy as np + +from autofit.non_linear.initializer import AbstractInitializer +from autofit.non_linear.samples.adapter import RawSamples +from autofit.non_linear.samples.samples import Samples +from autofit.non_linear.search import capabilities as cap +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import POINT + + +class TemplateSearch(NonLinearSearch): + # 1. Static capabilities: class attributes, never identifier fields. + jax_use = cap.JaxUse.NONE + gradient = cap.Gradient.NONE + batched = False + honours_gradient_mode = False + posterior_kind = cap.PosteriorKind.POINT + produces_evidence = False + resumable = False + warm_start = cap.WarmStart.NEUTRAL + install_extra = "" + upstream_url = "https://github.com/PyAutoLabs/PyAutoFit" + citation_keys = () + status = cap.Status.EXPERIMENTAL + # What ``PYAUTO_TEST_MODE=1`` reduces (``attribute: value``). + test_mode_budget = {"n_steps": 10} + # What the objective returns, in which coordinates, and its value for an invalid model. + objective_target = cap.ObjectiveTarget( + cap.ObjectiveQuantity.LOG_POSTERIOR, cap.CoordinateSpace.PHYSICAL + ) + invalid_value = -float("inf") + + samples_cls = Samples + + # The constructor arguments that change the result, and so key the output folder. + __identifier_fields__ = ("n_steps", "step_size") + + def __init__( + self, + name: Optional[str] = None, + path_prefix: Optional[str] = None, + unique_tag: Optional[str] = None, + n_steps: int = 1000, + step_size: float = 0.1, + initializer: Optional[AbstractInitializer] = None, + iterations_per_quick_update: int = None, + iterations_per_full_update: int = None, + number_of_cores: int = 1, + silence: bool = False, + session=None, + **kwargs, + ): + """ + A random-walk hill climber: from a start point, propose a Gaussian step of + ``step_size`` times each parameter's interquartile prior width and keep it when it raises + the log posterior. Every visited point is a sample. + + Parameters + ---------- + n_steps + The number of proposals. + step_size + The proposal width, as a fraction of each parameter's interquartile prior + width. + """ + super().__init__( + name=name, + path_prefix=path_prefix, + unique_tag=unique_tag, + initializer=POINT.initializer_for(initializer), + iterations_per_quick_update=iterations_per_quick_update, + iterations_per_full_update=iterations_per_full_update, + number_of_cores=number_of_cores, + silence=silence, + session=session, + **kwargs, + ) + + self.n_steps = n_steps + self.step_size = step_size + + # 2. The backend loop. + def run(self, ctx): + """ + Climb for ``n_steps`` proposals, updating the fit every + ``iterations_per_full_update`` steps, and return the visited points. + """ + objective = ctx.fitness.call_wrap + rng = np.random.default_rng(ctx.rng.spawn(1)[0]) + + # Each parameter's interquartile prior width scales its proposals. + n_dim = ctx.model.prior_count + widths = np.asarray( + ctx.model.vector_from_unit_vector([0.75] * n_dim) + ) - np.asarray(ctx.model.vector_from_unit_vector([0.25] * n_dim)) + + parameters, log_posteriors = ctx.start_points(1) + current, current_log_posterior = parameters[0], float(log_posteriors[0]) + + internal = { + "parameter_lists": [current.tolist()], + "log_posterior_list": [current_log_posterior], + "total_steps": 0, + "n_accepted": 0, + } + + for chunk in ctx.schedule.chunks(self.n_steps): + for _ in range(chunk): + proposal = current + self.step_size * widths * rng.standard_normal( + current.shape + ) + log_posterior = float(objective(proposal)) + + if np.isfinite(log_posterior) and log_posterior > current_log_posterior: + current, current_log_posterior = proposal, log_posterior + internal["n_accepted"] += 1 + + internal["parameter_lists"].append(current.tolist()) + internal["log_posterior_list"].append(current_log_posterior) + + internal["total_steps"] += chunk + + if internal["total_steps"] < self.n_steps: + ctx.update(internal) + + return internal + + # 3. The samples adapter. + def raw_samples_from(self, model, internal): + """ + The visited points and their log posteriors, equally weighted. + """ + return RawSamples( + parameters=internal["parameter_lists"], + log_posterior=internal["log_posterior_list"], + info=self.info_from(internal), + label=type(self).__name__, + ) + + def info_from(self, internal) -> dict: + """ + The search's own ``samples_info`` entries. + """ + return { + "total_steps": internal["total_steps"], + "n_accepted": internal["n_accepted"], + } diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index b9f192555..04ac88544 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -25,12 +25,12 @@ from autofit.non_linear.fitness import ITERATIONS_NEVER, get_timeout_seconds # noqa: F401 from autofit.non_linear.search.runtime import ( # noqa: F401 SearchRuntimeSettings, - check_cores, configure_handler, log_fit_start, quick_update_message, warn_deprecated_jax_knob, warn_if_threads_unpinned, + warn_unknown_kwargs, ) from autofit.non_linear.parallel import PoolFactory from autofit.non_linear.search.updater import log_process_state @@ -160,13 +160,7 @@ def __init__( self.kwargs = kwargs - for key in kwargs: - if key not in self._known_kwargs: - logger.warning( - f"{type(self).__name__} received the unknown keyword argument " - f"{key!r}, which is ignored. Check its spelling against the " - f"search's constructor." - ) + warn_unknown_kwargs(self, kwargs, known=self._known_kwargs) self.number_of_cores = number_of_cores warn_if_threads_unpinned(number_of_cores) diff --git a/autofit/non_linear/search/execution.py b/autofit/non_linear/search/execution.py index 75aab13e1..6f9698d67 100644 --- a/autofit/non_linear/search/execution.py +++ b/autofit/non_linear/search/execution.py @@ -18,9 +18,8 @@ from autonerves import conf from autofit.non_linear.fitness import Fitness -from autofit.non_linear.parallel import PoolFactory, SneakyPool +from autofit.non_linear.parallel import PoolFactory from autofit.non_linear.search import capabilities as cap -from autofit.non_linear.search.runtime import check_cores from autofit.non_linear.search.seed import initializer_rng from autofit.non_linear.test_mode import test_mode_level @@ -329,30 +328,11 @@ def _pools(self, analysis: Optional[Analysis] = None) -> PoolFactory: The current fit's `PoolFactory` (the JAX fork rule applied to its analysis), or, outside a fit, one built for `analysis` (so a direct `_fit` caller still gets the fork rule), or from `number_of_cores` alone when no analysis is given. + + The only pool source of a search (search-extensibility A5 removed the legacy + pool shims of the `_fit` contract): a `run(ctx)` search reaches it as + `ctx.pool`, an external search that still overrides `_fit` as + `self._pools(analysis)` (`PoolFactory.__call__` / `PoolFactory.sneaky`). """ pools = self.__dict__.get("_fit_pools") return pools if pools is not None else PoolFactory(self, analysis) - - @check_cores - def make_pool(self): - """ - Deprecated, kept until every search is on ``run(ctx)`` (search-extensibility - phase A5): use ``ctx.pool`` / ``self._pools()`` (``PoolFactory``). - - Make the pool instance used to parallelize a `NonLinearSearch` alongside a set of unique ids for every - process in the pool. If the specified number of cores is 1, a pool instance is not made and None is returned. - - The pool cannot be set as an attribute of the class itself because this prevents pickling, thus it is generated - via this function before calling the non-linear search. - """ - return self._pools()() - - def make_sneaky_pool(self, fitness: Fitness) -> Optional[SneakyPool]: - """ - Deprecated, kept until every search is on ``run(ctx)`` (search-extensibility - phase A5): use ``self._pools(analysis).sneaky(fitness)`` (``PoolFactory.sneaky``). - - Create a pool for multiprocessing that uses slight-of-hand to avoid copying the - fitness function between processes multiple times, or ``None`` for one core. - """ - return self._pools(getattr(fitness, "analysis", None)).sneaky(fitness) diff --git a/autofit/non_linear/search/fit_context.py b/autofit/non_linear/search/fit_context.py index bfbda1ec7..d7029e1ae 100644 --- a/autofit/non_linear/search/fit_context.py +++ b/autofit/non_linear/search/fit_context.py @@ -3,9 +3,10 @@ ``docs/design/run_ctx.md`` (frozen) fixes the ``run(ctx)`` signature and the members of ``FitContext``. A search that implements ``run(ctx)`` (and ``raw_samples_from``) instead -of ``_fit`` is driven through a ``FitContext`` by ``NonLinearSearch._fit``, the bridge; -a search that overrides ``_fit`` keeps working unchanged. ``Drawer`` and ``Nautilus`` are -the first two searches on the bridge. +of ``_fit`` is driven through a ``FitContext`` by ``NonLinearSearch._fit``, the bridge. +``Drawer`` and ``Nautilus`` were the first two searches on it (A2); since A5 every +PyAutoFit search is. An external search that still overrides ``_fit`` keeps working (it +takes its pools from ``self._pools(analysis)``). Members filled by later phases: diff --git a/autofit/non_linear/search/runtime.py b/autofit/non_linear/search/runtime.py index afadc5441..5e8e969fc 100644 --- a/autofit/non_linear/search/runtime.py +++ b/autofit/non_linear/search/runtime.py @@ -9,13 +9,13 @@ unchanged. """ +import functools import logging import os import numpy as np import warnings from dataclasses import dataclass -from functools import wraps from typing import Optional from autonerves import conf @@ -145,20 +145,58 @@ def warn_deprecated_jax_knob(owner: str, name: str, instead: str): ) -def check_cores(func): +@functools.lru_cache(maxsize=None) +def _mro_init_parameters(cls) -> frozenset: """ - Deprecated (kept with the legacy pool shims until search-extensibility phase A5): - return ``None`` instead of calling the pool-creation function ``func`` when the - search is configured for one core. + The named parameters of every ``__init__`` in ``cls``'s MRO. """ + import inspect + + names = set() + for klass in cls.__mro__: + init = klass.__dict__.get("__init__") + if init is None: + continue + try: + parameters = inspect.signature(init).parameters.values() + except (TypeError, ValueError): + continue + names.update( + parameter.name + for parameter in parameters + if parameter.kind + not in (inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL) + ) + return frozenset(names) - @wraps(func) - def wrapper(self, *args, **kwargs): - if self.number_of_cores == 1: - return None - return func(self, *args, **kwargs) - return wrapper +def warn_unknown_kwargs(search, kwargs: dict, known=()): + """ + Warn (a log WARNING, never an error) about each keyword argument that reached + ``NonLinearSearch.__init__`` through ``**kwargs`` but that no ``__init__`` in the + search's MRO consumes -- a typo such as ``n_lives=`` that would otherwise be + silently ignored. + + Not warned about: the ``known`` keys the base class reads or ``search.json`` + records, a key some ``__init__`` in the MRO names (a subclass passing it on on + purpose), and ``use_jax_vmap=None`` -- the deprecated knob's default, which + ``SettingsSearch.search_dict`` hands every search and which only the searches that + accept it read (``SettingsSearch.search_dict_for`` drops it for the others). A + ``use_jax_vmap`` set to anything else on a search that does not accept it is + warned about like any other unknown argument. + """ + consumed = _mro_init_parameters(type(search)) + + for key, value in kwargs.items(): + if key in known or key in consumed: + continue + if key == "use_jax_vmap" and value is None: + continue + logger.warning( + f"{type(search).__name__} received the unknown keyword argument " + f"{key!r}, which is ignored. Check its spelling against the " + f"search's constructor." + ) def configure_handler(func): diff --git a/autofit/non_linear/search/seed.py b/autofit/non_linear/search/seed.py index 18d156814..f77f5d705 100644 --- a/autofit/non_linear/search/seed.py +++ b/autofit/non_linear/search/seed.py @@ -7,8 +7,9 @@ - **stream 0** seeds the initializer (``AbstractInitializer.samples_from_model`` draws from a ``numpy.random.Generator``, never from the global ``random`` module); - **streams 1+** seed the backend: ``FitContext.rng`` has stream 0 spawned already, so - ``ctx.rng.spawn(k)`` hands a ``run(ctx)`` backend streams ``1..k``; the legacy - ``_fit`` searches take theirs from ``backend_seed_sequences``; + ``ctx.rng.spawn(k)`` hands a ``run(ctx)`` backend streams ``1..k`` (Emcee's + ``RandomState``); a backend built outside ``run`` (Dynesty's ``rstate``, resolved in + ``_sampler_kwargs``) takes the same streams from ``backend_seed_sequences``; - **grid-search children** each get an independent child sequence through a spawn key (``_seed_spawn_key``), which is neither serialized nor hashed. diff --git a/docs/design/run_ctx.md b/docs/design/run_ctx.md index 896e5d7e5..0d2f1be81 100644 --- a/docs/design/run_ctx.md +++ b/docs/design/run_ctx.md @@ -196,3 +196,46 @@ The signature and the member list are unchanged. one, and is recomputed from the loaded search and model only when it does not. - **`ctx.test_mode_level`**: the level-1 reduction is applied by a post-init hook from the search's `test_mode_budget` (phase A4a), so `run` sees the reduced budget on `self`. + +## Revision 4 (phase A5, 2026-10-14): every search on `run(ctx)` + +The signature `run(self, ctx) -> Any` and the member list are unchanged. + +- **Every PyAutoFit search is on the bridge.** Emcee, Zeus, BFGS/LBFGS, DynestyStatic, + DynestyDynamic, BlackJAXNUTS, SMC and the four MultiStart searches implement `run(ctx)`; + `def _fit(` under `autofit/non_linear/search` is only the base class's bridge. Seeded + `samples.csv` of every migrated search is byte-identical to the pre-A5 `_fit`. +- **The legacy pool shims are gone.** `make_pool`, `make_sneaky_pool` and their + one-core decorator were removed from `execution.py`; `PoolFactory` is the only pool + source (`ctx.pool(n, **pool_kwargs)`, `ctx.pool.sneaky(fitness)`, and + `self._pools(analysis)` for an external search that still overrides `_fit`, which keeps + working for at least one more release). Dynesty's `ForkPool` takes its worker pool from + `ctx.pool`, so the JAX fork rule and the context's pool shutdown cover it too. + `SneakyPool` stays, built only by `PoolFactory.sneaky`. +- **`ctx.start_points(n)` honours one more search-side hook**, `_start_points_in_test_mode` + (default `True`; `Zeus` sets `False`): whether the initializer may return its test-mode + samples under `PYAUTO_TEST_MODE=1` (Zeus always drew real start points). Like + `_plots_start_point` it is a class attribute, not a context member. +- **Searches whose start points are not `(parameters, figures_of_merit)`** keep the + search's own `start_points` helper (the one initializer call site): Dynesty needs the + unit-cube live points without a start-point plot, and MultiStart draws its broad + population through `_broad_starts` on its `(seed, stream)` sequences (A4). +- **Archive writes.** A search whose resume state is its archive (`MultiStart`'s dill) + saves through `ctx.update` at an intermediate boundary and through `ctx.checkpointer` + at the last one; Zeus and BFGS, which declare no resume state, still archive their + dill after every chunk with `ctx.paths.save_search_internal`, and NUTS/SMC their pickle + with `output_search_internal`, exactly as before. +- **MultiStart's `run`** is split into `_step_functions`, `_restored_state`, + `_fresh_state` and `_step_loop`; its quick-update cadence is a `fitness_overrides` + entry, so the bridge builds the same `Fitness`. +- **`FitLifecycle` is not introduced (D22).** The migrations left no lifecycle code + duplicated across searches that the mixins cannot host: every chore the design note + lists (Fitness, pools, start points, seed streams, schedule, update, cleanup) is in the + bridge and `FitContext`, and what stays in each `run` is the backend's own loop. +- **The template.** `autofit/non_linear/search/_template/search.py` is a complete, + runnable search whose module docstring states this contract and the six PyAutoFit + touch points of a new search; `test_template_search.py` runs both conformance layers on + a copy of it (`template_toy_search.py`). +- **Unknown constructor keywords** that no `__init__` in the search's MRO names are + logged as a warning (never raised); `use_jax_vmap=None`, which + `SettingsSearch.search_dict` hands every search, is not reported. diff --git a/test_autofit/non_linear/search/template_toy_search.py b/test_autofit/non_linear/search/template_toy_search.py new file mode 100644 index 000000000..03fc581c7 --- /dev/null +++ b/test_autofit/non_linear/search/template_toy_search.py @@ -0,0 +1,158 @@ +""" +A toy search written from ``autofit/non_linear/search/_template/search.py`` (the +template copied and renamed, nothing else changed), kept as the fixture of the +template smoke: ``test_template_search.py`` runs both layers of the search +conformance suite on it. It is not exported, registered or documented. +""" + +from __future__ import annotations + +from typing import Optional + +import numpy as np + +from autofit.non_linear.initializer import AbstractInitializer +from autofit.non_linear.samples.adapter import RawSamples +from autofit.non_linear.samples.samples import Samples +from autofit.non_linear.search import capabilities as cap +from autofit.non_linear.search.abstract_search import NonLinearSearch +from autofit.non_linear.search.posterior_kind import POINT + + +class ToyHillClimb(NonLinearSearch): + # 1. Static capabilities: class attributes, never identifier fields. + jax_use = cap.JaxUse.NONE + gradient = cap.Gradient.NONE + batched = False + honours_gradient_mode = False + posterior_kind = cap.PosteriorKind.POINT + produces_evidence = False + resumable = False + warm_start = cap.WarmStart.NEUTRAL + install_extra = "" + upstream_url = "https://github.com/PyAutoLabs/PyAutoFit" + citation_keys = () + status = cap.Status.EXPERIMENTAL + # What ``PYAUTO_TEST_MODE=1`` reduces (``attribute: value``). + test_mode_budget = {"n_steps": 10} + # What the objective returns, in which coordinates, and its value for an invalid model. + objective_target = cap.ObjectiveTarget( + cap.ObjectiveQuantity.LOG_POSTERIOR, cap.CoordinateSpace.PHYSICAL + ) + invalid_value = -float("inf") + + samples_cls = Samples + + # The constructor arguments that change the result, and so key the output folder. + __identifier_fields__ = ("n_steps", "step_size") + + def __init__( + self, + name: Optional[str] = None, + path_prefix: Optional[str] = None, + unique_tag: Optional[str] = None, + n_steps: int = 1000, + step_size: float = 0.1, + initializer: Optional[AbstractInitializer] = None, + iterations_per_quick_update: int = None, + iterations_per_full_update: int = None, + number_of_cores: int = 1, + silence: bool = False, + session=None, + **kwargs, + ): + """ + A random-walk hill climber: from a start point, propose a Gaussian step of + ``step_size`` times each parameter's interquartile prior width and keep it when it raises + the log posterior. Every visited point is a sample. + + Parameters + ---------- + n_steps + The number of proposals. + step_size + The proposal width, as a fraction of each parameter's interquartile prior + width. + """ + super().__init__( + name=name, + path_prefix=path_prefix, + unique_tag=unique_tag, + initializer=POINT.initializer_for(initializer), + iterations_per_quick_update=iterations_per_quick_update, + iterations_per_full_update=iterations_per_full_update, + number_of_cores=number_of_cores, + silence=silence, + session=session, + **kwargs, + ) + + self.n_steps = n_steps + self.step_size = step_size + + # 2. The backend loop. + def run(self, ctx): + """ + Climb for ``n_steps`` proposals, updating the fit every + ``iterations_per_full_update`` steps, and return the visited points. + """ + objective = ctx.fitness.call_wrap + rng = np.random.default_rng(ctx.rng.spawn(1)[0]) + + # Each parameter's interquartile prior width scales its proposals. + n_dim = ctx.model.prior_count + widths = np.asarray( + ctx.model.vector_from_unit_vector([0.75] * n_dim) + ) - np.asarray(ctx.model.vector_from_unit_vector([0.25] * n_dim)) + + parameters, log_posteriors = ctx.start_points(1) + current, current_log_posterior = parameters[0], float(log_posteriors[0]) + + internal = { + "parameter_lists": [current.tolist()], + "log_posterior_list": [current_log_posterior], + "total_steps": 0, + "n_accepted": 0, + } + + for chunk in ctx.schedule.chunks(self.n_steps): + for _ in range(chunk): + proposal = current + self.step_size * widths * rng.standard_normal( + current.shape + ) + log_posterior = float(objective(proposal)) + + if np.isfinite(log_posterior) and log_posterior > current_log_posterior: + current, current_log_posterior = proposal, log_posterior + internal["n_accepted"] += 1 + + internal["parameter_lists"].append(current.tolist()) + internal["log_posterior_list"].append(current_log_posterior) + + internal["total_steps"] += chunk + + if internal["total_steps"] < self.n_steps: + ctx.update(internal) + + return internal + + # 3. The samples adapter. + def raw_samples_from(self, model, internal): + """ + The visited points and their log posteriors, equally weighted. + """ + return RawSamples( + parameters=internal["parameter_lists"], + log_posterior=internal["log_posterior_list"], + info=self.info_from(internal), + label=type(self).__name__, + ) + + def info_from(self, internal) -> dict: + """ + The search's own ``samples_info`` entries. + """ + return { + "total_steps": internal["total_steps"], + "n_accepted": internal["n_accepted"], + } diff --git a/test_autofit/non_linear/search/test_abstract_search.py b/test_autofit/non_linear/search/test_abstract_search.py index 745ff9fd9..89d6ea057 100644 --- a/test_autofit/non_linear/search/test_abstract_search.py +++ b/test_autofit/non_linear/search/test_abstract_search.py @@ -923,6 +923,55 @@ def test_settings_search_dict_for_filters_use_jax_vmap(caplog): assert _unknown_kwarg_messages(caplog) == [] +def test_settings_search_dict_splatted_into_any_search_logs_no_unknown_kwarg(caplog): + """ + ``SettingsSearch.search_dict`` hands every search the deprecated + ``use_jax_vmap=None``; only the searches that accept it read it, and its default + is never reported as unknown to the others (search-extensibility A5). + """ + import logging + + settings_search = af.SettingsSearch(path_prefix="settings_search_test") + + with caplog.at_level(logging.WARNING): + af.DynestyStatic(**settings_search.search_dict) + af.Emcee(**settings_search.search_dict) + af.Nautilus(**settings_search.search_dict) + + assert _unknown_kwarg_messages(caplog) == [] + + +def test_a_set_use_jax_vmap_on_a_search_without_it_is_still_unknown(caplog): + import logging + + with caplog.at_level(logging.WARNING): + af.Emcee(use_jax_vmap=True) + + messages = _unknown_kwarg_messages(caplog) + assert len(messages) == 1 + assert "'use_jax_vmap'" in messages[0] + + +def test_a_kwarg_an_mro_init_names_is_not_unknown(caplog): + """ + The guard warns only about keys no ``__init__`` in the MRO consumes: a subclass + that names an argument and passes it on through ``**kwargs`` is not warned about. + """ + import logging + + class Forwarding(af.Drawer): + def __init__(self, extra_setting=1, **kwargs): + super().__init__(extra_setting=extra_setting, **kwargs) + + with caplog.at_level(logging.WARNING): + Forwarding(extra_setting=2) + Forwarding(extra_typo=3) + + messages = _unknown_kwarg_messages(caplog) + assert len(messages) == 1 + assert "'extra_typo'" in messages[0] + + def test_deprecated_jax_knobs_warn_only_when_passed(): import warnings diff --git a/test_autofit/non_linear/search/test_template_search.py b/test_autofit/non_linear/search/test_template_search.py new file mode 100644 index 000000000..43e03aefa --- /dev/null +++ b/test_autofit/non_linear/search/test_template_search.py @@ -0,0 +1,126 @@ +""" +The template smoke (search-extensibility A5): a toy search written from +``autofit/non_linear/search/_template/search.py`` (``template_toy_search.ToyHillClimb``) +passes both layers of the search conformance suite -- layer (i), metadata and +serialization (``test_conformance.py``), and layer (ii), backend execution +(``test_conformance_backend.py``) -- through the very same test functions, with the +toy's own golden rows. +""" + +import inspect + +import pytest + +from test_autofit.non_linear.search import conformance_roster as roster +from test_autofit.non_linear.search import test_conformance as layer_i +from test_autofit.non_linear.search import test_conformance_backend as layer_ii + +TOY = roster.SearchEntry( + "ToyHillClimb", + "test_autofit.non_linear.search.template_toy_search.ToyHillClimb", + "mle", + jax_use="none", +) + +TOY_GOLDEN = roster.Golden( + identifier="d2250e3156c424efc1ff5c9f00267506", + identifier_fields=("n_steps", "step_size"), + constructor_arguments={ + "initializer", + "iterations_per_full_update", + "iterations_per_quick_update", + "kwargs", + "n_steps", + "name", + "number_of_cores", + "path_prefix", + "session", + "silence", + "step_size", + "unique_tag", + }, +) + + +@pytest.fixture(autouse=True) +def toy_rows(monkeypatch): + """ + The toy's rows in the golden tables both layers read by search name. + """ + monkeypatch.setitem(layer_i.GOLDEN, TOY.name, TOY_GOLDEN) + monkeypatch.setitem(layer_ii.SEARCH_INTERNAL_FILES, TOY.name, layer_ii._DILL) + monkeypatch.setitem( + layer_ii.SAMPLES_INFO_KEYS, + TOY.name, + layer_ii._CORE_KEYS | {"total_steps", "n_accepted"}, + ) + monkeypatch.setitem(layer_ii.SAMPLES_CLASS, TOY.name, "Samples") + + +def test_the_toy_is_the_template_renamed(): + template = roster.resolve_class_path( + "autofit.non_linear.search._template.search.TemplateSearch" + ) + + assert inspect.getsource(TOY.resolve()) == inspect.getsource(template).replace( + "TemplateSearch", "ToyHillClimb" + ) + + +def test_the_toy_is_at_most_250_lines(): + assert len(inspect.getsource(inspect.getmodule(TOY.resolve())).splitlines()) <= 250 + + +LAYER_I = [ + layer_i.test_default_construction, + layer_i.test_family_base, + layer_i.test_identifier_fields_golden, + layer_i.test_constructor_argument_set, + layer_i.test_search_json_round_trip, +] + + +@pytest.mark.parametrize("case", LAYER_I, ids=lambda case: case.__name__) +def test_layer_i(case): + case(TOY) + + +def test_layer_i_identifier(monkeypatch): + layer_i.test_identifier_golden(TOY, monkeypatch) + + +def test_layer_i_config_unchanged_by_construction(tmp_path): + fixture = layer_i.make_search_internal_off.__wrapped__(tmp_path) + next(fixture) + try: + layer_i.test_config_unchanged_by_construction(TOY, None) + finally: + next(fixture, None) + + +@pytest.fixture(name="toy_run", scope="module") +def make_toy_run(tmp_path_factory): + return layer_ii._execute(TOY, tmp_path_factory.mktemp("backend_toy")) + + +LAYER_II = [ + layer_ii.test_backend_runs_in_reduced_test_mode, + layer_ii.test_directory_paths_output_file_set, + layer_ii.test_completed_path_resumes_without_rerunning_the_backend, + layer_ii.test_null_paths_fit_returns_a_result, + layer_ii.test_null_paths_samples_from_none_raises_rather_than_falling_back, + layer_ii.test_restored_output_samples_from_none_loads_the_internal_state, + layer_ii.test_samples_info_key_set, +] + + +@pytest.mark.parametrize("case", LAYER_II, ids=lambda case: case.__name__) +def test_layer_ii(case, toy_run): + case(TOY, lambda entry: toy_run) + + +@pytest.mark.parametrize("error_type", [FileNotFoundError, NotImplementedError]) +def test_layer_ii_samples_from_falls_back(error_type, toy_run, monkeypatch, caplog): + layer_ii.test_samples_from_falls_back_to_paths_samples( + TOY, error_type, lambda entry: toy_run, monkeypatch, caplog + ) From 9c78451efdf44524762482be4fc94e1ad793cbb9 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 14 Oct 2026 16:52:01 +0100 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20PR=204=20review=20findings=20?= =?UTF-8?q?=E2=80=94=20search=5Fdict=20docstring,=20NSS=20in=20run=5Fctx?= =?UTF-8?q?=20revision=204,=20no=20class=20cache,=20inline=20config=20fixt?= =?UTF-8?q?ure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/search/runtime.py | 2 -- autofit/non_linear/settings.py | 4 ++-- docs/design/run_ctx.md | 5 +++-- test_autofit/non_linear/search/test_template_search.py | 9 ++++++--- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/autofit/non_linear/search/runtime.py b/autofit/non_linear/search/runtime.py index 5e8e969fc..6b0a54bd2 100644 --- a/autofit/non_linear/search/runtime.py +++ b/autofit/non_linear/search/runtime.py @@ -9,7 +9,6 @@ unchanged. """ -import functools import logging import os @@ -145,7 +144,6 @@ def warn_deprecated_jax_knob(owner: str, name: str, instead: str): ) -@functools.lru_cache(maxsize=None) def _mro_init_parameters(cls) -> frozenset: """ The named parameters of every ``__init__`` in ``cls``'s MRO. diff --git a/autofit/non_linear/settings.py b/autofit/non_linear/settings.py index 61c570747..44127d570 100644 --- a/autofit/non_linear/settings.py +++ b/autofit/non_linear/settings.py @@ -70,8 +70,8 @@ def search_dict(self): Every search setting as a dictionary, including ``use_jax_vmap``. Only searches whose constructor accepts ``use_jax_vmap`` (e.g. ``Nautilus``) use it; any other search - logs it as an unknown keyword argument. Use ``search_dict_for`` to get the settings filtered to what a - given search accepts. + ignores it, and logs it as an unknown keyword argument only when it is set (not ``None``). Use + ``search_dict_for`` to get the settings filtered to what a given search accepts. """ return { "path_prefix": self.path_prefix, diff --git a/docs/design/run_ctx.md b/docs/design/run_ctx.md index 0d2f1be81..4f0b6b94f 100644 --- a/docs/design/run_ctx.md +++ b/docs/design/run_ctx.md @@ -201,8 +201,9 @@ The signature and the member list are unchanged. The signature `run(self, ctx) -> Any` and the member list are unchanged. -- **Every PyAutoFit search is on the bridge.** Emcee, Zeus, BFGS/LBFGS, DynestyStatic, - DynestyDynamic, BlackJAXNUTS, SMC and the four MultiStart searches implement `run(ctx)`; +- **Every PyAutoFit search is on the bridge.** A5 moved Emcee, Zeus, BFGS/LBFGS, + DynestyStatic, DynestyDynamic, BlackJAXNUTS, SMC and the four MultiStart searches onto + `run(ctx)`, joining Drawer, Nautilus (A2) and NSS (A3b); `def _fit(` under `autofit/non_linear/search` is only the base class's bridge. Seeded `samples.csv` of every migrated search is byte-identical to the pre-A5 `_fit`. - **The legacy pool shims are gone.** `make_pool`, `make_sneaky_pool` and their diff --git a/test_autofit/non_linear/search/test_template_search.py b/test_autofit/non_linear/search/test_template_search.py index 43e03aefa..a79d3cebe 100644 --- a/test_autofit/non_linear/search/test_template_search.py +++ b/test_autofit/non_linear/search/test_template_search.py @@ -10,6 +10,7 @@ import inspect import pytest +from autonerves import conf from test_autofit.non_linear.search import conformance_roster as roster from test_autofit.non_linear.search import test_conformance as layer_i @@ -90,12 +91,14 @@ def test_layer_i_identifier(monkeypatch): def test_layer_i_config_unchanged_by_construction(tmp_path): - fixture = layer_i.make_search_internal_off.__wrapped__(tmp_path) - next(fixture) + # The `search_internal_off` fixture of layer (i), inline. + original_configs = list(conf.instance.configs) + (tmp_path / "output.yaml").write_text("search_internal: false\n") + conf.instance.push(new_path=str(tmp_path)) try: layer_i.test_config_unchanged_by_construction(TOY, None) finally: - next(fixture, None) + conf.instance.configs = original_configs @pytest.fixture(name="toy_run", scope="module")