Skip to content

refactor(fitness): jit(vmap(call)) in Fitness._vmap so the batched likelihood is cached #1636

Closed

Description

@Jammy2211

Overview

Fitness._vmap builds jax.vmap(jax.jit(self.call)) — vmap of jit. A vmap has no cache of its own, so every call re-enters Python: vmap_f -> flatten_fun_for_vmap -> cache_miss -> _pjit_batcher -> _pjit_call_impl, which is exactly where the two Release Integrate hangs of multi_dataset/jax_likelihood/delaunay.py parked (autogalaxy_workspace_test#118, runs 34018429178 and 34094964905, on the first and the second _vmap call respectively). analysis/latent.py already uses the conventional jax.jit(jax.vmap(...)). This task flips _vmap to jax.jit(jax.vmap(self.call)) so the batched likelihood is one cached executable served from the outer jit's C++ fast path on every same-shape call.

The ordering was A/B'd once already (PyAutoMind/complete/2026/08/jax-compile-stall-slow-vs-stall-audit.md, branch experiment/jax-vmap-jit-ordering, 2026-08-23, "not for merge without evidence"): on rectangular_mge.py control stalled 8/10 vs jit(vmap) 3/10, Fisher p = 0.070 — "contributory, not causal", n=10/arm. The root cause was found later (XLA CPU FftThunk re-enters the Eigen pool via ducc0, #1530), which is why the swap never merged. This is not a fix for that deadlock; it is a behaviour-preserving refactor that removes the per-call Python batching dispatch, matches latent.py, and carries the only measured stall-rate lever that stays in library code.

Premise correction, recorded so the PR does not overclaim. The prompt says the outer jit "halves the exposure" because the second call becomes a cache hit. The executable is already cached on main (the inner pjit's jaxpr and lowering caches key on the per-example avals, and batch_jaxpr2 is weakref_lru_cached), so the compile count is 1 either way; what repeats per call on main is the Python batching trace and the eager _pjit_call_impl dispatch. The deadlock fires at execution (FFT thunks run at execution time, #1530), and every call still executes the batched program once under either ordering — so the outer jit does not halve execution-time exposure by construction. What it does change is the HLO (the whole batch is one XLA program with cross-batch fusion instead of a batched inner pjit), and that is the thing the 8/10 vs 3/10 A/B measured. The PR body states this; the witness below is worded on what is actually observable.

Plan

  • Flip Fitness._vmap from jax.vmap(jax.jit(self.call)) to jax.jit(jax.vmap(self.call)), keeping the log_on_first_compile wrapper and its "vectorized (vmap) likelihood function" description unchanged.
  • Expose the jitted callable through the wrapper (__wrapped__) so a test can read the outer jit's cache size without reaching into the closure.
  • Add a unit test that calls _vmap twice at the same batch shape and asserts: one trace of the analysis likelihood, one entry in the outer jit's cache, bit-identical outputs; a third call at a different batch length adds exactly one more entry (documents, does not fix, the per-batch-length recompile).
  • Add a numerical parity test: jit(vmap(call)) and the old vmap(jit(call)) give identical figures of merit on af.ex.Analysis for a (B, d) batch and for the (d,) -> (1, d) promotion in call_wrap.
  • Prove the heartbeat contract is untouched: test_jax_compile.py passes unchanged and the first-call log lines are byte-identical.
  • Run the whole PyAutoFit suite; the pickling round-trip (__getstate__ strips _vmap) is already covered by test_fitness_jax_dispatch.py.
  • Measure once in CI: push the same branch name to autogalaxy_workspace_test (CI clones the dependency chain by matching branch name) and dispatch retime.yml on multi_dataset/jax_likelihood/delaunay.py ABAB against main; quote compile time before/after (the outer jit compiles the batched graph once, the inner compile goes away) and the likelihood values, which must be bit-identical.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)
  • autogalaxy_workspace_test / autolens_workspace_test — measurement only (a same-named branch for the retime dispatch; no code change expected)

Work Classification

Library

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main @ fa2d540 (PR #1634 merged 2026-09-17) clean (session clone)

Related branch already on origin: experiment/jax-vmap-jit-ordering (0a40c31, 2026-08-23, based on #1518 — 221 files behind main; do not merge or rebase it, re-apply its one hunk by hand).

Suggested branch: feature/fitness-vmap-outer-jit
Worktree root: ~/Code/PyAutoLabs-wt/fitness-vmap-outer-jit/ (created by /start_library)

Implementation Steps

  1. autofit/non_linear/fitness.py, Fitness._vmap (cached_property, ~line 843):
    return log_on_first_compile(
        jax.jit(jax.vmap(self.call)),
        "vectorized (vmap) likelihood function",
    )
    Rewrite the docstring: it currently says "wraps ... with both jax.jit and jax.vmap" — say the order and why (one XLA program per batch shape, served from the outer jit's cache; the inner jit was redundant under an outer one and made every call re-enter the Python batching trace). Cite research: why does XLA CPU's Eigen thread pool wedge on vmap graphs? #1530 and the 8/10 vs 3/10 A/B, and say plainly it is not the deadlock fix.
  2. autofit/non_linear/jax_compile.py, log_on_first_compile: set wrapper.__wrapped__ = func so the jitted callable is reachable. Prefer the explicit attribute over functools.wraps — wraps copies __dict__ and would alias the jit object's attributes onto the wrapper. Nothing else in the module changes; the heartbeat / watchdog / two-half reporting is untouched.
  3. test_autofit/non_linear/test_fitness_jax_dispatch.py (or a new test_fitness_vmap_cache.py beside it), pytest.importorskip("jax"):
    • test_vmap_traces_once_and_caches_the_batched_executable: build Fitness(model, analysis, use_jax_vmap=True) with af.ex.Analysis whose log_likelihood_function is wrapped to count Python entries; call fitness._vmap(np.ones((4, d))) twice; assert count == 1, fitness._vmap.__wrapped__._cache_size() == 1, and np.array_equal on the two outputs. Then call at (3, d) and assert _cache_size() == 2 with a comment pointing at PyAutoMind/draft/bug/autofit/vmap_jit_recompiles_per_nautilus_batch_length.md — the outer jit keys on the batch shape exactly as the inner one did, so that prompt is neither fixed nor worsened here.
    • test_vmap_ordering_is_numerically_identical: compare jax.jit(jax.vmap(fitness.call))(batch) against jax.vmap(jax.jit(fitness.call))(batch) with np.array_equal (bit-identical is the witness; if XLA's cross-batch fusion reorders a reduction and only allclose holds, record the max ulp difference in the PR and say so rather than loosening silently).
    • test_call_wrap_promotes_a_vector_to_a_batch_on_the_vmap_path: (d,) in, (1,)-shaped result equal to the numpy-path call value.
  4. test_autofit/non_linear/test_jax_compile.py: no edits; run it to prove the log contract (test_the_compile_wait_and_the_execution_wait_are_reported_separately etc.) is unchanged. The description string is unchanged, so the multi_dataset scripts' grep for "compiling vectorized (vmap) likelihood function" still matches.
  5. Check consumers that reach through _vmap: nautilus/search.py uses fitness.call_wrap with vectorized=fitness.use_jax_vmap (unchanged contract, (n_batch, d) in, (n_batch,) out); multi_start_gradient/search.py only mentions the compile notice; result.py / abstract_search.py only drop the cached attribute. __getstate__ already strips _vmap.
  6. Measurement (workspace_test, CI): push feature/fitness-vmap-outer-jit to autogalaxy_workspace_test (an empty commit is fine — the branch-name match is what selects the library branch), dispatch retime.yml on multi_dataset/jax_likelihood/delaunay.py with --arm ABAB vs control, 300 s cap. Quote: compile seconds from the "traced, lowered and compiled in" line before/after, pass/hang per arm, and the likelihood printed by the script (bit-identical). Record in the PR; do not touch no_run.yaml.
  7. PR body: ## API Changes — none (private cached_property; log_on_first_compile's wrapper gains __wrapped__); state the premise correction above so nobody reads "halves exposure" as measured.

Key Files

  • autofit/non_linear/fitness.py — Fitness._vmap (line ~843), call_wrap (line ~552, the (d,) -> (1, d) promotion), __getstate__/__setstate__ (line ~816)
  • autofit/non_linear/jax_compile.py — log_on_first_compile (line 252), the heartbeat contract
  • autofit/non_linear/analysis/latent.py — the existing jax.jit(jax.vmap(...)) precedent (line 169)
  • test_autofit/non_linear/test_fitness_jax_dispatch.py, test_autofit/non_linear/test_jax_compile.py
  • autofit/non_linear/search/nest/nautilus/search.py — the only production caller (call_wrap, vectorized=)

Adjacent prompts (do not fold in)

  • PyAutoMind/draft/bug/autofit/vmap_jit_recompiles_per_nautilus_batch_length.md — padding/bucketing the leading dim; same line of code, separate task. Its compile-count probe is the _cache_size() read this task's test introduces.
  • PyAutoMind/draft/refactor/autofit/ep_analysis_level_compile_cache.md — cross-factor reuse of the compiled likelihood; unaffected.
  • PyAutoMind/draft/refactor/autofit/split_fitness_batch_size_lh_vs_latent.md — batch_size semantics; unaffected.

Risks / trade-offs

  • jit(vmap(call)) lets XLA fuse across the batch; a reduction-order change would break bit-identity. The parity test decides; a real difference is reported, not papered over.
  • The inner jax.jit is dropped rather than kept: jit(vmap(jit(call))) compiles the same program with an extra call boundary and no benefit.
  • The August A/B is n=10/arm, p=0.070: cite it as suggestive, never as the reason the deadlock is gone.

Original Prompt

Click to expand starting prompt

Fitness._vmap re-traces and eagerly executes the batched pjit on every call — wrap it in an outer jit

Type: refactor
Target: PyAutoFit
Repos:

  • PyAutoFit
    Difficulty: medium
    Autonomy: supervised
    Priority: medium
    Status: formalised
    Consequence: notify
    Witness: Fitness._vmap called twice on the same shapes traces once (assert via jax.make_jaxpr count or a trace-counter callback), all PyAutoFit JAX tests pass, and the multi_dataset jax_likelihood scripts in autolens_workspace_test / autogalaxy_workspace_test produce bit-identical likelihoods before and after.
    Review-minutes: 0
    Unattended: ready
    Filed: 2026-09-07

CI forensics on autogalaxy_workspace_test#118 (2026-09-07): the two Release Integrate
hangs of multi_dataset/jax_likelihood/delaunay.py (runs 34018429178 and 34094964905)
park in jax _pjit_call_impl reached via
vmap_f -> flatten_fun_for_vmap -> cache_miss -> _pjit_batcher — the inner pjit that
Fitness._vmap = jax.vmap(jax.jit(self.call)) executes eagerly under the batching trace.

With no outer jit every call re-traces, so a script that calls _vmap twice gets two
independent exposures to the intermittent xla-cpu-eigen-pool-deadlock (epic), and the two
CI hangs landed on the first and the second call respectively. Wrapping the vmap in an
outer jax.jit (or caching the batched executable) makes the second call a cache hit and
halves the exposure for every composite-vmap script in the workspace_test repos.

Not a fix for the deadlock itself; a real reduction in how often it is rolled.

Measure compile time before/after on one script (the outer jit adds one compile) and
confirm no change to jax_compile.py's heartbeat contract in PyAutoNerves/PyAutoHands.

Related quarantines: autolens_workspace_test and autogalaxy_workspace_test
config/build/no_run.yaml eigen-pool entries.

Activity

  1. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created

    • PR: refactor(fitness): compose Fitness._vmap as jit(vmap(call)) so the batch is one cached executable #1638 (feature/fitness-vmap-outer-jit @ f28e986, label pending-release)
    • Change: Fitness._vmap is now jax.jit(jax.vmap(self.call)) (was jax.vmap(jax.jit(self.call))); log_on_first_compile's wrapper exposes the jitted callable on __wrapped__; new test_autofit/non_linear/test_fitness_vmap_cache.py (4 tests). Full serial suite 2807 passed / 48 skipped; jit(vmap) vs vmap(jit) bitwise equal on the example analysis.
    • API changes: none (private cached_property, same (B, d) -> (B,) contract). Workspace impact: option (iii), no migration; /smoke_test is not runnable from this web session, so the next door is /prm once the CI matrix is green.

    Measurement, dispatched at PR-open (autogalaxy_workspace_test retime.yml, multi_dataset/jax_likelihood/delaunay.py, 5 repeats, 300 s cap, both Python legs):

    Arm Run Chain
    jit(vmap) https://github.com/PyAutoLabs/autogalaxy_workspace_test/actions/runs/35248541614 branch feature/fitness-vmap-outer-jit (empty, off main e8b2f38, exists only so the chain checkout picks this PR's PyAutoFit branch)
    control https://github.com/PyAutoLabs/autogalaxy_workspace_test/actions/runs/35248545944 main

    Read from each: the traced, lowered and compiled in N seconds line of the first _vmap call, the printed _vmap result (must be bit-identical between arms), and the JAX Time Taken using VMAP second-call time. This is a compile-time and parity check, not a stall-rate measurement: 5 repeats cannot resolve a hang rate of ~2 per several dozen release-integrate runs, and the smoke profile keeps --xla_cpu_multi_thread_eigen=false in force.

    Premise correction stands as written in the issue body and the PR: the outer jit removes the per-call Python batching dispatch and changes the HLO; it does not halve execution-time exposure to #1530.


    Generated by Claude Code

  2. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Measurement (autogalaxy_workspace_test retime.yml, multi_dataset/jax_likelihood/delaunay.py, 5 repeats, 300 s cap, smoke profile, last run of each leg quoted)

    Arm Run Leg first _vmap compile printed _vmap result second _vmap call verdict
    jit(vmap) (this PR) 35248541614 3.12 1.5 s [2223.24259723 2223.24259723 2223.24259723] 0.400 s NEITHER, 5/5, slowest 18.9 s
    jit(vmap) (this PR) 35248541614 3.13 1.7 s same 0.496 s NEITHER, 5/5, slowest 19.0 s
    control (main @ fa2d540) 35248545944 3.12 1.6 s same 0.399 s NEITHER, 5/5, slowest 17.1 s
    control (main @ fa2d540) 35248545944 3.13 1.5 s same 0.400 s NEITHER, 5/5, slowest 16.1 s
    • Likelihoods: the printed _vmap batch is identical across all four legs at the script's print precision, and the script's own full-precision jit scalar (JIT log_likelihood_function: 2223.242597233474) is byte-identical in all four. Bitwise identity of the batched path itself is pinned by the unit test on the example analysis; the workspace script prints eight decimals, so "identical as printed" is the honest claim for the delaunay graph.
    • Compile: no measurable change (1.5 to 1.7 s in both arms, persistent JAX compile cache restored in both). The feature arm wrote more new compile-cache entries than control on both legs (33 vs 22 on 3.12; 33 vs 22 on 3.13), which is the new HLO being compiled and the indirect confirmation that the chain checkout picked up the PyAutoFit branch.
    • Second-call time is unchanged (~0.40 s for a batch of 3); at this size execution dominates and the removed Python batching dispatch is below the noise.
    • Stall rate: not measurable here (0/20 hangs in both arms under the smoke profile, which keeps --xla_cpu_multi_thread_eigen=false); the no_run.yaml quarantine of this script stays as it is, per the PR.

    The empty measurement branch feature/fitness-vmap-outer-jit in autogalaxy_workspace_test (off main e8b2f38, no PR) is left for branch_sweep.yml.


    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