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
6 changes: 3 additions & 3 deletions autofit/non_linear/parallel/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------
Expand Down
Empty file.
198 changes: 198 additions & 0 deletions autofit/non_linear/search/_template/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""
The template for a new non-linear search (search-extensibility phase A5).

Copy this file to ``autofit/non_linear/search/<family>/<name>/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.<arg>``,
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/<Name>.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"],
}
10 changes: 2 additions & 8 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
32 changes: 6 additions & 26 deletions autofit/non_linear/search/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
7 changes: 4 additions & 3 deletions autofit/non_linear/search/fit_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
58 changes: 47 additions & 11 deletions autofit/non_linear/search/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import numpy as np
import warnings
from dataclasses import dataclass
from functools import wraps
from typing import Optional

from autonerves import conf
Expand Down Expand Up @@ -145,20 +144,57 @@ def warn_deprecated_jax_knob(owner: str, name: str, instead: str):
)


def check_cores(func):
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):
Expand Down
5 changes: 3 additions & 2 deletions autofit/non_linear/search/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading