Skip to content

fix: Model.from_instance carries attrs the constructor rejects #1607

Closed

Description

@Jammy2211

Overview

af.Model.from_instance(instance) copies every attribute in instance.__dict__ onto the model, including attributes __init__ derives from its arguments (ExternalShear's centre, Isothermal's slope). The model.json a search then writes is typed instance, and from_dict calls cls(**arguments), which raises TypeError: unexpected keyword argument. Aggregator.from_directory therefore fails before reading any result of a search whose model was anchored on a truth instance.

Plan

  • Pass only constructor parameters from from_instance to Model, using the same signature inspection Model.constructor_argument_names already relies on.
  • Keep all keys for classes whose __init__ accepts **kwargs; keep current behaviour when the signature cannot be inspected.
  • Regression tests: derived-attribute class round-trips through dict()/from_dict; Aggregator.from_directory loads a model.json written from such a model.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main clean

Suggested branch: claude/autofit-model-instance-roundtrip-erf439
Work classification: Library
Worktree root: n/a (web session clone)

Implementation Steps

  1. autofit/mapper/prior_model/abstract.py, from_instance, generic-object branch: filter instance.__dict__ to inspect.getfullargspec(instance.__class__) args + kwonlyargs (minus self); skip the filter when varkw is set or inspection raises TypeError.
  2. test_autofit/mapper/model/: regression test on a class with a derived attribute (set in __init__) and a @property; assert model keys, dict()["arguments"], and af.Model.from_dict(model.dict()) all succeed; assert a **kwargs class keeps its extra keys.
  3. test_autofit/aggregator/test_from_directory.py: copy the search_output fixture, overwrite files/model.json with from_instance(...).dict() of the derived-attribute class, assert Aggregator.from_directory yields one output whose model loads.
  4. pytest -n auto test_autofit/mapper test_autofit/aggregator, then the full suite.

Key Files

  • autofit/mapper/prior_model/abstract.py — from_instance (line ~1580), the fix
  • autofit/mapper/prior_model/prior_model.py — Model.__init__ / constructor_argument_names, the inspection pattern to mirror
  • autofit/mapper/model_object.py — from_dict instance branch that calls cls(**arguments)
  • test_autofit/aggregator/test_from_directory.py — fixture pattern for the aggregator test

Original Prompt

Click to expand starting prompt

af.Model.from_instance serialises derived attributes the class __init__ rejects, so the aggregator cannot deserialise model.json

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Difficulty: small
    Autonomy: safe
    Priority: high
    Status: formalised
    Consequence: judge
    Witness: af.Model.from_dict(af.Model.from_instance(al.mp.ExternalShear(gamma_1=0.02, gamma_2=0.02)).dict()) and the same for al.mp.Isothermal(...) round-trip without error, a regression test in test_autofit/mapper pins it on a class whose __init__ rejects a derived attribute, and an Aggregator.from_directory over a search whose model was composed with from_instance loads the result.
    Review-minutes: 15
    Unattended: ready
    Filed: 2026-09-10

Symptom

Found 2026-09-10 while writing the autolens_workspace_test latent integration smoke
(autolens_workspace_test#315 / PR #316). Composing a model with
af.Model.from_instance(<profile instance>) copies derived attributes onto the model
that the class constructor does not accept, and the model.json the search then writes
cannot be deserialised, so Aggregator.from_directory raises before reading any result:

af.Model.from_dict(af.Model.from_instance(al.mp.ExternalShear(gamma_1=.02, gamma_2=.02)).dict())
  -> TypeError: ExternalShear.__init__() got an unexpected keyword argument 'centre'
af.Model.from_instance(al.mp.Isothermal(...))
  -> TypeError: ... unexpected keyword argument 'slope'

The serialised dict carries centre / ell_comps (ExternalShear) and slope
(Isothermal) as Constant / tuple arguments. af.Model(cls, ...) round-trips fine, and
al.lp.Sersic via from_instance also round-trips (no derived attribute clashes).

Blast radius

  • euclid_strong_lens_modeling_pipeline/tests/test_latent_run_level.py composes its
    model with from_instance; any output written that way is unreadable by the
    aggregator (the test never aggregates, so it passes).
  • Any workspace example that anchors a search on a truth instance via from_instance
    produces results the aggregator / AggregateCSV cannot open.

Do

  1. from_instance should only carry attributes that are constructor parameters
    (inspect the class signature, as Model.__init__ already does for priors) — or
    from_dict should drop non-constructor keys with a warning. Prefer the former: the
    written model.json should be loadable as-is.
  2. Regression test on a small class with a derived attribute (@property or an
    attribute set in __init__ from other arguments) plus an aggregator round-trip.

The smoke composes its models with af.Model(cls, **fixed_values) as a workaround; the
script docstring records why.

Activity

  1. Jammy2211 commented on Sep 11, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    API changes: none — internal. from_instance now passes only constructor parameters to Model (all keys kept for **kwargs / uninspectable constructors); derived attributes are recomputed by __init__ on rebuild.

    Tests: 5 new round-trip tests in test_autofit/mapper/model/test_from_instance_roundtrip.py and an Aggregator.from_directory regression in test_autofit/aggregator/test_from_directory.py, all failing without the fix. Full suite: 2575 passed, 43 skipped, 0 failed.

    Workspace impact: none (option iii) — no public symbol changed. Next: /prm once CI is green.

    Noted while validating, not touched here: pytest -n auto cannot run the suite because test_autofit/mapper/prior/test_prior_properties.py embeds object addresses in parametrize ids, so xdist workers collect different ids. Reproduced on a clean tree; worth its own issue.


    Generated by Claude Code

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

    @Jammy2211
    CollaboratorAuthor

    Shipped

    • PR: fix: Model.from_instance carries only constructor parameters (#1607) #1609 — MERGED (e612e20), CI green on all legs (unittest 3.12 / 3.13 / nojax, docs-build). Label pending-release stays until the next PyPI release publishes it.
    • Change: AbstractPriorModel.from_instance now passes only constructor parameters to Model (all attributes kept for **kwargs / uninspectable constructors), so a model.json written from from_instance round-trips through from_dict and loads in Aggregator.from_directory. No public API change.
    • Tests: test_autofit/mapper/model/test_from_instance_roundtrip.py (5) and test_autofit/aggregator/test_from_directory.py::test_model_written_from_instance_is_loaded, all failing without the fix.
    • Mind record: PyAutoMind/complete/2026/09/autofit-from-instance-roundtrip.md.

    Follow-up filed separately in PyAutoMind: the suite cannot run under pytest -n auto because test_autofit/mapper/prior/test_prior_properties.py embeds object addresses in its parametrize ids.


    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