Skip to content

fix: Model.tree_flatten fails on zero direct priors and drops TuplePrior children #1777

Closed

Description

@Jammy2211

Overview

Model.tree_flatten (autofit/mapper/prior_model/prior_model.py) builds the pytree from direct_prior_tuples alone. A Model with zero direct priors (e.g. af.Model(al.DatasetModel), whose grid_offset priors sit under a TuplePrior) crashes with ValueError: not enough values to unpack (expected 2, got 0), and a model with a free TuplePrior plus a scalar silently loses the tuple priors on round-trip (prior_count 3 → 1). Nothing reaches a search today (Fitness closes over the model), so this is a latent correctness fix.

Reproduced on fresh main (PyAutoFit@ac881b5c) with a DatasetModel-shaped class after autofit.jax.register_model:

a (nothing free)          0 -> ValueError not enough values to unpack (expected 2, got 0)
b (grid_offset free)      2 -> ValueError not enough values to unpack (expected 2, got 0)
c (grid_offset + sky)     3 -> 1

Plan

  • Make Model.tree_flatten cope with zero direct priors (empty children, empty names) instead of unpacking an empty zip.
  • Carry the model's TuplePrior attributes as pytree children alongside its direct priors, so tree_unflatten rebuilds them.
  • Give TuplePrior its own tree_flatten / tree_unflatten (prior members as children, fixed members in aux data) and register it in enable_pytrees, so JAX recurses into it rather than treating it as an opaque leaf.
  • Add a round-trip test over a DatasetModel-shaped Model for the three cases, asserting prior_count is 0, 2, 3 before and after.
  • Tier: glance — merge mode: auto-merge on green if the Witness passes, post-merge summary
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./fit/PyAutoFit main (behind 3) clean

PyAutoFit is claimed by active task ep-projected-model-shared-prior (PyAutoFit#1773, branch feature/ep-projected-model-shared-prior), which edits autofit/non_linear/samples/samples.py and test_autofit/graphical/test_unification.py. This task touches none of those files.

Suggested branch: feature/model-pytree-tuple-prior

Implementation Steps

  1. autofit/mapper/prior_model/prior_model.py Model.tree_flatten: tuples = list(self.direct_prior_tuples) + list(self.direct_tuple_priors); names = tuple(n for n, _ in tuples), children = tuple(v for _, v in tuples); return children, (names, self.cls). tree_unflatten is unchanged (Model(cls_, **arguments) already accepts TuplePrior kwargs — checked: rebuilds prior_count 0/2/3).
  2. autofit/mapper/prior/tuple_prior.py: add tree_flatten (children = prior members, aux = prior names + fixed (name, value) members excluding id) and classmethod tree_unflatten (TuplePrior(**priors, **fixed)).
  3. autofit/jax/pytrees.py enable_pytrees: add TuplePrior to the registered classes.
  4. Test test_autofit/jax/test_model_pytree_tuple_prior.py (or alongside the existing pytree tests): pytest.importorskip("jax"), a local DatasetModel(background_sky_level=0.0, grid_offset=(0.0, 0.0)) class, cases (a)/(b)/(c), register_model, tree_flatten → tree_unflatten, assert prior_count equal (0, 2, 3) and the rebuilt grid_offset is a TuplePrior.

Out of scope (noted, not changed)

  • Model.tree_flatten also omits direct child models and fixed constants (they are re-created from defaults on unflatten); Collection.tree_flatten has the same empty-zip unpack on an empty collection.

Key Files

  • autofit/mapper/prior_model/prior_model.py — Model.tree_flatten
  • autofit/mapper/prior/tuple_prior.py — TuplePrior pytree methods
  • autofit/jax/pytrees.py — enable_pytrees registration

Original Prompt

Click to expand starting prompt

DatasetModel with a free grid_offset cannot round-trip autofit.jax.register_model

Type: bug
Target: autofit
Repos:

  • PyAutoFit
    Themes:
  • jax
    Difficulty: small
    Autonomy: safe
    Priority: normal
    Status: draft
    Consequence: glance
    Witness: A round-trip test through jax.tree_util.tree_flatten / tree_unflatten after autofit.jax.register_model, over a Model with zero direct priors and a TuplePrior child (the DatasetModel shape) with (a) nothing free, (b) the tuple free, (c) the tuple plus one scalar free, passes with prior_count equal before and after (0, 2, 3).
    Review-minutes: 3
    Lane: any
    Filed: 2026-09-03

Symptom

A bare af.Model(al.DatasetModel) cannot be round-tripped through
jax.tree_util.tree_flatten / tree_unflatten after
autofit.jax.register_model: flattening raises

ValueError: not enough values to unpack (expected 2, got 0)
(autofit/mapper/prior_model/prior_model.py:331, Model.tree_flatten)

Corrected 2026-09-04 while triaging autolens_workspace#524. Three facts replace
the original description:

  1. The failure is a ValueError in Model.tree_flatten, not a TypeError in
    Prior.tree_unflatten (that line is never reached).
  2. It is not caused by a free grid_offset: the same model with no free
    parameters fails identically. The trigger is a Model with zero direct
    priors — the grid_offset priors live under a TuplePrior, which
    direct_prior_tuples excludes.
  3. Related silent defect: with grid_offset_0/1 and background_sky_level
    free (prior_count 3), the round-trip succeeds but the rebuilt model has
    prior_count 1 — Model.tree_flatten drops TuplePrior children.

None of this reaches a search: Fitness (autofit/non_linear/fitness.py:245)
captures the model as a closure constant and only traces the parameter vector.
A free grid_offset inside a FactorGraphModel(use_jax=True) compiles and runs
under the vmapped Nautilus fitness (verified on the corrected
multi_dataset/start_here.py). It blocks nothing today.

Originally found while building the free-grid_offset control for
gaussian-precompute-p2 (record complete/2026/09/gaussian-precompute-p2.md).

Fix

Make Model.tree_flatten handle zero direct priors and include TuplePrior
children (so tree_unflatten rebuilds them), and add a round-trip test over a
DatasetModel with (a) nothing free, (b) a free grid_offset, (c) a free
grid_offset plus background_sky_level, asserting prior_count survives.

Activity

  1. Jammy2211 commented on Nov 16, 2026

    @Jammy2211
    CollaboratorAuthor

    Parked by shift worker 2026-11-16-pm — question for the human.

    What was done. The premise check passed and the bug reproduces on fresh main (PyAutoFit@ac881b5c): cases (a) and (b) raise ValueError: not enough values to unpack (expected 2, got 0) in Model.tree_flatten, and case (c) round-trips with prior_count 3 → 1. The fix and its test are planned in full above. No branch or worktree has been made.

    Why it stopped. PyAutoFit is claimed in active.md by ep-projected-model-shared-prior (PyAutoFit#1773, branch feature/ep-projected-model-shared-prior, human-run, judge tier). The claim guard says two tasks on one repo must run one after the other unless you approve an override. That task changes autofit/non_linear/samples/samples.py and test_autofit/graphical/test_unification.py. This one would change autofit/mapper/prior_model/prior_model.py, autofit/mapper/prior/tuple_prior.py, autofit/jax/pytrees.py and one new test file, so no file overlaps. You approved the same kind of override for three-autos-public-framing on 2026-11-13.

    Options.

    1. Override (recommended): allow a separate worktree off main for feature/model-pytree-tuple-prior alongside fix: EP projection KeyError for a prior shared across model paths #1773, since no files overlap. The next shift implements the fix and opens a glance-tier PR.
    2. Wait: keep this task blocked until fix: EP projection KeyError for a prior shared across model paths #1773 merges, then a shift picks it up.
    3. Drop: the bug blocks nothing today (Fitness closes over the model), so shelve it.

    Resume after an answer: option 1 → conflict-override: line on the active.md row, start_library, then implement as above. Option 2 → move to planned.md with blocked-by: ep-projected-model-shared-prior.

  2. Jammy2211 commented on Nov 16, 2026

    @Jammy2211
    CollaboratorAuthor

    Use 1

  3. Jammy2211 commented on Nov 18, 2026

    @Jammy2211
    CollaboratorAuthor

    Unblocked 2026-11-18. #1773 has shipped as PR #1778 (awaiting /prm), and the override answered above stands: work on a separate worktree off main (feature/model-pytree-tuple-prior). There is no file overlap with #1778. Mind active.md now lists this task as ready.

  4. Jammy2211 commented on Nov 18, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR opened: #1779 (branch feature/model-pytree-tuple-prior).

    • Repro on the branch base: (a) and (b) raised ValueError; (c) failed on the rebuild. With the fix, prior_count is 0→0, 2→2 and 3→3, and grid_offset is rebuilt as a TuplePrior.
    • Tests: full test_autofit 4295 passed, 2 skipped, 1 xfailed. The new round-trip test fails 3 of 4 without the fix.
    • Smoke: autofit + autogalaxy 26/26 PASS. Heart dev readiness: GREEN.
    • Workspace impact: none (option iii). Stopped at PR-open; next step is a human /prm.
  5. Jammy2211 commented on Nov 18, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped in #1779 (merged 17b87edb, 2026-11-18). Model.tree_flatten handles zero direct priors and carries TuplePrior attributes as pytree children; TuplePrior has its own flatten/unflatten and is registered in enable_pytrees. Round-trip keeps prior_count 0/2/3. Tests: full test_autofit 4295 passed; autofit + autogalaxy smoke 26/26. Pending release. Follow-up (fixed non-prior attributes such as a fixed sky level are not carried through the round-trip) is being filed as its own task.

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