diff --git a/autofit/graphical/README.md b/autofit/graphical/README.md index e8b9ec225..1e13c7669 100644 --- a/autofit/graphical/README.md +++ b/autofit/graphical/README.md @@ -207,10 +207,13 @@ projection succeeds but dividing out the cavity is invalid for *some* variables (their marginal precision is below the cavity's), only those variables revert to the previous message (`update_invalid`) and the status names each of them with both precisions; the others update, so -the step is flagged `BAD_PROJECTION` but still counts as an update. A -skipped update does not count towards `max_consecutive_failures` (only -raises do), but a factor that is skipped on every sweep never updates, -and the **STALE FACTORS** warning covers that case too. +the step is flagged `BAD_PROJECTION` but still counts as an update. When +*every* variable reverts, nothing moved: that is a skipped update rather +than an update, so a factor whose projection is rejected on every sweep +is named stale instead of passing silently. A skipped update does not +count towards `max_consecutive_failures` (only raises do), but a factor +that is skipped on every sweep never updates, and the **STALE FACTORS** +warning covers that case too. The result is still returned in that state — a partly-failed graph may still hold converged messages worth having — but never quietly. If @@ -242,7 +245,8 @@ the exact 6.6 ± 2.9, inside the exact 5–95 % interval, where it used to read 2e-4 ± 0). The parent **mean** and the per-dataset variables are recovered. This is a property of projecting by the mode, not of the implementation: a hand-rolled EP with the same Gaussian family -reproduces the collapse under a Laplace projection and recovers the +reproduces the stale-factor state under a Laplace projection (every +site update rejected, the scatter returned at its prior) and recovers the closed form under moment matching (`autofit_workspace_test/scripts/graphical/analytic_ep_minimal.py`, autofit_workspace_test#91). diff --git a/autofit/graphical/mean_field.py b/autofit/graphical/mean_field.py index 697618064..572a58b9a 100755 --- a/autofit/graphical/mean_field.py +++ b/autofit/graphical/mean_field.py @@ -370,6 +370,26 @@ def update_invalid(self, other: "MeanField") -> "MeanField": def check_valid(self): return VariableData((v, m.check_valid()) for v, m in self.items()) + def check_changed(self, other: "MeanField") -> VariableData: + """ + Per variable, whether this mean field's message differs from `other`'s. + + Messages are compared on their natural parameters — the one + parameterisation every family exposes, `TransformedMessage` included, + and the one `update_invalid` copies from. The comparison is exact: + a reverted parameter is taken bit-for-bit out of the previous message, + so a tolerance would only let a genuine — if tiny — update read as no + change. A variable `other` does not carry counts as changed. + """ + changed = {} + for v, m in self.items(): + m2 = other.get(v) if other is not None else None + changed[v] = not is_message(m2) or not np.array_equal( + m.natural_parameters(), m2.natural_parameters() + ) + + return VariableData(changed) + def project_mode(self, res: OptResult): return self.from_mode_covariance(res.mode, res.hess_inv, res.log_norm) @@ -523,21 +543,28 @@ def update_factor_mean_field( ] messages += self._reverted_variable_messages(reverted, cavity_dist) factor_dist = factor_dist.update_invalid(last_dist) - # May want to check another way - # e.g. factor_dist.check_valid().sum() / factor_dist.check_valid().size - valid = factor_dist.check_valid() - if valid.any(): + # 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 = True - n_valid = valid.sum() - n_total = valid.size + n_changed = changed.sum() + n_total = changed.size logger.debug( "meanfield with variables: %r ," - "partially updated %d parameters " + "partially updated %d variables " "out of %d total, %.0%%", tuple(self.variables), - n_valid, + n_changed, n_total, - n_valid / n_total, + n_changed / n_total, + ) + else: + messages += ( + "factor update skipped: every parameter reverted", ) flag = StatusFlag.BAD_PROJECTION diff --git a/test_autofit/graphical/functionality/test_factor_failure_recovery.py b/test_autofit/graphical/functionality/test_factor_failure_recovery.py index 5acf2ac9d..ad44fade0 100644 --- a/test_autofit/graphical/functionality/test_factor_failure_recovery.py +++ b/test_autofit/graphical/functionality/test_factor_failure_recovery.py @@ -301,3 +301,103 @@ def test_nan_likelihoods_cannot_raise_the_identical_merit_exception(): assert not np.allclose(np.nan, [np.nan, np.nan]) assert "always returning `nan`" not in IDENTICAL_FIGURES_OF_MERIT_MESSAGE + + +class OverWideFit(AbstractFactorOptimiser): + """ + A factor fit that comes back wider than its cavity in every variable — the + shape a near-singular or noisy finite-difference Hessian produces. The + quotient `q* / cavity` then has negative precision, so `update_invalid` + reverts every parameter and the factor's message never moves. + """ + + def optimise(self, factor_approx, status=graph.Status()): + model_dist = graph.MeanField( + { + v: NormalMessage(float(m.mean), float(m.sigma) * 3.0) + for v, m in factor_approx.cavity_dist.items() + } + ) + return model_dist, graph.Status(success=True, messages=(), updated=True) + + +def test_fully_reverted_projection_reports_no_update(): + """ + `check_valid` after `update_invalid` is true by construction — the reverted + parameters come from a valid message — so it measured validity, not change, + and a projection that reverted everything claimed `updated=True` + (PyAutoFit#1571). + """ + x, y = Variable("x"), Variable("y") + q_star = graph.MeanField({x: NormalMessage(0.0, 2.0), y: NormalMessage(1.0, 4.0)}) + cavity = graph.MeanField({x: NormalMessage(0.0, 1.0), y: NormalMessage(1.0, 1.0)}) + last = graph.MeanField({x: NormalMessage(0.5, 3.0), y: NormalMessage(2.0, 5.0)}) + + new, status = q_star.update_factor_mean_field( + cavity_dist=cavity, + last_dist=last, + delta=1.0, + status=graph.Status(success=True, flag=StatusFlag.SUCCESS), + ) + + assert status.flag is StatusFlag.BAD_PROJECTION + assert status.updated is False + assert any("every parameter reverted" in m for m in status.messages) + for v in (x, y): + assert tuple(new[v].parameters) == tuple(last[v].parameters) + + +def test_partially_reverted_projection_still_reports_an_update(): + """ + The narrow half: only a *full* revert is a skipped update. A projection that + moves one variable and reverts another has really updated. + """ + x, y = Variable("x"), Variable("y") + # x's projection is valid (tighter than the cavity), y's is not + q_star = graph.MeanField({x: NormalMessage(0.0, 0.5), y: NormalMessage(1.0, 4.0)}) + cavity = graph.MeanField({x: NormalMessage(0.0, 1.0), y: NormalMessage(1.0, 1.0)}) + last = graph.MeanField({x: NormalMessage(0.5, 3.0), y: NormalMessage(2.0, 5.0)}) + + new, status = q_star.update_factor_mean_field( + cavity_dist=cavity, + last_dist=last, + delta=1.0, + status=graph.Status(success=True, flag=StatusFlag.SUCCESS), + ) + + assert status.updated is True + assert tuple(new[x].parameters) != tuple(last[x].parameters) + assert tuple(new[y].parameters) == tuple(last[y].parameters) + + +def test_always_reverting_factor_is_counted_as_skipped_and_warned_about(tmp_path): + """ + End to end: a factor whose projection is rejected every sweep returns its + starting message, so it belongs in `factors skipped` and must be named by + the STALE FACTORS warning — which it was not while `status.updated` came + back True. + """ + model_approx, factor_graph, prior, likelihood = make_shared_variable_approx() + (x,) = [v for v in model_approx.mean_field if v.name == "x"] + start = tuple(model_approx.factor_mean_field[likelihood][x].parameters) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={prior: ExactFactorFit(), likelihood: OverWideFit()}, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name="full_revert", path_prefix=str(tmp_path)), + ) + + result = optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + # the factor's message never moved off the one it started with + assert tuple(result.factor_mean_field[likelihood][x].parameters) == start + + assert likelihood in optimiser._factors_skipped + assert likelihood not in optimiser._factors_updated + + warnings = optimiser._stale_factor_warnings() + assert len(warnings) == 1 and likelihood.name in warnings[0] + + written = (optimiser.output_path / "ep_diagnostics.results").read_text() + assert "STALE FACTORS" in written and likelihood.name in written