diff --git a/autofit/graphical/README.md b/autofit/graphical/README.md index 1e13c7669..f5ddd44fc 100644 --- a/autofit/graphical/README.md +++ b/autofit/graphical/README.md @@ -230,6 +230,15 @@ mean field from a run that logged failures. A factor that failed intermittently but landed at least one update is not stale and is not reported. +Staleness is also reported **per variable**: a variable that reverts on +every projection while its factor's other variables move leaves the +factor "updated" and unreported at factor level, yet its own posterior is +still the message it started with — the hierarchical-scatter case of +§3.5 — so `run` names each such (factor, variable) pair in the same +**STALE FACTORS** block. `ep_history.csv` carries the raw signal as a +`reverted_variables` column, one semicolon-separated list of the +variables each update did not move. + ### 3.5 Caveat — a hierarchical *scatter* cannot be projected by its mode For a hierarchical factor `N(xᵢ | μ, σ)` the tilted density in `σ` is diff --git a/autofit/graphical/expectation_propagation/diagnostics.py b/autofit/graphical/expectation_propagation/diagnostics.py index 5279db116..9bad2b849 100644 --- a/autofit/graphical/expectation_propagation/diagnostics.py +++ b/autofit/graphical/expectation_propagation/diagnostics.py @@ -25,7 +25,8 @@ are enabled: - ``ep_history.csv`` — one row per factor update: - ``step, factor, success, updated, flag, log_evidence, kl_divergence`` + ``step, factor, success, updated, flag, log_evidence, kl_divergence, + reverted_variables`` - ``mean_field_history.csv`` — one row per (factor update, variable): ``step, factor, variable, mean, std`` - ``mean_field_evolution.png`` — per-variable mean ± std vs update. @@ -138,6 +139,21 @@ 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. + if status.changed is not None: + reverted_variables = ";".join( + sorted( + variable.name + for variable, changed in status.changed.items() + if not changed + ) + ) + else: + reverted_variables = "" + self.factor_rows.append( { "step": self._step, @@ -147,6 +163,7 @@ def snapshot(self, factor, model_approx, status) -> None: "flag": status.flag.name, "log_evidence": log_evidence, "kl_divergence": kl, + "reverted_variables": reverted_variables, } ) diff --git a/autofit/graphical/expectation_propagation/optimiser.py b/autofit/graphical/expectation_propagation/optimiser.py index bce06d5cd..9544caccf 100644 --- a/autofit/graphical/expectation_propagation/optimiser.py +++ b/autofit/graphical/expectation_propagation/optimiser.py @@ -146,6 +146,7 @@ def factor_step(factor_approx, optimiser, model_approx=None): updated=status.updated, flag=status.flag, result=status.result, + changed=status.changed, ) except ( @@ -167,6 +168,7 @@ def factor_step(factor_approx, optimiser, model_approx=None): messages=(f"Factor: {factor} experienced error {e}",), updated=False, flag=StatusFlag.EXCEPTION, + changed=None, ) new_model_dist = factor_approx.model_dist @@ -249,6 +251,25 @@ def __init__( self._factors_raised: Set[Factor] = set() self._factors_skipped: Set[Factor] = set() self._factors_updated: Set[Factor] = set() + # The same question one level down: per factor, which of its variables + # were ever compared, and which of them ever moved. A variable in + # `seen` but never in `changed` reverted on every projection, so the + # posterior reported for it is the message it started with — even when + # the factor as a whole updated. See `_stale_factor_warnings`. + # + # Keyed by factor *name*, not factor: a `HierarchicalFactor` decomposes + # into one `_HierarchicalFactor` per drawn variable, each constructed + # with `name=distribution_model.name`, so the members of one logical + # factor share a name and nothing else does (`namer` gives distinct + # factors distinct names). Keying by name is therefore the parent + # identity, without the EP core having to know about the declarative + # layer — and a variable is stale for the group only if *no* member + # ever moved it. + self._variables_seen: Dict[str, set] = {} + self._variables_changed: Dict[str, set] = {} + # How many updates carried a per-variable mask for each group — the + # denominator the per-variable warning quotes. + self._factor_sweeps: Dict[str, int] = {} self.visualiser = None if paths is None: @@ -371,6 +392,20 @@ def _check_consecutive_failures( True if this factor has now failed enough consecutive sweeps that the 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. + if status.changed is not None: + group = factor.name + self._variables_seen.setdefault(group, set()).update(status.changed.keys()) + self._variables_changed.setdefault(group, set()).update( + variable for variable, changed in status.changed.items() if changed + ) + self._factor_sweeps[group] = self._factor_sweeps.get(group, 0) + 1 + if raised: self._factors_raised.add(factor) count = self._consecutive_failures.get(factor, 0) + 1 @@ -426,22 +461,61 @@ def _stale_factor_warnings(self) -> List[str]: update was skipped (failed line search, bad projection), at least once and *never once* updated. A factor that failed intermittently but landed at least one update has a real message and is not reported. + + The factor-level test cannot see a *partial* revert. On a hierarchical + graph every projection may be `BAD_PROJECTION` with one variable — the + parent scatter — reverted in each one, while the factor's mean and its + per-dataset variables update: the factor counts as updated, so no line + is emitted, yet the scatter's reported posterior is the hyper-prior it + started with. That is the #1405 stale-scatter state this warning exists + to catch, so a second pass reports every (factor, variable) pair whose + variable never once changed. + + That pass works on *groups*, not individual factors: a + `HierarchicalFactor` decomposes into one factor per drawn variable, all + sharing its name, and the parent scatter's message is the product of + every member's. One member moving it is enough for the reported + posterior to be a posterior, so a variable is only named when no member + of its group ever moved it. A group is skipped only when every one of + its factors is already named at factor level above. """ stale = (self._factors_raised | self._factors_skipped) - self._factors_updated - if not stale: - return [] - - names = ", ".join(sorted(factor.name for factor in stale)) - return [ - f"STALE FACTORS: {names} never completed a single update — their " - f"optimisers raised or their updates were skipped on every sweep. " - f"The mean field returned for " - f"them is the prior the fit started with, not a posterior. Do not " - f"read those values as a result. Note that EP may also report " - f"convergence in this state: with no factor updating, the KL step " - f"between sweeps is zero, which is indistinguishable from having " - f"converged." - ] + + warnings = [] + if stale: + names = ", ".join(sorted(factor.name for factor in stale)) + warnings.append( + f"STALE FACTORS: {names} never completed a single update — their " + f"optimisers raised or their updates were skipped on every sweep. " + f"The mean field returned for " + f"them is the prior the fit started with, not a posterior. Do not " + f"read those values as a result. Note that EP may also report " + f"convergence in this state: with no factor updating, the KL step " + f"between sweeps is zero, which is indistinguishable from having " + f"converged." + ) + + for group in sorted(self._variables_seen): + members = { + factor for factor in self.factor_optimisers if factor.name == group + } + if members and members <= stale: + # Every factor in the group is already reported at factor + # level; naming each of its variables again only repeats it. + continue + stale_variables = self._variables_seen[group] - self._variables_changed.get( + group, set() + ) + n_updates = self._factor_sweeps.get(group, 0) + for variable in sorted(stale_variables, key=lambda v: v.name): + warnings.append( + f"STALE FACTORS: variable '{variable.name}' of {group} " + f"never changed across {n_updates} updates (reverted on " + f"every projection of that factor); its reported posterior " + f"is the message it started with" + ) + + return warnings def _warn_stale_factors(self): """ @@ -499,6 +573,9 @@ def run( self._factors_raised = set() self._factors_skipped = set() self._factors_updated = set() + self._variables_seen = {} + self._variables_changed = {} + self._factor_sweeps = {} for _ in range(max_steps): _should_log = should_log() @@ -685,6 +762,9 @@ def run( self._factors_raised = set() self._factors_skipped = set() self._factors_updated = set() + self._variables_seen = {} + self._variables_changed = {} + self._factor_sweeps = {} for _ in range(max_steps): _should_log = should_log() diff --git a/autofit/graphical/mean_field.py b/autofit/graphical/mean_field.py index 572a58b9a..00c1fb765 100755 --- a/autofit/graphical/mean_field.py +++ b/autofit/graphical/mean_field.py @@ -501,6 +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. + changed = None if not status.success and last_dist is not None: # The optimiser did not succeed (failed line search, bad Hessian, # exception): keep the previous message rather than projecting a @@ -514,6 +521,7 @@ def update_factor_mean_field( updated=False, flag=flag, result=status.result, + changed=status.changed, ), ) try: @@ -570,6 +578,11 @@ 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 + ) except exc.MessageException as e: logger.exception(e) @@ -583,6 +596,7 @@ def update_factor_mean_field( updated=updated, flag=flag, result=status.result, + changed=changed, ), ) diff --git a/autofit/graphical/utils.py b/autofit/graphical/utils.py index cd1675d0d..7f7772a3a 100644 --- a/autofit/graphical/utils.py +++ b/autofit/graphical/utils.py @@ -283,6 +283,7 @@ class Status: updated: bool = True flag: StatusFlag = StatusFlag.SUCCESS result: Optional[Result] = None + changed: Optional[VariableData] = None def __init__( self, @@ -291,14 +292,33 @@ def __init__( updated: bool = True, flag: StatusFlag = StatusFlag.SUCCESS, result: Optional[Result] = None, + changed: Optional[VariableData] = None, ): + """ + 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); + 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. + """ self.success = success self.messages = messages self.updated = updated self.flag = flag self.result = result + self.changed = changed def __iter__(self): + # `changed` is deliberately absent: the 4-tuple unpack in + # `MeanField.update_factor_mean_field` depends on this arity. return iter((self.success, self.messages, self.updated, self.flag)) def __bool__(self): @@ -318,6 +338,7 @@ def _asdict(self): messages=self.messages, updated=self.updated, flag=self.flag, + changed=self.changed, ) diff --git a/test_autofit/graphical/functionality/test_diagnostics.py b/test_autofit/graphical/functionality/test_diagnostics.py index 57b5f90a8..14c9b3f34 100644 --- a/test_autofit/graphical/functionality/test_diagnostics.py +++ b/test_autofit/graphical/functionality/test_diagnostics.py @@ -41,6 +41,7 @@ def test_snapshot_records_rows(): "flag", "log_evidence", "kl_divergence", + "reverted_variables", } for row in factor_rows: assert set(row.keys()) == expected_columns @@ -85,6 +86,7 @@ def test_csv_outputs_written(tmp_path): "flag", "log_evidence", "kl_divergence", + "reverted_variables", ] ep_rows = list(reader) assert len(ep_rows) == len(opt.diagnostics.factor_rows) diff --git a/test_autofit/graphical/functionality/test_factor_failure_recovery.py b/test_autofit/graphical/functionality/test_factor_failure_recovery.py index ad44fade0..90674fa43 100644 --- a/test_autofit/graphical/functionality/test_factor_failure_recovery.py +++ b/test_autofit/graphical/functionality/test_factor_failure_recovery.py @@ -12,6 +12,7 @@ one shared variable, no `HierarchicalFactor` involved. """ +import csv import logging import numpy as np @@ -401,3 +402,266 @@ def test_always_reverting_factor_is_counted_as_skipped_and_warned_about(tmp_path written = (optimiser.output_path / "ep_diagnostics.results").read_text() assert "STALE FACTORS" in written and likelihood.name in written + + +def make_two_variable_approx(): + """ + Two variables joined by one factor, each with its own prior — the smallest + graph on which a factor can revert *one* of its variables on every + projection while the other updates (the partial revert of PyAutoFit#1575). + """ + x, y = Variable("x"), Variable("y") + + def joint(x, y): + return -0.5 * (np.sum((x - 3.0) ** 2) + np.sum((y - 2.0) ** 2)) + + prior_x = NormalMessage(1.0, 2.0).as_factor(x, name="prior_x") + prior_y = NormalMessage(1.0, 2.0).as_factor(y, name="prior_y") + likelihood = graph.Factor(joint, x, y, name="like_xy") + + factor_graph = graph.FactorGraph([prior_x, prior_y, likelihood]) + model_approx = graph.EPMeanField.from_approx_dists( + factor_graph, + {x: NormalMessage(0.0, 10.0), y: NormalMessage(0.0, 10.0)}, + ) + return model_approx, factor_graph, prior_x, prior_y, likelihood + + +class PartialRevertFit(AbstractFactorOptimiser): + """ + A factor fit that is valid in one variable and over-wide in another, on + every sweep: the quotient `q* / cavity` has positive precision for the + first (so it updates) and negative precision for the second (so + `update_invalid` reverts every one of its parameters and its message never + moves). This is the hierarchical scatter's shape — the factor updates, one + of its variables never does. + """ + + def __init__(self, reverting: str): + super().__init__() + self.reverting = reverting + + def optimise(self, factor_approx, status=graph.Status()): + model_dist = graph.MeanField( + { + v: NormalMessage( + float(m.mean), + float(m.sigma) * (3.0 if v.name == self.reverting else 0.5), + ) + for v, m in factor_approx.cavity_dist.items() + } + ) + return model_dist, graph.Status(success=True, messages=(), updated=True) + + +def test_partial_revert_names_the_stale_variable_not_the_factor(tmp_path): + """ + The gap #1574 left. A factor that reverts one variable on every projection + and updates the others is `updated`, so no factor-level STALE FACTORS line + is emitted — yet the reverted variable's reported posterior is the message + it started with. The warning must name the (factor, variable) pair. + """ + model_approx, factor_graph, prior_x, prior_y, likelihood = ( + make_two_variable_approx() + ) + (y,) = [v for v in model_approx.mean_field if v.name == "y"] + start = tuple(model_approx.factor_mean_field[likelihood][y].parameters) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name="partial_revert", path_prefix=str(tmp_path)), + ) + + result = optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + # the factor did update -- so the factor-level test cannot see this + assert likelihood in optimiser._factors_updated + + # ... but y's message never moved off the one it started with + assert tuple(result.factor_mean_field[likelihood][y].parameters) == start + + assert optimiser._variables_seen[likelihood.name] == { + v for v in likelihood.variables + } + assert y not in optimiser._variables_changed[likelihood.name] + + warnings = optimiser._stale_factor_warnings() + y_lines = [w for w in warnings if "variable 'y'" in w] + assert len(y_lines) == 1 + assert "STALE FACTORS" in y_lines[0] + assert likelihood.name in y_lines[0] + assert not [w for w in warnings if "variable 'x'" in w] + + diagnostics = (optimiser.output_path / "ep_diagnostics.results").read_text() + assert "WARNINGS" in diagnostics + assert y_lines[0] in diagnostics + + +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 + `_stale_factor_warnings` reports. + """ + model_approx, factor_graph, prior_x, prior_y, likelihood = ( + make_two_variable_approx() + ) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers={ + prior_x: ExactFactorFit(), + prior_y: ExactFactorFit(), + likelihood: PartialRevertFit(reverting="y"), + }, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name="partial_revert_csv", path_prefix=str(tmp_path)), + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + + with open(optimiser.output_path / "ep_history.csv", newline="") as f: + rows = list(csv.DictReader(f)) + + assert "reverted_variables" in rows[0] + + reverting_rows = [row for row in rows if row["factor"] == likelihood.name] + assert reverting_rows + # y is reverted on every one of the factor's projections ... + assert all( + "y" in row["reverted_variables"].split(";") for row in reverting_rows + ) + # ... and on the first sweep, before the graph settles, it is the only one: + # x moved on that same projection, which is the partial revert the + # factor-level `updated` flag cannot express. + assert reverting_rows[0]["reverted_variables"] == "y" + + exact_rows = [row for row in rows if row["factor"] == prior_x.name] + assert exact_rows + # an exact fit that moves its message records nothing as unmoved + assert exact_rows[0]["reverted_variables"] == "" + # and x is not stale: it moved at least once, so no warning names it + assert not [ + w for w in optimiser._stale_factor_warnings() if "variable 'x'" in w + ] + + +def test_factor_step_preserves_the_changed_mask_on_the_status(): + """ + `factor_step` rebuilds the `Status` it returns (to fold in caught + warnings), so every field it does not name is silently dropped. The + per-variable mask has to survive that reconstruction or the optimiser's + bookkeeping never sees it. + """ + from autofit.graphical.expectation_propagation.optimiser import factor_step + from autofit.mapper.variable import VariableData + + model_approx, _, prior_x, _, _ = make_two_variable_approx() + (x,) = [v for v in model_approx.mean_field if v.name == "x"] + mask = VariableData({x: False}) + + class MaskCarryingFit(AbstractFactorOptimiser): + def optimise(self, factor_approx, status=graph.Status()): + return factor_approx.model_dist, graph.Status( + success=True, updated=True, changed=mask + ) + + _, status = factor_step( + model_approx.factor_approximation(prior_x), MaskCarryingFit() + ) + + assert status.changed is mask + + +def _grouped_optimiser(tmp_path, name, reverting_first, reverting_second): + """ + A graph with two factors that share one name, each joined to the same + shared variable `s` and to its own drawn variable — the shape a + `HierarchicalFactor` takes once it decomposes into one factor per drawn + variable (each member built with `name=distribution_model.name`, `s` + standing in for the parent scatter). Each member gets a + `PartialRevertFit`, so the test controls exactly which variable it moves; + a `reverting` name matching nothing means the member moves everything. + """ + s, x1, x2 = Variable("s"), Variable("x1"), Variable("x2") + + def first_density(s, x1): + return -0.5 * (np.sum((s - 2.0) ** 2) + np.sum((x1 - 3.0) ** 2)) + + def second_density(s, x2): + return -0.5 * (np.sum((s - 2.0) ** 2) + np.sum((x2 - 3.0) ** 2)) + + priors = [ + NormalMessage(1.0, 2.0).as_factor(v, name=f"prior_{v.name}") + for v in (s, x1, x2) + ] + # distinct functions, so the two factors are distinct objects (`Factor` + # equality is on the function and its arguments) that nonetheless share a + # name, exactly as a decomposed hierarchical factor's members do + first = graph.Factor(first_density, s, x1, name=name) + second = graph.Factor(second_density, s, x2, name=name) + + factor_graph = graph.FactorGraph(priors + [first, second]) + model_approx = graph.EPMeanField.from_approx_dists( + factor_graph, + {v: NormalMessage(0.0, 10.0) for v in (s, x1, x2)}, + ) + + optimisers = {prior: ExactFactorFit() for prior in priors} + optimisers[first] = PartialRevertFit(reverting=reverting_first) + optimisers[second] = PartialRevertFit(reverting=reverting_second) + + optimiser = graph.EPOptimiser( + factor_graph, + factor_optimisers=optimisers, + ep_history=EPHistory(kl_tol=None), + paths=DirectoryPaths(name=f"group_{name}", path_prefix=str(tmp_path)), + ) + optimiser.run(model_approx, max_steps=4, max_consecutive_failures=100) + return optimiser + + +def test_one_member_of_a_group_moving_a_variable_clears_the_group(tmp_path): + """ + A `HierarchicalFactor` decomposes into one factor per drawn variable, all + sharing its name, and the parent scatter's message is the product of every + member's. One member moving it is enough for the reported value to be a + posterior, so the pair must be tracked per group, not per member — + otherwise every healthy hierarchical run is flagged. + """ + optimiser = _grouped_optimiser( + tmp_path, "group_mixed", reverting_first="s", reverting_second="none" + ) + + # the first member reverts the shared variable on every projection; the + # second moves it, so the group's message for it is a posterior + warnings = optimiser._stale_factor_warnings() + assert warnings == [] + + +def test_a_group_no_member_of_which_moves_a_variable_is_named_once(tmp_path): + """ + The other half: when *no* member of the group ever moves the variable, its + posterior really is the message it started with — one line, naming the + group, not one line per member. + """ + optimiser = _grouped_optimiser( + tmp_path, "group_stale", reverting_first="s", reverting_second="s" + ) + + warnings = optimiser._stale_factor_warnings() + assert len(warnings) == 1 + assert "STALE FACTORS" in warnings[0] + assert "variable 's' of group_stale" in warnings[0] + assert "updates (reverted on every projection of that factor)" in warnings[0]