diff --git a/autofit/graphical/expectation_propagation/diagnostics.py b/autofit/graphical/expectation_propagation/diagnostics.py index 9bad2b849..a97e1cc08 100644 --- a/autofit/graphical/expectation_propagation/diagnostics.py +++ b/autofit/graphical/expectation_propagation/diagnostics.py @@ -139,10 +139,11 @@ def snapshot(self, factor, model_approx, status) -> None: else: kl = float("nan") - # The variables this update did *not* move. `updated` is the - # factor-level summary — True as soon as anything moved — so a - # variable reverted on every projection is invisible in it; this - # column is what lets a referee script tally that per variable. + # The variables whose projection this update *rejected* (reverted). + # `updated` is the factor-level summary — True as soon as anything + # moved — so a variable reverted on every projection is invisible in + # it; this column is what lets a referee script tally that per + # variable. if status.changed is not None: reverted_variables = ";".join( sorted( diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index 9544caccf..c9c55a121 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -393,11 +393,11 @@ def _check_consecutive_failures( run should stop early. """ # Per-variable bookkeeping, one level below `status.updated`: which of - # this factor's variables were compared by this update, and which of - # them actually moved — accumulated per factor *name*, so a decomposed - # factor's per-dataset members count as one group. A raise never - # carries a mask (the update never reached the projection), so this is - # a no-op on that path. + # this factor's variables this update covered, and for which of them + # the projection was *accepted* — accumulated per factor *name*, so a + # decomposed factor's per-dataset members count as one group. A raise + # never carries a mask (the update never reached the projection), so + # this is a no-op on that path. if status.changed is not None: group = factor.name self._variables_seen.setdefault(group, set()).update(status.changed.keys()) diff --git a/autofit/graphical/mean_field.py b/autofit/graphical/mean_field.py index 00c1fb765..d6479ad9d 100755 --- a/autofit/graphical/mean_field.py +++ b/autofit/graphical/mean_field.py @@ -501,12 +501,13 @@ def update_factor_mean_field( """ success, messages, _, flag = status updated = False - # Per-variable mask of what this update actually moved, carried on the - # returned Status for the (factor, variable) staleness warning. It is - # computed on both branches below, against the *final* factor_dist — - # after `update_invalid` on the invalid branch, since it is exactly a - # variable whose every parameter was reverted that must read as - # unchanged. None when there is nothing to compare against. + # Per-variable mask of whether this update *accepted* each variable's + # projection, carried on the returned Status for the (factor, variable) + # staleness warning. A valid projection accepts every one of its + # variables, whether or not the message moved — landing on a fixed + # point is not a rejection. An invalid projection accepts exactly the + # variables `check_valid` passes, read before `update_invalid` reverts + # the rest. None when the update never reached the projection. changed = None if not status.success and last_dist is not None: # The optimiser did not succeed (failed line search, bad Hessian, @@ -544,23 +545,26 @@ def update_factor_mean_field( # Name the variables `update_invalid` reverts, with the # precisions that made the quotient invalid (a projected # marginal wider than the cavity has negative factor precision). - reverted = [ - v - for v, valid in factor_dist.check_valid().items() - if not np.all(valid) - ] + valid = factor_dist.check_valid() + reverted = [v for v, v_valid in valid.items() if not np.all(v_valid)] messages += self._reverted_variable_messages(reverted, cavity_dist) + # The acceptance mask is the projection's validity, read + # *before* the revert: a variable is accepted only if every one + # of its parameters survived. `check_valid` after the revert is + # true by construction — the reverted parameters come from a + # valid message — so it cannot be the signal (PyAutoFit#1571). + changed = VariableData( + {v: bool(np.all(v_valid)) for v, v_valid in valid.items()} + ) factor_dist = factor_dist.update_invalid(last_dist) - # Whether anything *moved*, not whether the result is valid: - # `check_valid` after the revert is true by construction, since - # the reverted parameters come from a valid message, so it used - # to report a fully reverted projection as an update and hide it - # from the STALE FACTORS warning (PyAutoFit#1571). - changed = factor_dist.check_changed(last_dist) - if changed.any(): + # `updated` stays on the numerical comparison: a projection + # whose every parameter was reverted moved nothing and counts + # as skipped. + moved = factor_dist.check_changed(last_dist) + if moved.any(): updated = True - n_changed = changed.sum() - n_total = changed.size + n_changed = moved.sum() + n_total = moved.size logger.debug( "meanfield with variables: %r ," "partially updated %d variables " @@ -578,11 +582,10 @@ def update_factor_mean_field( flag = StatusFlag.BAD_PROJECTION else: updated = True - changed = ( - factor_dist.check_changed(last_dist) - if last_dist is not None - else None - ) + # A valid projection is accepted for every variable, moved or + # not: reproducing a message exactly is a fixed point, not a + # rejection. + changed = VariableData({v: True for v in factor_dist}) except exc.MessageException as e: logger.exception(e) diff --git a/autofit/graphical/utils.py b/autofit/graphical/utils.py index 7f7772a3a..8db3ea3ad 100644 --- a/autofit/graphical/utils.py +++ b/autofit/graphical/utils.py @@ -298,16 +298,18 @@ def __init__( Parameters ---------- changed - Per-variable mask of whether this factor update actually moved - each of the factor's messages, as - ``MeanField.check_changed`` computes it. ``updated`` is the - factor-level summary of the same thing (did *anything* move); + Per-variable mask of whether this factor update's projection was + *accepted* for each of the factor's variables — not whether the + message moved numerically. A valid projection accepts every + variable (a message that reproduces itself is at a fixed point, + not rejected); an invalid one accepts the variables that passed + ``check_valid`` and rejects those ``update_invalid`` reverts. + ``updated`` remains the factor-level "did anything move"; this is the per-variable resolution the (factor, variable) staleness warning needs, so that a variable reverted on every projection is named even when its factor's other variables - update. ``None`` when the update carried no comparison — no - previous message to compare against, or a status that never - reached the mean-field projection. + update. ``None`` when the update never reached the mean-field + projection. """ self.success = success self.messages = messages diff --git a/test_autofit/graphical/functionality/test_factor_failure_recovery.py b/test_autofit/graphical/functionality/test_factor_failure_recovery.py index 90674fa43..6e98e8e4e 100644 --- a/test_autofit/graphical/functionality/test_factor_failure_recovery.py +++ b/test_autofit/graphical/functionality/test_factor_failure_recovery.py @@ -508,11 +508,11 @@ def test_partial_revert_is_recorded_in_ep_history_csv(tmp_path): `ep_history.csv` gains a `reverted_variables` column so a workspace referee can tally the per-variable signal without parsing the warning text. - The column records what each update did *not* move, which on a converging - graph is more than the reverted variables: once EP reaches a fixed point - every message stops moving, so a healthy factor's later rows list its - variables too. The signal a referee wants is therefore a variable that is - listed on *every* row for a factor -- never once absent -- which is what + The column records the variables whose projection each update *rejected* + -- the ones `update_invalid` reverted -- not the ones whose message + happened not to move: a valid projection accepts every variable, so a + healthy factor records nothing even once it has settled. A variable listed + on *every* row for a factor was therefore never accepted, which is what `_stale_factor_warnings` reports. """ model_approx, factor_graph, prior_x, prior_y, likelihood = ( @@ -557,6 +557,42 @@ def test_partial_revert_is_recorded_in_ep_history_csv(tmp_path): ] +def test_restart_from_fixed_point_is_not_stale(tmp_path): + """ + EP restarted from its own converged `EPMeanField` reproduces every message + exactly: nothing moves, but nothing is rejected either. A fixed point is + not a rejection (PyAutoFit#1579), so no factor may be reported stale and + no history row may name a reverted variable. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + + def run(approx, name, steps): + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior: ExactFactorFit(), + likelihood: ExactFactorFit(), + }, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name=name, path_prefix=str(tmp_path)), + ) + return optimiser, optimiser.run( + approx, max_steps=steps, max_consecutive_failures=100 + ) + + _, converged = run(model_approx, "burn_in", 6) + optimiser, _ = run(converged, "fixed_point", 4) + + assert optimiser._stale_factor_warnings() == [] + + with open(optimiser.output_path / "ep_history.csv", newline="") as f: + rows = list(csv.DictReader(f)) + + assert rows + assert all(row["flag"] == StatusFlag.SUCCESS.name for row in rows) + assert all(row["reverted_variables"] == "" for row in rows) + + def test_factor_step_preserves_the_changed_mask_on_the_status(): """ `factor_step` rebuilds the `Status` it returns (to fold in caught