Skip to content

Add the EP factor-graph diagnostic figure (af.EPPlotter, graph_state.png) (#1618) - #1619

Merged
Jammy2211 merged 6 commits into
mainfrom
feature/model-figures-ep-view
Sep 13, 2026
Merged

Jammy2211 merged 6 commits into
mainfrom
feature/model-figures-ep-view

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Summary

Gives an expectation-propagation run a picture of itself. The model-figure
machinery now has an ep/ layer that turns a FactorGraphModel (and, once a
run is under way, its EPMeanField approximation) into a factor-graph diagram:
factors, variables, the edges between them, and — on the state overlay — what
the run has done to each factor so far (updated, stale, reverted).

  • af.EPPlotter is the public door: point it at a factor graph, optionally at a
    mean-field approximation, and save a PNG.
  • Visualise now writes those figures into a fit's output directory: a static
    graph_model.png once at the start of the run, and graph_state.png
    refreshed on each visualise_interval tick. Both are gated by the existing
    output.yaml model_figure key, so nothing changes for users who leave it
    off.
  • The model_figure gate itself moved out of non_linear/paths/directory.py
    into autofit/model_figure/config.py, so the EP path and the samples path
    read one implementation.
  • docs/features/graphical.md gains a "Seeing the EP run" section with three
    rendered figures, built by docs/images/model_figures/make_figures.py.

API Changes

Additive only — nothing removed, renamed, or made required.

  • New public class af.EPPlotter, plus the autofit.model_figure exports
    behind it (autofit.model_figure.ep).
  • Visualise.__init__ gains an optional factor_graph=None, and
    Visualise.__call__ an optional model_approx=None. Existing call sites keep
    working unchanged.
  • _model_figure_enabled in autofit/non_linear/paths/directory.py is now an
    alias of autofit.model_figure.config.model_figure_enabled — same behaviour,
    one implementation.

See full details below.

Test Plan

  • python -m pytest test_autofit/ -x — 2843 passed, 2 skipped
  • New acceptance/unit coverage: test_autofit/model_figure/ep/
    (spec, state, presentation, layout, determinism, acceptance) and
    test_autofit/.../functionality/test_ep_visualise_output.py (the
    graph_model.png / graph_state.png output contract)
  • Sphinx build: 30 warnings == baseline
  • black and pyflakes clean on the touched files
  • Reviewer: open docs/features/graphical.md → "Seeing the EP run" and
    check the three figures read correctly
Full API Changes (for automation & release notes)

Removed

  • None.

Renamed

  • None.

Added

  • af.EPPlotter(factor_graph, model_approx=None, ...) — renders an EP factor
    graph to a PNG; the public entry point for the EP figure.
  • autofit.model_figure.ep — the supporting layer (spec, state,
    presentation, layout, render, plotter).
  • autofit.model_figure.config.model_figure_enabled() — the single
    output.yaml model_figure gate.

Changed Signature

  • Visualise.__init__(..., factor_graph=None) — new optional keyword.
  • Visualise.__call__(..., model_approx=None) — new optional keyword.

Changed Behaviour

  • With model_figure enabled in output.yaml, an EP fit now writes
    graph_model.png once at the start of the run and graph_state.png on each
    visualise_interval tick. With the key off (the default), nothing is written.
  • _model_figure_enabled (private, non_linear/paths/directory.py) delegates to
    autofit.model_figure.config.model_figure_enabled.

Migration

  • None required — all additions are optional keywords or new symbols.

Readiness gate

Opened under Heart RED (release validation FAILED (stage integrate), unrelated
autolens scripts) with explicit human authorisation on 2026-09-12; merge stays
human via /prm.

Generated by the PyAutoLabs agent workflow.

🤖 Generated with Claude Code

https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6

Jammy2211 and others added 6 commits September 12, 2026 21:18
`autofit/model_figure/ep/spec.py` reads an `EPOptimiser`'s
`DeclarativeFactorGraph` -- once, into tuples -- as a flat, frozen,
JSON-serialisable `EPGraphSpec`: factor nodes, variable nodes, the edges
between them, and the plates that collapse repeated structure.

The graph is never rebuilt from `AbstractDeclarativeFactor.graph` (which
renames every `PriorFactor` on each access, while `EPHistory` is keyed by the
optimiser's own factor objects) and never read through `FactorGraph.graph`
(a networkx view). A test counts accesses to all three to keep it that way.

Repetition is inferred at factor level, because phase 4's `_collapse_siblings`
needs a `GlobalPriorModel` that is unreachable here: `AnalysisFactor`s group by
signature (class name, dotted prior paths, prior class names) and
`_HierarchicalFactor`s by `factor.name` -- the optimiser's own stale-group key.
A variable incident on exactly one member of a plate is drawn inside it once
with `count=N`; one incident on every member is drawn once outside.

Labels come from `factor.name_for_variable`, never `variable.label`, and are
qualified when a factor answers with its own name for every variable (as
`_HierarchicalFactor` does) so that they stay unique within a factor -- the
lookup the state overlay will map a reverted variable through. Keys are built
from declaration indices alone, so two builds of the same model agree.

`PriorFactor`s are hidden by default: there is one per prior and they treble
the node count while saying what a stub on the variable already says. The
variables that have one are recorded in `prior_factor_variable_keys` so the
render layer can still draw that stub; `show_prior_factors=True` promotes them
to nodes, collapsed alongside the variable they wrap.

`model_figure_enabled` moves to `autofit/model_figure/config.py` so the
per-search `model.png` hook and the EP figures read the same strict
`output.yaml` key through the same accessor; `directory.py` keeps
`_model_figure_enabled` as an alias.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
`autofit/model_figure/ep/state.py` reads an `EPHistory` onto an `EPGraphSpec`:
per factor, how many sweeps it has been visited, how many landed an update, how
many sweeps since the last one, which of its variables the latest projection
rejected, and one of `stale` / `reverting` / `converged` / `working` /
`absent`.

`stale` is the complement of `EPOptimiser`'s own end-of-run check -- visited at
least once, never updated -- and outranks `reverting`, which outranks
`converged`: a factor that reverts everything on every projection is both, and
a factor that rejected a variable on its last projection is not "converged"
when that rejection is the thing the figure exists to show. `converged` is
`EPHistory.is_converged`, not a reimplementation of it.

The history is read through `EPHistory.history`, never `ep_history[factor]`,
which creates an empty history for any factor it is asked about and would turn
"not reached yet" into "visited zero times".

`_reverted_names` is a private copy of the `reverted_variables` CSV column
logic (`diagnostics.py`), pinned by a test to a real `ep_history.csv` written
by a real `PartialRevertFit` run rather than to a reading of that module --
`changed is None` and an all-True mask are never reversion. A reverted variable
is mapped onto its spec node through the label its factor gives it, the same
`name_for_variable` route the spec built its edges from.

Mean, std, precision and KL sparklines stay out of scope; `model_approx` is
accepted and ignored so the signature will not change when they arrive.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
The three layers that turn the phase-5 spec and state into a picture.

`presentation.py` decides what a reader is shown. A plate is drawn once,
badged `3 datasets` / `3 members`; an aggregate is never shown without the
members that contradict it, so any member with a different status, a rejected
projection or an older last update is named in the plate's note and expanded
as a node of its own beside it. A variable every member of a plate shares
loses the one member name its spec label had to carry; a hierarchical
distribution's own parameters keep theirs, because there is one of each and
that is what `graph.info` calls them. An edge carries the sharpest claim that
is true of it, and a plate's edges speak only for the members the plate still
stands for.

`layout.py` ranks the graph -- hyper factors, hyper variables, the
hierarchical group, the variables it draws, the analysis plates, prior stubs
-- so that reading top to bottom is reading the generative story. Within a
rank the order is declaration order, adjusted by one stable barycentre pass:
a figure that reorders itself when a factor is added cannot be diffed.
`networkx.multipartite_layout` supplies the base coordinates (networkx is
already a hard dependency; graphviz's `dot` is absent locally, on the runner
and on Colab), measured text scales them into inches, and a packing pass
guarantees no two boxes overlap. If networkx ever raises, the two-column
`bipartite_layout` of `graphical/factor_graphs/graph.py` takes over: a figure
must never be the reason a fit fails.

`render.py` imports the model figure's palette, box, text, badge and link
helpers rather than copying them, so the two figures cannot drift apart, and
adds only the diagnostic encoding: grey for a stale factor and its edges, a
red dashed arrow landing on a variable whose update was reverted, a green
outline for converged. There is no observed-data node -- the factor graph
carries no such notion and the figure may not invent one.

Tests: plate collapse and counts, the stripped shared label, the expanded
exceptional member and the note that names it, reverted and stale edge kinds,
footer counts, the ranks, declaration order, zero crossings and zero overlaps
on the hierarchical double, the monkeypatched fallback, and determinism --
the layout dict equal across builds and across a fresh interpreter, and PNG
bytes equal across two saves.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
`af.EPPlotter(factor_graph, ep_history=..., model_approx=...)` owns the five
layers and nothing else, exactly as `af.ModelPlotter` does: `.spec()`,
`.state()`, `.presentation(kind)`, `.layout()` and `.figure()`, each exposed
so a test can assert the vocabulary and the geometry without rendering a
pixel. `figure()` mirrors `ModelPlotter.figure` -- `path` is a directory,
`format` is `show | png | svg | pdf` or None, and the return value is the
figure -- with `kind="model"` (the graph) and `kind="state"` (the graph with
the run on it) defaulting the filename to `graph_model` / `graph_state`, the
names the phase-5 hook will write.

`kind="state"` without an `ep_history` raises and says how to supply one: a
diagnostic figure that silently contains no diagnostics is worse than an
error.

Exported from `autofit/model_figure/ep/__init__.py`,
`autofit/model_figure/__init__.py` and `autofit/__init__.py` beside
`ModelPlotter`, with every drawing import inside a function -- the
determinism test asserts that `import autofit.model_figure.ep` still pulls in
no matplotlib.

`test_acceptance_ep.py` asserts the prompt's four acceptance bullets on the
presentation and state dataclasses and then once more as a PNG smoke: both
views of a hierarchical graph are written; an `OverWideFit`-stalled factor is
a `stale` node badged `0 updates / 4 sweeps`; a `PartialRevertFit` marks a
`reverted` edge on `y` and none on `x`, while a fixed-point restart marks
nothing at all; and a plate with one failing member names it in the plate's
note and draws it beside the plate.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
An `EPOptimiser` with paths already writes `graph.info` and, on every
`visualise_interval` tick, the convergence curves. Behind `output.yaml`'s
`model_figure` key it now also writes the factor graph itself:
`graph_model.png` once beside `graph.info`, and `graph_state.png` on
every tick, so the state file always shows the sweep that just finished.

`Visualise` does the work. It takes the optimiser's own `factor_graph`
-- never a rebuilt one -- and `__call__` takes the current `EPMeanField`,
both optional, so `stochastic.py`'s no-argument calls go on working and
simply draw no factor-graph figure. The gate is the same strict
`model_figure` key the per-search `model.png` is behind, so a config
which has never heard of it writes nothing, and the whole body is
guarded the way `DirectoryPaths._save_model_info`'s is: a figure is a
diagnostic, never a dependency, and one that raises leaves the fit
running with the reason in the log.

`optimiser.py` changes three lines: the graph into the constructor, and
the mean field into the two `self.visualiser()` calls in `run`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`make_figures.py` gains the three EP renders: `ep_model`, the
hierarchical factor graph before a sweep; `ep_state_stale`, a plate of
three datasets one of which never updates; and `ep_state_reverted`, a
real four-sweep run whose factor has one variable's projection rejected
every time. The last is an `EPOptimiser.run`; the stale one is built
from exactly the statuses `OverWideFit` records, because a plate needs
`AnalysisFactor`s and those need a real search per factor per sweep --
minutes for a picture the statuses already determine. The two failure
doubles are copied in from the tests the reversion bugs were fixed
against, so the figures show the behaviour the suite pins.

`docs/features/graphical.md` gains "Seeing The EP Run": the two files a
fit writes and when, the `model_figure` key they are behind, what stale,
reverted and converged each mean, the rule that a plate names and draws
every member departing from its aggregate, and the offline door
`af.EPPlotter(optimiser.factor_graph, ep_history=...).figure(kind="state")`.

Also corrects `af.EPOptimiser` to `af.graphical.EPOptimiser` in the
plotter's own docstring example: the optimiser is not in the `af`
namespace.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AmyBwcVQBrWE4jSTqdATY6
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@Jammy2211 Jammy2211 added the pending-release PR queued for the next release build label Sep 12, 2026
@Jammy2211
Jammy2211 merged commit 9ad5fdf into main Sep 13, 2026
4 checks passed
@Jammy2211
Jammy2211 deleted the feature/model-figures-ep-view branch September 13, 2026 10:21
@Jammy2211 Jammy2211 removed the pending-release PR queued for the next release build label Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant