Repository navigation
Description
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
- In
AbstractSearch.optimise, release the search internals from theResultbefore it is pinned on the EPStatus, so theFitnessand its compiled executables become collectable when the factor step ends. - Regression test (JAX-free): two consecutive
optimisecalls on oneAnalysisFactorleave noFitnessalive from the first step andstatus.result._search_internal is None, whilelatest_result.projected_model/.samplesstill work. - Empirical witness (JAX): a small EP run (5 Gaussian factors × 4 steps, Nautilus,
use_jax=True) with RSS and live-Fitnesscount logged per step — growing before the fix, flat after; numbers go in the PR body. - Ship as a library PR (
pending-release), workspace impact none (no API change), issue + Mind close-out via/prm. - File two follow-up prompts via
/intake: analysis-level compile cache across EP steps; fixed-batch padding to stopvmap(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_vmapis a per-instancecached_propertywrappingjax.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), andvmap(jit)additionally compiles one executable per distinct Nautilus batch length, unlogged. - Nothing releases them.
AbstractSearch.optimise(abstract_search.py:435-455) doesstatus.result = result;EPHistory.__call__appends(approx, status)tohistoryfor every factor step (graphical/expectation_propagation/history.py:75).Result._search_internal(non_linear/result.py:387) holds thenautilus.Sampler, whoselikelihoodisfitness.call_wrap→ theFitness→ 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: falseonly affects the on-disk dump. - The retained sampler is never read: no graphical code touches
search_internal(latest_resultconsumers use.projected_model,.samples,.model). TheResult.search_internalproperty already falls back to loadingsearch_internal.dillfrom disk when the in-memory reference isNone(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_conflictfires: PyAutoFit is claimed byhowtofit-mode, whose PyAutoFit worktree is clean with zero commits ahead oforigin/main(README propagation not yet started). File sets are disjoint by construction → own parallel worktree (recommended; memoryfeedback_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 worktreeon theactive.mdrow.- Task
ep-release-search-internals, branchfeature/ep-release-search-internals, worktree~/Code/PyAutoLabs-wt/ep-release-search-internals/viaworktree_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 = NoneAlso 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):
- Build
factor_approx = model_approx.factor_approximation(factor); callsearch.optimise(factor_approx)twice (two "EP steps"), collecting the returned(model_dist, status). - Wrap the
Fitnessconstructor with a monkeypatch that recordsweakref.refto each instance. After the second call (anddelof local results), assert every recorded weakref is dead — noFitnesssurvives its factor step. - Assert
status.result._search_internal is Noneand thatstatus.result.projected_model,status.result.samplesandstatus.result.modelstill resolve (whatEPHistory.latest_resultconsumers use). - Assert
status.result.search_internaldoes not raise whenoutput.search_internalis off — it returnsNone/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 (thesearch_internalproperty 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). Labelpending-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_internalinautofit_workspace/*_workspace_testEP 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)
draft/refactor/autofit/…— cache the compiled_vmap/_jit/_gradon theAnalysiskeyed 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-readingEPAnalysisFactoranalyses; saves one compile per factor search (~2–3 s of ~8 min).draft/bug/autofit/…—vmap(jit)recompiles per distinct Nautilus batch length (Fitness.call_wrappromotes(d,)→(1,d);sample_shellbatch 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_issuemoves it toactive/, drop the second# …title + header block (lines 20–36) and keepGates: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_internaland the lazysearch_internalproperty (~387, 430-449)autofit/graphical/expectation_propagation/history.py—EPHistory.__call__/latest_result(the retention)autofit/graphical/expectation_propagation/optimiser.py—EPOptimiser.run/factor_stepautofit/non_linear/fitness.py—_vmap/_jit/_gradper-instance compile caches (842-883)autofit/non_linear/search/nest/nautilus/search.py— freshFitnessper 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
.errfills withE … execution_engine.cc:54] LLVM compilation error: Cannot allocate memoryandcontiguous_section_memory_manager.cc:71] releaseMappedMemory failed; factor dataset_24 then raisesjax.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 hitsLLVM 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
Jammy2211 commentedon Sep 17, 2026
Progress: fix implemented and pushed (remote session, 2026-09-17)
Branch
claude/vmapped-likelihood-jit-compiles-bhog4o, commit9afdc2b— no PR opened yet (next step is/ship_library, or/prmonce 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 walkschild_resultsbecauseAnalysisFactorCollection.make_resulthands the same sampler object to aCombinedResultand every child.AbstractSearch.optimisecalls it beforestatus.result = result(guarded withgetattr, since the regression suite'sStaticSearchreturns a bare object).search_internalkeeps its on-disk-dill fallback; ordinarysearch.fit()is untouched.test_autofit/graphical/test_ep_release_search_internal.py: twooptimisecalls on oneAnalysisFactor(dynesty, JAX-free) leave no liveFitnessandstatus.result._search_internal is None, while.projected_model/.samples/.modelstill resolve. Fails onmain(assert 1 == 0live Fitness;_search_internalis aMultiEllipsoidSampler), 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):Tests:
test_autofit/graphical+non_linear/test_jax_compile.py+non_linear/test_fitness_jax_dispatch.py+non_linear/resultserially: 333 passed. Under-n autobothgraphicalandnon_linear/searchare already flaky onmain(sharedtest_autofit/outputwiped by the autouse fixture across workers) — the knownep_test_suite_is_not_xdist_safeMind draft, not this change.Notes for the ship
Fitness.__init__alone cannot probe this, because a dynesty search that resumes from its checkpoint restores the sampler by unpickling and the restoredFitnessnever passes__init__; the test therefore counts liveFitnessobjects viagc.get_objects()as a delta against a pre-measured baseline.status.result.search_internalnow comes from disk (or isNonewhenoutput.search_internalis off). No consumer in this repo; downstream EP callers not checked.af.Nautilusas an EPdefault_optimisercrashes onPriorFactors becausenautilus/search.pyreadsanalysis._use_jaxunguarded (optimiseitself usesgetattr).draft/: analysis-level compile cache across EP steps;vmap(jit)recompiling per Nautilus batch length.Generated by Claude Code
Jammy2211 commentedon Sep 17, 2026
Shipped
Merged #1634 (merge commit
fa2d540, head9afdc2b) intomainwith all four CI legs green (unittest (3.12),unittest (3.13),unittest-nojax,docs-build). Labelpending-releasestays 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 onchild_results), so a factor step'sFitnessand its compiled JAX executables are collectable once the step ends. Thesearch_internalproperty keeps its on-disk fallback.AbstractSearch.optimisecalls it before pinning the result on the EPStatus. Plainsearch.fit()is unchanged.test_autofit/graphical/test_ep_release_search_internal.py(fails on main, passes with the fix); 5-factor JAX witness liveFitness5→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.Nautilusas EPdefault_optimiserreadinganalysis._use_jaxunguarded.Release note: after an EP factor step,
status.result.search_internalis served from disk (orNonewhenoutput.search_internalis off), not memory.Generated by Claude Code