Repository navigation
Description
Overview
Make every concrete Prior subclass's value_for(unit) and log_prior_from_value(value) JAX-traceable via an explicit xp kwarg dispatch, so the cube → physical mapping and prior log-density can run inside jax.jit without a jax.pure_callback host roundtrip. This is Phase 0 of the nss_first_class_sampler roadmap and the critical prerequisite — without it, af.NSS's measured 0.5 ms/eval advantage over Nautilus collapses back to the boundary-cost league (~18 ms/eval via pure_callback).
Plan
- Add
xp=npkwarg to everyPrior.value_for(5 subclasses + base + message-level) so the same code path runs symbolically under JAX or eagerly under NumPy. - Drop the
float(round(unit, 14))materialisation inUniformPrior.value_forfor the JAX path while preserving it for the NumPy path (existing tests rely on it as a hash key). - Replace the existing
isinstance(unit, np.ndarray)branch inNormalMessage.value_forwith explicitxpdispatch for consistency with the rest of the patch. - Audit every
log_prior_from_valuebody to usexp.log/xp.where/xp.zeros_likerather than Python scalars (subclasses already acceptxp=npbut most bodies ignore it). - Thread
xpthroughModel.vector_from_unit_vectorso an@jax.jitwrapper of cube → physical can trace end-to-end.Fitnessalready wiresxp=self._xpintoinstance_from_vectorandlog_prior_list_from_vector. - Validate via an extensive integration plan emphasising the graphical / expectation-propagation framework in
autofit_workspaceandautofit_workspace_test— see "Testing approach" below.
Detailed implementation plan
Affected Repositories
- PyAutoFit (primary)
Work Classification
Library
Branch Survey
| Repository | Current Branch | Dirty? |
|---|---|---|
| ./PyAutoFit | main | clean |
Suggested branch: feature/priors-jax-native
Worktree root: ~/Code/PyAutoLabs-wt/priors-jax-native/ (created later by /start_library)
Implementation Steps
-
Base + message layer
autofit/mapper/prior/abstract.py:140— addxp=nptoPrior.value_for, delegate toself.message.value_for(unit, xp=xp).autofit/messages/normal.py:402— replaceisinstance(unit, ...)dispatch with explicitxpkwarg; usejax.scipy.special.erfinvwhenxpisjnp,scipy.special.erfinvotherwise.autofit/messages/truncated_normal.py:445— addxpkwarg; usejax.scipy.stats.truncnorm.ppffor JAX path (verified available in pinned JAX install),scipy.stats.norm.{cdf,ppf}for NumPy.
-
Concrete Prior subclasses (
value_for)uniform.py:135— keepfloat(round(..., 14))for NumPy path (hash-key invariant); drop it for JAX path.gaussian.py— addvalue_for(unit, xp=np)override using closed-formself.mean + self.sigma * xp.sqrt(2) * erfinv(2*unit - 1)so we avoid the message indirection (cleaner trace).truncated_gaussian.py— addvalue_for(unit, xp=np)override delegating toxp.scipy.stats.truncnorm.ppfdirectly.log_uniform.py:127— closed-formlower * (upper/lower)**unitviaxp.log_gaussian.py:116— closed-formxp.exp(GaussianPrior-style erfinv).
-
log_prior_from_valueaudit (xp kwarg already exists on every subclass)uniform.py:160— returnxp.where(in_bounds, xp.zeros_like(value), -xp.inf)instead of0.0.log_uniform.py:113— confirm + fix the current1.0/valuebody (looks wrong; log-uniform log prior should be-xp.log(value)modulo bounds).log_gaussian.py:136— replacenp.logwithxp.log, replacefloat("-inf")early-return withxp.where.messages/normal.py:430— already xp-friendly via math operators.messages/truncated_normal.py:479— already branches onxp.__name__.startswith("jax"). Keep as-is or align with explicit kwarg dispatch.
-
Model-level
prior_model/abstract.py:648—vector_from_unit_vector(unit_vector, xp=np): whenxp is np, returnlist(map(...))as today (preserve existing return type for Nautilus / Dynesty / Emcee); whenxpis JAX, returnxp.stack([...])1-D array.prior_model/abstract.py:1126—log_prior_list_from_vectoralready acceptsxp; verify it returns a JAX-compatible iterable whenxp=jnp.
-
New JAX tests (added in this PR)
test_autofit/mapper/prior/test_uniform_jax.py,test_gaussian_jax.py,test_truncated_gaussian_jax.py,test_log_uniform_jax.py,test_log_gaussian_jax.py— NumPy↔JAX parity forvalue_forandlog_prior_from_valueatatol=1e-12, gated onimport jax. Edge values:unit ∈ {0, 0.5, 1}, near-bound values, vector (not scalar) inputs.test_autofit/messages/test_normal_jax.py,test_truncated_normal_jax.py— message-levelvalue_forparity.test_autofit/non_linear/test_fitness_jax.py—Fitness(use_jax_jit=True)traces cleanly end-to-end on a model spanning all 5 Prior types.test_autofit/mapper/test_model_jax.py(new) —@jax.jit cube_to_phys(unit_vector)end-to-end on a 5-prior mixed-type model; gradient viajax.gradoflog_prior_list_from_vectorsummed.
-
Regression
- Full
pytest test_autofitmust pass — defaults stayxp=npso all existing NumPy callers (Nautilus, Dynesty, Emcee, Zeus) keep working untouched.
- Full
Key Files
autofit/mapper/prior/abstract.py— basevalue_forsignatureautofit/mapper/prior/{uniform,gaussian,truncated_gaussian,log_uniform,log_gaussian}.py— 5 concrete priorsautofit/messages/normal.py,autofit/messages/truncated_normal.py— message-levelvalue_forxp dispatchautofit/mapper/prior_model/abstract.py:648—vector_from_unit_vectortest_autofit/mapper/test_model_jax.py(new) — JIT-trace testtest_autofit/mapper/prior/test_<subclass>_jax.py(×5, new) — per-prior parity
Open Questions / Risks
UniformPrior.value_forrounds to 14 decimals for NumPy; verify no caller depends on identical-rounded values when the same Prior is queried with JAX.LogUniformPrior.log_prior_from_valuebody looks wrong (1.0/valuerather than-log(value)). Confirm + fix as a side-quest; gate behind a separate test.jax.scipy.stats.truncnorm.ppfis available in the current JAX install — confirmed at planning time. Re-verify in CI once the branch is up.autoconfflipsJAX_ENABLE_X64=Trueon import. Tests must not assume x64 explicitly; the JAX paths should producefloat64when x64 is enabled andfloat32otherwise.
Testing approach — extensive integration + parity gates
This PR changes the prior/message dispatch surface used by every non-linear search
and by the entire graphical / expectation-propagation framework. The validation
plan is deliberately heavy on integration testing — unit-test green is necessary
but not sufficient.
1. NumPy regression baseline (must be byte-equivalent on main vs branch).
Default xp=np paths are guaranteed unchanged except for the explicit
message-level dispatch refactor (isinstance(unit, np.ndarray) → xp kwarg).
Both branches must produce identical samples.csv / samples_summary.json
for every graphical/EP/non-linear-search smoke script.
2. New JAX parity unit tests — per-prior, per-method (value_for +
log_prior_from_value), at atol=1e-12, gated on import jax. See the
"Implementation Steps" → "New JAX tests" section above.
3. PyAutoFit unit-test gates — must all pass:
pytest test_autofit/mapper/prior/(existing + new)pytest test_autofit/messages/(we modifyNormalMessage/TruncatedNormalMessage)pytest test_autofit/mapper/test_model.pypytest test_autofit/graphical/— full directory:test_combined_analysis,
test_ep_analysis_factor,test_history,test_declarative_deterministic,
test_hierarchical/,test_global/pytest test_autofit/non_linear/pytest test_autofit(full sweep)
4. Workspace integration gates (autofit_workspace_test) — must execute clean:
scripts/graphical/simultaneous.py(graphical fit w/ shared priors,
exercisesvector_from_unit_vectorinside Nautilus's inner search)scripts/graphical/ep.py(full EP loop — highest-value gate)scripts/graphical/hierarchical.py(hierarchical model w/ parent-distribution priors)scripts/jax_assertions/fitness_dispatch.py(explicit JAX dispatch test —
assertions here must keep passing)scripts/jax_assertions/nested.py(JAX-driven nested sampling — closest
existing analogue to the futureaf.NSSuse case)- all
scripts/searches/*.py(Nautilus, Dynesty, Emcee, etc.)
5. Workspace tutorial gates (autofit_workspace):
scripts/features/graphical_models.py(end-user tutorial: AnalysisFactor +
FactorGraph + EP discussion)scripts/cookbooks/multiple_datasets.py(multi-dataset graphical fitting)
6. JIT-trace test (new file test_autofit/mapper/test_model_jax.py) —
@jax.jit wrapping model.vector_from_unit_vector(unit, xp=jnp) traces
cleanly with zero pure_callbacks and zero TracerArrayConversionErrors
on a 5-prior mixed-type model.
7. Smoke set policy — smoke_tests.txt is intentionally NOT extended.
The integration scripts above run as pre-merge gates inside /ship_library,
not as recurring smoke (per the small-curated-subset guideline).
Original Prompt
Click to expand starting prompt
Make PyAutoFit's Prior.value_for(unit) and
Prior.log_prior_from_value(value) JAX-traceable on every concrete
Prior subclass, so cube → physical and the prior log-density can run
inside a jax.jit boundary without a jax.pure_callback host
roundtrip.
This is Phase 0 of z_features/nss_first_class_sampler.md — the
critical prerequisite. Without it, the cube → physical mapping inside
an af.NSS likelihood would have to go through jax.pure_callback
which costs ~18 ms/eval (we measured this on the
numpyro_ess_one_config.py profiling sweep — pure_callback brings
ESS up to 412–680 ms/eval). That would erase the ~30× per-eval
advantage nss_jit currently has over Nautilus on this likelihood
(see z_projects/profiling/FINDINGS_v3.md).
Why this matters
The profiling project on the RAL HPC measured:
| Sampler | ms/eval | Why |
|---|---|---|
nss_jit |
0.52 | Pure JAX, no boundary, JIT'd end-to-end. |
| nautilus | 17.9 | NumPy↔JAX boundary on every call. |
| bjsmc | 32.6 | pure_callback inside JIT. |
| npess | 412 | pure_callback × multiple slice steps per sample. |
nss_jit's 0.5 ms/eval requires the entire likelihood (including
cube → physical and log_prior) to be JIT-traceable. Everything else
(Nautilus, PocoMC) pays the boundary cost on every call.
af.NSS (Phase 1) intends to call Fitness.call(unit_vector) from
inside the JIT'd loglikelihood_fn. Today that path goes through
model.vector_from_unit_vector(unit_vector) which is NumPy-only.
Phase 0 changes that.
What exists today
@PyAutoFit/autofit/mapper/prior/uniform.py:135 —
UniformPrior.value_for(self, unit: float) -> float:
def value_for(self, unit: float) -> float:
return float(
round(super().value_for(unit), 14)
)super().value_for lives in @PyAutoFit/autofit/mapper/prior/abstract.py:140.
The float(round(...)) is the JIT-breaking line — round produces a
Python float, which forces materialisation during tracing.
@PyAutoFit/autofit/mapper/prior/uniform.py:160 —
log_prior_from_value(self, value, xp=np) already takes an xp kwarg
but all five Prior subclasses thread xp inconsistently (some
return Python scalars regardless, some use xp.where, some import
scipy.stats directly).
Model.vector_from_unit_vector(unit_vector) (and the related
log_prior_list_from_vector) iterate prior.value_for(u) /
prior.log_prior_from_value(v) per parameter and return a Python
list[float]. The list-construction also breaks JIT tracing.
What to change
Concrete files (use git grep "def value_for\|def log_prior_from_value"
under PyAutoFit/autofit/mapper/prior/ to confirm exhaustive coverage):
@PyAutoFit/autofit/mapper/prior/uniform.py—UniformPrior@PyAutoFit/autofit/mapper/prior/gaussian.py—GaussianPrior@PyAutoFit/autofit/mapper/prior/truncated_gaussian.py—TruncatedGaussianPrior@PyAutoFit/autofit/mapper/prior/log_uniform.py—LogUniformPrior@PyAutoFit/autofit/mapper/prior/log_gaussian.py—LogGaussianPrior@PyAutoFit/autofit/mapper/prior/abstract.py:140—Prior.value_for
base method@PyAutoFit/autofit/mapper/model.py—Model.vector_from_unit_vector
andModel.log_prior_list_from_vector@PyAutoFit/autofit/mapper/prior/tuple_prior.pyandconstant.py
must keep working but probably don't need JAX paths (TuplePrior is
a collection, ConstantPrior is fixed) — confirm.
1. Add xp kwarg to every Prior.value_for
Signature change:
def value_for(self, unit, xp=np) -> float | jnp.ndarray:Inside each implementation:
UniformPrior:xp.where(...)if needed for limits, noround,
returnxp.float64not Pythonfloat.GaussianPrior: replacescipy.stats.norm.ppfwith
xp.scipy.stats.norm.ppf(works for bothnumpyand
jax.numpy).xp.scipy.stats.norm.ppfexists in JAX 0.4.x — verify
available in the pinned versions of JAX used byautoarray's tests.TruncatedGaussianPrior:jax.scipy.stats.truncnorm.ppfdoes NOT
exist as of JAX 0.4.38. Either roll our own using
jax.scipy.special.ndtri+ bounds, OR add ajax_wrappershim that
branchestruncnorm = jax.scipy.stats.truncnorm if hasattr else _manual_truncnorm.
Seejax.scipy.statsdocs and confirm at implementation time.LogUniformPrior:lower * (upper / lower) ** unit— straight
math, no special functions, works in anyxp.LogGaussianPrior:xp.exp(GaussianPrior-style ppf).
Critical: do not call Python float(), round(), or .item()
when xp is jax.numpy — those force tracing materialisation and
break the JIT. Keep operations symbolic.
2. Update every log_prior_from_value to use the existing xp kwarg
UniformPrior.log_prior_from_value returns 0.0 today —
that's a Python scalar. Change to xp.zeros_like(value) (so it
broadcasts when value is a JAX array). Returning -xp.inf outside
bounds requires xp.where(in_bounds, 0.0, -xp.inf).
For Gaussian-family priors, the current implementations probably
already use xp.log, xp.square, etc. — audit that they don't use
np.log literally where xp.log should be.
3. Make Model.vector_from_unit_vector JAX-traceable
@PyAutoFit/autofit/mapper/model.py — find the method. Currently:
def vector_from_unit_vector(self, unit_vector):
return [
prior.value_for(u)
for prior, u in zip(self.priors_ordered_by_id, unit_vector)
]Change to accept xp=np:
def vector_from_unit_vector(self, unit_vector, xp=np):
return xp.stack([
prior.value_for(u, xp=xp)
for prior, u in zip(self.priors_ordered_by_id, unit_vector)
])(xp.stack produces a (ndim,) 1-D array of the right backend.)
Model.log_prior_list_from_vector analogously.
Both methods are exercised today as Python-only paths — Nautilus
calls them with NumPy. Default xp=np keeps existing callers
working.
4. Confirm downstream consumers tolerate the array return
Two existing consumers call vector_from_unit_vector:
Fitness.callin@PyAutoFit/autofit/non_linear/fitness.py— needs
to threadxpif the Fitness is being called inside a JIT trace.
AuditFitness.__init__for an existinguse_jax_jitflag (likely
exists per the ellipse-fitting work) — wirexp=jnpwhen that flag
is set.model.instance_from_vector(vector)in
@PyAutoFit/autofit/mapper/model.py— already acceptsxp=jnpper
the autolens MGE work. Should already work with JAX arrays.
What to verify
-
Unit tests for each Prior subclass. Pattern:
import numpy as np import jax.numpy as jnp from autofit.mapper.prior import UniformPrior def test_uniform_value_for_jax_matches_numpy(): prior = UniformPrior(lower_limit=0.5, upper_limit=2.5) u = 0.3 np_v = prior.value_for(u, xp=np) jnp_v = float(prior.value_for(jnp.float64(u), xp=jnp)) assert np.isclose(np_v, jnp_v, atol=1e-12)
Add per subclass × per method (
value_for+log_prior_from_value).
Test files probably under
@PyAutoFit/test_autofit/mapper/prior/test_<subclass>.py. -
Round-trip test. A model with 5 priors (one of each type),
unit_vector = jnp.linspace(0.1, 0.9, 5), run
model.vector_from_unit_vector(unit_vector, xp=jnp), then
model.log_prior_list_from_vector(physical, xp=jnp), check no
tracing errors and finite results. -
JIT trace test. The full motivation:
@jax.jit def cube_to_phys(unit): return model.vector_from_unit_vector(unit, xp=jnp) _ = cube_to_phys(jnp.array([0.5] * model.prior_count))
This must succeed without an
XlaRuntimeErroror
TracerArrayConversionError. Add this as a separate test file
undertest_autofit/mapper/test_model_jax.py(gated onimport jax
so the test suite still passes without JAX installed). -
Existing Nautilus + Dynesty smoke. Their NumPy paths must
still work — defaultxp=npeverywhere. Run/smoke_teston
autofit_workspace_test,autolens_workspace_test, and the
searches_minimalreference suite under
autolens_workspace_developer/. -
autoconf.jax_wrapperinteraction. Importing autoconf flips
JAX_ENABLE_X64=True. The new tests must not assume x64; default
to whatever JAX has when the test runs. The Prior JAX paths
themselves must producefloat64outputs when x64 is enabled
(consistent with the autolens MGE pipeline).
Out of scope
af.NSSitself — separate prompt (Phase 1,
autofit/nss_search_wrapper.md).- Removing the
round(..., 14)precision-snapping in
UniformPrior.value_for(unit)for the NumPy path. That snap is
load-bearing for some existing unit tests (rounded values are used
as hash keys inmodel.priors); keep it forxp=np, drop it for
xp=jnp. - New Prior types (e.g. Beta, Exponential). Stick with the existing
five. - The
width_modifierandvectorizedPrior helpers — they're
meta-priors and don't havevalue_forof their own.
Risks / open questions
-
jax.scipy.stats.truncnorm.ppfmay not exist in JAX 0.4.38.
Verify before starting and either:- Manual implementation using
jax.scipy.special.ndtriand clipping. - Conditional import + helper function in a new
@PyAutoFit/autofit/mapper/prior/_jax_helpers.pymodule.
- Manual implementation using
-
Performance.
Model.vector_from_unit_vectoriterates priors
in Python. Insidejax.jitthe loop unrolls at trace time, so
trace cost grows with the number of priors. For a 15-parameter
MGE model this is ~15 trace iterations — negligible. For a
1000-parameter MGE problem it could matter. Consider whether
jax.lax.scanover a homogeneous prior-type batch is worth it —
probably not until we hit a model that complains. -
Compatibility with
paths.parquet/paths.csvserialisation.
The Sample.parameter_lists output should remain Pythonfloats
when written to disk. JAX-array prior outputs need to be converted
to NumPy before the existing serialisers see them. The Phase 1
af.NSSwrapper will handle this at the sampler boundary.
Reference
@PyAutoFit/autofit/mapper/prior/uniform.py:135— current
UniformPrior.value_for@PyAutoFit/autofit/mapper/prior/abstract.py:140— basePrior.value_for@PyAutoFit/autofit/mapper/model.py—Model.vector_from_unit_vector@autolens_workspace_developer/searches_minimal/nss_jit.py— original
smoke reference: today uses a hard-boundlog_priorbecause of this
exact gap@z_projects/profiling/FINDINGS_v3.md— measured per-eval cost
table that motivates Phase 0@PyAutoPrompt/z_features/nss_first_class_sampler.md— Phase 0 in
the sequenced roadmap
Activity
Jammy2211 commentedon May 14, 2026
Smoke Test Results — 2026-05-14
44/44 smoke tests passed across the five workspaces unaffected by an orthogonal pin issue.
Pre-existing failure (not caused by this branch)
euclid_strong_lens_modeling_pipeline— all 6 scripts fail withWorkspaceVersionMismatchError(workspace 2026.5.8.2 vs library 2026.5.14.2). Reproduces onmain. Tracked separately.Jammy2211 commentedon May 15, 2026
Shipped — 2026-05-14
PRs
Summary
Phase 0 of the
nss_first_class_samplerroadmap landed. Every concretePriorsubclass, theNormalMessage/TruncatedNormalMessagevalue_for, andModel.vector_from_unit_vectornow accept anxp=npkwarg. Concrete priors gained JAX-traceable closed-formvalue_foroverrides bypassing the scipy-backed message stack. NumPy paths are byte-equivalent —xp=npdefaults everywhere keep all existing callers (Nautilus, Dynesty, Emcee, Zeus, EP) untouched.Validation
pytest test_autofit(full sweep): 1242 passed, 1 skippedautofit_workspace_test/scripts/jax_assertions/priors_xp_dispatch.py: 24 new assertions pass (per-prior parity, JIT-trace,jax.gradfiniteness)jax_assertions/*.pyscripts still passautofit_workspace_test/scripts/graphical/ep.pyfull EP loop runs to completionSession Notes
phi_transform,log_10_transform, etc.). Cleaner trace, smaller surface, NumPy stack untouched.UniformPrior.value_forpreserves the historicalfloat(round(..., 14))snap forxp=np(hash-key invariant) and drops it forxp=jnp(symbolic trace).LogUniformPrior.log_prior_from_valuebody (1.0 / value) is left as-is — the formula looks wrong (true LogUniform log-prior is-log(value)modulo a constant) but changing it risks regressions in MCMC posteriors. Worth a dedicated follow-up issue.VisualizerExample.visualize_combined() got an unexpected keyword argument 'quick_update'— reproduces onmain, orthogonal to this PR. Likely worth its own ticket.WorkspaceVersionMismatchErrorineuclid_strong_lens_modeling_pipeline(workspace 2026.5.8.2 vs library 2026.5.14.2) — orthogonal, fix is to refresh the workspace version pin.Next
Phase 1 of the roadmap (
autofit/nss_search_wrapper.md) — theaf.NSSNonLinearSearchwrapper itself — is unblocked. Phase 0's JAX-traceable cube → physical mapping is the prerequisite that's now in place.Jammy2211 commentedon May 15, 2026
Followup Shipped — 2026-05-15
Bug A from this issue's followup audit: missing
quick_updatekwarg onVisualizerExample.visualize_combinedandVisualizerImaging.visualize_combined.PRs
Summary
Pure additive one-line kwarg fix on both visualizers, mirroring the plumbing that commit `a1e360567` ("Fix `AnalysisFactor.visualize_combined` dispatch in FactorGraph") added to PyAutoFit's base class + AnalysisFactor + PyAutoLens visualizers — but missed PyAutoFit's example visualizer and PyAutoGalaxy's imaging visualizer.
Validation
Bug B (sign-convention) status
Deferred to #1266 — the deeper audit surfaced that `Prior.log_prior_from_value` returns cost form across the Gaussian-family priors while `Fitness._call` expects density form, biasing all MCMC posteriors with non-uniform priors. That fix needs its own focused planning cycle (sign-flip across NormalMessage, TruncatedNormalMessage, LogGaussianPrior, LogUniformPrior + pin-test updates + Emcee regression validation + release-notes warning that cached MCMC posteriors are biased).