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
9 changes: 9 additions & 0 deletions autofit/graphical/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 18 additions & 1 deletion autofit/graphical/expectation_propagation/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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,
}
)

Expand Down
108 changes: 94 additions & 14 deletions autofit/graphical/expectation_propagation/optimiser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
14 changes: 14 additions & 0 deletions autofit/graphical/mean_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -514,6 +521,7 @@ def update_factor_mean_field(
updated=False,
flag=flag,
result=status.result,
changed=status.changed,
),
)
try:
Expand Down Expand Up @@ -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)
Expand All @@ -583,6 +596,7 @@ def update_factor_mean_field(
updated=updated,
flag=flag,
result=status.result,
changed=changed,
),
)

Expand Down
21 changes: 21 additions & 0 deletions autofit/graphical/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ class Status:
updated: bool = True
flag: StatusFlag = StatusFlag.SUCCESS
result: Optional[Result] = None
changed: Optional[VariableData] = None

def __init__(
self,
Expand All @@ -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):
Expand All @@ -318,6 +338,7 @@ def _asdict(self):
messages=self.messages,
updated=self.updated,
flag=self.flag,
changed=self.changed,
)


Expand Down
2 changes: 2 additions & 0 deletions test_autofit/graphical/functionality/test_diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading