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
3 changes: 0 additions & 3 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,3 @@ def check_model(self, model: AbstractPriorModel):

def __eq__(self, other):
return isinstance(other, NonLinearSearch) and self.__dict__ == other.__dict__

def plot_results(self, samples):
raise NotImplementedError
22 changes: 22 additions & 0 deletions autofit/non_linear/search/deprecated_family.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
The deprecation hook of the former family bases (search-extensibility A4c, D14).

``AbstractMCMC``, ``AbstractNest`` and ``AbstractMLE`` are no longer in any public
search's MRO. Their modules still export them, as distinct thin subclasses of
``NonLinearSearch`` that keep the former constructor defaults and plots, so external
subclasses keep working for one release; subclassing one warns.
"""

import warnings


def warn_family_subclass(cls, family: str, kind: str):
warnings.warn(
f"{cls.__name__} subclasses {family}, which is deprecated and will be removed "
f"one release after search-extensibility phase A4. Subclass "
f"`autofit.NonLinearSearch` directly, declare `posterior_kind = "
f"PosteriorKind.{kind}` and apply that kind's defaults in `__init__` "
f"(`autofit.non_linear.search.posterior_kind.{kind}`).",
FutureWarning,
stacklevel=3,
)
39 changes: 20 additions & 19 deletions autofit/non_linear/search/mcmc/abstract_mcmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,35 @@

from typing import Optional, TYPE_CHECKING

from autonerves import conf
from autofit.non_linear.search.abstract_search import NonLinearSearch
from autofit.non_linear.initializer import Initializer, InitializerBall
from autofit.non_linear.initializer import Initializer
from autofit.non_linear.search.deprecated_family import warn_family_subclass
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.plot import corner_cornerpy
from autofit.non_linear.search.posterior_kind import CHAIN
from autofit.non_linear.samples.mcmc import SamplesMCMC

if TYPE_CHECKING:
from autofit.database.sqlalchemy_ import sa


class AbstractMCMC(NonLinearSearch):
"""
**Deprecated** (search-extensibility A4c): no public search inherits it any more,
and it is removed one release later. Subclass ``NonLinearSearch`` with
``posterior_kind = PosteriorKind.CHAIN`` and apply
``autofit.non_linear.search.posterior_kind.CHAIN`` in ``__init__`` instead.

Kept as a distinct class with the former defaults (``InitializerBall(0.49, 0.51)``,
``auto_correlation_settings``, ``SamplesMCMC``, the cornerpy corner plot), so an
existing subclass behaves exactly as before; subclassing it warns.
"""

samples_cls = SamplesMCMC

def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
warn_family_subclass(cls, "AbstractMCMC", "CHAIN")

def __init__(
self,
name: Optional[str] = None,
Expand All @@ -36,9 +51,7 @@ def __init__(
name=name,
path_prefix=path_prefix,
unique_tag=unique_tag,
initializer=initializer or InitializerBall(
lower_limit=0.49, upper_limit=0.51
),
initializer=CHAIN.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,
Expand All @@ -48,16 +61,4 @@ def __init__(
)

def plot_results(self, samples):

if not samples.pdf_converged:
return

def should_plot(name):
return conf.instance["visualize"]["plots_search"]["mcmc"][name]

if should_plot("corner_cornerpy"):
corner_cornerpy(
samples=samples,
path=self.paths.image_path / "search",
format="png",
)
CHAIN.plot_results(self, samples)
19 changes: 12 additions & 7 deletions autofit/non_linear/search/mcmc/blackjax/nuts/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
from autofit.non_linear.checkpoint import PICKLE_FILENAME, PickleCheckpointer
from autofit.non_linear.fitness import Fitness
from autofit.non_linear.initializer import Initializer
from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC
from autofit.non_linear.search.abstract_search import NonLinearSearch
from autofit.non_linear.search.posterior_kind import CHAIN
from autofit.non_linear.samples.mcmc import SamplesMCMC
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.search.mcmc.blackjax.chains import (
Expand All @@ -36,7 +38,9 @@
logger = logging.getLogger(__name__)


class BlackJAXNUTS(AbstractMCMC):
class BlackJAXNUTS(NonLinearSearch):
samples_cls = SamplesMCMC

# Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored
# by ``search/registry.py``. Never identifier fields.
jax_use = cap.JaxUse.REQUIRED
Expand Down Expand Up @@ -81,9 +85,7 @@ def __init__(
inverse_mass_matrix: InverseMassMatrixSpec = None,
mass_matrix_shrinkage: float = 0.0,
share_adaptation: bool = False,
auto_correlation_settings: AutoCorrelationsSettings = AutoCorrelationsSettings(
check_for_convergence=False
),
auto_correlation_settings: Optional[AutoCorrelationsSettings] = None,
iterations_per_quick_update: Optional[int] = None,
iterations_per_full_update: Optional[int] = None,
number_of_cores: int = 1,
Expand Down Expand Up @@ -236,8 +238,7 @@ def __init__(
name=name,
path_prefix=path_prefix,
unique_tag=unique_tag,
initializer=initializer,
auto_correlation_settings=auto_correlation_settings,
initializer=CHAIN.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,
Expand All @@ -247,6 +248,10 @@ def __init__(
**kwargs,
)

self.auto_correlation_settings = CHAIN.auto_correlation_settings_for(
auto_correlation_settings, check_for_convergence=False
)

self.num_warmup = num_warmup
self.num_samples = num_samples
self.num_chains = num_chains
Expand Down
84 changes: 73 additions & 11 deletions autofit/non_linear/search/mcmc/blackjax/smc/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import math
import os
import warnings
from pathlib import Path
from typing import List, Optional, Tuple, TYPE_CHECKING

Expand All @@ -12,8 +13,8 @@
from autofit.non_linear.checkpoint import PICKLE_FILENAME, PickleCheckpointer
from autofit.non_linear.objective import jax_objective
from autofit.non_linear.initializer import Initializer, InitializerPrior
from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.search.abstract_search import NonLinearSearch
from autofit.non_linear.search.posterior_kind import WEIGHTED
from autofit.non_linear.search.mcmc.blackjax.chains import (
InverseMassMatrixSpec,
SERIALISED_KINDS,
Expand Down Expand Up @@ -53,7 +54,7 @@
VALID_KERNELS = ("mala", "hmc")


class SMC(AbstractMCMC):
class SMC(NonLinearSearch):
samples_cls = SamplesSMC

# Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored
Expand Down Expand Up @@ -104,9 +105,7 @@ def __init__(
seed: Optional[int] = None,
initializer: Optional[Initializer] = None,
inverse_mass_matrix: InverseMassMatrixSpec = None,
auto_correlation_settings: AutoCorrelationsSettings = AutoCorrelationsSettings(
check_for_convergence=False
),
*legacy_positional,
iterations_per_quick_update: Optional[int] = None,
iterations_per_full_update: Optional[int] = None,
number_of_cores: int = 1,
Expand Down Expand Up @@ -258,9 +257,6 @@ def __init__(
``search.json`` records only the kind (``"none"``, ``"array"`` or ``"result"``), so a search loaded
from it receives that string: ``"none"`` behaves as ``None``, while ``"array"`` / ``"result"`` raise at
fit time because the covariance was not saved.
auto_correlation_settings
Kept for API parity with the other MCMC searches. SMC particles are not a chain, so no
auto-correlation diagnostics are computed and ``check_for_convergence`` defaults to ``False``.
iterations_per_full_update
Inherited from the autonerves config when ``None``. SMC calls ``perform_update`` once per
temperature (SMC steps are coarse and few), so this does not chunk the run.
Expand All @@ -271,14 +267,39 @@ def __init__(
If True, the default print output of the non-linear search is silenced.
session
An SQLalchemy session instance.
legacy_positional
Deprecated. SMC used to take ``auto_correlation_settings`` positionally after
``inverse_mass_matrix``; the arguments after it are now keyword-only. Old positional
calls are still bound to their former slots (the auto-correlation settings are ignored)
with a ``FutureWarning``, instead of being silently shifted one slot.
"""

# SMC is a weighted-posterior search (A4c): its particles are not a chain, so it
# takes no auto-correlation settings. An old `search.json` still records them;
# they are accepted and ignored so it loads.
kwargs.pop("auto_correlation_settings", None)

if legacy_positional:
(
iterations_per_quick_update,
iterations_per_full_update,
number_of_cores,
silence,
session,
) = _bind_legacy_positional(
legacy_positional,
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,
)

super().__init__(
name=name,
path_prefix=path_prefix,
unique_tag=unique_tag,
initializer=initializer or InitializerPrior(),
auto_correlation_settings=auto_correlation_settings,
initializer=WEIGHTED.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,
Expand Down Expand Up @@ -1031,3 +1052,44 @@ def _build_search_internal(
"max_smc_steps": max_smc_steps,
"converged": bool(lambda_list) and float(lambda_list[-1]) >= 1.0,
}


# The arguments SMC took positionally after ``inverse_mass_matrix`` before A4c removed
# ``auto_correlation_settings`` (adversary review 07, finding 4).
_LEGACY_POSITIONAL = (
"auto_correlation_settings",
"iterations_per_quick_update",
"iterations_per_full_update",
"number_of_cores",
"silence",
"session",
)


def _bind_legacy_positional(legacy_positional, **current):
"""
Bind positional arguments passed after ``inverse_mass_matrix`` to the slots they had
when SMC still took ``auto_correlation_settings`` there, so an old positional call
keeps its meaning instead of shifting every value one slot. The auto-correlation
settings are dropped (SMC is a weighted search). Warns with a ``FutureWarning``; pass
these arguments by keyword instead.
"""
if len(legacy_positional) > len(_LEGACY_POSITIONAL):
raise TypeError(
f"SMC takes at most {len(_LEGACY_POSITIONAL)} deprecated positional arguments "
f"after inverse_mass_matrix ({', '.join(_LEGACY_POSITIONAL)}); got "
f"{len(legacy_positional)}. Pass them by keyword."
)
warnings.warn(
"Passing SMC arguments positionally after `inverse_mass_matrix` is deprecated: SMC no "
"longer takes `auto_correlation_settings` (it is a weighted search, not a chain), so "
f"these slots ({', '.join(_LEGACY_POSITIONAL[: len(legacy_positional)])}) are bound "
"as they were and the auto-correlation settings are ignored. Pass them by keyword.",
FutureWarning,
stacklevel=3,
)
bound = dict(zip(_LEGACY_POSITIONAL, legacy_positional))
bound.pop("auto_correlation_settings", None)
return tuple(
bound.get(name, current[name]) for name in _LEGACY_POSITIONAL[1:]
)
17 changes: 12 additions & 5 deletions autofit/non_linear/search/mcmc/emcee/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
load_emcee_backend,
)
from autofit.non_linear.initializer import Initializer
from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC
from autofit.non_linear.search.abstract_search import NonLinearSearch
from autofit.non_linear.search.posterior_kind import CHAIN
from autofit.non_linear.samples.mcmc import SamplesMCMC
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations
from autofit.non_linear.test_mode import is_test_mode
Expand All @@ -30,7 +32,9 @@
logger = logging.getLogger(__name__)


class Emcee(AbstractMCMC):
class Emcee(NonLinearSearch):
samples_cls = SamplesMCMC

# Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored
# by ``search/registry.py``. Never identifier fields.
jax_use = cap.JaxUse.NONE
Expand Down Expand Up @@ -69,7 +73,7 @@ def __init__(
nwalkers: int = 50,
nsteps: int = 2000,
initializer: Optional[Initializer] = None,
auto_correlation_settings=AutoCorrelationsSettings(),
auto_correlation_settings: Optional[AutoCorrelationsSettings] = None,
iterations_per_quick_update: int = None,
iterations_per_full_update: int = None,
number_of_cores: int = 1,
Expand Down Expand Up @@ -118,8 +122,7 @@ def __init__(
name=name,
path_prefix=path_prefix,
unique_tag=unique_tag,
initializer=initializer,
auto_correlation_settings=auto_correlation_settings,
initializer=CHAIN.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,
Expand All @@ -128,6 +131,10 @@ def __init__(
**kwargs,
)

self.auto_correlation_settings = CHAIN.auto_correlation_settings_for(
auto_correlation_settings
)

self.nwalkers = nwalkers
self.nsteps = nsteps

Expand Down
17 changes: 12 additions & 5 deletions autofit/non_linear/search/mcmc/zeus/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
from autofit.mapper.model_mapper import ModelMapper
from autofit.mapper.prior_model.abstract import AbstractPriorModel
from autofit.non_linear.initializer import Initializer
from autofit.non_linear.search.mcmc.abstract_mcmc import AbstractMCMC
from autofit.non_linear.search.abstract_search import NonLinearSearch
from autofit.non_linear.search.posterior_kind import CHAIN
from autofit.non_linear.samples.mcmc import SamplesMCMC
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.search.mcmc.auto_correlations import AutoCorrelations
from autofit.non_linear.test_mode import is_test_mode
Expand All @@ -23,7 +25,9 @@
logger = logging.getLogger(__name__)


class Zeus(AbstractMCMC):
class Zeus(NonLinearSearch):
samples_cls = SamplesMCMC

# Static capabilities (see ``autofit.non_linear.search.capabilities``); mirrored
# by ``search/registry.py``. Never identifier fields.
jax_use = cap.JaxUse.NONE
Expand Down Expand Up @@ -70,7 +74,7 @@ def __init__(
check_walkers: bool = True,
maxcall: Optional[int] = None,
initializer: Optional[Initializer] = None,
auto_correlation_settings=AutoCorrelationsSettings(),
auto_correlation_settings: Optional[AutoCorrelationsSettings] = None,
iterations_per_quick_update: int = None,
iterations_per_full_update: int = None,
number_of_cores: int = 1,
Expand Down Expand Up @@ -119,8 +123,7 @@ def __init__(
name=name,
path_prefix=path_prefix,
unique_tag=unique_tag,
initializer=initializer,
auto_correlation_settings=auto_correlation_settings,
initializer=CHAIN.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,
Expand All @@ -129,6 +132,10 @@ def __init__(
**kwargs
)

self.auto_correlation_settings = CHAIN.auto_correlation_settings_for(
auto_correlation_settings
)

self.nwalkers = nwalkers
self.nsteps = nsteps
self.tune = tune
Expand Down
Loading
Loading