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
14 changes: 14 additions & 0 deletions autofit/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ class SearchException(Exception):
pass


class SearchBudgetExceeded(SearchException):
"""A search reached its budget before it produced any posterior samples."""

def __init__(self, termination_reason: str):
super().__init__(termination_reason)
self.termination_reason = termination_reason

def __str__(self):
return (
f"The search reached its {self.termination_reason} budget "
"without posterior samples."
)


class ProjectionException(ValueError):
"""
Raised when an importance-weighted message projection
Expand Down
35 changes: 18 additions & 17 deletions autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from autofit.database.sqlalchemy_ import sa
from autofit.non_linear.result import Result

from autofit.exc import SearchBudgetExceeded
from autofit.graphical import FactorApproximation, MeanField
from autofit.graphical.utils import Status
from autofit.graphical.expectation_propagation import (
Expand Down Expand Up @@ -391,16 +392,10 @@ def pre_fit_output(

@configure_handler
def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Result:
"""
Start a non-linear search from scratch, or resume one which was previously
terminated mid-way through (from the samples it left off at), and return its
``Result``.

When the search completes a `.completed` file is output, so a rerun is not
repeated and loads its results via `result_via_completed_fit`; results are also
output to the `files` folder via the analysis' `save_results`. Under
``PYAUTO_TEST_MODE>=2`` the backend is bypassed (``TestModeBypass``); both
paths end in ``finalize_result``.
"""Run or resume the search and return its result.

Both the real backend and the test-mode bypass finish in `finalize_result`.
Only successful finalization writes `.completed` for subsequent reuse.
"""
if self.paths.has_timer:
self.timer.start()
Expand Down Expand Up @@ -438,13 +433,19 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res
if hasattr(fitness, "shutdown_quick_update"):
fitness.shutdown_quick_update()

samples = self.perform_update(
model=model,
analysis=analysis,
search_internal=search_internal,
fitness=fitness,
during_analysis=False,
)
try:
samples = self.perform_update(
model=model,
analysis=analysis,
search_internal=search_internal,
fitness=fitness,
during_analysis=False,
)
except SearchBudgetExceeded:
# Finalization normally unfreezes the model. A caller can recover
# from a budget stop without samples and reuse this model.
model.unfreeze()
raise

samples_summary = None

Expand Down
99 changes: 70 additions & 29 deletions autofit/non_linear/search/nest/nautilus/search.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from __future__ import annotations

import math
import multiprocessing
import numpy as np
import logging
import os
import sys
from contextlib import contextmanager, nullcontext
from pathlib import Path
from time import monotonic
from typing import Dict, Optional, Tuple, TYPE_CHECKING


Expand Down Expand Up @@ -346,6 +348,7 @@ def __init__(
session: Optional[sa.orm.Session] = None,
use_jax_vmap: Optional[bool] = None,
checkpoint: bool = True,
timeout: Optional[float] = None,
**kwargs,
):
"""
Expand Down Expand Up @@ -382,6 +385,13 @@ def __init__(
Number of likelihood evaluations performed at each step.
n_like_max
Maximum number of likelihood evaluations before stopping.
timeout
Optional positive wall-clock budget in seconds across the sampling
loop, including intervening full updates. Nautilus checks it between
batches, so in-flight work can finish after the deadline. If a budget
stops the search early, the samples record the ``termination_reason``.
If there are no posterior samples, the fit raises
``SearchBudgetExceeded`` with the same reason.
f_live
Maximum fraction of evidence in the live set before terminating.
n_eff
Expand Down Expand Up @@ -444,6 +454,11 @@ def __init__(
self.n_shell = n_shell
self.n_eff = n_eff
self.n_like_max = n_like_max
if timeout is not None and (not math.isfinite(timeout) or timeout <= 0):
raise ValueError(
"Nautilus timeout must be a finite positive number of seconds."
)
self.timeout = timeout
self.discard_exploration = discard_exploration
self.verbose = verbose

Expand Down Expand Up @@ -810,7 +825,9 @@ def call_search(self, search_internal, model, analysis, fitness, update=None):
the log likelihood the search maximizes.
"""

finished = False
timeout = getattr(self, "timeout", None)
deadline = monotonic() + timeout if timeout is not None else None
termination_reason = None

minimum_iterations_per_full_updates = 3 * self.n_live

Expand All @@ -834,9 +851,16 @@ def call_search(self, search_internal, model, analysis, fitness, update=None):
"""
)

while not finished:

iterations, total_iterations = self.iterations_from(
while True:
run_options = {}
if deadline is not None:
remaining = deadline - monotonic()
if remaining <= 0:
termination_reason = "timeout"
break
run_options["timeout"] = remaining

iterations, calls_before_run = self.iterations_from(
search_internal=search_internal,
iterations_per_full_update=iterations_per_full_update,
)
Expand All @@ -848,33 +872,38 @@ def call_search(self, search_internal, model, analysis, fitness, update=None):
discard_exploration=self.discard_exploration,
verbose=self.verbose,
n_like_max=iterations,
**run_options,
)

iterations_after_run = self.iterations_from(search_internal=search_internal)[1]

if (
converged
or total_iterations == iterations_after_run
or (
self.n_like_max is not None
and iterations_after_run >= self.n_like_max
)
calls_after_run = search_internal.n_like

if converged:
break
if self.n_like_max is not None and calls_after_run >= self.n_like_max:
termination_reason = "n_like_max"
break
if deadline is not None and (
calls_after_run < iterations or monotonic() >= deadline
):
finished = True

if not finished:

if update is not None:
update(search_internal)
else:
self.perform_update(
model=model,
analysis=analysis,
during_analysis=True,
fitness=fitness,
search_internal=search_internal
)
# Nautilus returns False only for a likelihood or time limit.
# Below the chunk's likelihood limit it stopped on its timeout.
termination_reason = "timeout"
break
if calls_before_run == calls_after_run:
break

if update is not None:
update(search_internal)
else:
self.perform_update(
model=model,
analysis=analysis,
during_analysis=True,
fitness=fitness,
search_internal=search_internal,
)

# Keep the outcome with the sampler through archival and sample conversion.
search_internal._autofit_termination_reason = termination_reason
return search_internal

def progress(self, search_internal) -> Optional[Dict]:
Expand Down Expand Up @@ -941,13 +970,17 @@ def iterations_from(
return iterations, total_iterations

def samples_info_from(self, search_internal=None):
return {
info = {
"log_evidence": search_internal.log_z,
"total_samples": int(search_internal.n_like),
"total_accepted_samples": int(search_internal.n_like),
"time": self.timer.time if self.timer else None,
"number_live_points": int(search_internal.n_live),
}
termination_reason = getattr(search_internal, "_autofit_termination_reason", None)
if termination_reason is not None:
info["termination_reason"] = termination_reason
return info

def raw_samples_from(self, model, search_internal):
"""
Expand All @@ -961,7 +994,15 @@ def raw_samples_from(self, model, search_internal):
search_internal
The nautilus sampler.
"""
termination_reason = getattr(search_internal, "_autofit_termination_reason", None)
if termination_reason is not None and search_internal.n_like == 0:
# Nautilus can reach its timeout before its first batch.
raise exc.SearchBudgetExceeded(termination_reason)

parameters, log_weights, log_likelihoods = search_internal.posterior()
if termination_reason is not None and len(parameters) == 0:
# For example, discard_exploration can exclude every point collected.
raise exc.SearchBudgetExceeded(termination_reason)

return RawSamples(
parameters=parameters,
Expand Down
1 change: 1 addition & 0 deletions test_autofit/non_linear/search/conformance_roster.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ class Golden:
"n_update",
"seed",
"split_threshold",
"timeout",
"use_jax_vmap",
"vectorized",
"verbose",
Expand Down
Loading
Loading