Skip to content

fix: corner_anesthetic takes 40+ min on 20-parameter models #1760

Closed

Description

@Jammy2211

Overview

corner_anesthetic takes 40+ minutes on a 20-parameter model (HowToLens ch2 tutorial 2, 14.5k weighted Nautilus samples). Profiling shows the dominant cost is pandas' shared-axis label pass. It runs once per panel and walks every axis in the figure, so it scales as n⁴. The 2D KDE contours are a secondary n² cost. The search calls this plot after every fit (PosteriorKind.plot_results), so every many-parameter fit pays this, not just tutorial readers.

Plan

  • Add a profiling harness that times each phase (axes, KDE, pandas label pass, save) at n = 6/10/14/20, with a stable, repeatable setup.
  • Remove the n⁴ cost: stop pandas' shared-axis pass from running inside corner_anesthetic (anesthetic's own axes already handle tick labels), and check with an image-diff test that the output stays visually identical.
  • Above a configurable parameter count (visualize config, default about 12), switch the default lower-panel kind from KDE to a cheaper one (hist_2d). A caller can still ask for KDE.
  • When the search runs, skip the full corner plot above that count; the per-component corner plots already cover it.
  • Add unit tests, plus a witness: the HowToLens ch2 tutorial 2 result needs to plot in under 60 s on the laptop CPU.
  • File a short upstream note to anesthetic/pandas about the n⁴ label pass.

Tier: glance — merge mode: auto-merge on green if the Witness passes, post-merge summary

Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary)

HowToLens is claimed by howtolens-stored-results (HowToLens#130). The library fix speeds up every tutorial call without editing the tutorials. An optional mass-only parameter_indices subset in ch2 tutorial 2 can follow in that branch or a follow-up.

Branch Survey

Repository Current Branch Dirty?
./fit/PyAutoFit main clean

Suggested branch: feature/corner-anesthetic-speed

Measurements so far (laptop CPU, synthetic 14,534 weighted samples)

  • n=6 default kinds: 56 s plotting. Of that, pandas.plotting._matplotlib.tools.handle_shared_axes takes about 22 s (36 calls → 2,340 _remove_labels_from_axis → matplotlib _update_ticks), and kde_contour_plot_2d takes about 21 s (about 1.4 s per lower panel; boundary_correction_2d / _kde_eval about 12 s).
  • Projected to n=20: the label pass grows as n⁴, to about 45 min; the KDE grows as n², to about 4–5 min.
  • n=8: default 64 s, kinds=hist_1d/hist_2d 16 s, thinning (compress) 94 s, so thinning doesn't help.
  • A first quick monkeypatch of pandas.plotting._matplotlib.core.handle_shared_axes gave no clear speed-up at n=8 (60 s) and changed about 7% of pixels at n=4. Laptop timings are noisy (16–66 s for the same run), so before relying on the patch, find the binding anesthetic actually calls and A/B it carefully.

Implementation Steps

  1. autofit/non_linear/plot/nest_plotters.py::corner_anesthetic: wrap nested_samples.plot_2d in a context manager that no-ops pandas' handle_shared_axes at the binding actually called, restoring it in finally. If the attribute is missing (pandas rename), fall back to the unpatched path.
  2. In the same function, choose default kinds by parameter count from config (kde_2d below the threshold, hist_2d above); an explicit kinds= kwarg wins.
  3. autofit/config/visualize/plots_settings.yaml: add corner_anesthetic.max_kde_parameters and a full-plot cap.
  4. autofit/non_linear/search/posterior_kind.py::plot_results: skip the full plot above the cap, log at info level, and still make the per-component plots.
  5. Tests in test_autofit/non_linear/plot/: patch restored on exception, kinds switch at the threshold, explicit kinds respected, axes count unchanged, search-side cap.
  6. Witness: time aplt.corner_anesthetic(samples=result.samples) on the HowToLens ch2 tutorial 2 result (20 params). It needs to finish in under 60 s.

Key Files

  • autofit/non_linear/plot/nest_plotters.py — the corner plot
  • autofit/non_linear/search/posterior_kind.py — corner plots made by the search
  • autofit/config/visualize/plots_settings.yaml — defaults
  • autofit/non_linear/plot/plot_util.py — decorators (log_plot_exception)

Trade-off

Patching a pandas private function is fragile. It's guarded by a fallback, and a test catches a rename.

Original Prompt

Click to expand starting prompt

corner_anesthetic takes 40+ minutes on a 20-parameter model (HowToLens ch2 tutorial 2)

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
  • HowToLens
  • workspaces
    Difficulty: medium
    Autonomy: safe
    Priority: normal
    Status: formalised
    Consequence: glance
    Witness: aplt.corner_anesthetic(samples=result.samples) on the HowToLens chapter 2 tutorial 2 result (20 free parameters, 14,534 weighted Nautilus samples) completes in under 60 s on the laptop CPU.
    Review-minutes: 3
    Unattended: ready

Found 2026-11-06 while working on HowToLens#130 (stored tutorial results).

Symptom

HowToLens scripts/chapter_2_lens_modeling/tutorial_2_practicalities.py line 453, aplt.corner_anesthetic(samples=result.samples), ran for more than 44 minutes without finishing in a real (non-test-mode) run, then again for several minutes when the fit was loaded from disk ("Fit Already Completed"). It is not deadlocked: faulthandler dumps 60 s apart show progress in different frames. Line 472 (latent=True) follows and is likely similar.

Stack (faulthandler, repeated)

tutorial_2_practicalities.py:453 → autofit/non_linear/plot/plot_util.py:112/121 wrapper → autofit/non_linear/plot/nest_plotters.py:140 corner_anesthetic → anesthetic/samples.py:478 plot_2d → pandas plotting core.py:773 _adorn_subplots → tools.py:422 handle_shared_axes → tools.py:336 _remove_labels_from_axis → matplotlib axis.get_minorticklabels → _update_ticks → ticker tick_values.

Cause (hypothesis)

20 parameters → 20×20 = 400 axes from make_2d_axes; anesthetic's default kinds put 2D KDE contours on 190 lower panels over 14.5k weighted samples, and pandas' shared-axis label pass walks tick locators on all 400 axes. Cost scales ~quadratically with parameter count.

Fix options

  • Tutorial side: plot a parameter subset (e.g. mass model only) — anesthetic make_2d_axes takes the column list.
  • Library side: in corner_anesthetic, cap the default number of parameters drawn and/or default to cheaper kinds (hist diagonal, scatter/hist_2d lower) above N parameters; thin to equal-weight samples before KDE.
  • Measure where the time actually goes (KDE vs pandas label pass) before choosing.

Notes

Affects every HowTo reader regardless of stored results (HowToLens#130 ships thin samples, which also helps, but does not fix the library default). Check other corner_anesthetic call sites in HowToLens ch4 tutorial 2, chapter_optional/tutorial_searches, workspaces.

Activity

  1. Jammy2211 commented on Nov 6, 2026

    @Jammy2211
    CollaboratorAuthor

    Why this wasn't slow before

    The plot didn't use to be made at all for this model. The n⁴ cost was always there, but it was hidden by a silent failure.

    • Before 2026-10-04, LaTeX labels were the anesthetic column keys, and the superscript was the attribute name. The tutorial model has two components called bulge (lens and source), so it had repeated labels: $y^{\rm bulge}$, $\epsilon_{\rm 1}^{\rm bulge}$ and others. The only notation.yaml override then was ExternalShear: ext. Reproduced: plot_2d raises KeyError after 0.1 s, and @log_plot_exception logs it as "posterior not yet sufficient", so no plot was ever made.
    • 9db2921 (10-04) keyed columns by position, so the plot is now actually drawn. That exposed the cost.
    • 941bd9d (10-17) made labels unique via component paths and added per-component and latent corner plots.
    • Not the cause: the 10-28 dependency upgrades (pandas 2.2.3→3.0.6, anesthetic 2.14.6→2.16.0, matplotlib 3.10→3.11). The same unpatched benchmark (n=8, hist kinds) takes ~20 s in both the old PyAuto and new PyAuto313 venvs.

    Models whose labels were already unique (one component per type) always paid this cost. They just rarely had 20 parameters.

    Progress on the fix branch

    • Deferring pandas' shared-axis label pass: n=12 went from 146 s to 15 s. Output matches except for a one-pixel autoscale difference in one panel, and a unit test checks label and tick visibility on every axis.
    • Above 10 parameters, the lower panels switch from KDE to hist_2d.
    • Witness (real 20-parameter model, 14,534 weighted samples): 127 s, still over the 60 s target. A profile points at tick updates when the 80×80-inch figure (20 × figsize_per_parammeter 4) is saved, plus make_2d_axes (~18 s). Next step.
  2. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Heart RED override (development only), recorded

    Authorization: James Nightingale, 2026-11-09, live in the shipping session, for this issue only. Answered "Override, open PR (Recommended)" to: "Do you authorize the 'Human override for Heart RED (development only)' to open the PyAutoFit#1760 PR now? It only opens the PR; the merge still needs your /prm with green checks."

    Heart's RED reasons at the time (verbatim):

    Heart: RED — Release RED; monitoring RED · 11/100 · 143 unresolved (updated 4h ago)
      [red] PyAutoGalaxy: CI failure — https://api.github.com/repos/PyAutoLabs/PyAutoGalaxy/actions/runs/42605341827
      [red] PyAutoLens: CI failure — https://api.github.com/repos/PyAutoLabs/PyAutoLens/actions/runs/42605339633
      [red] PyAutoGalaxy: PyAutoGalaxy: CI failure
      [red] PyAutoLens: PyAutoLens: CI failure
      [red] PyAutoGalaxy/Tests: failure
      [red] PyAutoGalaxy/workflows/Tests: failure
      [red] PyAutoHands/workflows/Python Version Matrix: failure
      [red] PyAutoHeart/workflows/Workspace Smoke: failure
      [red] PyAutoLens/Tests: failure
      [red] PyAutoLens/workflows/Tests: failure
      [red] PyAutoGalaxy: PyAutoGalaxy: CI failure
      [red] PyAutoLens: PyAutoLens: CI failure
      [red] autolens_test: red
      [red] Workspace validation: NOT ready — 1399p / 14f / 125s @ cloud#42607741369
      [red] test_run: red
      [red] PyAutoArray: red
      [red] PyAutoGalaxy: red
      [red] PyAutoLens: red
      [red] Worktree drift: 0 orphan / 0 missing / 3 dirty
    

    None involves this branch. PyAutoFit main CI is green.

    Branch gates passed:

    • Unit tests: the full suite passes apart from the Zeus conformance test, which fails identically on main.
    • Smoke: 160/160 across the six workspaces.
    • Independent review: first FINDINGS (twin-axis curve shift, misleading skip log). Both fixed in 1607eee; re-review CLEAN.
    • Witness: 23.6–31.9 s, target < 60 s.

    Scope: commit, push, and open the pending-release PR. Merging needs a separate /prm with every required check green. This does not claim to fix Heart, and Heart stays RED for releases.

  3. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Merged in PR #1761 (bdb7af0e9), pending release.

    • Speed: a 20-parameter corner_anesthetic plot now takes ~25–32 s, down from 40+ min. The witness (real HowToLens ch2 tutorial 2 model, 14,534 weighted samples) ran in 23.6–31.9 s.
    • Compact style above 10 parameters: 2D histograms in the lower triangle, and no upper triangle. A caller's kinds / upper overrides it.
    • End of fit only: weighted and chain corner plots are made once the fit completes. Point-search progress plots still update during the fit.
    • Skipped full plot: above 30 parameters a search skips the full corner plot. The log says whether per-component plots replace it.

    Checks:

    • Tests: 3/3 legs green.
    • Docs: GitHub never started its jobs on any of 3 attempts ("workflow file issue", 0 jobs; the workflow is unchanged and passes on main). docs-build passed in attempt 2, and generated-search-docs passes locally on the PR head. The human chose to merge on that basis.
    • Smoke: 160/160.
    • Independent review: CLEAN after fixes.
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