Skip to content

fix(ep): release each factor search's internals so JAX executables are collectable #1631

Closed

Description

@Jammy2211

Overview

slope_hierarchy_scale job 342410 (25 AnalysisFactors, JAX likelihood, Nautilus number_of_cores=1, 64 GB) ran ~3 EP steps — 76 factor searches, each logging a fresh vmapped-likelihood jit — and died with LLVM compilation error: Cannot allocate memory / LLVM ERROR: Unable to allocate section memory!. The cause is a retention chain, not compile time: every factor step's Status is kept in EPHistory, its Result._search_internal holds the Nautilus sampler, the sampler holds the Fitness, and the Fitness holds every compiled XLA executable of that search. Nothing in EP reads the sampler afterwards. Fix: release the in-memory search internal at the EP entry so each search's executables are collectable when its factor step ends; cross-step compile reuse and the vmap(jit) batch-shape churn are filed as follow-ups.

Status 2026-09-15: planned and parked by the human — not started. Resume with /start_library ep-release-search-internals from the active.md row; the detailed plan below is the full brief.

Plan

  1. In AbstractSearch.optimise, release the search internals from the Result before it is pinned on the EP Status, so the Fitness and its compiled executables become collectable when the factor step ends.
  2. Regression test (JAX-free): two consecutive optimise calls on one AnalysisFactor leave no Fitness alive from the first step and status.result._search_internal is None, while latest_result.projected_model / .samples still work.
  3. Empirical witness (JAX): a small EP run (5 Gaussian factors × 4 steps, Nautilus, use_jax=True) with RSS and live-Fitness count logged per step — growing before the fix, flat after; numbers go in the PR body.
  4. Ship as a library PR (pending-release), workspace impact none (no API change), issue + Mind close-out via /prm.
  5. File two follow-up prompts via /intake: analysis-level compile cache across EP steps; fixed-batch padding to stop vmap(jit) shape churn.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary; library)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main clean (0 ahead/behind origin)

Suggested branch: feature/ep-release-search-internals — worktree ~/Code/PyAutoLabs-wt/ep-release-search-internals/. worktree_check_conflict fires because howtofit-mode also claims PyAutoFit; that worktree is clean with zero commits ahead of origin/main (README propagation only), so the file sets are disjoint and this task takes its own parallel worktree (recorded as parallel-claim on the active.md row).

Root cause (PyAutoFit main @ 27d41e7)

Job 342410 (25 AnalysisFactors, JAX likelihood, Nautilus number_of_cores=1, --mem=64gb) ran ~3 EP steps (76 factor searches, ~11 h) then died with LLVM compilation error: Cannot allocate memory / LLVM ERROR: Unable to allocate section memory!.

Root cause (traced on PyAutoFit main @ 27d41e7c8):

  • Every factor step creates a fresh Fitness (autofit/non_linear/search/nest/nautilus/search.py:330-347), whose _vmap is a per-instance cached_property wrapping jax.vmap(jax.jit(self.call)) (autofit/non_linear/fitness.py:842-861). The jit cache lives on that object, so each search compiles anew (the logged 76 compiles), and vmap(jit) additionally compiles one executable per distinct Nautilus batch length, unlogged.
  • Nothing releases them. AbstractSearch.optimise (abstract_search.py:435-455) does status.result = result; EPHistory.__call__ appends (approx, status) to history for every factor step (graphical/expectation_propagation/history.py:75). Result._search_internal (non_linear/result.py:387) holds the nautilus.Sampler, whose likelihood is fitness.call_wrap → the Fitness → all its executables. So every executable ever compiled in the run stays live: memory grows monotonically until LLVM cannot map section memory. output.search_internal: false only affects the on-disk dump.
  • The retained sampler is never read: no graphical code touches search_internal (latest_result consumers use .projected_model, .samples, .model). The Result.search_internal property already falls back to loading search_internal.dill from disk when the in-memory reference is None (result.py:430-449), so dropping it after the fit is API-preserving.

Fix chosen: break the retention chain at the EP entry — one locus, no JAX semantics touched, bounds memory to one factor search's executables regardless of step count. Cross-step compile reuse (an analysis-level compiled-callable cache) and the batch-shape churn are real but secondary (compile ≈ 2–3 s of an ≈ 8 min factor search); they are filed as follow-up prompts, not done here.

Implementation Steps

Worktree and claim

  • worktree_check_conflict fires: PyAutoFit is claimed by howtofit-mode, whose PyAutoFit worktree is clean with zero commits ahead of origin/main (README propagation not yet started). File sets are disjoint by construction → own parallel worktree (recommended; memory feedback_repo_claim_conflict_allows_parallel_worktrees). Record - parallel-claim: PyAutoFit also claimed by howtofit-mode (docs/README only, 0 commits at 2026-09-15); disjoint files, own worktree on the active.md row.
  • Task ep-release-search-internals, branch feature/ep-release-search-internals, worktree ~/Code/PyAutoLabs-wt/ep-release-search-internals/ via worktree_create ep-release-search-internals PyAutoFit (/start_library).

A. autofit/non_linear/search/abstract_search.py — optimise (EP entry, ~line 435-455)

After result = self.fit(model=model, analysis=analysis) and after log_evidence / new_model_dist are derived, and before status.result = result:

# EP keeps every factor step's Status (and its Result) in EPHistory. The
# Result's in-memory search internal (e.g. the nautilus Sampler) holds the
# Fitness and, under JAX, every compiled likelihood executable of this
# search. Left in place, an N-factor × M-step run retains N*M sets of
# executables and dies in LLVM section-memory allocation (slope_hierarchy_scale
# job 342410: 76 searches, 64 GB). Nothing in EP reads the sampler; the
# `search_internal` property falls back to the on-disk dill if asked.
result._search_internal = None

Also gc.collect() is not added (no cycles are created here; leave collection to refcounting — the test proves it).

Check Result subclasses used by searches (autofit/non_linear/result.py, search/nest/.../result.py if any) all inherit _search_internal; if a subclass names it differently, set through a small Result.release_search_internal() method instead of poking the attribute — decide on reading, keep it to one method if needed.

B. Test — test_autofit/graphical/test_ep_release_search_internal.py (new; JAX-free)

Reuse the factor_model-style fixture from test_autofit/graphical/test_ep_no_multiprocessing.py (g.AnalysisFactor + numpy Analysis from test_autofit/graphical/gaussian/model.py) and af.DynestyStatic(maxcall=5) (or af.Nautilus(n_live=..., number_of_cores=1) if faster/available without JAX):

  1. Build factor_approx = model_approx.factor_approximation(factor); call search.optimise(factor_approx) twice (two "EP steps"), collecting the returned (model_dist, status).
  2. Wrap the Fitness constructor with a monkeypatch that records weakref.ref to each instance. After the second call (and del of local results), assert every recorded weakref is dead — no Fitness survives its factor step.
  3. Assert status.result._search_internal is None and that status.result.projected_model, status.result.samples and status.result.model still resolve (what EPHistory.latest_result consumers use).
  4. Assert status.result.search_internal does not raise when output.search_internal is off — it returns None/falls through exactly as the resumed-fit path does (mirror the existing property behaviour; do not add a guard that swallows a real load error).

Run pytest test_autofit/graphical -q and pytest test_autofit/non_linear/test_jax_compile.py test_autofit/non_linear/test_fitness_jax_dispatch.py -q in the worktree (source activate.sh).

C. Empirical witness (JAX; in the worktree, not committed as a test)

Script in the scratchpad ($SCRATCHPAD/ep_rss_witness.py): 5 AnalysisFactors over af.ex.Gaussian with a JAX-capable analysis (af.ex.Analysis(..., use_jax=True) if supported — check test_autofit/non_linear/test_fitness_jax_dispatch.py; else test_autofit/graphical/gaussian/model.py adapted with jnp), af.Nautilus(n_live=50, n_batch=10, number_of_cores=1), LaplaceOptimiser, max_steps=4, JAX_PLATFORMS=cpu. After each EP step log: resource.getrusage(RUSAGE_SELF).ru_maxrss, psutil.Process().memory_info().rss (if psutil present), and sum(isinstance(o, Fitness) for o in gc.get_objects()). Run once on origin/main (worktree stash or a second scratch checkout) and once with the fix; table of RSS/live-Fitness per step for both goes into the PR body. Expected: before — live Fitness grows 5 → 10 → 15 → 20 and RSS climbs; after — live Fitness ≤ 5 (or 0 between steps) and RSS flat after step 1. Budget ≈ 10–20 min per run; stop at 30 min and report.

D. Ship (/ship_library, execution tier)

  • Commit message (drafted by the judgment tier at ship): fix(ep): release each factor search's internals so JAX executables are collectable, body naming the chain (EPHistory → Status.result → Result._search_internal → Sampler → Fitness → executables), job 342410, and the follow-ups. Refs PyAutoFit#<issue>.
  • PR body: ## Summary, ## API Changes — none (the search_internal property keeps its contract; EP results no longer hold the sampler in memory), ## Evidence (test run counts + the RSS/live-Fitness table), ## Follow-ups (the two intake prompts). Label pending-release.
  • Heart readiness read at ship; STALE/YELLOW acknowledged on the row if not GREEN. Library-first gate: no workspace PR.
  • Workspace impact: grep search_internal in autofit_workspace / *_workspace_test EP scripts — expected no consumer of the in-memory sampler after an EP fit; report the grep.

E. Follow-ups to file (/intake, after PR-open; human sees the text)

  1. draft/refactor/autofit/… — cache the compiled _vmap/_jit/_grad on the Analysis keyed by the compile-affecting statics (use_jax_vmap, fom_is_log_likelihood, convert_to_chi_squared, resample_figure_of_merit, log_likelihood_ceiling, traced assertions, ordered prior-id tuple), invalidated for cavity-reading EPAnalysisFactor analyses; saves one compile per factor search (~2–3 s of ~8 min).
  2. draft/bug/autofit/… — vmap(jit) recompiles per distinct Nautilus batch length (Fitness.call_wrap promotes (d,)→(1,d); sample_shell batch sizes vary); pad/bucket the leading dimension with a masked FoM so one executable serves a search.

Mind record notes

  • Prompt file currently carries two header blocks (intake kept the drafted header verbatim under its own); when /create_issue moves it to active/, drop the second # … title + header block (lines 20–36) and keep Gates: on the surviving one.

Verification

check evidence
retention broken new test: all Fitness weakrefs dead after step 2; status.result._search_internal is None
EP API intact latest_result.projected_model / .samples / .model resolve; test_autofit/graphical green
memory flat witness table: live-Fitness count and RSS per EP step, main vs fix
no regression elsewhere pytest test_autofit/non_linear/test_jax_compile.py test_fitness_jax_dispatch.py; CI legs on the PR

Key Files

  • autofit/non_linear/search/abstract_search.py — optimise (EP entry), the fix locus (~line 435-455)
  • autofit/non_linear/result.py — Result._search_internal and the lazy search_internal property (~387, 430-449)
  • autofit/graphical/expectation_propagation/history.py — EPHistory.__call__ / latest_result (the retention)
  • autofit/graphical/expectation_propagation/optimiser.py — EPOptimiser.run / factor_step
  • autofit/non_linear/fitness.py — _vmap / _jit / _grad per-instance compile caches (842-883)
  • autofit/non_linear/search/nest/nautilus/search.py — fresh Fitness per fit (330-347), fit_x1_cpu (400-446)
  • test_autofit/graphical/test_ep_no_multiprocessing.py, test_autofit/non_linear/test_fitness_jax_dispatch.py, test_autofit/non_linear/test_jax_compile.py — test templates

Original Prompt

Click to expand starting prompt

EP re-jit-compiles the vmapped likelihood per factor search until LLVM section memory…

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Themes:
  • graphical-ep
  • jax
    Difficulty: medium
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Witness: an EP run over 25 AnalysisFactors with a JAX likelihood completes 12 factor_steps (300 factor searches) inside a fixed memory budget; RSS / XLA compile-cache size is flat across steps, not growing by one compiled executable per factor search.
    Review-minutes: 20
    Unattended: ready

Gates:

Report (slope_hierarchy_scale job 342410, RAL ral partition, 2026-09-09/10)

The N=25 EP arm ran on the JAX-on-CPU path with no pool (the PyAutoFit#1608 ruling):
each of the 25 AnalysisFactors is fitted by its own af.Nautilus(number_of_cores=1) under
LaplaceOptimiser, max_steps 12, SBATCH --mem=64gb, 10 kernel threads.

  • 76 factor searches completed in ~11 h (22:25 → 09:16), i.e. ~3 EP steps of 25 factors.
  • Every factor search logged "JAX jit compiling vectorized (vmap) likelihood function" — 76
    compiles, one per search (grep -c 'jit compiling vectorized' output.342410_0.out = 76).
    Each factor step builds a fresh Fitness / jitted function for the same 25 analyses, so
    nothing is reused across steps.
  • At 09:15:58 the .err fills with E … execution_engine.cc:54] LLVM compilation error: Cannot allocate memory and contiguous_section_memory_manager.cc:71] releaseMappedMemory failed; factor dataset_24 then raises jax.errors.JaxRuntimeError: INTERNAL: Failed to materialize symbols: { (<xla_jit_dylib_22>, { subtract_select_fusion }) } and the EP
    optimiser skips it ("Factor dataset_24 raised on 1 consecutive step(s)"); the next factor
    search hits LLVM ERROR: Unable to allocate section memory! and the process aborts
    (core dumped) at 09:29:41.
  • Logs: slope_hierarchy_scale/hpc/batch_cpu/output/output.342410_0.out,
    hpc/batch_cpu/error/error.342410_0.err (pulled to the local clone).

Hypothesis to test first: XLA's CPU JIT keeps every compiled executable's section memory
alive for the life of the process (the jitted callable is dropped but the dylib is not, or
the jax_compile.py wrapper caches on a key that includes the fresh Fitness object), so the
footprint grows by one executable per factor search. Candidates: reuse the compiled
likelihood across EP steps for the same analysis (cache on the analysis + model structure,
not the Fitness instance), or jax.clear_caches() / explicit executable release between
factor searches, with a test that asserts the compile count stays at one per factor over
several steps.

Not the same defect as PyAutoFit#1608 (pool hang) — that path is fixed; this is the memory
ceiling of the path we now take.

Activity

  1. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Progress: fix implemented and pushed (remote session, 2026-09-17)

    Branch claude/vmapped-likelihood-jit-compiles-bhog4o, commit 9afdc2b — no PR opened yet (next step is /ship_library, or /prm once a PR exists).

    Change (2 source files + 1 test, 54 source lines):

    • Result.release_search_internal() (autofit/non_linear/result.py) drops the in-memory sampler reference, and walks child_results because AnalysisFactorCollection.make_result hands the same sampler object to a CombinedResult and every child.
    • AbstractSearch.optimise calls it before status.result = result (guarded with getattr, since the regression suite's StaticSearch returns a bare object). search_internal keeps its on-disk-dill fallback; ordinary search.fit() is untouched.
    • test_autofit/graphical/test_ep_release_search_internal.py: two optimise calls on one AnalysisFactor (dynesty, JAX-free) leave no live Fitness and status.result._search_internal is None, while .projected_model / .samples / .model still resolve. Fails on main (assert 1 == 0 live Fitness; _search_internal is a MultiEllipsoidSampler), passes with the fix.

    Witness (5 AnalysisFactors, af.ex.Analysis(use_jax=True), af.Nautilus(n_live=50, n_batch=10, number_of_cores=1) per factor, 4 EP steps, JAX_PLATFORMS=cpu, ~3.5 min per run):

    step main RSS MB main live Fitness fix RSS MB fix live Fitness
    1 529.4 5 462.6 0
    2 607.8 10 462.7 0
    3 617.4 11 463.0 0
    4 632.9 12 464.0 0

    Tests: test_autofit/graphical + non_linear/test_jax_compile.py + non_linear/test_fitness_jax_dispatch.py + non_linear/result serially: 333 passed. Under -n auto both graphical and non_linear/search are already flaky on main (shared test_autofit/output wiped by the autouse fixture across workers) — the known ep_test_suite_is_not_xdist_safe Mind draft, not this change.

    Notes for the ship

    • Deviation from the plan: a weakref on Fitness.__init__ alone cannot probe this, because a dynesty search that resumes from its checkpoint restores the sampler by unpickling and the restored Fitness never passes __init__; the test therefore counts live Fitness objects via gc.get_objects() as a delta against a pre-measured baseline.
    • Behaviour change to state in the PR body: after an EP factor step, status.result.search_internal now comes from disk (or is None when output.search_internal is off). No consumer in this repo; downstream EP callers not checked.
    • Latent bug found while building the witness, filed separately in Mind: af.Nautilus as an EP default_optimiser crashes on PriorFactors because nautilus/search.py reads analysis._use_jax unguarded (optimise itself uses getattr).
    • Follow-ups filed in PyAutoMind draft/: analysis-level compile cache across EP steps; vmap(jit) recompiling per Nautilus batch length.

    Generated by Claude Code

  2. Jammy2211 commented on Sep 17, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Merged #1634 (merge commit fa2d540, head 9afdc2b) into main with all four CI legs green (unittest (3.12), unittest (3.13), unittest-nojax, docs-build). Label pending-release stays on the PR until the next release publishes it.

    What changed

    • Result.release_search_internal() drops the in-memory sampler reference (and the shared one on child_results), so a factor step's Fitness and its compiled JAX executables are collectable once the step ends. The search_internal property keeps its on-disk fallback.
    • AbstractSearch.optimise calls it before pinning the result on the EP Status. Plain search.fit() is unchanged.
    • Regression test test_autofit/graphical/test_ep_release_search_internal.py (fails on main, passes with the fix); 5-factor JAX witness live Fitness 5→12 on main vs 0 with the fix, RSS flat.

    Follow-ups filed in PyAutoMind draft/: analysis-level compile cache across EP steps; vmap(jit) recompiling per Nautilus batch length; af.Nautilus as EP default_optimiser reading analysis._use_jax unguarded.

    Release note: after an EP factor step, status.result.search_internal is served from disk (or None when output.search_internal is off), not memory.


    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