Skip to content
Merged
30 changes: 29 additions & 1 deletion autofit/aggregator/search_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down
9 changes: 9 additions & 0 deletions autofit/mapper/identifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions autofit/non_linear/grid/grid_search/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
37 changes: 30 additions & 7 deletions autofit/non_linear/initializer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import configparser
import logging
import os
import random
from abc import ABC, abstractmethod
from typing import Dict, Tuple, List, Optional

Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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)

Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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):
Expand Down
5 changes: 5 additions & 0 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ def __init__(
silence: bool = False,
session: Optional[sa.orm.Session] = None,
paths: Optional[AbstractPaths] = None,
seed: Optional[int] = None,
**kwargs,
):
"""
Expand All @@ -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__()

Expand All @@ -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,
Expand Down
13 changes: 12 additions & 1 deletion autofit/non_linear/search/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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``).

Expand Down Expand Up @@ -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,
)
)
Expand Down
11 changes: 8 additions & 3 deletions autofit/non_linear/search/fit_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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 = (
Expand Down
40 changes: 36 additions & 4 deletions autofit/non_linear/search/mcmc/blackjax/nuts/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -232,6 +243,7 @@ def __init__(
number_of_cores=number_of_cores,
silence=silence,
session=session,
seed=legacy_default_seed(seed),
**kwargs,
)

Expand All @@ -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
Expand All @@ -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 "
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading