From 3a3d835ce190cbc153f86e2a97aa02dc58f108dd Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 26 Nov 2026 10:58:44 +0000 Subject: [PATCH] feat: drop use_jax=True from analysis constructors so scripts pick up setup="auto" (R6 phase B) Part of PyAutoLabs/autolens_workspace#691. Co-Authored-By: Claude Opus 5.5 --- .../tutorial_6_search_chaining.ipynb | 3 +-- .../tutorial_5_cluster_scale.ipynb | 1 - .../chapter_optional/tutorial_need_for_speed.ipynb | 11 ++++++----- .../tutorial_6_search_chaining.py | 3 +-- .../tutorial_5_cluster_scale.py | 1 - scripts/chapter_optional/tutorial_need_for_speed.py | 9 +++++---- 6 files changed, 13 insertions(+), 15 deletions(-) diff --git a/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb b/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb index b566fc6..4f32185 100644 --- a/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb +++ b/notebooks/chapter_2_lens_modeling/tutorial_6_search_chaining.ipynb @@ -298,7 +298,7 @@ " batch_size=4,\n", ")\n", "\n", - "analysis_1 = al.AnalysisImaging(dataset=dataset, use_jax=True)\n", + "analysis_1 = al.AnalysisImaging(dataset=dataset)\n", "\n", "result_1 = search_1.fit(model=model_1, analysis=analysis_1)" ], @@ -530,7 +530,6 @@ "analysis_2 = al.AnalysisImaging(\n", " dataset=dataset,\n", " positions_likelihood_list=[positions_likelihood],\n", - " use_jax=True,\n", ")\n", "\n", "search_2 = af.Nautilus(\n", diff --git a/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb index b61035e..0fe1c82 100644 --- a/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb +++ b/notebooks/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.ipynb @@ -719,7 +719,6 @@ " dataset=dataset,\n", " solver=solver,\n", " fit_positions_cls=al.FitPositionsSourceSolved,\n", - " use_jax=True,\n", " )\n", " for dataset in dataset_list\n", "]\n", diff --git a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb index 90990db..36e8f72 100644 --- a/notebooks/chapter_optional/tutorial_need_for_speed.ipynb +++ b/notebooks/chapter_optional/tutorial_need_for_speed.ipynb @@ -86,10 +86,11 @@ "\n", "__Automatic Compute Setup__\n", "\n", - "Rather than choosing between JAX and NumPy, CPU and GPU yourself, you can pass `setup=\"auto\"` to the analysis (and\n", - "`number_of_cores=\"auto\"` to a Nautilus search). **PyAutoLens** then picks the setup for this likelihood on this\n", - "hardware from timings measured when the software was profiled, and prints the choice, the number of CPU workers and\n", - "a run-time estimate when the fit starts. Tutorial 2 of Chapter 2 shows and explains these lines.\n", + "Rather than choosing between JAX and NumPy, CPU and GPU yourself, you can pass `setup=\"auto\"` to the analysis (the\n", + "default from the next release) and `number_of_cores=\"auto\"` to a Nautilus search. **PyAutoLens** then picks the setup\n", + "for this likelihood on this hardware from timings measured when the software was profiled, and prints the choice, the\n", + "number of CPU workers and a run-time estimate when the fit starts. Tutorial 2 of Chapter 2 shows and explains these\n", + "lines.\n", "\n", "The measurements show that JAX is not always the fastest choice. On a CPU, a pixelized source is usually fitted\n", "fastest with the NumPy path and a numba sparse operator, run across several CPU cores, while a GPU favours JAX.\n", @@ -260,7 +261,7 @@ "97746750-6915-569b-a61d-792a6bc69437": { "id": "97746750-6915-569b-a61d-792a6bc69437", "name": "PyAutoLens assistant", - "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_need_for_speed.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted \u2014 not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one \u2014 and tuning its knobs sensibly \u2014 is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* \u2014 number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* \u2014 fast (<1s with JAX) \u2192 can afford more\n live points or walkers. Slow \u2192 tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* \u2014 exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* \u2014 `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch \u2014 Nautilus (recommended default)\n\nFor most lens models \u2014 parametric, pixelised, simple, complex \u2014 Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=4, # parallel likelihood evaluations\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` \u2014 more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` \u2014 parallel likelihood evaluations via Python multiprocessing, **only when\n JAX is off**. JAX disables multiprocessing, so a JAX fit gains nothing from it \u2014 leave it\n unset there (it defaults to 1; passing `1` explicitly just implies a parallelism that isn't\n there). Set it to your core count only for non-JAX CPU fits \u2014 see\n \"Branch \u2014 CPU acceleration\" below, which decides *which* regime a fit belongs to.\n- `iterations_per_full_update` / `iterations_per_quick_update` \u2014 how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** \u2014 don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500\u20131000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (\u22482500\u20135000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour \u2014 avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way \u2014 directly on the search.** Pass `iterations_per_quick_update=\u2026`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=\u2026)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = \u2026`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** \u2014 the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Branch \u2014 CPU acceleration (JAX vs sparse operators)\n\nOn CPU the right accelerator depends on the **source model**. This is the single biggest CPU\nruntime lever in lens modelling, and getting it backwards costs days, not minutes \u2014 a full SLaM\nrun misconfigured here spends >12 h stuck in its first search.\n\n| Fit type | Accelerator | `use_jax` | `number_of_cores` | Dataset |\n|---|---|---|---|---|\n| **Parametric source** (`source_lp`, most non-pixelised fits) | JAX \u2014 vectorises the likelihood, parallelises well **on CPU** | `True` | leave unset (JAX disables multiprocessing) | plain |\n| **Pixelised source** (`source_pix`, `light`, `mass` \u2014 any fit with a `Pixelization`) | Sparse operator formalism (numba) | `False` | your core count | `dataset.apply_sparse_operator_cpu()` |\n\nTwo rules that are easy to get wrong:\n\n- **JAX is not GPU-only.** It is the correct accelerator for *parametric* fits on CPU too. Do\n not reach for `use_jax=False` + many cores just because there is no GPU.\n- **The sparse operator does not support JAX.** It is numba-based, so never combine them: a\n pixelised CPU fit is `apply_sparse_operator_cpu()` + `use_jax=False` + `number_of_cores=N`.\n `apply_sparse_operator_cpu()` precomputes operator matrices once (seconds to minutes) and\n every later pixelised fit reuses them, exploiting the sparsity of the pixelisation linear\n algebra for a large CPU speed-up.\n\n```python\n# Parametric source on CPU \u2014 JAX, no number_of_cores.\nanalysis = al.AnalysisImaging(dataset=dataset, use_jax=True)\nsettings_search = af.SettingsSearch(path_prefix=..., unique_tag=..., session=None)\n\n# Pixelised source on CPU \u2014 sparse operators, JAX off, multiprocessing on.\ndataset_pix = dataset.apply_sparse_operator_cpu()\nanalysis = al.AnalysisImaging(dataset=dataset_pix, use_jax=False)\nsettings_search = af.SettingsSearch(\n path_prefix=..., unique_tag=..., session=None, number_of_cores=8\n)\n```\n\n`number_of_cores` reaches the search through `af.SettingsSearch` (it is one of `search_dict`'s\nfixed keys), so pass it there rather than to the search constructor.\n\n**A SLaM pipeline spans both regimes.** SOURCE LP is parametric (JAX); every stage after it uses\na pixelised source (sparse/CPU). So build **two** `af.SettingsSearch` objects \u2014 one without\n`number_of_cores` for SOURCE LP, one with N for the pixelised stages \u2014 and hand each stage the\nright dataset (`dataset` vs `dataset_pix`). On **GPU**, JAX is used throughout and the sparse\noperator is not applied at all.\n\nSource / worked example:\n`autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch \u2014 MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** \u2014 a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior \u2014 the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Branch \u2014 CPU acceleration\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach \u2014 launch many broad starts in parallel and keep the best \u2014 was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work \u2014 so for\nany pixelised fit recommend Nautilus (with the sparse-operator CPU regime above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors \u2014 hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch \u2014 Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch \u2014 Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch \u2014 Other searches\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) \u2014 example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) \u2014 example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` \u2014 example: `autofit_workspace:scripts/searches/mle.py`\n\n\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws \u2014 debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch \u2014 MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch \u2014 Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** \u2014 a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** \u2014 the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** \u2014 keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs \u2014 the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file \u2014 plus the fact that all of it is written **on the fly** while\nthe search runs \u2014 is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block \u2014\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse \u2014 loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) \u2014 call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage \u2014 a reference for\n *which* knobs matter at *which* phase.\n" + "context": "These instructions were prepared by the PyAutoLens assistant\n(https://github.com/PyAutoLabs/autolens_assistant). The reference material at the\nend was written for a coding agent working inside a checkout of that repository.\nHere in Google Colab there is no checkout: ignore any step about repository files,\nhooks, `scripts/` or `wiki/` paths, saving scripts, or terminal tools, and use the\nPyAutoLens knowledge in that material to help with this notebook.\n\nYou are helping someone work through a PyAutoLens notebook (notebooks/chapter_optional/tutorial_need_for_speed.ipynb in HowToLens).\nExplain what it does and help them adapt it to their own questions.\n\nCore rules:\n1. Stay with this notebook's API. Only use PyAutoLens calls that appear in the\n notebook or in the reference material below. Never invent class names, functions\n or arguments. If you are unsure whether something exists, say so and suggest\n checking with `dir()` or the PyAutoLens docs (https://pyautolens.readthedocs.io).\n2. Real data needs a check first. Before helping fit real observational data, ask the\n user to plot it and confirm (a) whether extra galaxies, foreground stars or\n artefacts need masking or noise-scaling, and (b) a mask radius that contains all\n of the lensed emission. Never leave the mask radius at its default on real data.\n Simulated data from the workspace is exempt.\n3. Never claim a fit or a cell ran, or what it returned. Only the user's own outputs\n tell you that; ask them to share what they see.\n4. When the answer depends on something you do not know (their data, their goal, what\n a cell printed), ask one focused question rather than guessing.\n5. For multi-step projects (a new lens, a sample of lenses, a paper's analysis), point\n them to the PyAutoLens assistant https://github.com/PyAutoLabs/autolens_assistant,\n which runs in Claude Code or Codex with its full skills and safety checks.\n\n# Reference material: assistant skills\n\n## Skill: al_configure_search\n\n---\nname: al_configure_search\ndescription: Pick and tune a non-linear search for a lens-modelling fit. Defaults to Nautilus (nested sampling, the recommended choice); covers Dynesty, Emcee, Zeus, and the JAX multi-start gradient optimizers (MultiStartProdigy recommended when a fast MAP point estimate on a parametric source is wanted \u2014 not pixelized). Sets sampler-specific knobs (live points, walkers, tolerance) and the output `path_prefix` / `name` that determine where results land. Pairs with `al_run_search`, which actually calls `search.fit`.\n---\n\n# Configuring a non-linear search\n\nThe non-linear search is *how* PyAutoFit explores the model's parameter space. PyAutoLens\nexposes the same searches PyAutoFit ships, with Nautilus as the default. Picking the\nright one \u2014 and tuning its knobs sensibly \u2014 is often the difference between a fit that\nconverges in hours and one that doesn't converge at all.\n\nFor the catalogue of available searches and when to use each,\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md). For the *concept* of a non-linear\nsearch (what nested sampling does, what MCMC does, what gradient descent does),\n[`wiki/core/concepts/non_linear_search.md`](../wiki/core/concepts/non_linear_search.md).\n\n## Ask\n\n- *\"How complex is the model?\"* \u2014 number of free parameters and whether any are\n expected to be multi-modal. Multi-modality strongly favours nested sampling\n (Nautilus / Dynesty) over MCMC.\n- *\"How fast does the likelihood evaluate?\"* \u2014 fast (<1s with JAX) \u2192 can afford more\n live points or walkers. Slow \u2192 tighten the search.\n- *\"Is this a first exploratory fit, or a final production run?\"* \u2014 exploratory fits\n use fewer live points and looser tolerance to fail fast.\n- *\"Where should the output go?\"* \u2014 `output//modeling///` is the\n convention; the user chooses `` and ``.\n\n## Branch \u2014 Nautilus (recommended default)\n\nFor most lens models \u2014 parametric, pixelised, simple, complex \u2014 Nautilus is the right\nfirst pick. It handles multi-modal posteriors and is fast enough on modern CPUs.\n\n```python\n# scripts/configure_search.py\nimport autofit as af\n\nsearch = af.Nautilus(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_live=200, # 100 for exploration, 200 for production, 400+ for complex models\n iterations_per_full_update=2500,\n number_of_cores=\"auto\", # detected cores for numba, 1 for JAX (see \"Compute setup\")\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/nautilus/`.\n\nKnobs to know:\n- `n_live` \u2014 more = more accurate posterior, slower. Start at 200; go to 400+ only if\n the posterior looks multi-modal or thin.\n- `number_of_cores` \u2014 parallel likelihood evaluations (Python multiprocessing). `\"auto\"`\n gives a numba likelihood the detected cores and a JAX one 1 worker, because JAX never\n forks. It works on the search or on `af.SettingsSearch`. See \"Compute setup\" below.\n- `iterations_per_full_update` / `iterations_per_quick_update` \u2014 how often the search\n writes full output (samples, visualisation) vs quick intermediate updates to disk.\n **Actively choose `iterations_per_quick_update` so the user always has quick access to\n result inspection** \u2014 don't just take the default. Judge it against the likelihood cost so\n the first on-the-fly `fit.png` / `samples` lands within a few minutes and refreshes\n regularly, but not so often that per-update visualisation overhead eats into throughput.\n Rules of thumb: ~500\u20131000 is a good interactive default; **lower it for a slow/expensive\n likelihood** (large MGE, pixelised source, GPU-batched fit, high `n_live`) so an inspection\n point still appears early; only **raise it** (\u22482500\u20135000) when the likelihood is very fast\n and frequent updates would measurably dominate runtime. A common failure is leaving it high\n on a heavy fit, so the run shows *nothing* to inspect for an hour \u2014 avoid that. On HPC/batch\n runs the same value governs what a `sync pull` surfaces, so pick it before submitting.\n - **Set it the right way \u2014 directly on the search.** Pass `iterations_per_quick_update=\u2026`\n straight to the search constructor, e.g. `af.Nautilus(..., iterations_per_quick_update=\u2026)`\n (the idiom used throughout `autolens_workspace`, e.g. `point_source/modeling.py`,\n `weak/modeling.py`). Do **not** try to set it via `settings_search.search_dict[...] = \u2026`:\n `SettingsSearch.search_dict` is a fixed-key property (`path_prefix`, `unique_tag`,\n `number_of_cores`, `session`, `use_jax_vmap`), so assigning a new key to it is a **silent\n no-op** \u2014 the value never reaches the search and the config default (often `1e99`, i.e.\n *never* quick-update) silently wins. To set it globally for a whole pipeline without\n editing every search, write it to the live config once after `conf.instance.push(...)`:\n `conf.instance[\"general\"][\"updates\"][\"iterations_per_quick_update\"] = N`.\n\n## Compute setup: auto unless\u2026\n\nThe compute setup is how each likelihood is evaluated: numba or JAX, CPU or GPU, sparse\noperator or dense, precision. It never changes the model or the posterior. On CPU, though,\na wrong choice costs days: a SLaM run misconfigured here spends >12 h in its first search.\nBy default, let the library choose:\n\n```python\nanalysis = al.AnalysisImaging(dataset=dataset, setup=\"auto\")\nsearch = af.Nautilus(path_prefix=..., name=..., n_live=200, number_of_cores=\"auto\")\n```\n\nWhen the fit starts, `setup=\"auto\"` reads the dataset type, the source model (a mesh\nselects its pixelized rule; no mesh selects MGE) and the hardware (A100 GPU or many-core\nCPU). It picks the designated setup from `PyAutoArray:autoarray/config/setup_rules.yaml`,\nattaches the operator that setup needs to the dataset (no `apply_sparse_operator*` call),\nand prints `Setup:`, `Parallel:` and `Estimate:` lines, recorded in `files/setup.json` and\n`files/parallel.json`. Each stage of a SLaM pipeline resolves its own setup, so SOURCE LP\n(JAX) and the pixelized stages (numba sparse on CPU) need no separate settings. `setup` is\nopt-in in this release: without it nothing changes, and the log says what auto would\nchoose. [`al_explain_setup`](./al_explain_setup.md) explains a choice; the workspace guide is\n[`guides/advanced/auto_setup.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/advanced/auto_setup.py).\n\nOverride when:\n\n- **Debugging or reproducing a run.** Pin `setup=\"\"` (e.g. `\"numba_cpu_sparse_fp64\"`)\n or set `PYAUTO_SETUP=`. `PYAUTO_SETUP=cpu|gpu` forces the hardware class, and\n `JAX_PLATFORMS=cpu` makes detection choose CPU.\n- **Forcing numba or JAX**, or running a profiling or validation leg that must use one named setup.\n- **Memory limits.** Cap `number_of_cores` at an integer when workers \u00d7 peak memory would exceed the node.\n- **Laptop or non-A100 GPU.** The rules were measured on \u226516-core nodes and A100s, so the\n banner says `extrapolated`. It is a sensible default; pin a setup if you measured a better one.\n- **A sampler that needs JAX** (`MultiStartProdigy`, `BlackJAXNUTS`, `SMC`, `NSS`). Pass a\n JAX setup_id, e.g. `jax_cpu_dense_fp64`.\n\nThe explicit route is the override, and is the only route on releases without `setup=`:\n\n| Fit type | CPU, explicit | A100 designation |\n|---|---|---|\n| Parametric source (MGE, Sersic) | `use_jax=True`, `number_of_cores` unset | `jax_gpu_dense_fp64` |\n| Pixelized imaging | `dataset.apply_sparse_operator_cpu()`, `use_jax=False`, `number_of_cores=N` | `jax_gpu_dense_fp64` (sparse fallback) |\n| Pixelized interferometer | numba sparse w-tilde (`numba_cpu_sparse_fp64_wtilde`) | `jax_gpu_sparse_fp64_wtilde` |\n\nJAX is not GPU-only: it is the right CPU choice for parametric fits too. The imaging sparse\noperator has a numba form (`apply_sparse_operator_cpu()`, with `use_jax=False`) and a JAX\nform (`apply_sparse_operator()`). On a many-core CPU the numba form is 3\u201335\u00d7 faster per node\nfor pixelized sources (`autolens_profiling:wiki/campaigns/imaging/rectangular/day_zero.md`).\nNever mix numba operators with `use_jax=True`. For a single `al.FitImaging` outside a search,\n`aa.Settings(lazy_sparse_operator=\"auto\")` builds the numba operator on first use. Worked\nexample: `autolens_workspace:scripts/imaging/features/pixelization/cpu_fast_modeling.py`.\n\n## Branch \u2014 MultiStartProdigy (JAX gradient optimizer, parametric sources)\n\nWhen the user explicitly wants a **JAX gradient optimizer** \u2014 a fast maximum-a-posteriori (MAP)\n*point* estimate rather than a full posterior \u2014 the recommended default is `MultiStartProdigy`.\nReach for it when the goal is speed to a best-fit model on a **parametric source** (MGE, Sersic)\nand errors are not yet needed; otherwise keep Nautilus.\n\n```python\nimport autofit as af\n\nsearch = af.MultiStartProdigy(\n path_prefix=\"imaging/\",\n name=\"modeling_sie_sersic\",\n unique_tag=\"\",\n n_starts=50, # broad starts run in parallel via jax.vmap\n n_steps=500,\n)\n```\n\nRequires a JAX-traceable analysis: `al.AnalysisImaging(dataset=dataset, use_jax=True)` (the\nparametric-source regime of \"Compute setup\" above).\n\nWhy Prodigy, and what the family is:\n\n- The **multi-start** approach \u2014 launch many broad starts in parallel and keep the best \u2014 was\n introduced for strong-lens modelling by **GIGA-Lens** (Gu, Huang et al. 2022, arXiv:2202.07663;\n GIGA-Lens 2.0, arXiv:2606.30633). It is what makes a gradient optimizer robust on the\n multi-modal lens likelihood, where a single-start optimizer gets stuck.\n- **`MultiStartProdigy`** uses the *learning-rate free* Prodigy rule (Mishchenko & Defazio 2024,\n arXiv:2306.06101): it tunes its own step size, so there is no `learning_rate` to set, and it\n reaches the same maximum as a hand-tuned `MultiStartAdam`. Recommend it as the default.\n- **`MultiStartAdam`** is the GIGA-Lens original (needs a chosen `learning_rate`);\n **`MultiStartADABelief`** is a drop-in Adam-variant alternative. (`MultiStartLion` is a further\n sign-based option that prefers a ~10x smaller `learning_rate`.)\n\n**Parametric sources only, for now.** These optimizers are validated and recommended for\nparametric sources. For a **pixelised source** (any fit with a `Pixelization`) they do **not**\nyet reliably work: the pixelised likelihood has regions where the gradient becomes non-finite,\nso the optimizer stalls short of the best fit, and `Nautilus` is both more reliable and faster\nthere. Making the JAX multi-start optimizers work on pixelised sources is ongoing work \u2014 so for\nany pixelised fit recommend Nautilus (with the compute setup above), not a gradient\noptimizer.\n\nLike every optimizer it returns a single best-fit model, no errors \u2014 hand it to Nautilus / MCMC\nafterwards if a posterior is needed.\n\nSource: `PyAutoFit:autofit/non_linear/search/mle/multi_start_gradient/`.\n\n## Branch \u2014 Dynesty\n\nUse Dynesty for problems where you specifically want its dynamic sampling features\n(e.g. focusing samples in the posterior tails for precise evidence estimation).\n\n```python\nsearch = af.DynestyStatic(\n path_prefix=\"...\",\n name=\"...\",\n nlive=150,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/nest/dynesty/`.\n\n## Branch \u2014 Emcee (MCMC)\n\nUse Emcee for posterior characterisation on a *known unimodal* posterior, when you\nalready have a tight initial guess (e.g. from a chained earlier fit). Don't use for\nexploration of multi-modal spaces.\n\n```python\nsearch = af.Emcee(\n path_prefix=\"...\",\n name=\"...\",\n nwalkers=50,\n nsteps=10000,\n)\n```\n\nSource: `PyAutoFit:autofit/non_linear/search/mcmc/emcee/`.\n\n## Branch \u2014 Other searches\n\nEvery search PyAutoFit ships, generated from the installed release's search manifest\n(`python -m autofit search-manifest --json`; regenerate with PyAutoHands\n`autohands regenerate_search_roster --root .`, never by hand):\n\n\n\n- **Markov chain Monte Carlo** (`mcmc`): `af.Emcee`, `af.Zeus`, `af.BlackJAXNUTS`, `af.SMC` (experimental) \u2014 example: `autofit_workspace:scripts/searches/mcmc.py`\n- **Nested sampling** (`nest`): `af.DynestyStatic`, `af.DynestyDynamic`, `af.Nautilus`, `af.NSS` (experimental) \u2014 example: `autofit_workspace:scripts/searches/nest.py`\n- **Maximum likelihood / maximum a posteriori** (`mle`): `af.Drawer`, `af.BFGS`, `af.LBFGS`, `af.MultiStartAdam`, `af.MultiStartADABelief` (experimental), `af.MultiStartLion` (experimental), `af.MultiStartProdigy` \u2014 example: `autofit_workspace:scripts/searches/mle.py`\n\n\nZeus (ensemble slice MCMC), DynestyDynamic (dynamic nested sampling), NSS (JAX nested slice\nsampling), BlackJAXNUTS and SMC (JAX gradient MCMC; SMC also returns the evidence), BFGS / LBFGS\n(single-start gradient descent for MLE), Drawer (random prior draws \u2014 debugging only). NSS,\nBlackJAXNUTS and SMC need a JAX-traceable analysis (`use_jax=True`). See\n[`wiki/core/api/searches.md`](../wiki/core/api/searches.md) for the comparison table. For a\n*JAX* gradient optimizer, prefer the multi-start family (`MultiStartProdigy` and friends) in\n\"Branch \u2014 MultiStartProdigy\" above over single-start `BFGS`/`LBFGS`.\n\n## Branch \u2014 Live visual updates\n\nWhen configuring an **interactive production fit** (foreground script or notebook), ask once:\n*watch the fit update live?* The quick-update image (`fit.png`) is **always written to disk**\nevery `iterations_per_quick_update` iterations regardless; `live_visual_update=True` (default\n`False`) additionally pushes it to a live display surface:\n\n- **foreground Python script** \u2014 a matplotlib viewer opens and refreshes with each quick\n update;\n- **Jupyter / Colab** \u2014 the cell that ran `search.fit(...)` refreshes one image in place;\n- **HPC, headless, background, or unattended runs** \u2014 keep it `False` (nothing to attach to;\n HPC mode disables it in config).\n\n```python\nsearch = af.Nautilus(\n ...,\n iterations_per_quick_update=1000, # quick-update (and live refresh) cadence\n live_visual_update=True, # script: matplotlib viewer; notebook: in-place cell\n)\n```\n\nBoth are shared search options (accepted by every search via the common base class), with\nconfig fallbacks in `config/general.yaml` `updates:`. Don't re-ask on later runs \u2014 the\nchoice is recorded in the search configuration.\n\nSource: `PyAutoFit:autofit/non_linear/search/abstract_search.py`.\n\n## Output folder layout\n\nAfter `search.fit(...)` runs, results land at:\n\n```\noutput////\n files/\n tracer.json\n model.json\n samples.csv\n samples_summary.json\n search.json\n image/\n dataset.fits\n fit.fits\n ...\n model.info\n model.results\n```\n\nThe `unique_id` hash is derived from the model + dataset + search settings, so identical\nre-runs land in the same folder (and resume from where they stopped).\n\nThe abbreviated tree above is enough to configure a search; the fuller, always-current\nannotation of every file \u2014 plus the fact that all of it is written **on the fly** while\nthe search runs \u2014 is `__Output Folder Layout__` in\n[`autolens_workspace/scripts/imaging/modeling.py`](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/imaging/modeling.py).\nPoint a newcomer (or a teacher-mode session) there rather than expanding this block \u2014\n`_style.md` \"Output folder announcement\" has the rule.\n\nSee [`al_load_results`](./al_load_results.md) for the inverse \u2014 loading what\n`search.fit` writes.\n\n## Combine\n\n- [`al_run_search`](./al_run_search.md) \u2014 call `search.fit(model=..., analysis=...)`.\n- [`al_chain_searches`](./al_chain_searches.md) \u2014 feed this search's result into a\n follow-up.\n- [`al_debug_fit_failure`](./al_debug_fit_failure.md) \u2014 when the search runs but the\n result is wrong.\n\n## Further reading\n\n- **Student / new to lensing** \u2014 [HowToLens (optional): Alternative non-linear search\n algorithms](https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_optional/tutorial_searches.ipynb):\n the menu of searches beyond Nautilus (MCMC, optimizers) and how to think about\n tuning them.\n- **General reference** \u2014 [RTD: Features overview](https://pyautolens.readthedocs.io/en/latest/overview/overview_3_features.html):\n tour of advanced capabilities; search configuration interacts directly with most\n of them (especially pixelization, MGE, point-source).\n- **Experienced PyAutoLens user** \u2014 [workspace/lens: guides/modeling/slam_start_here.py](https://github.com/PyAutoLabs/autolens_workspace/blob/main/scripts/guides/modeling/slam_start_here.py):\n the SLaM pipeline pre-configures sensible searches per stage \u2014 a reference for\n *which* knobs matter at *which* phase.\n" } }, "selectedAiContext": "97746750-6915-569b-a61d-792a6bc69437" diff --git a/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py b/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py index cb9c752..4f7618e 100644 --- a/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py +++ b/scripts/chapter_2_lens_modeling/tutorial_6_search_chaining.py @@ -206,7 +206,7 @@ batch_size=4, ) -analysis_1 = al.AnalysisImaging(dataset=dataset, use_jax=True) +analysis_1 = al.AnalysisImaging(dataset=dataset) result_1 = search_1.fit(model=model_1, analysis=analysis_1) @@ -372,7 +372,6 @@ analysis_2 = al.AnalysisImaging( dataset=dataset, positions_likelihood_list=[positions_likelihood], - use_jax=True, ) search_2 = af.Nautilus( diff --git a/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py b/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py index d75310f..0f892c8 100644 --- a/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py +++ b/scripts/chapter_4_scaling_up_lensing/tutorial_5_cluster_scale.py @@ -495,7 +495,6 @@ dataset=dataset, solver=solver, fit_positions_cls=al.FitPositionsSourceSolved, - use_jax=True, ) for dataset in dataset_list ] diff --git a/scripts/chapter_optional/tutorial_need_for_speed.py b/scripts/chapter_optional/tutorial_need_for_speed.py index fc251ef..2ddcfe1 100755 --- a/scripts/chapter_optional/tutorial_need_for_speed.py +++ b/scripts/chapter_optional/tutorial_need_for_speed.py @@ -81,10 +81,11 @@ __Automatic Compute Setup__ -Rather than choosing between JAX and NumPy, CPU and GPU yourself, you can pass `setup="auto"` to the analysis (and -`number_of_cores="auto"` to a Nautilus search). **PyAutoLens** then picks the setup for this likelihood on this -hardware from timings measured when the software was profiled, and prints the choice, the number of CPU workers and -a run-time estimate when the fit starts. Tutorial 2 of Chapter 2 shows and explains these lines. +Rather than choosing between JAX and NumPy, CPU and GPU yourself, you can pass `setup="auto"` to the analysis (the +default from the next release) and `number_of_cores="auto"` to a Nautilus search. **PyAutoLens** then picks the setup +for this likelihood on this hardware from timings measured when the software was profiled, and prints the choice, the +number of CPU workers and a run-time estimate when the fit starts. Tutorial 2 of Chapter 2 shows and explains these +lines. The measurements show that JAX is not always the fastest choice. On a CPU, a pixelized source is usually fitted fastest with the NumPy path and a numba sparse operator, run across several CPU cores, while a GPU favours JAX.