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
2 changes: 1 addition & 1 deletion autofit/non_linear/search/abstract_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def _fit_and_output(self, model, analysis, info=None):
model.freeze()
analysis = analysis.modify_before_fit(paths=self.paths, model=model)
model.unfreeze()
resolve_fit_parallel(self, analysis)
resolve_fit_parallel(self, analysis, model=model)

if not skip_fit_output():
self.pre_fit_output(analysis=analysis, model=model, info=info)
Expand Down
45 changes: 42 additions & 3 deletions autofit/non_linear/search/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def log_fit_start(search, analysis):
logger.info(search.quick_update_message)


def resolve_fit_parallel(search, analysis):
def resolve_fit_parallel(search, analysis, model=None):
"""
Resolve a fit's worker count once ``modify_before_fit`` has resolved the analysis's
compute setup (``autofit.non_linear.parallel.pool.resolve_number_of_cores``:
Expand All @@ -281,6 +281,12 @@ def resolve_fit_parallel(search, analysis):
``"auto"`` request gets its thread warning here, for the resolved count. Writes
``files/parallel.json`` unless the fit is already complete (a completed fit keeps
the record of the run that produced it).

After the banner, an analysis that defines ``runtime_estimate(search, model,
number_of_cores)`` (duck-typed; PyAutoLens implements it) is asked for a one-line
run-time estimate, which is logged and recorded as ``estimate_line`` in
``files/parallel.json``. The hook is advisory: an analysis without it, a hook
returning anything but a non-empty string, or a hook that raises never affects the fit.
"""
from autofit.non_linear.parallel.pool import resolve_number_of_cores
from autofit.non_linear.parallel.resources import is_auto
Expand All @@ -294,18 +300,51 @@ def resolve_fit_parallel(search, analysis):
search._parallel_resolution = resolution
search._parallel_summary = resolution.summary

getattr(search, "logger", logger).info(resolution.banner)
search_logger = getattr(search, "logger", logger)
search_logger.info(resolution.banner)

estimate_line = runtime_estimate_line(
search=search,
analysis=analysis,
model=model,
number_of_cores=resolution.number_of_cores,
)
if estimate_line is not None:
search_logger.info(estimate_line)

if is_auto(resolution.requested):
warn_if_threads_unpinned(resolution.number_of_cores)

paths = getattr(search, "paths", None)
if paths is not None and not paths.is_complete:
paths.save_json("parallel", resolution.to_dict())
record = resolution.to_dict()
record["estimate_line"] = estimate_line
paths.save_json("parallel", record)

return resolution


def runtime_estimate_line(search, analysis, model, number_of_cores):
"""
The one-line run-time estimate an analysis gives for this fit, or ``None``.

Calls ``analysis.runtime_estimate(search=..., model=..., number_of_cores=...)`` when
the analysis defines it. Only a non-empty string is used; any exception is logged at
debug level and ignored, so an estimate can never stop or change a fit.
"""
hook = getattr(analysis, "runtime_estimate", None)
if not callable(hook):
return None
try:
line = hook(search=search, model=model, number_of_cores=number_of_cores)
except Exception as e:
logger.debug(f"runtime_estimate failed and was ignored: {e!r}")
return None
if isinstance(line, str) and line.strip():
return line.strip()
return None


def fit_pools(search, analysis):
"""
The fit's ``PoolFactory``, built on the resolution ``resolve_fit_parallel`` made
Expand Down
92 changes: 92 additions & 0 deletions test_autofit/non_linear/test_number_of_cores_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ def test_fit_logs_one_banner_after_modify_before_fit_and_writes_parallel_json(
"detected_cores": 64,
"available_memory_gb": None,
"setup_id": "numba_cpu_sparse_fp64",
"estimate_line": None,
}

assert search_json["arguments"]["number_of_cores"] == "auto"
Expand All @@ -381,3 +382,94 @@ def test_fit_banner_for_jax_auto(monkeypatch, caplog, tmp_path):
assert [r.getMessage() for r in _banner_records(caplog)] == [
"Parallel: 1 worker (requested auto; JAX analyses run single-process)"
]


# ------------------------------------------------- runtime_estimate hook (5E-2)


class _EstimateAnalysis(_SetupAnalysis):
"""An analysis with a duck-typed ``runtime_estimate`` hook that records its call."""

def __init__(self, *args, line="Estimate: ~2 ms/eval", raises=False, **kwargs):
super().__init__(*args, **kwargs)
self.line = line
self.raises = raises
self.calls = []

def runtime_estimate(self, search, model, number_of_cores):
self.calls.append((search, model, number_of_cores))
if self.raises:
raise RuntimeError("no estimate data")
return self.line


def _fit_with(analysis, tmp_path, monkeypatch, caplog, name):
monkeypatch.setenv("PYAUTO_TEST_MODE", "2")
search = af.Emcee(name=name, path_prefix=str(tmp_path), number_of_cores="auto")
model = af.Model(af.ex.Gaussian)
with caplog.at_level(logging.INFO):
search.fit(model=model, analysis=analysis)
with zipfile.ZipFile(search.paths._zip_path) as archive:
record = json.loads(archive.read("files/parallel.json"))
messages = [r.getMessage() for r in caplog.records]
return search, model, record, messages


def test_runtime_estimate_hook_is_logged_after_the_banner_and_recorded(
monkeypatch, caplog, tmp_path
):
analysis = _EstimateAnalysis(data=np.ones(10), noise_map=np.ones(10))
search, model, record, messages = _fit_with(
analysis, tmp_path, monkeypatch, caplog, "estimate_hook"
)

banner = next(i for i, m in enumerate(messages) if m.startswith("Parallel:"))
assert messages[banner + 1] == "Estimate: ~2 ms/eval"
assert record["estimate_line"] == "Estimate: ~2 ms/eval"

assert len(analysis.calls) == 1
called_search, called_model, called_cores = analysis.calls[0]
assert called_search is search
assert called_model.prior_count == model.prior_count
assert called_cores == 64


def test_runtime_estimate_hook_that_raises_is_ignored(monkeypatch, caplog, tmp_path):
analysis = _EstimateAnalysis(
data=np.ones(10), noise_map=np.ones(10), raises=True
)
_, _, record, messages = _fit_with(
analysis, tmp_path, monkeypatch, caplog, "estimate_raises"
)

assert record["estimate_line"] is None
assert not [m for m in messages if m.startswith("Estimate:")]
assert len([m for m in messages if m.startswith("Parallel:")]) == 1


@pytest.mark.parametrize("line", [None, "", " ", 42])
def test_runtime_estimate_hook_non_string_or_empty_is_ignored(line):
from autofit.non_linear.search.runtime import runtime_estimate_line

class _Analysis:
def runtime_estimate(self, search, model, number_of_cores):
return line

assert (
runtime_estimate_line(
search=None, analysis=_Analysis(), model=None, number_of_cores=1
)
is None
)


def test_runtime_estimate_line_without_hook_is_none():
from autofit.non_linear.search.runtime import runtime_estimate_line

assert (
runtime_estimate_line(
search=None, analysis=object(), model=None, number_of_cores=4
)
is None
)

Loading