Repository navigation
Description
Overview
The flagship JAX profiling script jax_profiling/imaging/mge.py currently JITs a closure that takes a flat 1D parameter vector and unpacks it via model.instance_from_vector inside the trace. This obscures parameter identity under jax.jit, forces vmap callers to stack (batch, N) arrays, and does not match the pytree-native direction the rest of the codebase has moved toward. This task migrates the script to pytree inputs so JIT and vmap flatten/unflatten parameters automatically and preserve their names.
Plan
- Dig through ~12-month-old git history for prior pytree implementations in PyAutoFit, PyAutoArray and PyAutoGalaxy; use them as templates rather than designing from scratch.
- Re-enable / extend pytree registration on
af.ModelInstance(and supporting classes in autogalaxy / autoarray as needed) so it can cross ajax.jitboundary directly. - Replace the flat
jnp_paramsJIT input inmge.pywith a structured pytree. - Update
mapping_matrix_from_params,blurred_mm_from_params, the full-pipeline JIT and the vmap path to consume the pytree directly — removingmodel.instance_from_vectorfrom inside the trace. - Keep profiling outputs (per-step timings, JSON summary, bar chart) format-compatible; timings should match within noise.
- Refresh the module docstring to document pytree inputs as the recommended pattern for new profiling scripts.
- Follow-up (separate work): propagate the same pattern to
pixelization.pyanddelaunay.py.
Detailed implementation plan
Affected Repositories
PyAutoLabs/autolens_workspace_developer(primary — originating request)rhayes777/PyAutoFit(pytree registration onPriorModel/ModelInstance)Jammy2211/PyAutoArray(potentially — extend existinguniform.py/ triangle pytree wrapping)Jammy2211/PyAutoGalaxy(potentially —Galaxy,Tracer, light/mass profiles)
Work Classification
Library + Workspace. /start_library first; autolens_workspace_developer script changes follow once library-side registration is in place.
Historical pytree references
| Repo | Commit / PR | Content |
|---|---|---|
| PyAutoFit | autofit/mapper/prior_model/prior_model.py:281,289 |
tree_flatten / tree_unflatten on PriorModel already present; register_pytree_node call at line 211 is currently commented out — check git blame for the reason before re-enabling |
| PyAutoFit | PR #1037 feature/jax_pytree, PR #1103 feature/graphical_pytrees |
AnalysisFactor, FactorGraphModel pytree methods, prior-id children |
| PyAutoArray | 9a8d17fe "tree flatten point and circle" (Sep 2024) |
autoarray/structures/triangles/shape.py |
| PyAutoArray | e6419042 + PR #137 feature/jax_tracer (Oct 2024) |
autoarray/operators/over_sampling/uniform.py — still present today |
| PyAutoGalaxy | feature/jax_mge, feature/jax_tracer branches |
precursor profile/tracer pytree work |
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./autolens_workspace_developer | main | dirty (unrelated fits / json / png results + untracked probe scripts; snapshotted to z_staging/imaging-mge-pytree-migration-dirty-snapshot/; do not touch) |
| ./PyAutoFit | main | (check at worktree creation) |
| ./PyAutoArray | main | (check at worktree creation) |
| ./PyAutoGalaxy | main | (check at worktree creation) |
Suggested branch: feature/imaging-mge-pytree-migration (used consistently across all affected repos)
Worktree root: ~/Code/PyAutoLabs-wt/imaging-mge-pytree-migration/ (created later by /start_library)
Implementation Steps
git show/git diffthe historical commits listed above to understand the prior pytree approach. Readautofit/mapper/prior_model/prior_model.py:205-295and investigate whyregister_pytree_nodewas commented out.- Re-enable
register_pytree_nodeonPriorModel(andModelInstanceif needed) in PyAutoFit. If the reason for the original comment-out still applies, work around it (e.g. selective leaf registration) rather than blindly uncommenting. - Extend pytree registration to
Galaxy,Tracer, and thelp_linear.MultiGaussian/mp.Isothermal/mp.ExternalShearprofile classes used inmge.py— only as far as needed to let aModelInstancecross a JIT boundary and be rebuilt into aTracerinside the trace. - Add unit tests in PyAutoFit / PyAutoGalaxy covering flatten → unflatten round-trip and
jax.jit/jax.vmapover a simpleModelInstance. - In
autolens_workspace_developer/jax_profiling/imaging/mge.py:- After
instance = model.instance_from_vector(vector=param_vector)(setup, not JIT), passinstance(pytree-registered) directly as the JIT input. - Rewrite
mapping_matrix_from_params(mge.py:336): accept the pytree, buildTracerviaal.Tracer(galaxies=list(instance.galaxies))— noinstance_from_vectorin the trace. - Rewrite
blurred_mm_from_params(mge.py:373): same change. - Replace the full-pipeline
fitness.call(jnp_params)profile block (mge.py:554-563) with a pytree-accepting closure defined inside the script. Do NOT modifyFitness.callitself (explicit out-of-scope per original prompt). - vmap section (mge.py:572-603): build batched pytree via
jax.tree_util.tree_map(lambda leaf: jnp.broadcast_to(leaf, (batch_size, *leaf.shape)), instance), vmap the new closure, keep the correctness assertion. - Static memory analysis block (mge.py:609-621): point
batched_callat the pytree closure. - Update the top-of-file docstring and inline comments to document pytree inputs as the recommended pattern.
- After
- Verify:
cd jax_profiling/imaging && NUMBA_CACHE_DIR=/tmp/numba_cache MPLCONFIGDIR=/tmp/matplotlib python mge.py. Correctness asserts must pass; timings within noise of prior JSON results.
Key Files
PyAutoFit/autofit/mapper/prior_model/prior_model.py— re-enable pytree registrationPyAutoGalaxy/autogalaxy/galaxy/galaxy.py,.../profiles/**— extend registration as neededPyAutoLens/autolens/lens/tracer.py— extend registration as neededautolens_workspace_developer/jax_profiling/imaging/mge.py— the migration
Out of scope (explicit)
PyAutoFit/autofit/non_linear/fitness.py(Fitness.call)PyAutoFitmodel.instance_from_vector(production path)jax_profiling/imaging/pixelization.py— follow-upjax_profiling/imaging/delaunay.py— follow-up- Any dirty/untracked files in
autolens_workspace_developer(snapshotted toz_staging/imaging-mge-pytree-migration-dirty-snapshot/; left alone)
Original Prompt
Click to expand starting prompt
# Imaging MGE JAX JIT Profiling — Migrate to Pytree Inputs
## Context
`autolens_workspace_developer/jax_profiling/imaging/mge.py` is the
flagship JAX JIT profiling script for the MGE source model. It
builds `Fitness.call` around a 1D parameter vector
(`jnp_params`, shape `(N,)`) and JITs that closure.
Passing parameters as a flat 1D vector has two long-term downsides:
1. **`model.instance_from_vector` is the JIT boundary**. That call
has to unpack the flat vector into every named structured
parameter (centres, ell_comps, intensities, sigmas, redshifts,
…) inside the trace. For a model with many parameters this is
pure Python shape-juggling that runs once per compile but
obscures the parameter identity under `jax.jit`.
2. **Batching with `vmap`** requires the caller to stack parameter
vectors into a 2D `(batch, N)` array. The structured parameter
names are lost along the way — any diagnostic that wants to
plot likelihood vs `einstein_radius` has to know the positional
index of `einstein_radius` in the flat vector, which is
fragile.
The rest of the codebase (tracers, galaxies, profiles) has moved
toward **pytree-native** inputs: nested dicts / `ModelInstance`
objects registered as JAX pytrees, so `jax.jit` flattens and
unflattens them automatically, and `vmap` batches over the pytree
leaves without the caller having to reshape anything.
## Task
Update `autolens_workspace_developer/jax_profiling/imaging/mge.py`
so that:
1. The JIT'd closure takes a **pytree** of parameters (e.g. a
nested dict keyed by galaxy name → profile name → parameter
name, or the `af.ModelInstance` object itself if it's now
pytree-registered) rather than a flat 1D array.
2. `jax.jit` and `jax.vmap` are applied to that pytree-accepting
closure directly — no flat-vector shim.
3. The profiling output (compile time, steady-state runtime, vmap
batch throughput) should be unchanged within noise — this is a
clarity / API-ergonomics change, not a performance change.
4. Update the inline commentary to point at the pytree inputs as
the recommended pattern for new profiling scripts.
Once `mge.py` is updated, treat it as the new reference style and
propagate the same pattern to `pixelization.py` and `delaunay.py`
as a follow-up.
## Why this matters
- Downstream users reading the script will more easily see *which*
parameter is which, because the pytree preserves names.
- `jax.jit` compile caches are keyed on the abstract pytree
structure; this change makes the cache key human-readable.
- Eventually we will want to build user-facing `jax.jit`'d
likelihood functions that accept a `ModelInstance` directly —
the profiling script should demonstrate that end-state, not an
older flat-vector style.
## Risks / blockers
- If `af.ModelInstance` is not yet registered as a JAX pytree,
this change either (a) needs that registration to happen first,
or (b) uses a plain nested dict as an interim representation.
Check `autofit`'s pytree registration status before starting;
file a blocker issue if registration is missing.
- `model.instance_from_vector(..., xp=jnp)` is currently relied on
by several other profiling scripts and by the production
`Fitness.call`. This task *only* changes the profiling script,
not the production path — do not touch `Fitness` or `model.instance_from_vector`.
## Pytree Registration Old
Older versions (12ish months ago) of PyAutoFit, PyAutoArray and PyAutoGalaxy had working Pytree circulations.
Dig through their git history first and see if you can find source code there to help you as a reference.
Activity
Jammy2211 commentedon Apr 16, 2026
Library PRs Created — 2026-04-16
PRs
Status
Workspace changes needed. Next:
/start_workspaceto ship themge.pymigration inautolens_workspace_developer.API Changes
Purely additive — no removals or signature changes.
autoconf.jax_wrapper.register_pytree_node_class(cls)/register_pytree_node(nodetype, flatten_func, unflatten_func)— lazy, no-op if JAX missing.autofit.jaxsub-package exposingenable_pytrees()andregister_model(model). The latter walks aModel/Collectionand partitions eachModel.cls's constructor args: constants (fromdirect_instance_tuples) → JAXaux_dataso they stay concrete under JIT; priors →children. This keeps code likesorted(galaxies, key=lambda g: g.redshift)working insidejax.jit.Workspace Usage
autolens_workspace_developer/jax_profiling/imaging/mge.pynow runs its fullvmap(jit(full_pipeline_from_params))pipeline on a pytreeModelInstanceinstead of a flat 1D vector — no moreinstance_from_vectorinside the trace.Fitness.callis untouched.Jammy2211 commentedon Apr 16, 2026
Shipped — 2026-04-16
PRs
Upstream PRs
Summary
Migrated
jax_profiling/imaging/mge.pyfrom a flat 1D parameter vector to pytreeModelInstanceinputs. Full-pipeline JIT + vmap now consume the pytree directly viaanalysis.log_likelihood_function(instance=params_tree)withuse_jax=True.Fitness.callandmodel.instance_from_vectorare untouched — the production sampler path is unaffected.The library side adds
autofit.jaxwithenable_pytrees()+register_model(model).register_modelpartitions eachModel.clsconstructor's arguments: constants (fromdirect_instance_tuples) go into JAXaux_dataso they stay concrete under JIT, priors becomechildren. This keeps code likesorted(galaxies, key=lambda g: g.redshift)working insidejax.jit.Session Notes
Galaxy.redshift=0.5became a tracer andTracer.galaxies_ascending_redshiftblew up onsorted(..., key=lambda g: g.redshift)withTracerBoolConversionError. Routing constants frommodel.direct_instance_tuplesintoaux_datafixed it.use_jax=Trueon the Analysis, notFitImagingdirectly. An earlier attempt usedal.FitImaging(dataset, tracer, settings)which ranxp=npinternally and raisedTracerArrayConversionErrorinsideautogalaxy/convert.py(np.whereon a JAX bool). Switching toal.AnalysisImaging(dataset, use_jax=True)+analysis.log_likelihood_function(...)threadsxp=jnpthrough the whole pipeline.register_pytree_node_classcalls that forced ajax.tree_utilimport on everyimport autofitare intentionally not restored.enable_pytrees()defers the JAX import to call time and no-ops if JAX is missing;ValueErrors from duplicate registration are tolerated silently.jax_profiling/imaging/pixelization.pyanddelaunay.py. Called out in the original prompt as follow-up.Jammy2211 commentedon Apr 17, 2026
Library PR Created — 2026-04-17
PR
Status
Workspace changes needed. Next: /ship_workspace (workspace script migration is already implemented; this PR ships it).
Summary
Fixes two bugs in
autofit.jax._build_instance_pytree_funcsthat surfaced when migratingjax_profiling/imaging/pixelization.pyto pass aModelInstancepytree into JIT/vmap directly:Galaxy(pixelization=<Pixelization>)) were routed intochildreninstead ofaux_data, so underjax.jitthe pixelization became a tracer andisinstance(x, aa.Pixelization)silently returned False — leavingfit.inversionNone.**kwargsclasses likeGalaxyproduce instances with different attribute sets across models (lens:bulge/mass/shear; source:pixelization). JAX allows one flatten per class, so the first model's captured name list raisedAttributeErrorwhen flattening the other instance.Fix
Shared
_CLASS_FIELD_CLASSIFIERS[cls]dict accumulates classifications across everyregister_modelwalk.flattennow iteratesvars(instance)at call time and defaults unknown attrs to aux_data.Jammy2211 commentedon Apr 17, 2026
Shipped (pixelization) — 2026-04-17
PRs
Summary
jax_profiling/imaging/pixelization.pynow passes aModelInstancepytree directly intojit/vmapviaautofit.jax.register_model, matching themge.pypattern shipped in #11. Both correctness assertions pass end-to-end (step-by-steplog_evidencevs reference rtol=1e-4; vmap batch=3 vs single JIT rtol=1e-4).Session Notes
autofit.jax._build_instance_pytree_funcs: concrete non-Prior kwargs (e.g.Galaxy(pixelization=<Pixelization>)) were classified usingdirect_argument_names/direct_instance_tuples, which don't see attributes stored directly onmodel.__dict__. They ended up inchildrenand became JAX tracers under JIT, breakingisinstance(x, aa.Pixelization)insideFitImagingsofit.inversionsilently resolved toNone.model.items()for classification) was still insufficient:Galaxy.__init__(self, redshift, **kwargs)produces instances with different attribute sets per model (lens:bulge/mass/shear; source:pixelization) while sharing onecls. JAX registers flatten per-class, so the captured name list from whichever model was seen first raisedAttributeError: 'Galaxy' object has no attribute 'bulge'when flattening the other instance._CLASS_FIELD_CLASSIFIERS[cls]dict accumulates classifications across everyregister_modelwalk viasetdefault;flatteniteratesvars(instance)at call time and defaults unknown attrs toaux_data(safer than tracing an unknown object). Regression testtest_register_model_keeps_kwarg_constants_staticcovers the concrete-kwarg +**kwargspattern.FitImaging(..., xp=jnp)kept insideblurred_mm_from_paramsbecause that closure extractsoperated_mapping_matrixwhichAnalysisImaging.log_likelihood_functiondoes not expose.Jammy2211 commentedon Apr 17, 2026
Shipped (follow-up) — 2026-04-17
PRs
Summary
Migrated
jax_profiling/imaging/mge_gradients.pyto pass aModelInstancepytree throughjit/value_and_gradinstead of a flat 1D parameter vector, matching the pattern shipped in #11 (mge.py) and #12 (pixelization.py). TheFitnesswrapper andModel.instance_from_vectorno longer appear inside the JIT trace — gradient profiling now reflects how a real pytree-native sampler would run.Session Notes
Fitness.calltoAnalysisImaging(use_jax=True).log_likelihood_function(instance=params_tree), same substitution used in mge.py (feat: migrate jax_profiling/imaging/mge.py to pytree inputs #11). pixelization.py (refactor(jax_profiling): migrate imaging/pixelization.py to pytree inputs #12) keptFitImaging(..., xp=jnp)inside its per-step closure because it specifically needsoperated_mapping_matrix; mge_gradients.py's per-step closures don't need inversion internals, soAnalysisImagingfits cleanly for the full-pipeline step only.test_gradhelper now tree-flattens the gradient viajax.tree_util.tree_leaves(grad)+np.concatenate(...)for statistics — gradient shape is no longer a flat 1D vector._diagnose_kappainner_lossusesjax.value_and_grad(_loss)(params_tree)with the same tree-flatten pattern; all four kappa values (1e-3, 1e-2, 1e-1, 1.0) reported FULLY FINITE GRADIENTS.jax_profiling/imaging/) becausedataset_pathis relative to pwd. The CLAUDE.md "cd jax_profiling/imaging" hint is misleading for this specific script.Jammy2211 commentedon Jul 28, 2026
Closing as complete — swept by an issue-tracker reconciliation pass.
This work shipped and is recorded in PyAutoMind:
PyAutoMind/complete/2026/04/imaging-mge-pytree-migration.mdPyAutoMind/complete/2026/04/mge-gradients-pytree-migration.mdPyAutoMind/complete/2026/04/pixelization-pytree-migration.mdVerified via two independent legs: the record claims this issue in its
- issue:header, and its pull request is confirmed merged. Reopen if anything here is still outstanding.