Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 86 additions & 1 deletion autofit/graphical/declarative/collection.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import List, Union, Optional
from typing import Dict, List, Union, Optional

from autofit.graphical.declarative.factor.analysis import AnalysisFactor
from autofit.graphical.declarative.factor.hierarchical import HierarchicalFactor

from autofit.tools.namer import namer
Expand Down Expand Up @@ -141,6 +142,90 @@ def check_backend_agreement(self):
f"(graph.optimise) allows mixed factors."
)

def modify_before_fit(self, paths: AbstractPaths, model):
"""
Forward ``modify_before_fit`` to every factor's analysis before a whole-graph fit,
so each factor resolves its own compute setup (e.g. a PyAutoGalaxy / PyAutoLens
``setup=``) exactly as it would fitted alone.

Each analysis factor gets its own sub-paths (``analyses/analysis_<i>``, as
``_for_each_analysis`` names them) and its own model: the ``i``-th child of the
fitted ``model`` (which may carry replacement priors, e.g. in a grid-search
cell), else the factor's ``prior_model``. ``AnalysisFactor.modify_before_fit``
rebinds both of the factor's analysis references to the object returned.
Hierarchical factors carry no analysis and are skipped. The factors must then
agree on their resolved setup (``check_setup_agreement``).

Returns
-------
This graph, its factors now holding their modified analyses.
"""
factors = self.model_factors
for i, factor in enumerate(factors):
if not isinstance(factor, (AnalysisFactor, FactorGraphModel)):
continue
child_paths = paths.for_sub_analysis(analysis_name=f"analyses/analysis_{i}")
factor.modify_before_fit(child_paths, self._factor_model(model, i, factor))

self.check_setup_agreement()
return self

def _factor_model(self, model, index: int, factor):
"""
The model of factor ``index`` within the fitted graph ``model``, or the factor's
own ``prior_model`` when ``model`` does not have one child per factor.
"""
try:
if model is not None and len(model) == len(self.model_factors):
return model[index]
except (TypeError, KeyError, IndexError, AttributeError):
pass
return factor.prior_model

def setup_ids(self) -> Dict[str, str]:
"""
The resolved compute setup of each factor that has one, as {factor name:
setup_id} (``analysis.setup.setup_id``, duck-typed: factors whose analysis has
no ``setup`` are left out).
"""
from autofit.non_linear.parallel.pool import setup_id_of

ids = {}
for factor in self._flat_factors():
setup_id = setup_id_of(factor)
if setup_id is not None:
ids[factor.name] = setup_id
return ids

def check_setup_agreement(self):
"""
Raise ``SearchException`` when the factors resolved different compute setups.

A whole-graph fit evaluates every factor in one process, so every factor that
has a setup must have resolved the same one (factors without a setup are
ignored). Called at the end of ``modify_before_fit`` and by the runtime gates
beside ``check_backend_agreement``.
"""
ids = self.setup_ids()
if len(set(ids.values())) <= 1:
return

from autofit import exc

by_setup = {}
for name, setup_id in ids.items():
by_setup.setdefault(setup_id, []).append(name)
listing = "; ".join(
f"{setup_id}: {', '.join(names)}" for setup_id, names in by_setup.items()
)
raise exc.SearchException(
f"The FactorGraphModel {self.name} is fitted as one analysis, but its "
f"factors resolved different compute setups ({listing}). Whole-graph "
f"fitting evaluates every factor in one process, so every factor must use "
f"the same setup: build every factor's analysis with the same setup= (or "
f"none, so each resolves the default)."
)

@property
def gradient_mode(self) -> str:
"""
Expand Down
23 changes: 23 additions & 0 deletions autofit/graphical/declarative/factor/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,29 @@ def __init__(
name=name,
)

def modify_before_fit(self, paths: AbstractPaths, model: AbstractPriorModel):
"""
Forward ``modify_before_fit`` to the wrapped analysis and rebind this factor to
the analysis it returns (``rebind_analysis``), so the factor evaluates the
modified analysis (e.g. one whose compute setup is resolved).

Returns
-------
This factor.
"""
self.rebind_analysis(self.analysis.modify_before_fit(paths=paths, model=model))
return self

def rebind_analysis(self, analysis: Analysis):
"""
Point both of this factor's analysis references at ``analysis``: the factor's own
``analysis`` and the ``FactorCallable`` the graph evaluates.
"""
self.analysis = analysis
factor = self.__dict__.get("_factor")
if isinstance(factor, FactorCallable):
factor.analysis = analysis

@property
def is_jax(self) -> bool:
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,16 @@ def optimise(
search._visualize_fit = visualize_ep_factor_searches
search._visualize_before_fit = visualize_ep_factor_searches or number == 0

# Marks the fit as an EP factor search, so a `number_of_cores="auto"` request
# resolves to 1 (`autofit.non_linear.parallel.pool.resolve_number_of_cores`).
search._ep_factor_search = True

try:
result = search.fit(model=model, analysis=analysis)
finally:
search._visualize_fit = True
search._visualize_before_fit = True
search._ep_factor_search = False

# Record the sampler's log-evidence of this tilted-distribution fit on
# the projected mean field — the per-factor Ẑₐ that README §5 documents
Expand Down
8 changes: 6 additions & 2 deletions autofit/non_linear/grid/grid_search/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@ def __init__(

self.logger.info("Creating grid search")

self.number_of_cores = number_of_cores or 1
# "auto" is the detected cores: each job is a whole fit, so there is no one
# analysis to cap the count by.
from autofit.non_linear.parallel.resources import resolve_job_cores

self.logger.info(f"Using {number_of_cores} core(s)")
self.number_of_cores = resolve_job_cores(number_of_cores, where="GridSearch")

self.logger.info(f"Using {self.number_of_cores} core(s)")

self._result_output_interval = result_output_interval

Expand Down
9 changes: 7 additions & 2 deletions autofit/non_linear/grid/sensitivity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ def __init__(
mapping. This is useful for removing regions of the sensitivity grid that are expected to have no
sensitivity, for example because they have no signal.
number_of_cores
How many cores does this computer have?
The number of jobs run in parallel: a whole number >= 1, or "auto" for every core this process may
use (`SLURM_CPUS_PER_TASK`, then the CPU affinity, then `os.cpu_count()`).
limit_scale
Scales the priors for each perturbation model.
A scale of 1 means priors have limits the same size as the grid square.
Expand Down Expand Up @@ -130,7 +131,11 @@ def __init__(
"""
)

self.number_of_cores = number_of_cores
# "auto" is the detected cores: each job is a whole fit, so there is no one
# analysis to cap the count by.
from autofit.non_linear.parallel.resources import resolve_job_cores

self.number_of_cores = resolve_job_cores(number_of_cores, where="Sensitivity")

self.limit_scale = limit_scale

Expand Down
10 changes: 10 additions & 0 deletions autofit/non_linear/parallel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,18 @@
from .sneaky import SneakyJob
from .sneaky import SneakyPool
from .pool import (
ParallelResolution,
PoolFactory,
check_factor_search_cores,
effective_number_of_cores,
jax_backend_initialized,
resolve_number_of_cores,
setup_id_of,
)
from .resources import (
available_memory_gb,
detected_cores,
is_auto,
resolve_job_cores,
validate_number_of_cores,
)
Loading
Loading