Repository navigation
Description
Overview
Samples.errors_at_sigma(as_instance=True) — the default — crashes with TypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'> at position 0 whenever the model contains a component whose class is a Prior (e.g. the Model(af.GaussianPrior) a HierarchicalFactor contributes to FactorGraphModel.global_prior_model). The bounds list [(lower, upper), …] is fed through instance_from_vector, which then calls GaussianPrior(mean=(lo, hi), sigma=(lo, hi)) and constructs a message from a tuple. values_at_sigma(as_instance=True) hits the same path.
This is finding D6 of the analytic Gaussian benchmark (autofit_workspace_test#91) and the last open phase-1 finding of the graphical-ep campaign. It is minor but it forced analytic_autofit.py to read errors with as_instance=False and re-map them by hand.
Plan
- Reproduce the
broadcast_arraysTypeError on a hierarchical global model (FactorGraphModel.global_prior_modelwith aHierarchicalFactor→Model(af.GaussianPrior)component). - Make
Model.instance_for_argumentsreturn an attribute container instead of constructing a Prior from(lower, upper)bounds pairs. - Pin it with tests for
errors_at_sigmaandvalues_at_sigma(instance attributes == raw tuples), and confirmmedian_pdf(as_instance=True)still builds a real prior. - Remove the
as_instance=Falseworkaround from the analytic benchmark's autofit adapter (autofit_workspace_test); referee numbers unchanged.
Detailed implementation plan
Work Classification
Library — PyAutoFit source first; the autofit_workspace_test docstring/workaround follow-up ships second, behind the library-first merge gate.
Affected Repositories
- PyAutoFit (primary)
- autofit_workspace_test (workspace follow-up, same task branch, after the library PR merges)
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./PyAutoFit | main | clean |
| ./autofit_workspace_test | main | clean |
Suggested branch: feature/samples-errors-at-sigma-instance
Worktree root: ~/Code/PyAutoLabs-wt/samples-errors-at-sigma-instance/ (created later by /start_library)
Implementation Steps
-
Root cause path (deepest frame last).
autofit/non_linear/samples/pdf.py:236errors_at_sigmareturns[(lower, upper), …]→ theto_instancewrapper (autofit/non_linear/samples/interface.py:56) →_instance_from_vector→Model.instance_for_arguments(autofit/mapper/prior_model/prior_model.py~541,result = self.cls(**constructor_arguments)) →GaussianPrior(mean=(lo, hi), sigma=(lo, hi))→NormalMessage→broadcast_arraysTypeError.values_at_sigma(as_instance=True)is tuple-valued too and crashes identically. -
Design decision. The prompt's option 1 (return a pair of instances, one from the lower vector and one from the upper) is rejected — it would break the public tuple-attribute instance contract already used by
autofit_workspace_test/scripts/graphical/ep_parity.py:176,simultaneous.py:200and the workspace result tutorials, all of which readinstance.<param>as an(lower, upper)tuple. -
Fix — PyAutoFit
autofit/mapper/prior_model/prior_model.py,Model.instance_for_arguments, immediately beforeresult = self.cls(**constructor_arguments): ifinspect.isclass(self.cls) and issubclass(self.cls, Prior)and any constructor argument is atuple(a bounds pair — aPriorconstructor only takes scalars, andTuplePriorcentres never reach a Prior-class model), returnModelInstance(constructor_arguments)(autofit/mapper/model.py:404, dict form →.mean == (lo, hi),.sigma == (lo, hi)). Scalar vectors keep constructing the real prior. Write it as an explicit typed branch with a comment — not atry/exceptguard around the construction. -
Tests —
test_autofit/non_linear/samples/test_pdf.py(pattern oftest__errors_at__converged), or a newtest_autofit/graphical/global/test_errors_at_sigma_instance.pyusing theglobal_prior_modelfixture pattern oftest_hierarchical.py:14-28:errors_at_sigma(1.0, as_instance=True)on a model with aModel(af.GaussianPrior)component does not raise, and that component's.mean/.sigmaequal theas_instance=Falsetuples read back throughmodel.prior_tuples_ordered_by_id; ordinary components are unchanged.- The same for
values_at_sigma. median_pdf(as_instance=True)still yields a realaf.GaussianPrior(scalar path untouched).
Tests (1) and (2) must fail without the fix.
-
Verification.
pytest test_autofit/non_linear/samples test_autofit/mapper test_autofit/graphical -q, then the full suite. CI legs:Tests [pull_request]3.12 / 3.13 / nojax, plusDocs. -
Workspace follow-up (autofit_workspace_test, same task branch, ships after the library PR merges):
scripts/graphical/analytic_autofit.pyline ~212errors_at_sigma(sigma=1.0, as_instance=False)→ the instance path, removing the hand re-mapping and the module-docstring sentence (lines ~52-54) that says the instance path cannot be used.analytic_gaussian.py's[info] graphical median_pdf +/- mean|errors_at_sigma(1)|lines must print identical numbers before and after (capture both in the PR); the refereeanalytic_gaussian_collapse.pyRECOVER 5/5 stays unchanged;Smoke Tests [pull_request]green.
Key Files
autofit/mapper/prior_model/prior_model.py—Model.instance_for_arguments, the fix site (~line 541)autofit/mapper/model.py:404—ModelInstance, the attribute container returned insteadautofit/non_linear/samples/pdf.py:236—errors_at_sigma/values_at_sigma, the tuple-valued producersautofit/non_linear/samples/interface.py:56— theto_instancewrapperautofit/mapper/prior/gaussian.py:52,autofit/messages/abstract.py:63— where the tuple becomes abroadcast_arraysTypeErrortest_autofit/non_linear/samples/test_pdf.py,test_autofit/graphical/global/test_hierarchical.py:14-28— test patternsautofit_workspace_test/scripts/graphical/analytic_autofit.py(~52-54, ~212) — the workaround to removeautofit_workspace_test/scripts/graphical/ep_parity.py:176,simultaneous.py:200— the tuple-attribute contract the fix must preserve
Context
- Epic: graphical-ep, phase 1, finding D6 (the last open phase-1 finding). Ledger:
PyAutoMind/draft/research/graphical_ep/ep_campaign.md. - autofit_workspace_test#91 — test(graphical): analytic Gaussian benchmark — closed form vs minimal EP vs autofit EP/graphical autofit_workspace_test#91 (evidence comments: 1, 2)
- PyAutoFit#1405 — Hierarchical EP: parent scale hyperparameter collapses to ~0 with over-confident error (+ init-crash) #1405 (umbrella for the EP findings; this one is adjacent, not a cause)
- Siblings shipped 2026-09-02: D1 PyAutoFit#1558, D2/D3 fix(graphical): Laplace projection uses a finite-difference Hessian at the mode; failed updates are skipped, not written (#1561) #1562, D4/D5 fix(messages): carry truncation limits through every message rebuild; TransformedMessage.from_mode applies every Jacobian (#1559) #1560.
Original Prompt
Click to expand starting prompt
Samples.errors_at_sigma(as_instance=True) crashes on a model whose component class is a Prior
Type: bug
Target: PyAutoFit
Repos:
- PyAutoFit
Themes: - graphical-ep
Difficulty: small
Autonomy: safe
Priority: medium
Status: formalised
Consequence: glance
Witness:errors_at_sigma(1.0, as_instance=True)on aFactorGraphModelglobal model containingModel(af.GaussianPrior)returns without raising, and its values equal theas_instance=Falsetuples read back throughprior_tuples_ordered_by_id
Review-minutes: 3
Unattended: ready
Epic: graphical-ep
Filed: 2026-09-02
D6 of the analytic Gaussian benchmark findings (autofit_workspace_test#91).
Minor, but it forced analytic_autofit.py to read errors with
as_instance=False and re-map them by hand (see its module docstring, lines
52-54).
Why
On the hierarchical graph's global model (a HierarchicalFactor contributes a
Model(af.GaussianPrior) component), samples.errors_at_sigma(1.0) — the
as_instance=True default — raises:
TypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'> at position 0
Plain dataclass models tolerate the tuples; a Prior used as a Model class does
not, because constructing it constructs a message.
Root cause (deepest frame last)
errors_at_sigma(autofit/non_linear/samples/pdf.py:236-255) returns a list
of(lower, upper)tuples per parameter.- The
to_instancewrapper (autofit/non_linear/samples/interface.py:56) calls
model.instance_from_vector(vector)on that tuple list. prior_model.py:541—self.cls(**constructor_arguments)for
Model(af.GaussianPrior).autofit/mapper/prior/gaussian.py:52—NormalMessage(mean=(lo, hi), ...).autofit/messages/abstract.py:63—broadcast_arrayson the tuple -> TypeError.
Minimal repro
import autofit as af
class Level:
def __init__(self, x): self.x = x
class A(af.Analysis):
def log_likelihood_function(self, i): return -0.5 * (51.0 - i.x) ** 2
m = af.Model(Level); m.x = af.GaussianPrior(50, 20)
hf = af.HierarchicalFactor(af.GaussianPrior, mean=af.GaussianPrior(50, 10), sigma=af.GaussianPrior(10, 5))
hf.add_drawn_variable(m.x)
fg = af.FactorGraphModel(af.AnalysisFactor(m, A()), hf)
samples = ... # the EP result's Samples over fg.global_prior_model, as analytic_autofit.py builds them
samples.errors_at_sigma(1.0, as_instance=False) # fine: list of (lo, hi)
samples.errors_at_sigma(1.0) # TypeError from broadcast_arraysFix sketch
Either build two instances — instance_from_vector(lower) and
instance_from_vector(upper) — and return them as a pair (mirrors how
values_at_sigma style callers already split the bounds), or fall back to the
tuple list when the model contains prior-valued components. The first is the
cleaner contract; pick it unless it breaks an existing caller.
Acceptance
- Unit test: a
Samplesover a model with aModel(af.GaussianPrior)component;
errors_at_sigma(1.0, as_instance=True)does not raise and its bounds equal
theas_instance=Falsetuples. autofit_workspace_test/scripts/graphical/analytic_autofit.py: the
as_instance=Falseworkaround and the docstring note at lines 52-54 can be
removed;analytic_gaussian.py'smedian_pdf +/- errors_at_sigma(1.0)
information line is produced through the instance path with identical numbers
on every row (this line is informational, not a PASS/FAIL cell).
Links
- autofit_workspace_test#91 — test(graphical): analytic Gaussian benchmark — closed form vs minimal EP vs autofit EP/graphical autofit_workspace_test#91
- PyAutoFit#1405 (umbrella for the EP findings; this one is adjacent, not a cause) — Hierarchical EP: parent scale hyperparameter collapses to ~0 with over-confident error (+ init-crash) #1405
- Campaign ledger:
draft/research/graphical_ep/ep_campaign.md(phase 1) - Siblings:
complete/2026/09/ep-prior-id-zero.md(D1 shipped 2026-09-02, PyAutoFit#1558),
complete/2026/09/ep-laplace-hessian.md(D2/D3 shipped 2026-09-02, PyAutoFit#1562),
complete/2026/09/ep-message-support.md(D4/D5 shipped 2026-09-02, PyAutoFit#1560) - Scripts:
autofit_workspace_test/scripts/graphical/analytic_{reference,ep_minimal,autofit,gaussian,gaussian_priors,gaussian_collapse}.py
on branchfeature/analytic-gaussian-benchmark
Activity
Jammy2211 commentedon Sep 7, 2026
Library PR Created
PR: #1578 (
pending-release)Commit:
154c87dd48aa481017810354eecd2d2e0deac2e4Model.instance_for_argumentsnow returns aModelInstanceof the constructor arguments when the model class is aPriorsubclass and any argument is a tuple (the(lower, upper)bounds pair fromSamples.errors_at_sigma/values_at_sigma), instead of handing the pair to the Prior constructor and raisingTypeError: broadcast_arrays requires ndarray or scalar arguments, got <class 'tuple'>. Scalar vectors (median_pdf,max_log_likelihood) still construct the real prior.API changes
Bug fix only — no signatures changed.
errors_at_sigma/values_at_sigmawithas_instance=Truenow return an instance on global models containing aModel(af.GaussianPrior)(anyFactorGraphModelwith aHierarchicalFactor) where they previously raised; the Prior-class component becomes aModelInstancewhose attributes hold the bounds pairs.Tests
test_autofit/graphical/global/test_errors_at_sigma_instance.py— 3 new tests; the two tuple-valued ones fail without the fixpytest test_autofit -q: 2472 passed, 2 skipped (baseline 2469 + 3 new); graphical 278, messages 95Workspace impact — option (ii), migration
grep -rn "errors_at_sigma(\|values_at_sigma("over the workspace scripts:autofit_workspace_test/scripts/graphical/analytic_autofit.py:212— carries theas_instance=Falseworkaround this fix removes (follow-up)autofit_workspace_test/scripts/graphical/ep_parity.py:176,simultaneous.py:200— use the instance contract, unchanged by this fixNext:
/start_workspace— remove theas_instance=Falseworkaround fromanalytic_autofit.pyand verify theanalytic_gaussian.pyinfo lines are byte-identical through the instance path. The workspace PR ships after this library PR merges (library-first gate).Finding D6 of autofit_workspace_test#91; graphical-ep phase 1; umbrella PyAutoFit#1405.
Jammy2211 commentedon Sep 8, 2026
Workspace PR: PyAutoLabs/autofit_workspace_test#99
scripts/graphical/analytic_autofit.py's module docstring no longer claimserrors_at_sigma(as_instance=True)is unusable on the hierarchical global model; it now records that the read staysas_instance=Falsebecauseread_joint_posteriorsindexes the sample columns positionally throughprior_tuples_ordered_by_id. Docstring only, no code change. Library-first: merges after PyAutoFit#1578.Jammy2211 commentedon Sep 8, 2026
Shipped
6331b80031b1dedae3ce277a8c2b116b52ddd261(head154c87dd)9321910765f77d4f7f092e455bce33127d154610(head94b72b20)Summary.
Model.instance_for_argumentsconstructed aPriorfrom the(lower, upper)bounds pairs thatSamples.errors_at_sigma/values_at_sigma(as_instance=True) hand it whenever the global model holds aModel(af.GaussianPrior)component (everyHierarchicalFactorgraph), soNormalMessage'sbroadcast_arraysraisedTypeError. There is now an explicit typed branch: a Prior-class model whose constructor arguments contain a tuple returnsModelInstance(constructor_arguments)(.mean == (lo, hi),.sigma == (lo, hi)); scalar vectors (median_pdf,max_log_likelihood) still build the real prior. Workspace side: theanalytic_autofit.pydocstring no longer claims the instance path is unusable; the rawas_instance=Falseread stays, because the weighted-moment comparison indexes columns positionally throughprior_tuples_ordered_by_id.Decision. The prompt's option 1 (return a pair of instances) was rejected — it would break the public tuple-attribute instance contract used by
ep_parity.py,simultaneous.pyand the workspace result tutorials.Tests / evidence.
test_autofit/graphical/global/test_errors_at_sigma_instance.py; the two tuple-valued ones fail without the fix.analytic_gaussian_collapse.py: RECOVER 5/5, STALE 0/5.analytic_gaussian.pycell byte-identical before/after (PARITY FAIL 38/41 on both sides — the same three autofit-EP cells, i.e. the known Laplace-on-scatter caveat).Tests [pull_request]3.12 / 3.13 / nojax +Docsgreen; autofit_workspace_testSmoke Tests [pull_request]changes / 3.12 / 3.13 green; both PRs CLEAN; library merged first.Side finding (filed, not fixed here).
analytic_gaussian.py's graphical column is an unseededDynestyStaticrun — its PARITY count and[info]lines drift run to run (37 vs 38 of 41 on an identical tree). Drafted asdraft/bug/graphical_ep/analytic_gaussian_unseeded_graphical_column.mdin PyAutoMind.Remaining. This was finding D6 of the phase-1 analytic Gaussian benchmark (autofit_workspace_test#91) — the findings table D1–D6 is now fully shipped.
analytic_gaussian.py/analytic_gaussian_priors.pystay parked NEEDS_FIX for the scatter-estimation cure (moment-matching projection,draft/feature/autofit/ep_hierarchical_scatter_moment_matching.md) — a human decision.Record:
complete/2026/09/samples-errors-at-sigma-instance.md(PyAutoMind).