Repository navigation
Description
Overview
AbstractPriorModel.parameterization (the (N=k) header block of every model.info) walks every prefix of every leaf path and calls obj.prior_count on each prefix node. prior_count is itself a full recursive subtree walk (unique_prior_tuples → attribute_tuples_with_type → path_instances_of_class), and every leaf re-triggers the walk for the root and every ancestor, so the cost is O(leaves × subtree) rather than O(N). On autogalaxy_workspace_test mge_group.py the two .info prints cost 7.25 s of a 19.4 s warm smoke run (1,498 prior_count calls → 763,555 recursive path_instances_of_class calls for model.info; 2,438,255 for global_prior_model.info). 25 of the 39 smoke entries print an .info, so this is a standing cost across that gate. Behaviour-preserving fix: compute each node's unique-prior set once, bottom-up, inside the single parameterization call.
Plan
- Add a private bottom-up helper inside
parameterizationthat computes the set of unique priors under each node once (memoised by object identity for the duration of the call), mirroring exactly the traversalpath_instances_of_class(obj, Prior, ignore_children=True)performs. - Keep the existing leaf listing and prefix enumeration untouched so the entries reach the
TextFormatterin the same order; only the per-nodeobj.prior_countlookup is replaced by the memoised count. - Resolve each unique prefix path once instead of once per leaf.
- Prove byte-identical output with an oracle test: the pre-change algorithm kept verbatim in the test module and compared against
parameterizationover nested collections, shared priors, lists of models, tuple priors, constants, floats and zero-dimension children. - Prove the call-count witness:
path_instances_of_classinvocations during a freshparameterizationequal those of a single leaf walk (at most one per node). - Leave
prior_countitself,model_tuples_with_type, and the smoke scripts'.infoprints unchanged (the prompt forbids trimming the prints).
Detailed implementation plan
Affected Repositories
- PyAutoFit (primary, only)
Work Classification
Library
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./PyAutoFit | main (fa2d540) | clean |
Remote branches: main, claude/slowest-ci-tests-s81dza, experiment/jax-vmap-jit-ordering (unrelated). No active.md entry claims PyAutoFit.
Suggested branch: claude/parameterization-prior-count-blowup-jzsrj0 (web-github session branch; local-dev equivalent feature/parameterization-prior-count)
Worktree root: ~/Code/PyAutoLabs-wt/parameterization-prior-count/ (not created — this runs in a web-github session clone at /home/user/pyautofit)
Implementation Steps
autofit/mapper/prior_model/abstract.py— add a module-private function_unique_priors_by_node(obj, memo)(or a nested closure insideparameterization) that returns adictkeyed byPrior(the same keyingunique_prior_tuplesuses, so shared priors count once) for the subtree underobj:isinstance(obj, Prior)→{obj: obj}(stop; matchesignore_children=True).isinstance(obj, list)→ union over items.dictorobj.__dict__→ union over values whose key does not start with_;AttributeError/TypeError→ empty (same fallthrough aspath_instances_of_class).- Memoise by
id(obj), keeping a reference to every memoised object alive for the call so ids cannot be recycled; place an empty in-progress entry before recursing so a cyclic reference terminates.
- In
parameterization: build the memo lazily; keep thepath_instance_tuples_for_class((Prior, float, Constant, tuple), ignore_children=True)listing and thefor i in range(len(t[0]))prefix loop exactly as they are; replacen = obj.prior_countwithn = len(_unique_priors_by_node(obj, memo)). Cache(path → (name, n))per unique prefix soobject_for_pathruns once per prefix, preserving append order forfind_groups. test_autofit/mapper/test_parameterization.py:_reference_parameterization(model)— the pre-change algorithm copied verbatim (callsobj.prior_count), used as the oracle.test_parameterization_matches_reference[...]parametrised over: nestedCollections; twoModels sharing a prior (parent N counts it once);af.Collection([...])list children;TuplePrior; aConstantand a float instance; a zero-dimension child; aModelwith an integer attribute. Assertmodel.parameterization == _reference_parameterization(model)byte-for-byte on a fresh model each time.test_parameterization_walks_each_node_once— monkeypatchautofit.mapper.model.path_instances_of_classwith a counting wrapper; assert the count during a freshparameterizationequals the count of onepath_instance_tuples_for_class((Prior, float, Constant, tuple), ignore_children=True)walk on an identical model (at most one call per node).
- Micro-benchmark in the PR body (synthetic nested collection of ~200 models): before/after wall time and
path_instances_of_classcall count, since the workspace witness (mge_group.py, needs autogalaxy) cannot run in this session — that timing witness is for the human's local re-run / CI smoke.
Key Files
autofit/mapper/prior_model/abstract.py—parameterization(~L2288),prior_count(~L1956),unique_prior_tuples(~L805)autofit/mapper/model.py—path_instances_of_class(~L339),attribute_tuples_with_type,object_for_pathtest_autofit/mapper/test_parameterization.py— existing byte-exact expectations plus the new oracle and call-count tests
Key trade-offs
- The helper duplicates the traversal rules of
path_instances_of_classfor thePriorcase rather than calling it, because that function cannot share work across nodes. The oracle test pins the two together; a divergence surfaces as a text diff. - Bottom-up set unions are still O(N·depth) in set-element operations, but in C-level set ops rather than Python recursion; the recursion count (the witness) becomes one per node.
prior_counton its own is left as is: outsideparameterizationit is called on one node at a time and is cached on frozen models.
Original Prompt
Click to expand starting prompt
Memoise prior_count inside AbstractPriorModel.parameterization (O(N·depth) walk)
Type: refactor
Target: autofit
Repos:
- PyAutoFit
Themes: - performance
- hygiene
Difficulty: medium
Autonomy: safe
Priority: medium
Status: formalised
Consequence: notify
Witness:model.infoandfactor_graph.global_prior_model.infoonautogalaxy_workspace_testmge_group.pyare byte-identical before and after;path_instances_of_classcalls undermodel.infodrop from 763,555 to at most one per node; the warm smoke run of that script drops by at least 5 s (19.3 -> <= 14 s).
Review-minutes: 0
Unattended: ready
Filed: 2026-09-10
AbstractPriorModel.parameterization
(autofit/mapper/prior_model/abstract.py:2069) walks every prefix path of every
prior/constant and calls obj.prior_count on each node. prior_count →
unique_prior_tuples → attribute_tuples_with_type → path_instances_of_class
is itself a full recursive subtree walk, so the whole thing is O(N·depth) and
the cost lands on any script that prints a model .info.
Measurement
Found by /ci_speedup (2026-09-10) while auditing the slowest CI smoke scripts.
Measured on autogalaxy_workspace_test
scripts/multi_dataset/jax_likelihood/mge_group.py, smoke profile, warm JAX cache:
| phase | s | share |
|---|---|---|
print(model.info) |
1.72 | 9% |
print(factor_graph.global_prior_model.info) |
5.53 | 28% |
both .info prints |
7.25 | 37% of a 19.4s warm run |
Call counts on that model:
model.info— 1,498prior_countcalls driving 763,555 recursive
path_instances_of_classcalls.global_prior_model.info— 3,497prior_countcalls driving 2,438,255.
All of that produces ~25 lines of (N=k) annotation text.
cProfile attributes ~99% of the .info time to parameterization.
parameterization is already memoised per object (_parameterization_cache), so
a caller cannot pre-warm it — the blowup happens within a single call.
A/B, prints commented out and nothing else changed: warm 19.3 → 12.7s,
cold 26.8 → 19.8s.
Why this is worth doing centrally
25 of the 39 entries in autogalaxy_workspace_test/smoke_tests.txt print a
*.info, so this is a standing cost across most of that gate, not one script.
The same pattern appears in the autolens test workspace.
The fix
Memoise prior_count bottom-up across a single parameterization walk: compute
each node's count once from its children instead of re-walking the subtree per
node. Behaviour-preserving by definition — the rendered .info text must be
byte-identical before and after, which is the acceptance test.
Explicitly NOT the fix
Deleting or trimming the .info prints in the smoke scripts. That text is those
lines' deliverable; removing smoke output is a coverage decision for a human, and
/ci_speedup forbids it as a speed-up. The scripts were left pristine.
Activity
Jammy2211 commentedon Sep 17, 2026
Library PR created: #1637 (branch
claude/parameterization-prior-count-blowup-jzsrj0, commit 97a92e6, labelpending-release).Implemented as planned: a module-private
_subtree_unique_priorsmemoises each node's distinct-prior set bottom-up inside oneparameterizationcall; leaf listing and entry order untouched. Fulltest_autofit/suite: 2813 passed, 48 skipped. Synthetic 561-prior model: 6.2 s / 3,244,174path_instances_of_classcalls → 0.012 s / 2,374.Workspace impact: none (no API change; option iii). Left for the human: the
mge_group.pytiming witness (needsautogalaxy_workspace_test), then/prmonce CI is green. This session ends at PR-open.Generated by Claude Code
Jammy2211 commentedon Sep 17, 2026
Shipped
mainat 7c0e79a (CI green on every leg: unittest 3.12 / 3.13 / nojax, docs-build). Labelpending-releasecarried; the library is merged, not yet released.AbstractPriorModel.parameterizationnow computes each node's distinct-prior set once, bottom-up, memoised by object identity for the duration of one call, instead of callingprior_count(a full subtree walk) on every prefix of every leaf path. Rendered.infotext is byte-identical (oracle test keeps the old algorithm verbatim); onepath_instances_of_classcall per node. Synthetic 561-prior model: 6.2 s / 3,244,174 calls → 0.012 s / 2,374.model.identifieris byte-identical onmainand this branch for six model shapes, before and after touching.info(the identifier hashes__dict__skipping underscore keys; the change adds no attribute).mge_group.pytiming witness onautogalaxy_workspace_test(needs that workspace; expected warm run 19.3 s → ≤ 14 s).Generated by Claude Code
Jammy2211 commentedon Sep 17, 2026
Timing witness measured (
autogalaxy_workspace_testscripts/multi_dataset/jax_likelihood/mge_group.py, smoke-profile env with JAX and full datasets enabled per the script'sENV:line, this container: 4 cores,XLA_FLAGS=--xla_cpu_multi_thread_eigen=false,JAX_ENABLE_X64=True; PyAutoFit3abbc13=mainbefore this merge,7c0e79a= after):parameterization(2 calls)model.infoandfactor_graph.global_prior_model.infobyte-identical before and after (332 lines, same sha256).Generated by Claude Code