Skip to content

feat(ep): report staleness per (factor, variable) and record reverted variables in ep_history.csv #1575

Closed

Description

@Jammy2211

Overview

PyAutoFit#1574 made a fully reverted EP projection count as skipped, so a factor whose message never moves is named by the STALE FACTORS warning. It cannot name a partial revert: on the phase-2 campaign graph every hierarchical projection is BAD_PROJECTION with the sigma variable reverted in each one (its message stays bit-identical, the reported E[sigma] never leaves the hyper-prior mean), while the factor's mean and per-dataset variables update. The factor therefore counts as "updated", no STALE FACTORS line appears — and that is exactly the #1405 stale-scatter state the warning exists to catch.

This task tracks staleness per (factor, variable) pair rather than per factor, and records the reverted variables in ep_history.csv so the workspace referee scripts can read the signal directly.

Epic: graphical-ep. Umbrella: #1405. Follows #1574.

Plan

  • Carry the per-variable changed mask on Status so it survives every reconstruction of the status object through the EP call chain.
  • Compute that mask on both branches of MeanField.update_factor_mean_field (valid and invalid projection), not only in the fix(ep): a fully reverted projection counts as skipped, not updated #1574 invalid-branch logic.
  • Accumulate, per factor and across sweeps, the set of variables seen and the set of variables that ever changed — in both the serial and parallel EP optimisers.
  • Extend _stale_factor_warnings to emit one STALE FACTORS line per (factor, variable) pair that never changed, for factors not already reported stale at factor level.
  • Add a reverted_variables column to ep_history.csv, and document the per-variable reporting in the graphical README.
Detailed implementation plan

Work Classification

Both (library first, workspace follow-up once the API impact is known).

Affected Repositories

  • PyAutoFit (primary)
  • autofit_workspace_test

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main (4e6a160) clean
./autofit_workspace_test main (a48344f) clean

Suggested branch: feature/ep-stale-tracking-per-variable
Worktree root: ~/Code/PyAutoLabs-wt/ep-stale-tracking-per-variable/

Implementation Steps

  1. Status (autofit/graphical/utils.py:280-321, a plain class): add a keyword field changed: Optional[VariableData] = None after result. Do not add it to __iter__ — the 4-tuple unpack at autofit/graphical/mean_field.py:502 depends on the current arity — but do include it in _asdict. Thread changed=status.changed through every Status reconstruction: autofit/graphical/expectation_propagation/optimiser.py:143-149 and :165-170, autofit/graphical/mean_field.py:508-516 and :580-586.

  2. MeanField.update_factor_mean_field (autofit/graphical/mean_field.py:457-587): compute changed = factor_dist.check_changed(last_dist) (existing helper at :373-391) once, before the is_valid split, guarded when last_dist is None (then changed = None). The invalid branch keeps its fix(ep): a fully reverted projection counts as skipped, not updated #1574 logic, now using this mask; the valid branch (:571-572) returns it on the Status as well.

  3. EPOptimiser (autofit/graphical/expectation_propagation/optimiser.py): add _variables_seen: Dict[Factor, set] and _variables_changed: Dict[Factor, set] beside the existing stale sets (:245-251); reset both in EPOptimiser.run (:498-501) and ParallelEPOptimiser.run (:684-687); update both in _check_consecutive_failures (:337-406, beside the status.updated bookkeeping) — when status.changed is not None, seen |= set(changed.keys()) and changed_set |= {v for v, c in changed.items() if c}.

  4. _stale_factor_warnings (:409-444): after the existing factor-level lines, for each factor with stale_vars = seen - changed (only for factors not already named stale at factor level, to avoid double reporting), emit one line per variable sorted by v.name:
    STALE FACTORS: variable '<v.name>' of <factor.name> never changed across <n_sweeps> sweeps (reverted on every projection); its reported posterior is the message it started with
    Keep the literal STALE FACTORS token. These reach the log and ep_diagnostics.results through _output_diagnostics (:556-579) with no further change.

  5. autofit/graphical/expectation_propagation/diagnostics.py snapshot (:139-148): new row key reverted_variables = ";".join(sorted(v.name for v, c in status.changed.items() if not c)) when status.changed is not None, else "". Update the module docstring column list (:26-32) and the two pinned column lists in test_autofit/graphical/functionality/test_diagnostics.py:36-45 and :80-88.

  6. Tests in test_autofit/graphical/functionality/test_factor_failure_recovery.py (reusing make_shared_variable_approx :33-46 and OverWideFit :306-322):

    • a PartialRevertFit optimiser giving a valid projection for x and an over-wide one for y on every sweep; run EPOptimiser for 4 sweeps and assert the factor is in optimiser._factors_updated, that _stale_factor_warnings() contains a STALE FACTORS line naming y and none naming x, and that the written ep_diagnostics.results contains it;
    • ep_history.csv rows for that factor carry reverted_variables == "y" on every step, and the exact factor's rows carry "";
    • Status(changed=...) survives factor_step's reconstruction (unit test at the optimiser.py:143-149 site or the smallest equivalent).
      Leave every fix(ep): a fully reverted projection counts as skipped, not updated #1574 test untouched.
  7. autofit/graphical/README.md STALE FACTORS paragraph (~207-216): one sentence that staleness is also reported per variable (a variable that reverts on every projection while its factor's other variables move), and that ep_history.csv carries a reverted_variables column.

Testing

  • python -m pytest test_autofit/graphical -q (270 currently, plus the new tests)
  • python -m pytest test_autofit/messages -q (95)
  • Workspace referees from autofit_workspace_test against the worktree autofit: scripts/graphical/ep_deterministic.py (must PASS) and scripts/graphical/analytic_gaussian_collapse.py (report the per-seed table, the classification line, and each seed's ep_diagnostics.results WARNINGS block — the new per-variable lines are expected on some seeds; report, do not tune).

Workspace follow-up (after the library PR)

The STALE classification in autofit_workspace_test/scripts/graphical/analytic_gaussian_collapse.py should read the new per-variable flag rather than "no SUCCESS on the HierarchicalFactor".

Key Files

  • autofit/graphical/utils.py — Status
  • autofit/graphical/mean_field.py — update_factor_mean_field, check_changed
  • autofit/graphical/expectation_propagation/optimiser.py — EPOptimiser, _check_consecutive_failures, _stale_factor_warnings
  • autofit/graphical/expectation_propagation/diagnostics.py — snapshot, ep_history.csv columns
  • test_autofit/graphical/functionality/test_factor_failure_recovery.py, test_diagnostics.py
  • autofit/graphical/README.md

Original Prompt

Click to expand starting prompt
# Track EP staleness per (factor, variable), not per factor

Type: feature
Target: PyAutoFit
Repos:
- PyAutoFit
- autofit_workspace_test
Themes:
- graphical-ep
Difficulty: medium
Autonomy: supervised
Priority: medium
Status: formalised
Consequence: judge
Witness: the phase-2 campaign graph (N=2, `TruncatedGaussianPrior(10, 0.5, 0, 100)` on sigma, Laplace) names the sigma variable as stale in `ep_diagnostics.results` when its message never moves while the factor's other variables update
Review-minutes: 10
Unattended: needs-slicing
Epic: graphical-ep
Filed: 2026-09-07

Follow-up to `complete/2026/09/ep-full-revert-not-updated.md` (PyAutoFit#1574, finding 2 of the Codex review of
the phase-2 fixes). That fix makes a *fully* reverted projection count as skipped. It cannot name a
*partial* revert: on the campaign graph every hierarchical projection is `BAD_PROJECTION` with the
sigma variable reverted in each one (its message stays `[10.0, 0.7071]` bit-identical, the reported
E[sigma] never leaves the hyper-prior mean), while the factor's mean and per-dataset variables
update — so the factor is "updated" and no STALE FACTORS line appears, which is exactly the #1405
stale-scatter state the warning exists to catch.

Human decided 2026-09-07: the diagnostics lever (per-variable tracking) goes ahead now; the
moment-matching projection cure stays its own prompt.

## Scope

- `EPOptimiser.factor_step` / `_stale_factor_warnings`
  (`autofit/graphical/expectation_propagation/optimiser.py:399-430`): track which *variables* of
  each factor changed on each sweep (the per-variable `changed` mask the bug fix introduces in
  `MeanField.update_factor_mean_field`), and warn on any (factor, variable) pair that never
  changed once — "HierarchicalFactor: variable `sigma` never completed a single update".
- `ep_history.csv` gains a per-variable column or a `reverted_variables` field so the referee
  scripts (`autofit_workspace_test/scripts/graphical/analytic_gaussian_collapse.py`) can tally it.
- The STALE classification in `analytic_gaussian_collapse.py` should then read the per-variable
  flag rather than "no SUCCESS on the HierarchicalFactor".

A prototype tracker exists from the 2026-09-07 verification session (scratch only). Gated by the
campaign's EP-internals check-in like the moment-matching cure
(`ep_hierarchical_scatter_moment_matching.md`); the human decides whether the diagnostics or the
projection is the right lever.

Activity

  1. Jammy2211 commented on Sep 7, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    API-change summary: Status(changed=...) new optional keyword (not in Status.__iter__, so the existing 4-tuple unpack is unchanged); ep_history.csv gains a trailing reverted_variables column. No removals or renames.

    Design revision during implementation. Pairs are keyed by factor name, not by factor object: 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. A variable is named stale only when no member of the group ever moved it. Keying per factor object flagged 3–4 of the 5 members on all five referee seeds, including the four healthy RECOVER ones; keying per group flags none of them, because at least one member moves sigma on every seed (seed 0 has SUCCESS=1).

    Tests: test_autofit/graphical 275 passed, test_autofit/messages 95 passed, full test_autofit/ 2469 passed / 2 skipped. Workspace referees against the branch: ep_deterministic.py PASS; analytic_gaussian_collapse.py COLLAPSE CONFIG: PASS (5/5 seeds), RECOVER 5/5 ... inside [q05, q95] on 5/5 seeds.

    Heart at ship time: YELLOW — "workspace validation not passing (5 failed, 2 timeout, cloud#34099198772: autolens notebooks/multi_dataset/modeling.ipynb, autolens scripts/multi_dataset/modeling.py, autolens_test scripts/imaging/delaunay.py, +4 more)", plus the stale "release validation incomplete: no rehearsal for current source". Organism-scope; nothing in this branch touches those scripts.

    Workspace impact: ep_history.csv gains a column — analytic_autofit.py reads that CSV by column name, so it is unaffected. The analytic_gaussian_collapse.py STALE classification reading the new per-variable signal ships as the workspace half of this task.

    Next: /start_workspace (autofit_workspace_test).

  2. Jammy2211 commented on Sep 7, 2026

    @Jammy2211
    CollaboratorAuthor

    Workspace PR Created

    Library-first gate: PR #98 merges only after PyAutoFit#1576 — the reverted_variables column it reads is added there. Against an older library the script treats the missing column as no information and behaves exactly as before, so the ordering is a correctness preference, not a hard break.

    What changed: scripts/graphical/analytic_gaussian_collapse.py — the STALE label now also fires when the scatter variable is listed in reverted_variables on every HierarchicalFactor row of the run (a fixed point lists every variable, so "on every row" is the correct test, not "on any row"); a new sig-rev column prints reverted-rows / HierarchicalFactor-rows per seed; the module docstring taxonomy is updated. The documented test (the STALE FACTORS token) is unchanged.

    Validation: autofit_workspace_test is not a key in PyAutoHeart's smoke workspace table (PyAutoHeart/config/repos.yaml → smoke.workspaces), so pyauto-heart smoke cannot target it; the repo's own PR gate, .github/scripts/run_smoke.py, was run instead — the same shared autohands/run_python.py entry point CI uses — and passed 14/14 under the smoke profile, graphical/analytic_gaussian_collapse.py included (it is curated at line 14 of smoke_tests.txt).

    Referee against the library branch: COLLAPSE CONFIG: PASS (5/5 seeds); RECOVER 5/5, STALE 0/5, library warning 0/5. sig-rev reads 8/10, 10/14, 9/14, 6/11, 8/13 — sigma reverts on 55–71 % of hierarchical rows on these healthy seeds and never on all of them, which is why no seed reads STALE and the verdict is unchanged.

    Heart at ship time: unchanged from the library half — YELLOW, same two reasons, organism-scope.

    Both halves are now open. /prm is the close-out door: merge PyAutoFit#1576 first, then autofit_workspace_test#98.

  3. Jammy2211 commented on Sep 7, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Merged both halves of this task.

    Repo PR Head Merge commit
    PyAutoFit #1576 9b2429f9 2680b32d
    autofit_workspace_test PyAutoLabs/autofit_workspace_test#98 8184d046 7050ac3b

    Library merged first, then the workspace half (library-first gate).

    CI — PyAutoFit Tests [pull_request] 3.12 / 3.13 / nojax + Docs: green.
    autofit_workspace_test Smoke Tests [pull_request] changes / 3.12 / 3.13: green.
    Both PRs CLEAN.

    Files changed

    PyAutoFit (7 files, +422/-15):

    • autofit/graphical/utils.py — Status.changed carries the per-variable changed mask
    • autofit/graphical/mean_field.py — mask computed in MeanField.update_factor_mean_field on both branches, after update_invalid
    • autofit/graphical/expectation_propagation/optimiser.py — EPOptimiser accumulates seen / changed variables per factor name across sweeps (serial and parallel); _stale_factor_warnings names every (factor, variable) pair no member of the group ever moved
    • autofit/graphical/expectation_propagation/diagnostics.py — ep_history.csv gains reverted_variables
    • autofit/graphical/README.md, test_autofit/graphical/functionality/test_diagnostics.py, test_autofit/graphical/functionality/test_factor_failure_recovery.py (new, 264 lines)

    autofit_workspace_test (1 file, +51/-10):

    • scripts/graphical/analytic_gaussian_collapse.py — referee reads reverted_variables; STALE also when the scatter is reverted on every HierarchicalFactor row; new sig-rev column

    Verdict — per-variable stale tracking lands, keyed by factor name. The first cut keyed pairs by factor object and flagged all five referee seeds: a HierarchicalFactor decomposes into per-dataset sub-factors sharing a name, and a few members never move sigma even when the aggregate is healthy. Grouping by name clears the healthy seeds (sig-rev 8/10, 10/14, 9/14, 6/11, 8/13 — never n/n) while still catching a group that never moves it. The STALE FACTORS token is kept.

    Referee: RECOVER 5/5, STALE 0/5, warnings (none) on every seed, σ/μ identical to the phase-2 record. PyAutoFit graphical 275 / messages 95 / full suite 2469 passed; workspace smoke gate 14/14.

    Second half of the Codex phase-2 review finding 2 (after PyAutoFit#1574), epic graphical-ep, umbrella #1405.

    Remaining, not part of this task: the campaign's N=2 witness configuration (TruncatedGaussian(10, 0.5, 0, 100) on sigma) is expected to drive sig-rev to n/n and be named — not run as a curated script. The moment-matching projection cure stays filed at draft/feature/autofit/ep_hierarchical_scatter_moment_matching.md.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions