Skip to content

perf: bottom-up prior_count in parameterization (O(N·depth) walk) #1635

Closed

Description

@Jammy2211

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 parameterization that computes the set of unique priors under each node once (memoised by object identity for the duration of the call), mirroring exactly the traversal path_instances_of_class(obj, Prior, ignore_children=True) performs.
  • Keep the existing leaf listing and prefix enumeration untouched so the entries reach the TextFormatter in the same order; only the per-node obj.prior_count lookup 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 parameterization over nested collections, shared priors, lists of models, tuple priors, constants, floats and zero-dimension children.
  • Prove the call-count witness: path_instances_of_class invocations during a fresh parameterization equal those of a single leaf walk (at most one per node).
  • Leave prior_count itself, model_tuples_with_type, and the smoke scripts' .info prints 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

  1. autofit/mapper/prior_model/abstract.py — add a module-private function _unique_priors_by_node(obj, memo) (or a nested closure inside parameterization) that returns a dict keyed by Prior (the same keying unique_prior_tuples uses, so shared priors count once) for the subtree under obj:
    • isinstance(obj, Prior) → {obj: obj} (stop; matches ignore_children=True).
    • isinstance(obj, list) → union over items.
    • dict or obj.__dict__ → union over values whose key does not start with _; AttributeError/TypeError → empty (same fallthrough as path_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.
  2. In parameterization: build the memo lazily; keep the path_instance_tuples_for_class((Prior, float, Constant, tuple), ignore_children=True) listing and the for i in range(len(t[0])) prefix loop exactly as they are; replace n = obj.prior_count with n = len(_unique_priors_by_node(obj, memo)). Cache (path → (name, n)) per unique prefix so object_for_path runs once per prefix, preserving append order for find_groups.
  3. test_autofit/mapper/test_parameterization.py:
    • _reference_parameterization(model) — the pre-change algorithm copied verbatim (calls obj.prior_count), used as the oracle.
    • test_parameterization_matches_reference[...] parametrised over: nested Collections; two Models sharing a prior (parent N counts it once); af.Collection([...]) list children; TuplePrior; a Constant and a float instance; a zero-dimension child; a Model with an integer attribute. Assert model.parameterization == _reference_parameterization(model) byte-for-byte on a fresh model each time.
    • test_parameterization_walks_each_node_once — monkeypatch autofit.mapper.model.path_instances_of_class with a counting wrapper; assert the count during a fresh parameterization equals the count of one path_instance_tuples_for_class((Prior, float, Constant, tuple), ignore_children=True) walk on an identical model (at most one call per node).
  4. Micro-benchmark in the PR body (synthetic nested collection of ~200 models): before/after wall time and path_instances_of_class call 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_path
  • test_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_class for the Prior case 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_count on its own is left as is: outside parameterization it 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.info and factor_graph.global_prior_model.info on autogalaxy_workspace_test mge_group.py are byte-identical before and after; path_instances_of_class calls under model.info drop 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,498 prior_count calls driving 763,555 recursive
    path_instances_of_class calls.
  • global_prior_model.info — 3,497 prior_count calls 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

  1. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR created: #1637 (branch claude/parameterization-prior-count-blowup-jzsrj0, commit 97a92e6, label pending-release).

    Implemented as planned: a module-private _subtree_unique_priors memoises each node's distinct-prior set bottom-up inside one parameterization call; leaf listing and entry order untouched. Full test_autofit/ suite: 2813 passed, 48 skipped. Synthetic 561-prior model: 6.2 s / 3,244,174 path_instances_of_class calls → 0.012 s / 2,374.

    Workspace impact: none (no API change; option iii). Left for the human: the mge_group.py timing witness (needs autogalaxy_workspace_test), then /prm once CI is green. This session ends at PR-open.


    Generated by Claude Code

  2. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    • PR: perf: memoise prior_count bottom-up in AbstractPriorModel.parameterization #1637 — merged into main at 7c0e79a (CI green on every leg: unittest 3.12 / 3.13 / nojax, docs-build). Label pending-release carried; the library is merged, not yet released.
    • What changed: AbstractPriorModel.parameterization now computes each node's distinct-prior set once, bottom-up, memoised by object identity for the duration of one call, instead of calling prior_count (a full subtree walk) on every prefix of every leaf path. Rendered .info text is byte-identical (oracle test keeps the old algorithm verbatim); one path_instances_of_class call per node. Synthetic 561-prior model: 6.2 s / 3,244,174 calls → 0.012 s / 2,374.
    • Run identifiers verified unchanged: model.identifier is byte-identical on main and this branch for six model shapes, before and after touching .info (the identifier hashes __dict__ skipping underscore keys; the change adds no attribute).
    • Left for the human: the mge_group.py timing witness on autogalaxy_workspace_test (needs that workspace; expected warm run 19.3 s → ≤ 14 s).

    Generated by Claude Code

  3. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Timing witness measured (autogalaxy_workspace_test scripts/multi_dataset/jax_likelihood/mge_group.py, smoke-profile env with JAX and full datasets enabled per the script's ENV: line, this container: 4 cores, XLA_FLAGS=--xla_cpu_multi_thread_eigen=false, JAX_ENABLE_X64=True; PyAutoFit 3abbc13 = main before this merge, 7c0e79a = after):

    PyAutoFit warm wall parameterization (2 calls)
    before (3abbc13) 15.5 s 4.51 s
    after (7c0e79a) 10.6 s 0.01 s
    • model.info and factor_graph.global_prior_model.info byte-identical before and after (332 lines, same sha256).
    • Warm run down 4.9 s here (the prompt's ≥ 5 s was measured on a laptop where the two prints cost 7.25 s; here they cost 4.5 s, and nearly all of it is gone). The prompt's ≤ 14 s ceiling is met at 10.6 s.

    Generated by Claude Code

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