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
114 changes: 71 additions & 43 deletions autofit/text/text_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,57 +196,72 @@ def _scaler_summary_from(samples_info) -> [str]:
return [f"Scaler = {scaler}\n"]


def _resampling_summary_from(samples_info) -> [str]:
"""
The ``search.summary`` resampling lines from the gradient searches
(``MultiStartGradient``), or none.

Guarded on the key rather than the search type, following the duck-typed
MCMC block in ``search_summary_from_samples``: every search's summary path
(``paths/abstract.py`` -> ``search_summary_to_file``) reaches this, so a
search whose ``samples_info`` lacks these keys — Nautilus, which is
jit-only and has no gradient to be non-finite — must emit nothing at all.

Rates, not just counts: raw totals are not comparable across runs, since
they scale with the lane-step budget. 797 on a 16x3000 run and 10 on an
8x300 run differ 80x raw but only ~2x per lane-step.

Named as the neutral facts they are. These are counts of undefined and
non-differentiable likelihood evaluations; they are deliberately NOT
presented as a smoothness or sampler-difficulty metric, because the
correlation with (for example) HMC divergence rates is unvalidated.

These lines are diagnostics, not headline results, so they are placed by
``search_summary_to_file`` at the bottom of ``search.summary`` under a
``Resampling Info`` subheader rather than between the sample counts and
the timing lines.
"""
if "n_value_nan_lane_steps" not in samples_info:
return []

n_value_nan = int(samples_info.get("n_value_nan_lane_steps", 0))
n_grad_nan = int(samples_info.get("n_grad_nan_lane_steps", 0))

line = [f"Resurrections = {int(samples_info.get('n_resurrections', 0))}\n"]
line.append(f"Value-NaN Lane-Steps = {n_value_nan}\n")
line.append(f"Gradient-NaN Lane-Steps = {n_grad_nan}\n")

# The trapped-lane counter (PyAutoFit#1475). It reached ``samples_info``
# when it shipped but was never emitted here, so the one artefact a user
# reads to find out what the search did did not report it. Keyed
# separately from the NaN counters because a ``search_internal`` written
# before it existed has no such key, and a zero it never wrote must not
# be reported as a measured zero.
if "n_constrained_lane_steps" in samples_info:
n_constrained = int(samples_info["n_constrained_lane_steps"])
line.append(f"Constrained Lane-Steps = {n_constrained}\n")

# ``n_starts * total_steps`` is the number of lane-steps actually taken.
# A search that died before its first step has a zero denominator, so
# the rates are omitted rather than reported as a division error.
lane_steps = int(samples_info.get("n_starts", 0)) * int(
samples_info.get("total_steps", 0)
)
if lane_steps > 0:
line.append(f"Value-NaN Lane-Step Rate = {n_value_nan / lane_steps}\n")
line.append(f"Gradient-NaN Lane-Step Rate = {n_grad_nan / lane_steps}\n")

return line


def search_summary_from_samples(samples) -> [str]:
line = [f"Total Samples = {samples.total_samples}\n"]
if hasattr(samples, "total_accepted_samples"):
line.append(f"Total Accepted Samples = {samples.total_accepted_samples}\n")
line.append(f"Acceptance Ratio = {samples.acceptance_ratio}\n")

# Per-step non-finite accounting from the gradient searches
# (``MultiStartGradient``). Guarded on the key rather than the search type,
# following the duck-typed MCMC block above: this function is on every
# search's summary path (``paths/abstract.py`` -> ``search_summary_to_file``),
# so a search whose ``samples_info`` lacks these keys — Nautilus, which is
# jit-only and has no gradient to be non-finite — must emit nothing at all.
#
# Rates, not just counts: raw totals are not comparable across runs, since
# they scale with the lane-step budget. 797 on a 16x3000 run and 10 on an
# 8x300 run differ 80x raw but only ~2x per lane-step.
#
# Named as the neutral facts they are. These are counts of undefined and
# non-differentiable likelihood evaluations; they are deliberately NOT
# presented as a smoothness or sampler-difficulty metric, because the
# correlation with (for example) HMC divergence rates is unvalidated.
samples_info = getattr(samples, "samples_info", None) or {}

if "n_value_nan_lane_steps" in samples_info:
n_value_nan = int(samples_info.get("n_value_nan_lane_steps", 0))
n_grad_nan = int(samples_info.get("n_grad_nan_lane_steps", 0))

line.append(f"Resurrections = {int(samples_info.get('n_resurrections', 0))}\n")
line.append(f"Value-NaN Lane-Steps = {n_value_nan}\n")
line.append(f"Gradient-NaN Lane-Steps = {n_grad_nan}\n")

# The trapped-lane counter (PyAutoFit#1475). It reached ``samples_info``
# when it shipped but was never emitted here, so the one artefact a user
# reads to find out what the search did did not report it. Keyed
# separately from the NaN counters because a ``search_internal`` written
# before it existed has no such key, and a zero it never wrote must not
# be reported as a measured zero.
if "n_constrained_lane_steps" in samples_info:
n_constrained = int(samples_info["n_constrained_lane_steps"])
line.append(f"Constrained Lane-Steps = {n_constrained}\n")

# ``n_starts * total_steps`` is the number of lane-steps actually taken.
# A search that died before its first step has a zero denominator, so
# the rates are omitted rather than reported as a division error.
lane_steps = int(samples_info.get("n_starts", 0)) * int(
samples_info.get("total_steps", 0)
)
if lane_steps > 0:
line.append(f"Value-NaN Lane-Step Rate = {n_value_nan / lane_steps}\n")
line.append(f"Gradient-NaN Lane-Step Rate = {n_grad_nan / lane_steps}\n")

line += _clipper_summary_from(samples_info=samples_info)
line += _scaler_summary_from(samples_info=samples_info)

Expand Down Expand Up @@ -285,6 +300,19 @@ def search_summary_to_file(
if visualization_time is not None:
summary.append(f"Visualization Time (seconds) = {visualization_time}")

# The resampling diagnostics close the file, one blank line after the
# timing lines. The 'Visualization Time' line above carries no trailing
# newline while every other tail line does, so the separator first ends
# the previous line where needed and then inserts the one empty line.
resampling = _resampling_summary_from(
samples_info=getattr(samples, "samples_info", None) or {}
)
if resampling:
if summary and not summary[-1].endswith("\n"):
summary.append("\n")
summary.append("\nResampling Info\n")
summary += resampling

frm.output_list_of_strings_to_file(file=filename, list_of_strings=summary)


Expand Down
83 changes: 74 additions & 9 deletions test_autofit/text/test_text_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,23 @@ def _gradient_samples(model, samples_info):
)


def test__search_summary__nan_lane_step_counters(model):
def _summary_file_text(samples, tmp_path, visualization_time=None) -> str:
"""
The resampling lines live at the bottom of the WRITTEN summary (not in
``search_summary_from_samples``), so the resampling tests go through
``search_summary_to_file`` and read the file back.
"""
filename = tmp_path / "search.summary"
text_util.search_summary_to_file(
samples=samples,
log_likelihood_function_time=1.0,
filename=filename,
visualization_time=visualization_time,
)
return filename.read_text()


def test__search_summary__nan_lane_step_counters(model, tmp_path):
"""
The gradient searches report both non-finite failure modes, plus rates
normalised by lane-steps (``n_starts * total_steps``) -- raw counts are not
Expand All @@ -139,7 +155,7 @@ def test__search_summary__nan_lane_step_counters(model):
},
)

summary = "".join(text_util.search_summary_from_samples(samples=samples))
summary = _summary_file_text(samples=samples, tmp_path=tmp_path)

assert "Resurrections = 40\n" in summary
assert "Value-NaN Lane-Steps = 40\n" in summary
Expand All @@ -149,8 +165,52 @@ def test__search_summary__nan_lane_step_counters(model):
assert "Value-NaN Lane-Step Rate = 0.05\n" in summary
assert "Gradient-NaN Lane-Step Rate = 0.01\n" in summary

# The diagnostics close the file as their own section, not interleaved
# with the headline sample counts.
assert "\nResampling Info\nResurrections = 40\n" in summary
assert summary.index("Resampling Info") > summary.index(
"Expected Time To Run"
)


def test__search_summary__nan_counters_absent_for_other_searches(model):
def test__search_summary__resampling_info_section_at_bottom(model, tmp_path):
"""
The Witness for the section move: a completed search's ``search.summary``
ends with a blank line after the 'Visualization Time' line, then a
'Resampling Info' subheader followed by the six resampling lines.
"""
samples = _gradient_samples(
model=model,
samples_info={
"total_samples": 10,
"time": None,
"n_starts": 8,
"total_steps": 100,
"n_resurrections": 40,
"n_value_nan_lane_steps": 40,
"n_grad_nan_lane_steps": 8,
"n_constrained_lane_steps": 0,
},
)

summary = _summary_file_text(
samples=samples, tmp_path=tmp_path, visualization_time=1.0
)

assert summary.endswith(
"Visualization Time (seconds) = 1.0\n"
"\n"
"Resampling Info\n"
"Resurrections = 40\n"
"Value-NaN Lane-Steps = 40\n"
"Gradient-NaN Lane-Steps = 8\n"
"Constrained Lane-Steps = 0\n"
"Value-NaN Lane-Step Rate = 0.05\n"
"Gradient-NaN Lane-Step Rate = 0.01\n"
)


def test__search_summary__nan_counters_absent_for_other_searches(model, tmp_path):
"""
``search_summary_from_samples`` is on EVERY search's summary path, so a
search without the counters -- Nautilus, which is jit-only and has no
Expand Down Expand Up @@ -190,8 +250,13 @@ def test__search_summary__nan_counters_absent_for_other_searches(model):
# The MCMC block it sits beside is untouched.
assert "Total Accepted Samples = 2\n" in summary

# The written file gains no 'Resampling Info' section either -- a search
# without the counters must be completely unaffected, file included.
file_text = _summary_file_text(samples=samples, tmp_path=tmp_path)
assert "Resampling Info" not in file_text

def test__search_summary__nan_rates_omitted_when_no_lane_steps_taken(model):

def test__search_summary__nan_rates_omitted_when_no_lane_steps_taken(model, tmp_path):
"""
A search that died before its first step has a zero denominator. The counts
still report; the rates are omitted rather than raising ZeroDivisionError.
Expand All @@ -209,7 +274,7 @@ def test__search_summary__nan_rates_omitted_when_no_lane_steps_taken(model):
},
)

summary = "".join(text_util.search_summary_from_samples(samples=samples))
summary = _summary_file_text(samples=samples, tmp_path=tmp_path)

assert "Value-NaN Lane-Steps = 0\n" in summary
assert "Rate" not in summary
Expand Down Expand Up @@ -318,7 +383,7 @@ def test__search_summary__clipper_absent_for_other_searches(model):
assert "Clipped" not in summary


def test__search_summary__constrained_lane_steps_reported(model):
def test__search_summary__constrained_lane_steps_reported(model, tmp_path):
"""
The trapped-lane counter (PyAutoFit#1475) reached ``samples_info`` when it
shipped but was never emitted, so the artefact a user reads to find out what
Expand All @@ -338,12 +403,12 @@ def test__search_summary__constrained_lane_steps_reported(model):
},
)

summary = "".join(text_util.search_summary_from_samples(samples=samples))
summary = _summary_file_text(samples=samples, tmp_path=tmp_path)

assert "Constrained Lane-Steps = 667\n" in summary


def test__search_summary__constrained_absent_when_never_written(model):
def test__search_summary__constrained_absent_when_never_written(model, tmp_path):
"""
A ``search_internal`` written before the trapped-lane counter existed has no
such key. A zero it never wrote must not be reported as a measured zero --
Expand All @@ -362,6 +427,6 @@ def test__search_summary__constrained_absent_when_never_written(model):
},
)

summary = "".join(text_util.search_summary_from_samples(samples=samples))
summary = _summary_file_text(samples=samples, tmp_path=tmp_path)

assert "Constrained" not in summary
Loading