Skip to content

fix(messages): truncation limits lost on natural-parameter ops; TransformedMessage.from_mode skips the Jacobian (EP) #1559

Closed

Description

@Jammy2211

Overview

Found by the analytic Gaussian benchmark (autofit_workspace_test#91 / PR #92): two message-layer defects make every non-Gaussian hyper-prior family in an EP graph wrong from the first sweep. D4: a TruncatedNormalMessage loses its (lower_limit, upper_limit) on every natural-parameter operation (__pow__, _multiply/_divide → from_natural_parameters), starting with the very first prior.message ** (1/(count-1)) in message_dict, so the leg-B scatter runs untruncated and either collapses or sits biased-tight (3.73 ± 0.75 vs closed form 6.57 ± 2.88). D5: TransformedMessage.from_mode skips the Jacobian for 0-d covariances — and the guard is hiding a crash (jac.quad(DiagonalMatrix) raises for any DiagonalMatrix) while the transform loop keeps only the innermost Jacobian — so a LogGaussianPrior scatter writes its physical variance as its log-space variance and never moves (all 150 hierarchical updates BAD_PROJECTION). Second of three fixes in the EP campaign's fix wave (D1 #1557 merged → D4/D5 → D2/D3). Umbrella symptom: #1405 (records the untruncated message without a cause).

Plan

  • Make truncation limits message state carried through every rebuild (copy, __pow__, products, quotients, update_invalid, from_natural_parameters, pickle) via one _support_kwargs property; products take the intersection of supports and raise only when it is empty.
  • Fix TransformedMessage.from_mode: accept DiagonalMatrix covariances (0-d or n-d), accumulate every Jacobian in the transform stack, never pass physical-space limits to the base message.
  • Unit tests for the message algebra and the transform, an EP-level regression asserting the scatter message keeps (0, 100), and a prior-properties sweep entry.
  • Measure the referee: analytic_gaussian_priors.py truncated family reports (0, 100) and its mu row passes; the loggaussian log_sigma row moves off its start; report the leg-B after-numbers (remaining bias belongs to D2/D3).
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main (809b4fd, post-#1558) clean (other claim resampling-info-summary-section is a web session on disjoint files)

Suggested branch: feature/ep-message-support
Worktree: ~/Code/PyAutoLabs-wt/ep-message-support/

Implementation Steps

  1. D4 — support as state: TruncatedNormalMessage.__init__ (truncated_normal.py:103-112) stops passing the limits positionally (they become attributes set by AbstractMessage.__init__), parameters == (mean, sigma); add MessageInterface._support_kwargs (default {}), overridden on TruncatedNormalMessage (lower_limit/upper_limit) and TransformedMessage (delegates to base_message); forward **self._support_kwargs at copy, __getitem__, merge, scalar __mul__/__truediv__, __pow__, update_invalid, _init_kwargs, __reduce__/_reconstruct (4th tuple element, old 3-tuple pickles still load) in abstract.py, and at sum_natural_parameters/sub_natural_parameters in interface.py (products via _combined_support = intersection, MessageException when empty; quotients keep self's support); the two instance callers of project pass the support kwargs.
  2. D5 — composed_transform.py from_mode: LinearOperator covariances → .diagonal(), np.asanyarray, pop lower_limit/upper_limit, apply jac.quad for every transform in the correct (inverse) order, pass **self.base_message._support_kwargs to the base from_mode. Verify the transform order numerically on a two-transform stack (UniformPrior(0,10) round trip: variance 0.04 in, 0.04 out).
  3. Tests: test_autofit/messages/test_truncated_normal.py (support survives every op; Truncated × Normal keeps (0,100); mismatched supports intersect / raise; from_mode keeps class + limits; vector update_invalid no longer a TypeError; TruncatedNaturalNormal.copy keeps limits); new test_autofit/messages/test_transformed_from_mode.py (0-d DiagonalMatrix(25.0) at mode 10 → base sigma 0.5, equal to the 1-d path and the plain-float path; UniformPrior stack round trip); test_autofit/graphical/hierarchical/test_truncated_support.py (manual 3-sweep Laplace loop on a hierarchical graph with TruncatedGaussianPrior(10,5,0,100) scatter: mean-field message keeps (0,100), no EXCEPTION); test_prior_properties.py P7 sweep ((prior.message ** 0.5) keeps the prior message's limits).
  4. pytest test_autofit -q in the worktree; referee: analytic_gaussian_priors.py and analytic_gaussian.py from the worktree, tables on this issue.

Key Files

  • autofit/messages/abstract.py — rebuild sites (copy, __pow__, update_invalid, _init_kwargs, __reduce__)
  • autofit/messages/interface.py — sum_natural_parameters / sub_natural_parameters, new _support_kwargs, _combined_support
  • autofit/messages/truncated_normal.py — constructor, _support_kwargs, invert_natural_parameters
  • autofit/messages/composed_transform.py — from_mode (D5), _support_kwargs
  • autofit/graphical/mean_field.py — from_mode_covariance forwards the (now real) limits
  • autofit_workspace_test/scripts/graphical/analytic_gaussian_priors.py — acceptance harness

Original Prompt

Click to expand starting prompt

EP messages lose their truncation limits on every natural-parameter operation, and TransformedMessage.from_mode skips the Jacobian for scalars

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • graphical-ep
    Difficulty: medium
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Review-minutes: 15
    Unattended: ready
    Epic: graphical-ep
    Filed: 2026-09-02

Two message-layer defects (D4 + D5) found by the analytic Gaussian benchmark
(autofit_workspace_test#91, analytic_gaussian_priors.py). Both make the
non-Gaussian prior families of an EP graph wrong from the very first sweep,
independently of the optimiser defects in the sibling prompts.

D4 — truncation limits are dropped by every natural-parameter operation

Why. Leg B with TruncatedGaussianPrior(10, 5, 0, 100) on the scatter: autofit
EP gives sigma 3.7348 +/- 0.7527 vs closed form 6.5667 +/- 2.8832
(q05/q50/q95 2.980/5.981/12.154); the returned TruncatedNormalMessage has limits
(-inf, inf). In other process histories the same leg collapses fully to
sigma ~ 1e-4. #1405 records the untruncated-message symptom without a cause.

Root cause. AbstractMessage.__pow__ (autofit/messages/abstract.py:225-234)
and _multiply / _divide -> from_natural_parameters (abstract.py:173-178)
rebuild the message as cls_(*invert_natural_parameters(eta));
TruncatedNormalMessage.invert_natural_parameters (truncated_normal.py:210)
returns only (mean, sigma), so the limits revert to (-inf, inf). The loss
happens at the very first step — message_dict's
prior.message ** (1 / (count - 1)) (declarative/abstract.py:82-94) — so the
whole leg-B mean field is untruncated from the start. Downstream,
OptimisationState.valid sees lower_limit = -inf, so sigma < 0 is only caught by
the -inf branch in hierarchical.py:312-324, and from_mode_covariance
(mean_field.py:393-399) forwards the already-lost limits.

D5 — TransformedMessage.from_mode skips the Jacobian for scalar variables

Why. LogGaussianPrior(log 10, 0.5) leg: autofit log sigma 2.3026 +/- 0.4564
— exactly its start — vs closed form 1.8338 +/- 0.3608 (minimal EP
1.8164 +/- 0.3716). BAD_PROJECTION on all 150 updates; log sigma never moves. Not
the #1498 fingerprint: the no-Jacobian reference 1.9692 +/- 0.3752 is not matched
either, and af.LogGaussianPrior.factor carries the Jacobian correctly.

Root cause. composed_transform.py:406-407:
if covariance.shape != (): covariance = jac.quad(covariance).
MeanField.from_mode_covariance passes covar.get(v), a 0-d DiagonalMatrix
(VariableFullOperator.__getitem__, variable_operator.py:305-308) whose
.shape == (), so the physical variance of sigma (25.0) is written as the
log-space variance (should be 0.25). Every projection then has
var(q*) >> var(cavity) -> BAD_PROJECTION.

Minimal repro

import numpy as np, autofit as af
from autofit.mapper.operator import DiagonalMatrix
print(af.TruncatedGaussianPrior(10, 5, 0, 100).message ** 0.2)   # ... lower_limit = -inf, upper_limit = inf
m = af.LogGaussianPrior(mean=np.log(10.0), sigma=0.5).message      # physical var 25.0, log-space var 0.25
print(m.from_mode(np.asarray(10.0), DiagonalMatrix(np.asarray(m.variance))).base_message)  # sigma = 5.0 (should be 0.5)

Fix sketch

  • D4: carry lower_limit / upper_limit through from_natural_parameters,
    __pow__ and update_invalid — they are _support, not natural parameters —
    and assert equal supports when multiplying / dividing two truncated messages.
    Note the open design question in
    draft/research/graphical_ep/transformed_message_declares_support.md
    (fix: LogGaussianPrior declares its own (0, inf) support #1527 shadowed the limits on the prior because they did not survive
    with_base / copy / project / __call__); this prompt fixes the
    message-level loss, which is the prerequisite for either answer there.
  • D5: test np.ndim(covariance) / .size rather than .shape != (), or always
    apply jac.quad for scalar LinearOperators.

Acceptance

  • Unit tests: (a) TruncatedNormalMessage(10, 5, 0, 100) ** 0.2, * other,
    / other and from_natural_parameters all keep (0, 100); multiplying two
    messages with different supports raises. (b) TransformedMessage.from_mode
    with a 0-d DiagonalMatrix covariance applies the Jacobian: log-space sigma
    0.5 from physical variance 25.0 at mode 10, identical to the 1-d path.
  • autofit_workspace_test/scripts/graphical/analytic_gaussian_priors.py:
    truncated family — the returned message reports limits (0, 100) and the
    mu row PASS (mu std currently 69% low); loggaussian family — the
    log_sigma row moves off its start (2.3026 +/- 0.4564) and PASS against
    1.8338 +/- 0.3608 within the autofit-EP tolerance (a 0.15, b 0.25);
    ep_history.csv no longer shows BAD_PROJECTION on all 150 updates.
  • analytic_gaussian.py leg B sigma row: report the after-number; the
    remaining bias is the Laplace-on-sigma finding recorded in
    ep_laplace_covariance_and_failed_update_projection.md, not this prompt.

Links

Activity

  1. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    API summary: TruncatedNormalMessage.parameters is now (mean, sigma) — limits are attributes / _support_kwargs; products intersect supports; TransformedMessage.from_mode accepts DiagonalMatrix covariances and applies every Jacobian.

    Next: /start_workspace — autofit_workspace_test/scripts/graphical/analytic_autofit.py unpacks the 4-tuple and must read the attributes.

  2. added a commit that references this issue on Sep 2, 2026
  3. Jammy2211 commented on Sep 2, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Summary. D4 — truncation limits are message state (_support_kwargs), carried through every rebuild (copy, __getitem__, merge, scalar ops, __pow__, update_invalid, pickle); products intersect supports, quotients keep the numerator's. D5 — TransformedMessage.from_mode accepts DiagonalMatrix/LinearOperator covariances and applies every Jacobian in the stack (inverse order). pytest test_autofit: 2430 passed, 2 skipped. Workspace follow-up: analytic_autofit.py reads the limits from lower_limit/upper_limit (smoke gate 13/13 PASS; analytic_gaussian.py leg B sigma message prints limits (0, 100)).

    Referee. Truncated family scatter message reports limits (0, 100) (was (−inf, inf)); loggaussian log_sigma row moves off its start, 2.30 → 1.55. The truncated mu row still collapses to ~2e-4 — that is D2/D3 (Laplace covariance / failed-update projection) territory, not the message algebra. The base control (809b4fd, autofit/ stashed) showed both the gaussian and truncated families collapse fully post-D1, so the residual is owned by ep_laplace_covariance_and_failed_update_projection.md, last in this wave.

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