diff --git a/autofit/non_linear/fitness.py b/autofit/non_linear/fitness.py index 2c4d2ed5c..67ade0295 100644 --- a/autofit/non_linear/fitness.py +++ b/autofit/non_linear/fitness.py @@ -844,19 +844,38 @@ def _vmap(self): """ Vectorized and JIT-compiled likelihood function. - This wraps the base likelihood function (`self.call`) with both - `jax.jit` and `jax.vmap`, producing a function that can evaluate - batches of parameter vectors efficiently in parallel. The first - call incurs compilation time, but subsequent calls are highly - optimized. - - Because this is a `cached_property`, the compiled function is stored - after its first creation, avoiding repeated JIT compilation overhead. + This wraps the base likelihood function (`self.call`) so that it evaluates a whole batch of + parameter vectors at once, as `jax.jit(jax.vmap(self.call))`. The order is jit **of** vmap: + the conventional composition, and the one `analysis/latent.py` already uses. + + That order means the batch is one XLA program. The outer jit traces `vmap(call)` once, keyed + on the shape of the batch it was given, and caches the compiled executable; a second call at + the same batch shape is a cache hit served from jit's C++ fast path, with no Python batching + trace in between. The previous composition, `jax.vmap(jax.jit(self.call))`, re-entered + Python's batching machinery on every call and dispatched the inner `pjit` eagerly underneath + the batching trace, which is where the `autogalaxy_workspace_test#118` hangs are parked. + + The inner jit is dropped rather than kept: a jit nested inside a jit is inlined, so it adds a + call boundary and nothing else. + + This is **not** a fix for the XLA CPU Eigen-pool FFT deadlock (`PyAutoFit#1530`). That fires + at execution time, and execution still happens once per call whatever the tracing order is. + The only measured effect of the ordering is the A/B run of 2026-08-23 on `rectangular_mge.py` + (control 8/10 stalls against 3/10 for jit-of-vmap, Fisher exact p=0.070), recorded there as + contributory rather than causal. + + The compiled executable is still specialised per batch *length*, so a search that varies its + batch size recompiles per distinct length (see the PyAutoMind draft + `vmap_jit_recompiles_per_nautilus_batch_length.md`). This change neither fixes nor worsens + that. + + Because this is a `cached_property`, the compiled function is stored after its first + creation, avoiding repeated JIT compilation overhead. """ import jax return log_on_first_compile( - jax.vmap(jax.jit(self.call)), + jax.jit(jax.vmap(self.call)), "vectorized (vmap) likelihood function", ) diff --git a/autofit/non_linear/jax_compile.py b/autofit/non_linear/jax_compile.py index 017b4bfb0..b5a827ee1 100644 --- a/autofit/non_linear/jax_compile.py +++ b/autofit/non_linear/jax_compile.py @@ -297,7 +297,8 @@ def log_on_first_compile(func, description): Returns ------- - A callable with the same signature as `func`. + A callable with the same signature as `func`, carrying the wrapped callable + itself on `__wrapped__`. """ state = {"compiled": False} @@ -356,4 +357,10 @@ def wrapper(*args, **kwargs): return result + # Keep the jitted callable reachable for tests and diagnostics: its + # `_cache_size()` is the compile-count probe. Set explicitly rather than via + # `functools.wraps`, which would also copy the jit object's `__dict__` onto + # the wrapper. + wrapper.__wrapped__ = func + return wrapper diff --git a/test_autofit/non_linear/test_fitness_vmap_cache.py b/test_autofit/non_linear/test_fitness_vmap_cache.py new file mode 100644 index 000000000..e5cf160ee --- /dev/null +++ b/test_autofit/non_linear/test_fitness_vmap_cache.py @@ -0,0 +1,114 @@ +""" +What the batched JAX likelihood path compiles, and how often (PyAutoFit#1636). + +`Fitness._vmap` composes the batched likelihood as `jax.jit(jax.vmap(call))` rather than +`jax.vmap(jax.jit(call))`, so the whole batch is a single XLA program cached by the outer jit and +keyed on the batch shape. These tests witness that ordering from the outside: the likelihood is +traced exactly once per batch shape, a repeat call at the same shape is a cache hit, and the values +are bitwise identical to the old composition's. + +The compile-count probe is `_vmap.__wrapped__._cache_size()` — `log_on_first_compile` keeps the +jitted callable reachable on `__wrapped__` for exactly this reason, so on the old composition (where +the wrapped callable was the vmap object, which has no cache) these tests cannot pass. +""" + +import pickle + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear.fitness import Fitness + +jax = pytest.importorskip("jax") + + +class CountingAnalysis(af.ex.Analysis): + """ + The example 1D Gaussian analysis, counting how many times its likelihood function runs. + + Under `jax.jit` the Python body runs only while tracing, so the counter is a count of traces — + not of evaluations. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.trace_count = 0 + + def log_likelihood_function(self, instance, **kwargs): + self.trace_count += 1 + return super().log_likelihood_function(instance=instance, **kwargs) + + +def _make_fitness(analysis_cls=af.ex.Analysis, **kwargs): + model = af.Model(af.ex.Gaussian) + analysis = analysis_cls( + data=np.ones(20), + noise_map=np.ones(20) * 0.1, + use_jax=True, + ) + return Fitness(model=model, analysis=analysis, **kwargs) + + +def _batch(model, rows): + """A `(rows, d)` batch of the model's prior-median parameter vector.""" + return np.tile(np.array(model.physical_values_from_prior_medians), (rows, 1)) + + +def test_the_batched_likelihood_is_traced_once_and_cached_per_shape(): + fitness = _make_fitness(analysis_cls=CountingAnalysis, use_jax_vmap=True) + parameters = _batch(fitness.model, 4) + + first = fitness._vmap(parameters) + second = fitness._vmap(parameters) + + # One trace for the whole batch, and the second call never re-enters Python: it is served + # from the outer jit's C++ fast path on the executable cached for this batch shape. + assert fitness.analysis.trace_count == 1 + assert fitness._vmap.__wrapped__._cache_size() == 1 + + assert np.array_equal(np.asarray(first), np.asarray(second)) + assert np.asarray(first).shape == (4,) + + # A different batch length is a different shape, so it is a different executable. That the + # cache grows per batch length is the separate, known cost written up in the PyAutoMind draft + # `vmap_jit_recompiles_per_nautilus_batch_length.md`; this test pins it, it does not bless it. + fitness._vmap(_batch(fitness.model, 3)) + assert fitness._vmap.__wrapped__._cache_size() == 2 + + +def test_jit_of_vmap_matches_vmap_of_jit_bitwise(): + fitness = _make_fitness(use_jax_vmap=True) + + medians = np.array(fitness.model.physical_values_from_prior_medians) + parameters = medians[None, :] * np.linspace(0.8, 1.2, 5)[:, None] + + jit_of_vmap = np.asarray(jax.jit(jax.vmap(fitness.call))(parameters)) + vmap_of_jit = np.asarray(jax.vmap(jax.jit(fitness.call))(parameters)) + + assert np.array_equal(jit_of_vmap, vmap_of_jit) + + +def test_call_wrap_promotes_a_vector_to_a_batch_on_the_vmap_path(): + fitness = _make_fitness(use_jax_vmap=True) + vector = np.array(fitness.model.physical_values_from_prior_medians) + + batched = np.asarray(fitness.call_wrap(vector)) + + assert batched.shape == (1,) + assert np.array_equal(batched, np.asarray(fitness.call(vector))[None]) + + +def test_vmap_survives_a_pickle_round_trip(): + fitness = _make_fitness(use_jax_vmap=True) + parameters = _batch(fitness.model, 4) + + expected = np.asarray(fitness._vmap(parameters)) + + restored = pickle.loads(pickle.dumps(fitness)) + restored_result = np.asarray(restored._vmap(parameters)) + + assert np.array_equal(restored_result, expected) + # `__getstate__` strips `_vmap`, so the restored object rebuilt it: a cache of exactly one + # entry after one call is what a freshly compiled function looks like. + assert restored._vmap.__wrapped__._cache_size() == 1