diff --git a/autofit/aggregator/search_output.py b/autofit/aggregator/search_output.py index 7f3e99f30..9a8965fbf 100644 --- a/autofit/aggregator/search_output.py +++ b/autofit/aggregator/search_output.py @@ -5,6 +5,7 @@ import tempfile import weakref from abc import ABC +from hashlib import md5 from pathlib import Path from shutil import rmtree from typing import Generator, Tuple, Optional, List, cast, Type @@ -316,9 +317,36 @@ def id(self) -> str: The unique identifier of the search. This is used as a directory name and as a database identifier. - """ + + It is the identifier the search wrote, when the output persisted one: the + ``.identifier`` file holds the identifier's description (its ``hash_list``, one + entry per line), whose md5 is the identifier. Recomputing it from today's + loaded search and model would give an old output a new identity whenever the + hashing rules change (e.g. the search-level seed, which reads main's default + BlackJAXNUTS / SMC ``seed: 42`` differently). Outputs without the file are + recomputed, as before. + """ + persisted = self.persisted_identifier + if persisted is not None: + return persisted return str(Identifier([self.search, self.model, self.unique_tag])) + @property + def persisted_identifier(self) -> Optional[str]: + """ + The identifier recorded in the output's ``.identifier`` file, or ``None`` when + the output has none (``DirectoryPaths.save_identifier`` writes + ``"\\n".join(hash_list)``; ``Identifier.__str__`` is the md5 of + ``".".join(hash_list)``). + """ + try: + description = (self.directory / ".identifier").read_text() + except (FileNotFoundError, NotADirectoryError): + return None + if not description: + return None + return md5(".".join(description.split("\n")).encode("utf-8")).hexdigest() + @property def model(self): """ diff --git a/autofit/mapper/identifier.py b/autofit/mapper/identifier.py index ae5d4461f..db17dab20 100644 --- a/autofit/mapper/identifier.py +++ b/autofit/mapper/identifier.py @@ -144,6 +144,15 @@ def _add_value_to_hash_list(self, value): raise AssertionError( f"Missing identifier fields for {type(value)}" ) from e + + # The search-level seed (search-extensibility A4, D4) is hashed only + # when not None, and only for a search whose fields do not already + # name it (Nautilus and NSS hash it statically). + identifier_seed = getattr(type(value), "_identifier_seed", None) + if identifier_seed is not None and "seed" not in fields: + seed = identifier_seed(value) + if seed is not None: + d["seed"] = seed elif ( hasattr(value, "__class__") and not inspect.isclass(value) diff --git a/autofit/non_linear/grid/grid_search/__init__.py b/autofit/non_linear/grid/grid_search/__init__.py index e9caa67b1..0083ab909 100644 --- a/autofit/non_linear/grid/grid_search/__init__.py +++ b/autofit/non_linear/grid/grid_search/__init__.py @@ -324,6 +324,9 @@ def job_for_analysis_grid_priors_and_values( search_instance = self.search_instance(name_path=name_path) search_instance.paths.model = model + # An independent child stream of the search-level seed per grid cell + # (`autofit.non_linear.search.seed`); not serialized and not hashed. + search_instance._seed_spawn_key = (index,) return Job( search_instance=search_instance, diff --git a/autofit/non_linear/initializer.py b/autofit/non_linear/initializer.py index e18ebaad4..32f10ea14 100644 --- a/autofit/non_linear/initializer.py +++ b/autofit/non_linear/initializer.py @@ -1,7 +1,6 @@ import configparser import logging import os -import random from abc import ABC, abstractmethod from typing import Dict, Tuple, List, Optional @@ -44,6 +43,22 @@ class AbstractInitializer(ABC): def _generate_unit_parameter_list(self, model): pass + @property + def rng(self) -> np.random.Generator: + """ + The generator every draw of this initializer uses: the search's stream-0 + generator during ``samples_from_model`` (``autofit.non_linear.search.seed``), + otherwise a fresh unseeded one. The global ``random`` module is never used. + """ + rng = self.__dict__.get("_rng") + if rng is None: + rng = np.random.default_rng() + self._rng = rng + return rng + + def _uniform(self, lower: float, upper: float) -> float: + return float(self.rng.uniform(lower, upper)) + def info_from_model(self, model : AbstractPriorModel) -> str: raise NotImplementedError @@ -69,6 +84,7 @@ def samples_from_model( use_prior_medians: bool = False, test_mode_samples: bool = True, n_cores: int = 1, + rng: Optional[np.random.Generator] = None, ): """ Generate the initial points of the non-linear search, by randomly drawing unit values from a uniform @@ -81,7 +97,11 @@ def samples_from_model( model An object that represents possible instances of some model with a given dimensionality which is the number of free dimensions of the model. + rng + The generator the points are drawn from: the search passes stream 0 of its seed, so the same seed gives + the same initial points. ``None`` draws from a fresh unseeded generator. """ + self._rng = rng if rng is not None else np.random.default_rng() if is_test_mode() and test_mode_samples: return self.samples_in_test_mode(total_points=total_points, model=model) @@ -295,7 +315,7 @@ def _generate_unit_parameter_list(self, model: AbstractPriorModel) -> List[float try: lower, upper = map(prior.unit_value_for, self.parameter_dict[prior]) - value = random.uniform(lower, upper) + value = self._uniform(lower, upper) except KeyError: key = ".".join(model.path_for_prior(prior)) if key not in self._generated_warnings: @@ -308,7 +328,9 @@ def _generate_unit_parameter_list(self, model: AbstractPriorModel) -> List[float lower = self.lower_limit upper = self.upper_limit - value = prior.unit_value_for(prior.random(lower, upper)) + value = prior.unit_value_for( + prior.value_for(self._uniform(lower, upper)) + ) unit_parameter_list.append(value) @@ -600,7 +622,7 @@ def _generate_unit_parameter_list(self, model: AbstractPriorModel) -> List[float f"Using defaults." ) self._generated_warnings.add(key) - value = prior.random(self.lower_limit, self.upper_limit) + value = prior.value_for(self._uniform(self.lower_limit, self.upper_limit)) unit_parameter_list.append(prior.unit_value_for(value)) @@ -654,9 +676,10 @@ def from_config(cls, config): ) def _generate_unit_parameter_list(self, model): - return model.random_unit_vector_within_limits( - lower_limit=self.lower_limit, upper_limit=self.upper_limit - ) + return [ + self._uniform(self.lower_limit, self.upper_limit) + for _ in model.priors_ordered_by_id + ] class InitializerPrior(Initializer): diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index e043aa48c..9e146f390 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -96,6 +96,7 @@ def __init__( silence: bool = False, session: Optional[sa.orm.Session] = None, paths: Optional[AbstractPaths] = None, + seed: Optional[int] = None, **kwargs, ): """ @@ -119,6 +120,9 @@ def __init__( If True, the default print output of the non-linear search is silenced. session An SQLAlchemy session instance so the results of the model-fit are written to an SQLite database. + seed + The search-level random seed: stream 0 of its ``SeedSequence`` seeds the initializer, streams 1+ the + backend; it enters the identifier only when not None (``autofit.non_linear.search.seed``). """ super().__init__() @@ -131,6 +135,7 @@ def __init__( self.path_prefix_no_unique_tag = path_prefix self._logger = None self.unique_tag = unique_tag + self.seed = seed self.paths = paths_from( name=name, diff --git a/autofit/non_linear/search/execution.py b/autofit/non_linear/search/execution.py index 70d872ad1..a74fc5170 100644 --- a/autofit/non_linear/search/execution.py +++ b/autofit/non_linear/search/execution.py @@ -21,6 +21,7 @@ from autofit.non_linear.parallel import PoolFactory, SneakyPool 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 if TYPE_CHECKING: @@ -111,6 +112,14 @@ def _run_bridge(self, model: AbstractPriorModel, analysis: Analysis): return search_internal, fitness + def _identifier_seed(self): + """ + The seed the identifier walk hashes when the search's ``__identifier_fields__`` + do not name ``"seed"``: the search-level seed, hashed only when not None + (``autofit.non_linear.search.seed``). + """ + return getattr(self, "seed", None) + def run(self, ctx) -> Any: """ The backend loop of a search on the ``run(ctx)`` hook: run the backend through @@ -267,7 +276,8 @@ def start_points( The search's ``n`` initial points, drawn by its initializer, with the start-point plot made once, here, from the first of them. - The one place the searches draw start points: the initializer is evaluated through + The one place the searches draw start points, from stream 0 of the search's seed + (``autofit.non_linear.search.seed``): the initializer is evaluated through ``fitness`` (so a JAX analysis runs its lazily jitted scalar objective) with the fit's effective core count (the JAX fork rule of ``PoolFactory``). @@ -297,6 +307,7 @@ def start_points( fitness=fitness, paths=self.paths, n_cores=self._pools(fitness.analysis).number_of_cores, + rng=initializer_rng(self), **initializer_kwargs, ) ) diff --git a/autofit/non_linear/search/fit_context.py b/autofit/non_linear/search/fit_context.py index a557b7ad8..e5f143d3c 100644 --- a/autofit/non_linear/search/fit_context.py +++ b/autofit/non_linear/search/fit_context.py @@ -14,8 +14,9 @@ interrupted run's file exists, else ``None`` (phase A3, ``autofit.non_linear.checkpoint``); ``ctx.resume`` is the ``Checkpointer`` handle, not the loaded state, because some backends reopen their own native file (``Nautilus``); -- ``ctx.rng`` is a ``numpy.random.SeedSequence`` from the search's ``seed`` attribute - when it has one (phase A4 adds one search-level seed and feeds the initializer). +- ``ctx.rng`` is the ``numpy.random.SeedSequence`` of the search-level ``seed`` (phase + A4, ``autofit.non_linear.search.seed``): stream 0 is already spawned for the + initializer, so ``ctx.rng.spawn(k)`` gives the backend streams 1..k. ``RawSamples`` and ``samples_from_raw`` are phase A3's samples adapter (``autofit/non_linear/samples/adapter.py``), re-exported here for ``run(ctx)`` searches. @@ -25,6 +26,7 @@ import numpy as np from autofit.non_linear.samples.adapter import RawSamples, samples_from_raw +from autofit.non_linear.search.seed import seed_sequence class UpdateSchedule: @@ -80,7 +82,10 @@ def __init__( self.fitness = fitness self.test_mode_level = test_mode_level self.pool = pool - self.rng = np.random.SeedSequence(getattr(search, "seed", None)) + # Stream 0 is the initializer's (`ctx.start_points`), spawned here so the + # backend's `ctx.rng.spawn(k)` hands out streams 1..k (search-level seed, A4). + self.rng = seed_sequence(search) + self.rng.spawn(1) self.checkpointer = search.checkpointer resume_state = search.resume_state self.resume = ( diff --git a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py index 7f94b4860..f91c8fd15 100644 --- a/autofit/non_linear/search/mcmc/blackjax/nuts/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/nuts/search.py @@ -24,6 +24,11 @@ ) from autofit.non_linear.samples.adapter import ChainPosterior, RawSamples from autofit.non_linear.search import capabilities as cap +from autofit.non_linear.search.seed import ( + LEGACY_DEFAULT_SEED, + child_seed, + legacy_default_seed, +) if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa @@ -71,7 +76,7 @@ def __init__( num_chains: int = 1, target_accept: float = 0.8, max_num_doublings: int = 10, - seed: int = 42, + seed: Optional[int] = None, initializer: Optional[Initializer] = None, inverse_mass_matrix: InverseMassMatrixSpec = None, mass_matrix_shrinkage: float = 0.0, @@ -161,7 +166,13 @@ def __init__( NUTS doubling cap. 10 means at most 1024 leapfrog steps per sample, which is the standard ceiling. seed - Integer seed passed to ``jax.random.PRNGKey``. + The search-level seed (``autofit.non_linear.search.seed``), passed to ``jax.random.PRNGKey``. + ``None`` (the default) runs with the historical ``42`` and is not hashed into the identifier; any + other seed you pass is hashed, so it names its own output folder. ``seed=42`` is the default: main + wrote ``seed: 42`` into every default search's ``search.json`` and pickle, so a 42 is read as + ``None`` and old outputs keep their identifiers. An explicit ``seed=42`` therefore shares the + default's identity and output folder. In a grid search each cell's backend gets a child-specific + seed derived from this one (``autofit.non_linear.search.seed.child_seed``). initializer Generates the starting point(s), one per chain. Defaults to ``InitializerBall(0.49, 0.51)`` from ``AbstractMCMC`` — small @@ -232,6 +243,7 @@ def __init__( number_of_cores=number_of_cores, silence=silence, session=session, + seed=legacy_default_seed(seed), **kwargs, ) @@ -240,7 +252,6 @@ def __init__( self.num_chains = num_chains self.target_accept = target_accept self.max_num_doublings = max_num_doublings - self.seed = seed # The raw specification (used at fit time to resolve an actual seed # array) is kept private; the public `inverse_mass_matrix` attribute @@ -259,6 +270,27 @@ def __init__( self.logger.debug("Creating BlackJAXNUTS Search") + @property + def backend_seed(self) -> int: + """ + The seed the backend's ``jax.random.PRNGKey`` uses: ``seed``, or the historical + ``42`` when it is ``None`` (the unhashed default; ``autofit.non_linear.search.seed``), + made child-specific for a grid-search child. + """ + return child_seed( + self, LEGACY_DEFAULT_SEED if self.seed is None else self.seed + ) + + def __setstate__(self, state): + """ + A pickle written by main records the default as ``seed = 42``; read it as the + unhashed default so the unpickled search keeps main's identifier + (``autofit.non_linear.search.seed.legacy_default_seed``). + """ + self.__dict__.update(state) + if "seed" in state: + self.seed = legacy_default_seed(state["seed"]) + def apply_test_mode(self): logger.warning( "TEST MODE 1 (reduced iterations): BlackJAXNUTS will run with " @@ -317,7 +349,7 @@ def _fit(self, model: AbstractPriorModel, analysis): # One-shot trace + compile so warmup timing is honest. _ = float(log_density(initial_positions[0])) - rng_key = jax.random.PRNGKey(self.seed) + rng_key = jax.random.PRNGKey(self.backend_seed) # ---- Inverse mass matrix ----------------------------------------- is_mass_matrix_diagonal, imm_seed = resolve_inverse_mass_matrix( diff --git a/autofit/non_linear/search/mcmc/blackjax/smc/search.py b/autofit/non_linear/search/mcmc/blackjax/smc/search.py index 8bd8f60fc..bb05e8624 100644 --- a/autofit/non_linear/search/mcmc/blackjax/smc/search.py +++ b/autofit/non_linear/search/mcmc/blackjax/smc/search.py @@ -25,6 +25,11 @@ from autofit.non_linear.search.mcmc.blackjax.smc.samples import SamplesSMC from autofit.non_linear.samples.adapter import RawSamples from autofit.non_linear.search import capabilities as cap +from autofit.non_linear.search.seed import ( + LEGACY_DEFAULT_SEED, + child_seed, + legacy_default_seed, +) if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa @@ -96,7 +101,7 @@ def __init__( whiten_inflate: float = 2.0, max_smc_steps: int = 200, batch_size: int = 0, - seed: int = 42, + seed: Optional[int] = None, initializer: Optional[Initializer] = None, inverse_mass_matrix: InverseMassMatrixSpec = None, auto_correlation_settings: AutoCorrelationsSettings = AutoCorrelationsSettings( @@ -222,7 +227,13 @@ def __init__( ``jax.lax.map`` instead of one full ``jax.vmap``, trading speed for peak GPU memory. ``0`` (default) keeps the full ``vmap``. seed - Integer seed passed to ``jax.random.PRNGKey``. + The search-level seed (``autofit.non_linear.search.seed``), passed to ``jax.random.PRNGKey``. + ``None`` (the default) runs with the historical ``42`` and is not hashed into the identifier; any + other seed you pass is hashed, so it names its own output folder. ``seed=42`` is the default: main + wrote ``seed: 42`` into every default search's ``search.json`` and pickle, so a 42 is read as + ``None`` and old outputs keep their identifiers. An explicit ``seed=42`` therefore shares the + default's identity and output folder. In a grid search each cell's backend gets a child-specific + seed derived from this one (``autofit.non_linear.search.seed.child_seed``). initializer Generates the initial particles. Defaults to `InitializerPrior` -- **cold SMC's evidence requires the particles to be drawn from the prior**, so the `InitializerBall` default the other MCMC searches use @@ -273,6 +284,7 @@ def __init__( number_of_cores=number_of_cores, silence=silence, session=session, + seed=legacy_default_seed(seed), **kwargs, ) @@ -297,7 +309,6 @@ def __init__( self.whiten_inflate = whiten_inflate self.max_smc_steps = max_smc_steps self.batch_size = batch_size - self.seed = seed # As in `BlackJAXNUTS`: the raw specification is kept private (it is resolved into an actual covariance # at fit time, when `n_dim` is known) and the public attribute is the small descriptive string used by @@ -312,6 +323,27 @@ def __init__( self.logger.debug("Creating SMC Search") + @property + def backend_seed(self) -> int: + """ + The seed the backend's ``jax.random.PRNGKey`` uses: ``seed``, or the historical + ``42`` when it is ``None`` (the unhashed default; ``autofit.non_linear.search.seed``), + made child-specific for a grid-search child. + """ + return child_seed( + self, LEGACY_DEFAULT_SEED if self.seed is None else self.seed + ) + + def __setstate__(self, state): + """ + A pickle written by main records the default as ``seed = 42``; read it as the + unhashed default so the unpickled search keeps main's identifier + (``autofit.non_linear.search.seed.legacy_default_seed``). + """ + self.__dict__.update(state) + if "seed" in state: + self.seed = legacy_default_seed(state["seed"]) + def apply_test_mode(self): logger.warning( "TEST MODE 1 (reduced iterations): SMC will run with num_particles<=16, num_mcmc_steps=2, " @@ -497,7 +529,7 @@ def smc_loglikelihood_fn(z): batch_size=self.batch_size, ) - rng_key = jax.random.PRNGKey(self.seed) + rng_key = jax.random.PRNGKey(self.backend_seed) rng_key, init_key = jax.random.split(rng_key) if self.is_warm_start: diff --git a/autofit/non_linear/search/mcmc/emcee/search.py b/autofit/non_linear/search/mcmc/emcee/search.py index b5b1a2123..d052ae6df 100644 --- a/autofit/non_linear/search/mcmc/emcee/search.py +++ b/autofit/non_linear/search/mcmc/emcee/search.py @@ -22,6 +22,7 @@ from autofit.non_linear.test_mode import is_test_mode from autofit.non_linear.samples.adapter import ChainPosterior, RawSamples from autofit.non_linear.search import capabilities as cap +from autofit.non_linear.search.seed import backend_random_state if TYPE_CHECKING: from autofit.database.sqlalchemy_ import sa @@ -169,6 +170,13 @@ def _fit(self, model: AbstractPriorModel, analysis): pool=pool, ) + # Backend stream 1 of the search-level seed (`autofit.non_linear.search.seed`); + # emcee otherwise copies numpy's global state. A resumed run restores the state + # its HDF backend saved. + random_state = backend_random_state(self) + if random_state is not None: + search_internal._random = random_state + try: state = search_internal.get_last_sample() samples = self.samples_from(model=model, search_internal=search_internal) diff --git a/autofit/non_linear/search/mle/multi_start_gradient/search.py b/autofit/non_linear/search/mle/multi_start_gradient/search.py index 044fad1b2..f260e9c66 100644 --- a/autofit/non_linear/search/mle/multi_start_gradient/search.py +++ b/autofit/non_linear/search/mle/multi_start_gradient/search.py @@ -416,6 +416,7 @@ def __init__( iterations_per_full_update=iterations_per_full_update, silence=silence, session=session, + seed=seed, **kwargs, ) @@ -433,7 +434,6 @@ def __init__( self.start_lower_limit = start_lower_limit self.start_upper_limit = start_upper_limit self.resurrect = resurrect - self.seed = seed # Resolved here rather than on ``AbstractMLE`` beside ``clipper``, # deliberately. The clipper is shared because LBFGS genuinely uses it # (it hands the bounds to scipy); a scaler has no meaning for a search @@ -1955,10 +1955,19 @@ def _seed_for(self, stream: int): start stream, so nominally independent seeds in a multi-seed study share draws. ``SeedSequence`` spreads each ``(seed, stream)`` pair over the full state space instead. + + A grid-search child (one with a spawn key, ``autofit.non_linear.search.seed``) + adds its key to the sequence, so the cells of a grid draw independent broad + starts and resurrections. Without a spawn key both paths above are unchanged. """ + from autofit.non_linear.search.seed import spawn_key + + key = spawn_key(self) if self.seed is None: - return stream - return np.random.SeedSequence([self.seed, stream]) + if not key: + return stream + return np.random.SeedSequence(stream, spawn_key=key) + return np.random.SeedSequence([self.seed, stream], spawn_key=key) def _broad_starts(self, model, value_and_grad_single, jnp): """ diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index ca425cee2..db64303b6 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -234,6 +234,34 @@ def search_kwargs(self) -> Dict: "first_update": self.first_update, } + def _rstate_kwargs(self) -> Dict: + """ + dynesty's ``rstate`` on backend stream 1 of the search-level seed when the search + has one (``autofit.non_linear.search.seed``); empty otherwise, so an unseeded + search keeps dynesty's own default generator. + """ + from autofit.non_linear.search.seed import backend_generator + + rstate = backend_generator(self) + return {} if rstate is None else {"rstate": rstate} + + def _sampler_kwargs(self) -> Dict: + """ + The keyword arguments every dynesty sampler constructor (static or dynamic, + pooled or not) receives beyond its positional set-up: ``search_kwargs`` plus + ``rstate``, resolved once. + + Precedence: an ``rstate`` already in ``search_kwargs`` (e.g. a subclass that + seeds dynesty's generator itself) wins; otherwise the search-level seed's + backend stream 1 (``_rstate_kwargs``); otherwise none, so dynesty keeps its own + default generator. Prefer the search-level ``seed=``, which also seeds the + initializer's live points. + """ + search_kwargs = dict(self.search_kwargs) + if "rstate" in search_kwargs: + return search_kwargs + return {**search_kwargs, **self._rstate_kwargs()} + @property def run_kwargs(self) -> Dict: """Run kwargs specific to each subclass, excluding maxcall.""" diff --git a/autofit/non_linear/search/nest/dynesty/search/dynamic.py b/autofit/non_linear/search/nest/dynesty/search/dynamic.py index 8f353cffb..cc3ebd509 100644 --- a/autofit/non_linear/search/nest/dynesty/search/dynamic.py +++ b/autofit/non_linear/search/nest/dynesty/search/dynamic.py @@ -166,7 +166,7 @@ def search_internal_from( ndim=model.prior_count, queue_size=queue_size, pool=pool, - **self.search_kwargs, + **self._sampler_kwargs(), ) self.write_uses_pool(uses_pool=False) @@ -177,7 +177,7 @@ def search_internal_from( ndim=model.prior_count, logl_args=[model, fitness], ptform_args=[model], - **self.search_kwargs, + **self._sampler_kwargs(), ) @property diff --git a/autofit/non_linear/search/nest/dynesty/search/static.py b/autofit/non_linear/search/nest/dynesty/search/static.py index 4ec093cbe..79201c728 100644 --- a/autofit/non_linear/search/nest/dynesty/search/static.py +++ b/autofit/non_linear/search/nest/dynesty/search/static.py @@ -173,7 +173,7 @@ def search_internal_from( queue_size=queue_size, pool=pool, nlive=self.nlive, - **self.search_kwargs, + **self._sampler_kwargs(), ) self.write_uses_pool(uses_pool=False) @@ -185,7 +185,7 @@ def search_internal_from( ptform_args=[model], live_points=live_points, nlive=self.nlive, - **self.search_kwargs, + **self._sampler_kwargs(), ) @property diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 2781eeee3..e5177f1ea 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -298,6 +298,7 @@ def __init__( number_of_cores=number_of_cores, silence=silence, session=session, + seed=seed, **kwargs, ) @@ -310,7 +311,6 @@ def __init__( self.n_batch = n_batch self.n_like_new_bound = n_like_new_bound self.vectorized = vectorized - self.seed = seed self.f_live = f_live self.n_shell = n_shell @@ -465,7 +465,7 @@ def fit_x1_cpu(self, fitness, model, analysis=None, update=None): n_networks=self.n_networks, n_batch=self.n_batch, n_like_new_bound=self.n_like_new_bound, - seed=self.seed, + seed=self.backend_seed, ) return self.call_search( @@ -561,7 +561,7 @@ def fit_multiprocessing(self, fitness, model, analysis=None, pools=None, update= n_batch=self.n_batch, n_like_new_bound=self.n_like_new_bound, vectorized=self.vectorized, - seed=self.seed, + seed=self.backend_seed, ) search_internal = self.call_search( @@ -756,3 +756,13 @@ def info_from(self, internal): @property def batch_size(self): return self.n_batch + + @property + def backend_seed(self) -> Optional[int]: + """ + The seed the backend takes directly: ``seed``, made child-specific for a + grid-search child (``autofit.non_linear.search.seed.child_seed``). + """ + from autofit.non_linear.search.seed import child_seed + + return child_seed(self, self.seed) diff --git a/autofit/non_linear/search/nest/nss/search.py b/autofit/non_linear/search/nest/nss/search.py index 12d943ae6..3a6fcb43c 100644 --- a/autofit/non_linear/search/nest/nss/search.py +++ b/autofit/non_linear/search/nest/nss/search.py @@ -274,7 +274,9 @@ def __init__( not used. If ``number_of_cores > 1`` a warning is logged. seed JAX random seed used to initialise the unit-cube draws for the - ``n_live`` initial particles and the inner slice-sampling RNG. + ``n_live`` initial particles and the inner slice-sampling RNG. It is the + search-level seed (``autofit.non_linear.search.seed``) and stays a static + identifier field, so seeded NSS output folders are unchanged. silence If True, suppresses NSS's progress bar output. session @@ -308,6 +310,7 @@ def __init__( number_of_cores=number_of_cores, silence=silence, session=session, + seed=seed, **kwargs, ) @@ -317,7 +320,6 @@ def __init__( self.chunk_size = chunk_size self.termination = termination self.checkpoint_interval = checkpoint_interval - self.seed = seed if number_of_cores is not None and number_of_cores > 1: logger.warning( @@ -329,6 +331,16 @@ def __init__( self.logger.debug("Creating NSS Search") + @property + def backend_seed(self) -> Optional[int]: + """ + The seed the backend takes directly: ``seed``, made child-specific for a + grid-search child (``autofit.non_linear.search.seed.child_seed``). + """ + from autofit.non_linear.search.seed import child_seed + + return child_seed(self, self.seed) + def fitness_overrides(self, analysis) -> dict: """ NSS fires its own quick update between outer iterations (``_fire_quick_update``), @@ -387,7 +399,7 @@ def prior_logprob(params): log_priors = model.log_prior_list_from_vector(vector=params, xp=jnp) return sum(log_priors) - rng_key = jax.random.PRNGKey(self.seed) + rng_key = jax.random.PRNGKey(self.backend_seed) rng_key, init_key, run_key = jax.random.split(rng_key, 3) unit_cube = jax.random.uniform(init_key, shape=(self.n_live, ndim)) diff --git a/autofit/non_linear/search/seed.py b/autofit/non_linear/search/seed.py new file mode 100644 index 000000000..18d156814 --- /dev/null +++ b/autofit/non_linear/search/seed.py @@ -0,0 +1,140 @@ +""" +The one search-level ``seed`` (search-extensibility phase A4, decision D4). + +Every search accepts ``seed`` (``NonLinearSearch.__init__``). It is fanned out with a +``numpy.random.SeedSequence``: + +- **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``; +- **grid-search children** each get an independent child sequence through a spawn key + (``_seed_spawn_key``), which is neither serialized nor hashed. + +The seed enters the search identifier through ``identifier_seed``: the identifier walk +(``autofit.mapper.identifier``) appends it when it is not ``None``, for a search whose +``__identifier_fields__`` do not already name ``"seed"``. Never by adding ``"seed"`` to +the base ``__identifier_fields__``, which would hash the field name for every search. +The legacy table: + +===================== ========================================================== +Search Seed rule +===================== ========================================================== +Nautilus, NSS ``"seed"`` stays a static identifier field (hashed as + before); their ``seed`` argument *is* the base seed. +BlackJAXNUTS, SMC ``seed=None`` (the default) runs the backend with the + historical ``42`` and is not hashed; any other seed is + hashed. ``seed=42`` *is* the default: main recorded + ``seed: 42`` in every default NUTS/SMC ``search.json`` and + pickle, so a 42 is read back as ``None`` (``legacy_default_seed``) + and an old output keeps its identifier. +every other search hashed only when not ``None``. +===================== ========================================================== + +What a seed promises: the same seed gives the same initial points for every search. +Bit-identical samples hold only within one backend and platform where that has been +demonstrated (e.g. Emcee on one machine); MCMC archive searches resume statistically, +not exactly. Backends that take the seed directly (Nautilus's ``Sampler(seed=)``, the +JAX ``PRNGKey`` of NSS, NUTS and SMC, MultiStart's own ``(seed, stream)`` sequences) +keep doing so, so an existing seeded run of those searches is reproduced exactly. +A grid-search child (one with a spawn key) instead gives those backends a child-specific +seed derived from the seed and its spawn key (``child_seed``), so grid cells do not share +backend randomness; without a spawn key the raw seed is passed through unchanged. +""" + +from typing import List, Optional, Tuple + +import numpy as np + +# The seed main hard-coded as the BlackJAXNUTS / SMC default (recorded in their +# ``search.json`` and pickles as ``seed: 42``). +LEGACY_DEFAULT_SEED = 42 + + +def legacy_default_seed(seed: Optional[int]) -> Optional[int]: + """ + The BlackJAXNUTS / SMC seed with main's default ``42`` read as ``None``. + + main ran these backends with an unhashed ``seed=42`` by default and wrote ``seed: 42`` + into every default ``search.json`` and pickle, whether the 42 was the default or + passed explicitly. Reading a 42 as the unhashed default keeps every such output's + identifier (and ``SearchOutput.id``) what main computed; the backend still runs + with 42, so sampling is bit-identical. The cost is that an explicit ``seed=42`` + shares the default identity. + """ + if seed is not None and not isinstance(seed, bool) and seed == LEGACY_DEFAULT_SEED: + return None + return seed + + +def spawn_key(search) -> Tuple[int, ...]: + """ + The grid-search child spawn key of a search (``()`` for a standalone search). + """ + return tuple(getattr(search, "_seed_spawn_key", ()) or ()) + + +def child_seed(search, seed: Optional[int]) -> Optional[int]: + """ + The raw integer seed a backend that takes one directly (Nautilus's + ``Sampler(seed=)``, the JAX ``PRNGKey`` of NSS, NUTS and SMC) should use. + + A standalone search (no spawn key), or no seed, passes ``seed`` through unchanged, so + an existing seeded run is reproduced exactly. A grid-search child derives a + child-specific seed from ``SeedSequence(seed, spawn_key=...)``, so the cells of a + grid do not share backend randomness. It is a non-negative 31-bit integer, valid + for ``jax.random.PRNGKey`` without 64-bit mode. The spawn key is neither hashed nor + serialized, so this never changes an identifier. + """ + key = spawn_key(search) + if seed is None or not key: + return seed + state = np.random.SeedSequence(int(seed), spawn_key=key).generate_state(1) + return int(state[0]) & 0x7FFFFFFF + + +def seed_sequence(search) -> np.random.SeedSequence: + """ + A fresh ``SeedSequence`` of the search's seed (and grid-child spawn key). + + ``SeedSequence(None)`` draws fresh OS entropy, so an unseeded search is not + reproducible, exactly as before; a fresh sequence per call keeps the stream indices + stable however often it is asked. + """ + return np.random.SeedSequence(getattr(search, "seed", None), spawn_key=spawn_key(search)) + + +def initializer_rng(search) -> np.random.Generator: + """ + The generator the initializer draws the search's start points from: stream 0. + """ + return np.random.default_rng(seed_sequence(search).spawn(1)[0]) + + +def backend_seed_sequences(search, k: int = 1) -> List[np.random.SeedSequence]: + """ + The backend's ``k`` streams: streams ``1..k`` of the search's seed sequence. + """ + return seed_sequence(search).spawn(k + 1)[1:] + + +def backend_random_state(search) -> Optional[np.random.RandomState]: + """ + A legacy ``numpy.random.RandomState`` on backend stream 1 when the search has a + seed, for backends built on ``RandomState`` (``emcee``); ``None`` when unseeded, so + the backend keeps its own default. + """ + if getattr(search, "seed", None) is None: + return None + return np.random.RandomState(np.random.MT19937(backend_seed_sequences(search)[0])) + + +def backend_generator(search) -> Optional[np.random.Generator]: + """ + A ``numpy.random.Generator`` on backend stream 1 when the search has a seed (e.g. + dynesty's ``rstate``); ``None`` when unseeded. + """ + if getattr(search, "seed", None) is None: + return None + return np.random.default_rng(backend_seed_sequences(search)[0]) diff --git a/docs/design/run_ctx.md b/docs/design/run_ctx.md index 5c57a870d..896e5d7e5 100644 --- a/docs/design/run_ctx.md +++ b/docs/design/run_ctx.md @@ -172,3 +172,27 @@ The signature and the member list are unchanged. after the test-mode bypass and the REQUIRED gate, before the context exists: the x64 check and one `jax.eval_shape` trace of the declared objective kind (and its gradient kind for `gradient == "uses"`). `run` therefore only ever sees a likelihood that traces. + +## Revision 3 (phase A4, 2026-10-14): the search-level seed + +The signature and the member list are unchanged. + +- **`ctx.rng`** is the `SeedSequence` of the one search-level `seed` that every search now + accepts (`autofit/non_linear/search/seed.py`, decision D4). Stream 0 is spawned when the + context is built and feeds the initializer (`ctx.start_points`, which no longer uses the + global `random` module), so `ctx.rng.spawn(k)` hands the backend streams `1..k`. Grid-search + children get an independent child sequence through a spawn key that is neither serialized + nor hashed. Backends that take a raw integer seed (Nautilus, NSS, BlackJAXNUTS, SMC) and + MultiStart's own `(seed, stream)` draws receive a child-specific seed derived from that + spawn key (`seed.child_seed`); a standalone search passes its raw seed through unchanged. +- **BlackJAXNUTS / SMC read `seed=42` as the default.** main ran them with an unhashed + default `seed=42` and wrote `seed: 42` into every default `search.json` and pickle. So + that every such output keeps its identifier, a 42 (from the constructor, `from_dict` or an + unpickled main search) becomes the unhashed default `None`; the backend still runs with 42. + An explicit `seed=42` on these two searches therefore shares the default's identity and + output folder; any other explicit seed is hashed. +- **The aggregator keeps persisted identities.** `SearchOutput.id` (also the database + scrape's key) is the md5 of the output's `.identifier` description when the output has + 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`. diff --git a/test_autofit/interpolator/test_covariance.py b/test_autofit/interpolator/test_covariance.py index 18b4bfe8a..c1397c4df 100644 --- a/test_autofit/interpolator/test_covariance.py +++ b/test_autofit/interpolator/test_covariance.py @@ -73,20 +73,39 @@ def seed_search_randomness(monkeypatch): Three independent generators feed that result, so seeding any one of them is not enough: - * `numpy.random`, used by `test_variable_and_constant` to build its samples; - * the stdlib `random` module, used by `autofit.non_linear.initializer` to - draw the search's initial unit values; - * dynesty's own `rstate`, which defaults to - `numpy.random.Generator(PCG64(None))` — seeded from OS entropy and - reachable from neither of the above. This is the dominant term, and the - only one `test_single_variable` (which makes no random call of its own) - depends on at all. + * `numpy.random`, used by `test_variable_and_constant` to build its samples + (the stdlib `random` module is seeded alongside it for the prior-model + helpers that still draw from it); + * the initializer's `numpy.random.Generator`, which draws the search's + initial unit values. The searches here are unseeded, so it comes from + `autofit.non_linear.search.seed.initializer_rng`, stream 0 of + `seed_sequence(search)` = `SeedSequence(None)`, i.e. fresh OS entropy + reachable from neither global generator. `seed_sequence` is patched to + substitute `SEED` for a missing search seed; + * dynesty's own `rstate`. An unseeded search passes none + (`AbstractDynesty._sampler_kwargs`), so dynesty falls back to + `dynesty.dynesty.get_random_generator()` = `Generator(PCG64(None))`, + also OS entropy; that function is patched to seed with `SEED`. This is + the dominant term. + + `test_single_variable` makes no random call of its own and depends only on + the last two. Global generator state is restored on teardown so the seeding cannot leak into whatever runs next in the same process. """ import dynesty.dynesty + from autofit.non_linear.search import seed as search_seed + + seed_sequence = search_seed.seed_sequence + + def seeded_sequence(search): + if getattr(search, "seed", None) is not None: + return seed_sequence(search) + return np.random.SeedSequence(SEED, spawn_key=search_seed.spawn_key(search)) + + monkeypatch.setattr(search_seed, "seed_sequence", seeded_sequence) monkeypatch.setattr( dynesty.dynesty, "get_random_generator", diff --git a/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py b/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py index cd7630c5d..ce3a09b66 100644 --- a/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py +++ b/test_autofit/non_linear/search/mcmc/test_blackjax_smc.py @@ -96,7 +96,9 @@ def test__defaults(): assert search.whiten_inflate == 2.0 assert search.max_smc_steps == 200 assert search.batch_size == 0 - assert search.seed == 42 + # The unhashed default: `seed` is None and the backend runs with 42 (A4b). + assert search.seed is None + assert search.backend_seed == 42 assert search.inverse_mass_matrix == "none" assert search.is_warm_start is False # Cold SMC's evidence is only valid if the initial particles are prior draws, so — unlike every other diff --git a/test_autofit/non_linear/search/seed_golden.json b/test_autofit/non_linear/search/seed_golden.json new file mode 100644 index 000000000..784668715 --- /dev/null +++ b/test_autofit/non_linear/search/seed_golden.json @@ -0,0 +1,1089 @@ +{ + "BFGS": { + "main_default": "979826a042aacbe511b97be84d8c2255", + "main_default_path": "31c36eaf16021be48f937e353fd07037", + "main_hash_list": [ + "BFGS", + "clipper", + "ClipperNone" + ], + "main_none": "979826a042aacbe511b97be84d8c2255", + "main_search_json": { + "arguments": { + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "disp": false, + "eps": 1e-08, + "ftol": 2.220446049250313e-09, + "gtol": 1e-05, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iprint": -1.0, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "maxcor": 10, + "maxfun": 15000, + "maxiter": 15000, + "maxls": 20, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "silence": false, + "tol": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.bfgs.search.BFGS", + "type": "instance" + }, + "main_seed7": "979826a042aacbe511b97be84d8c2255", + "main_seed7_path": "31c36eaf16021be48f937e353fd07037", + "seed42": "4db2d0f950bc2d7c44baaf47b3f21a00", + "seed7": "c0a63995db184dc83fb62499ce14ce20" + }, + "BlackJAXNUTS": { + "main_default": "2a6f5217539f82fab8ea42eda9bf3441", + "main_default_path": "c4dd259559739d33f225a91d8b45d1fd", + "main_hash_list": [ + "BlackJAXNUTS", + "num_warmup", + "500", + "num_samples", + "1000", + "num_chains", + "1", + "inverse_mass_matrix", + "none" + ], + "main_none": "2a6f5217539f82fab8ea42eda9bf3441", + "main_search_json": { + "arguments": { + "auto_correlation_settings": { + "arguments": { + "change_threshold": 0.01, + "check_for_convergence": false, + "check_size": 100, + "required_length": 50 + }, + "class_path": "autofit.non_linear.search.mcmc.auto_correlations.AutoCorrelationsSettings", + "type": "instance" + }, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "inverse_mass_matrix": "none", + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "mass_matrix_shrinkage": 0.0, + "max_num_doublings": 10, + "name": "", + "num_chains": 1, + "num_samples": 1000, + "num_warmup": 500, + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "seed": 42, + "share_adaptation": false, + "silence": false, + "target_accept": 0.8, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mcmc.blackjax.nuts.search.BlackJAXNUTS", + "type": "instance" + }, + "main_seed7": "2a6f5217539f82fab8ea42eda9bf3441", + "main_seed7_path": "c4dd259559739d33f225a91d8b45d1fd", + "seed42": "b120de220578c303f72789456b54e9fc", + "seed7": "1165d16a948cbbff3b0277d6de7f866b" + }, + "Drawer": { + "main_default": "0f80f695c0906253e9526e4c2f242dc7", + "main_default_path": "904273206ccb1fb6489bafff7969ea35", + "main_hash_list": [ + "Drawer", + "total_draws", + "50" + ], + "main_none": "0f80f695c0906253e9526e4c2f242dc7", + "main_search_json": { + "arguments": { + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "silence": false, + "total_draws": 50, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.drawer.search.Drawer", + "type": "instance" + }, + "main_seed7": "0f80f695c0906253e9526e4c2f242dc7", + "main_seed7_path": "904273206ccb1fb6489bafff7969ea35", + "seed42": "aa9a53a541c932539ebe10f8fb8e3106", + "seed7": "4f7056a05cb85a639dcc094f3c4f81ab" + }, + "DynestyDynamic": { + "main_default": "d39dcd32c65eb17c624b91343a46ee17", + "main_default_path": "82362e1835a33a9dee9f53cb580d256e", + "main_hash_list": [ + "DynestyDynamic", + "bound", + "multi", + "sample", + "auto", + "enlarge", + "bootstrap", + "walks", + "5", + "facc", + "0.2", + "slices", + "5", + "fmove", + "0.9", + "max_move", + "100" + ], + "main_none": "d39dcd32c65eb17c624b91343a46ee17", + "main_search_json": { + "arguments": { + "bootstrap": null, + "bound": "multi", + "dlogz_init": 0.01, + "enlarge": null, + "facc": 0.2, + "first_update": null, + "fmove": 0.9, + "force_x1_cpu": false, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": {}, + "class_path": "autofit.non_linear.initializer.InitializerPrior", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "logl_max_init": Infinity, + "max_move": 100, + "maxcall": null, + "maxcall_init": null, + "maxiter": null, + "maxiter_init": null, + "name": "", + "nlive_init": 500, + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "sample": "auto", + "silence": false, + "slices": 5, + "unique_tag": null, + "update_interval": null, + "use_jax_jit": null, + "walks": 5 + }, + "class_path": "autofit.non_linear.search.nest.dynesty.search.dynamic.DynestyDynamic", + "type": "instance" + }, + "main_seed7": "d39dcd32c65eb17c624b91343a46ee17", + "main_seed7_path": "82362e1835a33a9dee9f53cb580d256e", + "seed42": "4d48e9414fdff81409ac254e722c651d", + "seed7": "2e6699d5c96543461adf847268b33c6c" + }, + "DynestyStatic": { + "main_default": "d75351d847c453ff56e2a64b2d071d6f", + "main_default_path": "e67aeedcce033d4c5a28d2578d746dab", + "main_hash_list": [ + "DynestyStatic", + "nlive", + "50", + "bound", + "multi", + "sample", + "auto", + "bootstrap", + "enlarge", + "walks", + "5", + "facc", + "0.2", + "slices", + "5", + "fmove", + "0.9", + "max_move", + "100" + ], + "main_none": "d75351d847c453ff56e2a64b2d071d6f", + "main_search_json": { + "arguments": { + "bootstrap": null, + "bound": "multi", + "dlogz": null, + "enlarge": null, + "facc": 0.2, + "first_update": null, + "fmove": 0.9, + "force_x1_cpu": false, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": {}, + "class_path": "autofit.non_linear.initializer.InitializerPrior", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "logl_max": Infinity, + "max_move": 100, + "maxcall": null, + "maxiter": null, + "name": "", + "nlive": 50, + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "sample": "auto", + "silence": false, + "slices": 5, + "unique_tag": null, + "update_interval": null, + "use_jax_jit": null, + "walks": 5 + }, + "class_path": "autofit.non_linear.search.nest.dynesty.search.static.DynestyStatic", + "type": "instance" + }, + "main_seed7": "d75351d847c453ff56e2a64b2d071d6f", + "main_seed7_path": "e67aeedcce033d4c5a28d2578d746dab", + "seed42": "9551288b9ae6fff4e9b098c782045523", + "seed7": "3abe0c515e6d666adb71b7462bb3b2c0" + }, + "Emcee": { + "main_default": "f804af6499430da65cf8fba466dcfdd3", + "main_default_path": "cc9851e49f023d7dd78971bdffff63af", + "main_hash_list": [ + "Emcee", + "nwalkers", + "50" + ], + "main_none": "f804af6499430da65cf8fba466dcfdd3", + "main_search_json": { + "arguments": { + "auto_correlation_settings": { + "arguments": { + "change_threshold": 0.01, + "check_for_convergence": true, + "check_size": 100, + "required_length": 50 + }, + "class_path": "autofit.non_linear.search.mcmc.auto_correlations.AutoCorrelationsSettings", + "type": "instance" + }, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "name": "", + "nsteps": 2000, + "number_of_cores": 1, + "nwalkers": 50, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "silence": false, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mcmc.emcee.search.Emcee", + "type": "instance" + }, + "main_seed7": "f804af6499430da65cf8fba466dcfdd3", + "main_seed7_path": "cc9851e49f023d7dd78971bdffff63af", + "seed42": "d2e9fda936a8226ffa9506370da78b2d", + "seed7": "48f56afb7a6ac26da64b6f2b4e3fe4f0" + }, + "LBFGS": { + "main_default": "eb33da63306e10e4fd4276f1e83f372b", + "main_default_path": "0ce79d5c09f79a21f26e4ed1b51c0281", + "main_hash_list": [ + "LBFGS", + "clipper", + "ClipperNone" + ], + "main_none": "eb33da63306e10e4fd4276f1e83f372b", + "main_search_json": { + "arguments": { + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "disp": false, + "eps": 1e-08, + "ftol": 2.220446049250313e-09, + "gtol": 1e-05, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iprint": -1.0, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "maxcor": 10, + "maxfun": 15000, + "maxiter": 15000, + "maxls": 20, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "silence": false, + "tol": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.bfgs.search.LBFGS", + "type": "instance" + }, + "main_seed7": "eb33da63306e10e4fd4276f1e83f372b", + "main_seed7_path": "0ce79d5c09f79a21f26e4ed1b51c0281", + "seed42": "01dc746d8f9b6bc5f82e22ae675b3e5f", + "seed7": "524c09d6600ad479d3b525c858a2c990" + }, + "MultiStartADABelief": { + "main_default": "305f4ce87416b2ca58a74b9c597ac0f5", + "main_default_path": "a3b49d05218abb6d90cb3200ca2375f5", + "main_hash_list": [ + "MultiStartADABelief", + "clipper", + "ClipperNone" + ], + "main_none": "305f4ce87416b2ca58a74b9c597ac0f5", + "main_search_json": { + "arguments": { + "batch_size": null, + "bijector": { + "arguments": {}, + "class_path": "autofit.non_linear.bijector.BijectorNone", + "type": "instance" + }, + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "convergence": { + "arguments": { + "atol": 0.001, + "check_for_convergence": true, + "min_steps": 100, + "rtol": 0.0001, + "window": 50 + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.convergence.MultiStartGradientConvergence", + "type": "instance" + }, + "gradient_mode": null, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_log": 10, + "iterations_per_quick_update": 1e+99, + "learning_rate": 0.01, + "live_visual_update": false, + "max_consecutive_nan": 8, + "n_starts": 48, + "n_steps": 300, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "record_lane_nan_history": false, + "reset_momentum_on_clip": false, + "resurrect": false, + "scaler": { + "arguments": {}, + "class_path": "autofit.non_linear.scaler.ScalerNone", + "type": "instance" + }, + "seed": null, + "silence": false, + "start_lower_limit": 0.15, + "start_upper_limit": 0.85, + "trace_param_indices": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.search.MultiStartADABelief", + "type": "instance" + }, + "main_seed7": "305f4ce87416b2ca58a74b9c597ac0f5", + "main_seed7_path": "a3b49d05218abb6d90cb3200ca2375f5", + "seed42": "024b3aa888f1bf6c2a433f9d90c1b431", + "seed7": "288a53d188a59ae888e54716c6667c8d" + }, + "MultiStartAdam": { + "main_default": "bd3370e335bd0c947364b769700d1513", + "main_default_path": "97ca7c22816db96e37f769620a9d9f17", + "main_hash_list": [ + "MultiStartAdam", + "clipper", + "ClipperNone" + ], + "main_none": "bd3370e335bd0c947364b769700d1513", + "main_search_json": { + "arguments": { + "batch_size": null, + "bijector": { + "arguments": {}, + "class_path": "autofit.non_linear.bijector.BijectorNone", + "type": "instance" + }, + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "convergence": { + "arguments": { + "atol": 0.001, + "check_for_convergence": true, + "min_steps": 100, + "rtol": 0.0001, + "window": 50 + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.convergence.MultiStartGradientConvergence", + "type": "instance" + }, + "gradient_mode": null, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_log": 10, + "iterations_per_quick_update": 1e+99, + "learning_rate": 0.01, + "live_visual_update": false, + "max_consecutive_nan": 8, + "n_starts": 48, + "n_steps": 300, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "record_lane_nan_history": false, + "reset_momentum_on_clip": false, + "resurrect": false, + "scaler": { + "arguments": {}, + "class_path": "autofit.non_linear.scaler.ScalerNone", + "type": "instance" + }, + "seed": null, + "silence": false, + "start_lower_limit": 0.15, + "start_upper_limit": 0.85, + "trace_param_indices": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.search.MultiStartAdam", + "type": "instance" + }, + "main_seed7": "bd3370e335bd0c947364b769700d1513", + "main_seed7_path": "97ca7c22816db96e37f769620a9d9f17", + "seed42": "7b74977c7eaeccf66bd6e7ae40a0e530", + "seed7": "816e1871c9ecdef0c5a2f27f87a0dfcb" + }, + "MultiStartLion": { + "main_default": "3d7d54515bf9e6224ba6f6b6ee6b848d", + "main_default_path": "8e07f822689b824414c64394fcf59f6a", + "main_hash_list": [ + "MultiStartLion", + "clipper", + "ClipperNone" + ], + "main_none": "3d7d54515bf9e6224ba6f6b6ee6b848d", + "main_search_json": { + "arguments": { + "batch_size": null, + "bijector": { + "arguments": {}, + "class_path": "autofit.non_linear.bijector.BijectorNone", + "type": "instance" + }, + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "convergence": { + "arguments": { + "atol": 0.001, + "check_for_convergence": true, + "min_steps": 100, + "rtol": 0.0001, + "window": 50 + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.convergence.MultiStartGradientConvergence", + "type": "instance" + }, + "gradient_mode": null, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_log": 10, + "iterations_per_quick_update": 1e+99, + "learning_rate": 0.001, + "live_visual_update": false, + "max_consecutive_nan": 8, + "n_starts": 48, + "n_steps": 300, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "record_lane_nan_history": false, + "reset_momentum_on_clip": false, + "resurrect": false, + "scaler": { + "arguments": {}, + "class_path": "autofit.non_linear.scaler.ScalerNone", + "type": "instance" + }, + "seed": null, + "silence": false, + "start_lower_limit": 0.15, + "start_upper_limit": 0.85, + "trace_param_indices": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.search.MultiStartLion", + "type": "instance" + }, + "main_seed7": "3d7d54515bf9e6224ba6f6b6ee6b848d", + "main_seed7_path": "8e07f822689b824414c64394fcf59f6a", + "seed42": "ba924389b386559266fd5bca8d363dc3", + "seed7": "0ae6b4998a56ae4ec8cf613629ec0b08" + }, + "MultiStartProdigy": { + "main_default": "676f33a7e8e071125e92c4ffcd754c27", + "main_default_path": "337c6f093d251c6918a13ae03c86c68a", + "main_hash_list": [ + "MultiStartProdigy", + "clipper", + "ClipperNone" + ], + "main_none": "676f33a7e8e071125e92c4ffcd754c27", + "main_search_json": { + "arguments": { + "batch_size": null, + "bijector": { + "arguments": {}, + "class_path": "autofit.non_linear.bijector.BijectorNone", + "type": "instance" + }, + "clipper": { + "arguments": {}, + "class_path": "autofit.non_linear.clipper.ClipperNone", + "type": "instance" + }, + "convergence": { + "arguments": { + "atol": 0.001, + "check_for_convergence": true, + "min_steps": 100, + "rtol": 0.0001, + "window": 50 + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.convergence.MultiStartGradientConvergence", + "type": "instance" + }, + "gradient_mode": null, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_log": 10, + "iterations_per_quick_update": 1e+99, + "learning_rate": null, + "live_visual_update": false, + "max_consecutive_nan": 8, + "n_starts": 48, + "n_steps": 300, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "record_lane_nan_history": false, + "reset_momentum_on_clip": false, + "resurrect": false, + "scaler": { + "arguments": {}, + "class_path": "autofit.non_linear.scaler.ScalerNone", + "type": "instance" + }, + "seed": null, + "silence": false, + "start_lower_limit": 0.15, + "start_upper_limit": 0.85, + "trace_param_indices": null, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.mle.multi_start_gradient.search.MultiStartProdigy", + "type": "instance" + }, + "main_seed7": "676f33a7e8e071125e92c4ffcd754c27", + "main_seed7_path": "337c6f093d251c6918a13ae03c86c68a", + "seed42": "aa690132f3b95fd4fb1e94a608367733", + "seed7": "40a763507e4c1aaba984fc121e168f36" + }, + "NSS": { + "main_default": "a52ce705ede0c3f57e2e3fc3dbb0a3bd", + "main_default_path": "32487f9105af257c1b38564e4d817f4d", + "main_hash_list": [ + "NSS", + "n_live", + "200", + "num_mcmc_steps", + "5", + "num_delete", + "50", + "termination", + "-3.0", + "seed", + "42" + ], + "main_none": "43e2e7a58dd204becfaf9ddcfd50b894", + "main_search_json": { + "arguments": { + "checkpoint_interval": 100, + "chunk_size": null, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": {}, + "class_path": "autofit.non_linear.initializer.InitializerPrior", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "n_live": 200, + "name": "", + "num_delete": 50, + "num_mcmc_steps": 5, + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "seed": 42, + "silence": false, + "termination": -3.0, + "unique_tag": null + }, + "class_path": "autofit.non_linear.search.nest.nss.search.NSS", + "type": "instance" + }, + "main_seed7": "2d3a3c4442e96cdd23bcdc6956ff8af1", + "main_seed7_path": "db151d264421e447efaa71c75dc57084", + "seed42": "a52ce705ede0c3f57e2e3fc3dbb0a3bd", + "seed7": "2d3a3c4442e96cdd23bcdc6956ff8af1" + }, + "Nautilus": { + "main_default": "e521e1535fb162729c321a4faf34d235", + "main_default_path": "9f50faab92852abd04109c54f49a3fac", + "main_hash_list": [ + "Nautilus", + "n_live", + "3000", + "n_update", + "enlarge_per_dim", + "1.1", + "n_points_min", + "split_threshold", + "100", + "n_networks", + "4", + "n_like_new_bound", + "seed", + "n_shell", + "1", + "n_eff", + "500" + ], + "main_none": "e521e1535fb162729c321a4faf34d235", + "main_search_json": { + "arguments": { + "discard_exploration": false, + "enlarge_per_dim": 1.1, + "f_live": 0.01, + "force_x1_cpu": false, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": {}, + "class_path": "autofit.non_linear.initializer.InitializerPrior", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "live_visual_update": false, + "n_batch": 100, + "n_eff": 500, + "n_like_max": Infinity, + "n_like_new_bound": null, + "n_live": 3000, + "n_networks": 4, + "n_points_min": null, + "n_shell": 1, + "n_update": null, + "name": "", + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "seed": null, + "silence": false, + "split_threshold": 100, + "unique_tag": null, + "use_jax_vmap": null, + "vectorized": false, + "verbose": true + }, + "class_path": "autofit.non_linear.search.nest.nautilus.search.Nautilus", + "type": "instance" + }, + "main_seed7": "ebbf673122eb52b60fe73234e8ebb08f", + "main_seed7_path": "ef189d161789ec53586346e2a37c75b6", + "seed42": "ac7e861bf558dd12bada28484ad9c314", + "seed7": "ebbf673122eb52b60fe73234e8ebb08f" + }, + "SMC": { + "main_default": "3baa494f2ca7b37a8c4b85884cadd1f7", + "main_default_path": "df1d80f8201936a6a4b8e2cf5cc3f04d", + "main_hash_list": [ + "SMC", + "num_particles", + "256", + "kernel", + "mala", + "num_mcmc_steps", + "5", + "num_integration_steps", + "8", + "target_ess", + "0.5", + "inverse_mass_matrix", + "none" + ], + "main_none": "3baa494f2ca7b37a8c4b85884cadd1f7", + "main_search_json": { + "arguments": { + "auto_correlation_settings": { + "arguments": { + "change_threshold": 0.01, + "check_for_convergence": false, + "check_size": 100, + "required_length": 50 + }, + "class_path": "autofit.non_linear.search.mcmc.auto_correlations.AutoCorrelationsSettings", + "type": "instance" + }, + "batch_size": 0, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": {}, + "class_path": "autofit.non_linear.initializer.InitializerPrior", + "type": "instance" + }, + "inplace": false, + "inverse_mass_matrix": "none", + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "kernel": "mala", + "live_visual_update": false, + "max_smc_steps": 200, + "name": "", + "num_integration_steps": 8, + "num_mcmc_steps": 5, + "num_particles": 256, + "number_of_cores": 1, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "seed": 42, + "silence": false, + "step_size": null, + "target_ess": 0.5, + "unique_tag": null, + "whiten_inflate": 2.0 + }, + "class_path": "autofit.non_linear.search.mcmc.blackjax.smc.search.SMC", + "type": "instance" + }, + "main_seed7": "3baa494f2ca7b37a8c4b85884cadd1f7", + "main_seed7_path": "df1d80f8201936a6a4b8e2cf5cc3f04d", + "seed42": "933c180e80f42e17a24f9a4dcf271cb1", + "seed7": "87a1bfac965ce42ac43e22c408f7f8a1" + }, + "Zeus": { + "main_default": "6d171637e7fbdd903c674391faa0b197", + "main_default_path": "a733834062ddbee40783e7f208b0f132", + "main_hash_list": [ + "Zeus", + "nwalkers", + "50", + "tune", + "True", + "tolerance", + "0.05", + "patience", + "5", + "mu", + "1.0", + "light_mode", + "False" + ], + "main_none": "6d171637e7fbdd903c674391faa0b197", + "main_search_json": { + "arguments": { + "auto_correlation_settings": { + "arguments": { + "change_threshold": 0.01, + "check_for_convergence": true, + "check_size": 100, + "required_length": 50 + }, + "class_path": "autofit.non_linear.search.mcmc.auto_correlations.AutoCorrelationsSettings", + "type": "instance" + }, + "check_walkers": true, + "initial_values": { + "arguments": {}, + "type": "dict" + }, + "initializer": { + "arguments": { + "lower_limit": 0.49, + "upper_limit": 0.51 + }, + "class_path": "autofit.non_linear.initializer.InitializerBall", + "type": "instance" + }, + "inplace": false, + "iterations_per_full_update": 1e+99, + "iterations_per_quick_update": 1e+99, + "light_mode": false, + "live_visual_update": false, + "maxcall": null, + "maxiter": 10000, + "maxsteps": 10000, + "mu": 1.0, + "name": "", + "nsteps": 2000, + "number_of_cores": 1, + "nwalkers": 50, + "path_prefix": null, + "paths": { + "arguments": {}, + "class_path": "autofit.non_linear.paths.null.NullPaths", + "type": "instance" + }, + "patience": 5, + "shuffle_ensemble": true, + "silence": false, + "tolerance": 0.05, + "tune": true, + "unique_tag": null, + "vectorize": false + }, + "class_path": "autofit.non_linear.search.mcmc.zeus.search.Zeus", + "type": "instance" + }, + "main_seed7": "6d171637e7fbdd903c674391faa0b197", + "main_seed7_path": "a733834062ddbee40783e7f208b0f132", + "seed42": "222ccf265019dcd7bd5a0244ab3a6e35", + "seed7": "746ed58869c8030b6a06b43aa1dc3e3d" + } +} \ No newline at end of file diff --git a/test_autofit/non_linear/search/test_seed.py b/test_autofit/non_linear/search/test_seed.py new file mode 100644 index 000000000..6b1ba66f9 --- /dev/null +++ b/test_autofit/non_linear/search/test_seed.py @@ -0,0 +1,553 @@ +""" +The search-level ``seed`` (search-extensibility A4b, decision D4; +``autofit.non_linear.search.seed``). + +``seed_golden.json`` freezes, per search, what PyAutoFit main 8437a3b76 computed +(``main_*``: default and ``seed=7`` identifiers, output-path identifiers for a model, +the default ``hash_list`` and the default ``search.json``) next to the identifiers this +phase gives an explicit seed (``seed7``, ``seed42``). Identifiers are computed with +``PYAUTO_TEST_MODE`` unset. + +The cases, kept separate as the A4 witness asks: + +- **default** and **explicit-None** constructions: byte-identical to main for all 15 + (explicit None equals the default everywhere except NSS, as on main). +- **old incomplete output**: a default-constructed search (and a seeded Nautilus/NSS) + resolves the same output folder as main, so an interrupted fit resumes into it. +- **explicit seed**: Nautilus and NSS unchanged (``"seed"`` is a static field). Every + other search now hashes a seed it is given; for BlackJAXNUTS and SMC (which took an + unhashed ``seed`` before) and the four MultiStart searches (likewise) this is the + accepted re-key of existing explicit-seed output folders. BlackJAXNUTS and SMC read + ``seed=42`` as their default (adversary review 07, finding 1), so 42 is not re-keyed. +- **old JSON / pickle / output**: a main ``search.json`` loads and round-trips with the + default identifier for every search, including BlackJAXNUTS and SMC, whose old JSON + and pickles record ``seed: 42``; the aggregator keeps their output identifiers. +""" + +import json +import zipfile +from pathlib import Path + +import numpy as np +import pytest + +import autofit as af +from autonerves.conf import with_config +from autofit.mapper.identifier import Identifier +from autofit.non_linear.search.seed import ( + backend_generator, + backend_seed_sequences, + initializer_rng, +) + +from test_autofit.non_linear.search.conformance_roster import searches_under_test + +pytestmark = [ + pytest.mark.filterwarnings("ignore::FutureWarning"), + pytest.mark.filterwarnings("ignore::UserWarning"), +] + +GOLDEN = json.loads((Path(__file__).parent / "seed_golden.json").read_text()) + +ROSTER = {entry.name: entry for entry in searches_under_test()} + +STATIC_SEED = {"Nautilus", "NSS"} +UNHASHED_DEFAULT_42 = {"BlackJAXNUTS", "SMC"} +HAD_UNHASHED_SEED = UNHASHED_DEFAULT_42 | { + "MultiStartAdam", + "MultiStartADABelief", + "MultiStartLion", + "MultiStartProdigy", +} + + +@pytest.fixture(autouse=True) +def no_test_mode(monkeypatch): + monkeypatch.delenv("PYAUTO_TEST_MODE", raising=False) + + +def _cls(name): + entry = ROSTER[name] + missing = entry.missing_requirements() + if missing: + pytest.skip(f"{name} cannot be constructed without {missing}") + return entry.resolve() + + +def _path_identifier(search): + search.paths.model = af.Model(af.ex.Gaussian) + return search.paths.identifier + + +NAMES = sorted(GOLDEN) + + +def test_golden_covers_the_roster(): + assert set(NAMES) == set(ROSTER) + assert len(NAMES) == 15 + + +@pytest.mark.parametrize("name", NAMES) +def test_default_and_explicit_none_identifiers_unchanged(name): + cls = _cls(name) + + assert str(Identifier(cls())) == GOLDEN[name]["main_default"] + # Equal to the default for every search but NSS, whose static "seed" field + # defaults to 42 (an explicit None hashes differently there, as on main). + assert str(Identifier(cls(seed=None))) == GOLDEN[name]["main_none"] + + +@pytest.mark.parametrize("name", NAMES) +def test_default_hash_list_unchanged(name): + """`Nautilus().hash_list` (and every other search's) is unchanged.""" + assert Identifier(_cls(name)()).hash_list == GOLDEN[name]["main_hash_list"] + + +@pytest.mark.parametrize("name", NAMES) +def test_old_incomplete_output_resolves_the_same_folder(name): + cls = _cls(name) + + assert ( + _path_identifier(cls(name="seed_case", path_prefix="golden")) + == GOLDEN[name]["main_default_path"] + ) + if name in STATIC_SEED: + assert ( + _path_identifier(cls(name="seed_case", path_prefix="golden", seed=7)) + == GOLDEN[name]["main_seed7_path"] + ) + + +@pytest.mark.parametrize("name", NAMES) +def test_explicit_seed(name): + cls = _cls(name) + identifier = str(Identifier(cls(seed=7))) + + assert identifier == GOLDEN[name]["seed7"] + assert cls(seed=7).seed == 7 + + if name in STATIC_SEED: + assert identifier == GOLDEN[name]["main_seed7"] + else: + assert identifier != GOLDEN[name]["main_default"] + + if name in HAD_UNHASHED_SEED: + # The accepted re-key: main ignored this seed in the identifier. + assert GOLDEN[name]["main_seed7"] == GOLDEN[name]["main_default"] + assert identifier != GOLDEN[name]["main_seed7"] + + +@pytest.mark.parametrize("name", sorted(UNHASHED_DEFAULT_42)) +def test_nuts_smc_default_is_an_unhashed_42(name): + cls = _cls(name) + + assert cls().seed is None + assert cls().backend_seed == 42 + # Review 07 finding 1: main wrote ``seed: 42`` for every default NUTS/SMC, so 42 + # is the default sentinel; an explicit seed=42 shares the default identity. + assert cls(seed=42).seed is None + assert cls(seed=42).backend_seed == 42 + assert str(Identifier(cls(seed=42))) == GOLDEN[name]["main_default"] + assert af.to_dict(cls(seed=42)) == af.to_dict(cls()) + + +@pytest.mark.parametrize("name", NAMES) +def test_old_search_json_loads(name): + _cls(name) + old = GOLDEN[name]["main_search_json"] + + loaded = af.from_dict(json.loads(json.dumps(old))) + + assert af.to_dict(af.from_dict(af.to_dict(loaded))) == af.to_dict(loaded) + if name in UNHASHED_DEFAULT_42: + # Review 07 finding 1: main's ``seed: 42`` is the legacy default. + assert GOLDEN[name]["main_search_json"]["arguments"]["seed"] == 42 + assert loaded.seed is None + assert loaded.backend_seed == 42 + assert str(Identifier(loaded)) == GOLDEN[name]["main_default"] + + +def _start_points(search): + model = af.Model(af.ex.Gaussian) + model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=100.0) + model.normalization = af.UniformPrior(lower_limit=1.0, upper_limit=10.0) + model.sigma = af.UniformPrior(lower_limit=1.0, upper_limit=20.0) + analysis = af.ex.Analysis(data=np.ones(20), noise_map=np.ones(20)) + fitness = search.make_fitness(analysis=analysis, model=model) + _, parameters, _ = search.start_points(model=model, fitness=fitness, n=4, plot=False) + return np.asarray(parameters) + + +@pytest.mark.parametrize("name", NAMES) +def test_same_seed_same_initial_points(name): + cls = _cls(name) + + first = _start_points(cls(seed=11)) + again = _start_points(cls(seed=11)) + other = _start_points(cls(seed=12)) + + assert np.array_equal(first, again) + assert not np.array_equal(first, other) + + +def test_initializer_never_uses_the_global_random_module(monkeypatch): + import random + + def forbidden(*args, **kwargs): + raise AssertionError("the initializer used the global random module") + + monkeypatch.setattr(random, "uniform", forbidden) + monkeypatch.setattr(random, "random", forbidden) + + _start_points(af.Emcee(seed=1)) + _start_points(af.BFGS(seed=1)) + _start_points(af.DynestyStatic(seed=1)) + + +def test_streams_are_independent_and_stable(): + search = af.Emcee(seed=3) + + zero = initializer_rng(search).random(3) + one, two = backend_seed_sequences(search, k=2) + + assert np.array_equal(zero, initializer_rng(search).random(3)) + assert not np.array_equal(zero, np.random.default_rng(one).random(3)) + assert not np.array_equal( + np.random.default_rng(one).random(3), np.random.default_rng(two).random(3) + ) + assert backend_generator(af.Emcee()) is None + + +def test_fit_context_hands_the_backend_streams_one_onwards(): + from autofit.non_linear.search.fit_context import FitContext + + search = af.Drawer(seed=5) + ctx = FitContext( + search=search, + model=af.Model(af.ex.Gaussian), + analysis=None, + fitness=None, + pool=None, + test_mode_level=0, + ) + + (first,) = ctx.rng.spawn(1) + (expected,) = backend_seed_sequences(search, k=1) + + assert np.array_equal(first.generate_state(4), expected.generate_state(4)) + + +def test_grid_children_get_independent_streams_without_rekeying(): + parent = af.Emcee(seed=9) + child_0 = parent.copy_with_paths(af.DirectoryPaths(name="c0")) + child_1 = parent.copy_with_paths(af.DirectoryPaths(name="c1")) + child_0._seed_spawn_key = (0,) + child_1._seed_spawn_key = (1,) + + draws = [initializer_rng(s).random(3) for s in (parent, child_0, child_1)] + + assert not np.array_equal(draws[0], draws[1]) + assert not np.array_equal(draws[1], draws[2]) + assert str(Identifier(child_0)) == str(Identifier(child_1)) == str( + Identifier(parent) + ) + assert "_seed_spawn_key" not in af.to_dict(child_0)["arguments"] + + +def test_grid_search_sets_a_spawn_key_per_job(): + grid_search = af.SearchGridSearch( + search=af.m.MockSearch(name="grid_seed"), number_of_steps=2 + ) + model = af.Model(af.ex.Gaussian) + jobs = grid_search.make_jobs( + model=model, + analysis=af.m.MockAnalysis(), + grid_priors=[model.centre], + ) + + assert [job.search_instance._seed_spawn_key for job in jobs] == [(0,), (1,)] + + +def test_dynesty_rstate_from_backend_stream(): + assert af.DynestyStatic()._rstate_kwargs() == {} + + a = af.DynestyStatic(seed=4)._rstate_kwargs()["rstate"].random(3) + b = af.DynestyStatic(seed=4)._rstate_kwargs()["rstate"].random(3) + + assert np.array_equal(a, b) + + +@with_config("general", "output", "samples_to_csv", value=True) +def test_two_seeded_emcee_fits_write_identical_samples(tmp_path): + """The A4 witness: two `Emcee(seed=1)` fits on one platform, identical samples.csv.""" + pytest.importorskip("emcee") + + x = np.arange(30.0) + data = af.ex.Gaussian(centre=15.0, normalization=5.0, sigma=4.0).model_data_from( + xvalues=x + ) + model = af.Model(af.ex.Gaussian) + model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=30.0) + model.normalization = af.UniformPrior(lower_limit=1.0, upper_limit=10.0) + model.sigma = af.UniformPrior(lower_limit=1.0, upper_limit=10.0) + + csvs = [] + for run in range(2): + search = af.Emcee( + name=f"emcee_seed_{run}", + path_prefix=str(tmp_path), + nwalkers=10, + nsteps=30, + seed=1, + number_of_cores=1, + auto_correlation_settings=af.AutoCorrelationsSettings( + check_for_convergence=False, check_size=5 + ), + ) + search.fit( + model=model, + analysis=af.ex.Analysis(data=data, noise_map=np.ones(30)), + ) + csv = search.paths._files_path / "samples.csv" + if csv.exists(): + csvs.append(csv.read_bytes()) + else: # the output folder was zipped and removed (`remove_files`) + with zipfile.ZipFile(search.paths._zip_path) as archive: + csvs.append(archive.read("files/samples.csv")) + + assert csvs[0] == csvs[1] + + +# --------------------------------------------------------------------------- +# Adversary review 07. +# --------------------------------------------------------------------------- + +# The search identifiers PyAutoFit main 8437a3b76 computed for a default +# BlackJAXNUTS / SMC (whose search.json records ``seed: 42``). +MAIN_DEFAULT_IDENTIFIER = { + "BlackJAXNUTS": "2a6f5217539f82fab8ea42eda9bf3441", + "SMC": "3baa494f2ca7b37a8c4b85884cadd1f7", +} + + +@pytest.mark.parametrize("name", sorted(UNHASHED_DEFAULT_42)) +def test_old_nuts_smc_pickle_keeps_the_main_identifier(name): + """Review 07 finding 1: a main pickle carries ``seed = 42`` in its state.""" + import pickle + + cls = _cls(name) + search = cls() + state = search.__getstate__() + state["seed"] = 42 + + loaded = cls.__new__(cls) + loaded.__setstate__(state) + loaded = pickle.loads(pickle.dumps(loaded)) + + assert loaded.seed is None + assert loaded.backend_seed == 42 + assert str(Identifier(loaded)) == MAIN_DEFAULT_IDENTIFIER[name] + + +def _old_output_folder(directory, name, identifier_file=None): + """An output folder as main wrote it: main's search.json and a model.""" + files = directory / "files" + files.mkdir(parents=True) + (files / "search.json").write_text(json.dumps(GOLDEN[name]["main_search_json"])) + (files / "model.json").write_text(json.dumps(af.to_dict(af.Model(af.ex.Gaussian)))) + if identifier_file is not None: + (directory / ".identifier").write_text(identifier_file) + return af.SearchOutput(directory) + + +@pytest.mark.parametrize("name", sorted(UNHASHED_DEFAULT_42)) +def test_old_nuts_smc_output_keeps_the_main_identifier_in_the_aggregator( + name, tmp_path +): + """ + Review 07 finding 1: an old default NUTS/SMC output read by the aggregator keeps + main's search identifier, and ``SearchOutput.id`` (the database scrape's key) + keeps main's output identifier, with and without a persisted ``.identifier``. + """ + _cls(name) + + recomputed = _old_output_folder(tmp_path / "recomputed", name) + + assert str(Identifier(recomputed.search)) == MAIN_DEFAULT_IDENTIFIER[name] + assert recomputed.search.seed is None + assert recomputed.search.backend_seed == 42 + assert recomputed.id == GOLDEN[name]["main_default_path"] + + paths = af.DirectoryPaths(name="seed_case", path_prefix="golden") + paths.search = af.from_dict(GOLDEN[name]["main_search_json"]) + paths.model = af.Model(af.ex.Gaussian) + persisted = _old_output_folder( + tmp_path / "persisted", name, identifier_file=paths._identifier.description + ) + + assert persisted.id == GOLDEN[name]["main_default_path"] + + +def test_search_output_id_prefers_the_persisted_identifier(tmp_path): + """ + Review 07 finding 1: ``SearchOutput.id`` is the identifier the search wrote + (``.identifier`` holds its description, the md5 of which is the identifier), not a + recompute from today's search and model, which a later hashing change could move. + """ + from hashlib import md5 + + output = _old_output_folder( + tmp_path / "out", "Emcee", identifier_file="Emcee\nnwalkers\n50" + ) + + assert output.id == md5("Emcee.nwalkers.50".encode("utf-8")).hexdigest() + + +def test_search_output_id_recomputes_without_a_persisted_identifier(tmp_path): + output = _old_output_folder(tmp_path / "out", "Emcee") + + assert output.id == str( + Identifier([output.search, output.model, output.unique_tag]) + ) + + +# Review 07 finding 3: the backends that take a raw seed. +RAW_SEED_BACKENDS = ["Nautilus", "NSS", "BlackJAXNUTS", "SMC"] + + +def _children(search): + child_0 = search.copy_with_paths(af.DirectoryPaths(name="c0")) + child_1 = search.copy_with_paths(af.DirectoryPaths(name="c1")) + child_0._seed_spawn_key = (0,) + child_1._seed_spawn_key = (1,) + return child_0, child_1 + + +@pytest.mark.parametrize("name", RAW_SEED_BACKENDS) +def test_grid_children_get_distinct_raw_backend_seeds(name): + cls = _cls(name) + parent = cls(seed=9) + child_0, child_1 = _children(parent) + + # Standalone: the backend takes the raw seed, exactly as before. + assert parent.backend_seed == 9 + assert child_0.backend_seed != child_1.backend_seed + assert 9 not in (child_0.backend_seed, child_1.backend_seed) + # Child seeds are reproducible and fit a 32-bit signed JAX PRNGKey. + assert child_0.backend_seed == _children(cls(seed=9))[0].backend_seed + assert 0 <= child_0.backend_seed < 2**31 + # The spawn key never reaches the identifier or search.json. + assert str(Identifier(child_0)) == str(Identifier(child_1)) == str( + Identifier(parent) + ) + assert "_seed_spawn_key" not in af.to_dict(child_0)["arguments"] + + +@pytest.mark.parametrize( + "name", + ["MultiStartAdam", "MultiStartADABelief", "MultiStartLion", "MultiStartProdigy"], +) +def test_multi_start_grid_children_get_distinct_streams(name): + cls = _cls(name) + parent = cls(seed=9) + child_0, child_1 = _children(parent) + + def draws(search, stream): + return np.random.default_rng(search._seed_for(stream)).random(4) + + for stream in (0, 1): + assert not np.array_equal(draws(child_0, stream), draws(child_1, stream)) + # Standalone: exactly the historical (seed, stream) sequence. + assert np.array_equal( + draws(parent, stream), + np.random.default_rng(np.random.SeedSequence([9, stream])).random(4), + ) + # Unseeded standalone: the historical bare stream index. + assert cls()._seed_for(0) == 0 + assert cls()._seed_for(1) == 1 + + +@pytest.mark.parametrize("name", ["Nautilus", "NSS"]) +def test_raw_seed_backend_uses_backend_seed(name): + """The backend call sites read ``backend_seed``, not ``seed``.""" + import inspect + + cls = _cls(name) + source = inspect.getsource(cls) + assert "seed=self.backend_seed" in source or "PRNGKey(self.backend_seed)" in source + assert "PRNGKey(self.seed)" not in source + assert "seed=self.seed," not in source + + +# Review 07 finding 2: a subclass that already puts ``rstate`` in ``search_kwargs``. +class _SeededDynestyStatic(af.DynestyStatic): + def __init__(self, *args, rstate_seed=0, **kwargs): + super().__init__(*args, **kwargs) + self.rstate_seed = rstate_seed + + @property + def search_kwargs(self): + return { + **super().search_kwargs, + "rstate": np.random.default_rng(self.rstate_seed), + } + + +class _SeededDynestyDynamic(af.DynestyDynamic): + @property + def search_kwargs(self): + return {**super().search_kwargs, "rstate": np.random.default_rng(0)} + + +def test_dynesty_sampler_kwargs_resolve_rstate_once(): + assert "rstate" not in af.DynestyStatic()._sampler_kwargs() + seeded = af.DynestyStatic(seed=4)._sampler_kwargs()["rstate"].random(3) + assert np.array_equal( + seeded, af.DynestyStatic(seed=4)._rstate_kwargs()["rstate"].random(3) + ) + + # An explicit ``rstate`` in ``search_kwargs`` wins over the search-level seed. + explicit = _SeededDynestyStatic(seed=4, rstate_seed=0)._sampler_kwargs() + assert np.array_equal( + explicit["rstate"].random(3), np.random.default_rng(0).random(3) + ) + + +@pytest.mark.parametrize("cls", [_SeededDynestyStatic, _SeededDynestyDynamic]) +@pytest.mark.parametrize("pooled", [False, True]) +def test_dynesty_subclass_with_rstate_constructs_its_sampler(cls, pooled, monkeypatch): + """The real sampler construction, static and dynamic, pooled and not.""" + pytest.importorskip("dynesty") + + model = af.Model(af.ex.Gaussian) + analysis = af.ex.Analysis(data=np.ones(20), noise_map=np.ones(20)) + search = cls(seed=3, nlive=10) if cls is _SeededDynestyStatic else cls(seed=3) + fitness = search.make_fitness(analysis=analysis, model=model) + monkeypatch.setattr(search, "write_uses_pool", lambda uses_pool: None) + + pool = None + if pooled: + + class _Pool: + size = 1 + + def loglike(self, x): + return fitness(x) + + def prior_transform(self, x): + return x + + def map(self, f, xs): + return list(map(f, xs)) + + pool = _Pool() + + sampler = search.search_internal_from( + model=model, + fitness=fitness, + checkpoint_exists=False, + pool=pool, + queue_size=1 if pooled else None, + ) + + assert sampler is not None diff --git a/test_autofit/non_linear/test_dict.py b/test_autofit/non_linear/test_dict.py index 89495c64f..fff0fbc9d 100644 --- a/test_autofit/non_linear/test_dict.py +++ b/test_autofit/non_linear/test_dict.py @@ -40,6 +40,9 @@ def make_dynesty_dict(): "type": "instance", }, "sample": "auto", + # The search-level seed (search-extensibility A4b), recorded by every + # search's search.json; None unless the user passes one. + "seed": None, "silence": False, "slices": 5, "unique_tag": None,