Skip to content

docs: HowToFit ch1 gradients, the details and Bayesian formalism tutorials #49

Closed

Description

@Jammy2211

Overview

HowToFit chapter 1 teaches inference phenomenologically (tutorials 1–5 plus a prose-only scientific-workflow closer) and never mentions gradients, JAX, the unit cube, assertions, plateaus or NaN diagnostics, even though the installed PyAutoFit now has autodiff searches (MultiStartAdam, BlackJAXNUTS), traced assertions (PyAutoFit#1583) and NaN counters in search.summary. This task adds three tutorials in the existing voice: tutorial 6 "gradients", tutorial 7 "the_details" and an optional "Bayesian formalism" tutorial that maps tutorials 1–5 onto Bayes' theorem. The existing scientific-workflow tutorial is renumbered to tutorial 8 so it still closes the chapter.

Plan

  • Write tutorial_6_gradients.py: gradients as "which way is up" in tutorial 3's parameter space, finite differencing on the 1D Gaussian, JAX autodiff (Analysis(use_jax=True), jax.grad), then the MLE / MCMC / nested trio with gradient counterparts (LBFGS vs MultiStartAdam, Emcee vs BlackJAXNUTS, Nautilus with vmap), closing with errors from curvature (jax.hessian) compared against tutorial 5's sampled errors.
  • Write tutorial_7_the_details.py: parameter flips and assertions, plateaus at zero normalization, comparing searches on both, clipping of unphysical parameter combinations and the per-search resample figure of merit, value-NaN vs gradient-NaN in search.summary, unit cube vs physical space, closing summary.
  • Write tutorial_optional_bayesian_formalism.py: Bayes' theorem mapped term by term onto tutorials 1–6, with small numeric cells that reproduce each equation on the gaussian_x1 fit.
  • Rename tutorial_6_scientific_workflow.py → tutorial_8_scientific_workflow.py; update chapter README, start_here.py, llms.txt, markdown_examples.yaml, scripts/README.md, notebooks/README.md, AGENTS.md.
  • Add profile_smoke.yaml overrides so the two JAX tutorials run with JAX enabled in CI; regenerate notebooks + navigator catalogue with PyAutoHands; verify tutorial 8's notebook stays prose-only.
  • One PR (workspace workflow, no library changes).
Detailed implementation plan

Affected Repositories

  • HowToFit (primary)

Branch Survey

Repository Current Branch Dirty?
./HowToFit main clean (0/0 vs origin; no worktree claims; merged leftover feature/scientific-workflow-language ignored)

Suggested branch: feature/howtofit-ch1-gradients-details
Work Classification: Workspace
Worktree root: ~/Code/PyAutoLabs-wt/howtofit-ch1-gradients-details/

Implementation Steps

  1. scripts/chapter_1_introduction/tutorial_6_gradients.py — sections (the __Contents__ list must match the __Section__ markers): Data, Model (the Gaussian class re-pasted with model_data_from(self, xvalues, xp=np) written in xp.*), Analysis (use_jax forwarded to super().__init__, computes with self._xp), Gradients, Finite Differencing, JAX and Autodiff, Maximum Likelihood Estimation (MLE), Markov Chain Monte Carlo (MCMC), Nested Sampling, Errors From Curvature, Wrap Up. Dataset gaussian_x1. Searches: af.LBFGS, af.MultiStartAdam, af.Emcee, af.BlackJAXNUTS, af.Nautilus. No jax.config.update (autonerves enables x64).
  2. scripts/chapter_1_introduction/tutorial_7_the_details.py — sections: Data, Model, Analysis, Parameterization (2-Gaussian Collection on gaussian_x2, mirror solutions), Assertions (add_assertion(gaussian_0.sigma < gaussian_1.sigma); numpy FitException vs JAX traced xp.where penalty; changes the model identifier; never print() an assertion — installed RecursionError), Plateaus (2-Gaussian model on gaussian_x1, normalization → 0; fixes: LogUniformPrior floor, fixing a parameter, reducing the model), Comparing Searches (Emcee / Nautilus / MultiStartAdam on both problems), Clipping (unphysical combinations → NaN → resample figure of merit -inf MLE/MCMC vs -1e99 nested/SMC; clipper= on gradient searches), NaN Diagnostics (Value-NaN Lane-Steps vs Gradient-NaN Lane-Steps; double-where trap and safe pattern), Unit Cube Vs Physical (vector_from_unit_vector, LogUniformPrior(1e-2, 1e2).value_for(0.5) == 1.0), Summary.
  3. scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py — sections: Bayes Theorem, The Model, The Likelihood, The Prior, The Posterior, Maximum Likelihood vs Maximum A Posteriori, Marginalization, The Evidence, Gradients, Wrap Up. r""" LaTeX with plain-English glosses; numeric check that log_prior_list + log_likelihood_list == log_posterior_list.
  4. git mv tutorial_6_scientific_workflow.py tutorial_8_scientific_workflow.py; fix title/underline.
  5. Navigation: scripts/chapter_1_introduction/README.md (relative notebook links for new tutorials, as the workflow tutorial already does), start_here.py chapter list, llms.txt routing bullets, config/build/markdown_examples.yaml (insert with max_minutes; rename t6→t8), scripts/README.md + notebooks/README.md, AGENTS.md prose-only note → tutorial 8.
  6. config/build/profile_smoke.yaml: overrides entries for tutorial_6_gradients and tutorial_7_the_details with set: {PYAUTO_DISABLE_JAX: "0"} (defaults force JAX off, which makes MultiStartAdam / BlackJAXNUTS refuse to run).
  7. Regenerate from inside HowToFit: PYTHONPATH=../PyAutoHands/autohands python3 ../PyAutoHands/autohands/generate.py howtofit; commit only chapter-1 twins + llms-full.txt + workspace_index.json; confirm the tutorial 8 notebook has no code cells.

Verification

  • Each new script runs green from the repo root with real sampling (settings sized to ≤5 min).
  • python .github/scripts/run_smoke.py passes for chapter 1 with the smoke profile.
  • check_navigator.py passes; new README/llms.txt links resolve; notebooks validate.

Key Files

  • HowToFit/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py — the MLE/MCMC/nested structure and voice tutorial 6 mirrors.
  • HowToFit/scripts/chapter_1_introduction/tutorial_5_results_and_samples.py — __Errors__ section tutorial 6's curvature errors extend.
  • PyAutoFit/autofit/non_linear/fitness.py — Fitness.call NaN/assertion guards and the value-only-guard caveat.
  • PyAutoFit/autofit/text/text_util.py:224-252 — the Resampling Info block of search.summary.
  • PyAutoFit/autofit/non_linear/clipper.py — module docstring on why gradient searches need clipping.

Out of scope (file separately)

Installed-PyAutoFit findings: assertion repr() RecursionError (prior/arithmetic/compound.py:87); stale enable_pytrees()/register_model() text in NUTS/SMC error strings and autofit_workspace/scripts/searches/mcmc.py; af.ex.Analysis uses builtin sum; Emcee crashes with too few steps.

Original Prompt

Click to expand starting prompt

Original request (verbatim):

I want to improve HowToFIt, first reread it all to get a sense of the style, level of detail and information content.
Then write the following extra tutorials and aspect:

Chapter 1, tutorial 6, "gradients" write this based on the following Contents (but should could be multiple sections).

  • Gradients: Extend the phenomenoligcal description of a parameter space from tutorial 3 to include a gradient,
    the ideal that the walker or search knows for each sample which direction the likelihood around it increases it.
    Give an example of a gradient calculaiton on the 1D Gaussians using finite differencing.
  • JAX and autodiff: Now explain auto differention, motivate it by explaining that for many likliehood functions its
    too complicated to analytically compute a gradient, autodiff does it computatiojnally "under the hood". JAX-ify
    the 1D Gaussian likelihood function and illustrate it.
  • JAX search: Show a few examples of JAX gradient searches, I guess like tutorial 3 we should follow the MLE, MCMC, nested
    sampling approach explaining in each how gradients changes their approach. I guess oen section for each search type.
  • SHow how gradients can help with result analysis in a way which naturally follows a concept in tutorial 5
    (poserior predictive test?).

Chapter 1, tutorial 7, "the_details":

  • Discuss how you need to think carefully about your model parameteriation and avoid one where two parameters could
    "flip" and produce the same example, give example with 1D gAussian and example of using an assertion or other criteria
    to remove it.
  • Another example, you need to avoid parameterrs which lead to plataues in likelihood space, for example when the intensity
    or normalization of a gaussian is 0 all solutions become the same. Some searches may struggle with this, give example
    of fixing it.
  • This is a good point to show inference using different searches and rexplain how different searches will face
    the above issues differently, a walker based approach (MCMC) will get stuck in the mirror solutions of the first exampe
    or be unable to walk out of platues. On the other hand, a nested sampler will pretty much sample those regions, and
    pick one peak (if its single mode only), then the live points will move on past the plateau and perform will be
    good. Important lesson, comparing different searches can help us work out better how to improve inference.
  • Clipping: Models may have solutions which are unphysical outside certain bounds or for certain values, and just
    because your priors on individual parameters keep parameters physical sopmetimes its parameter combinations which
    can lead to this. This could, in turn, mean that models are rejected (e.g. return a NaN) or have plateaus again
    messing up searches. Give example but also explain how PyAutoFit has the resample_figure_of_merit which behaviour
    changes depending on the search.
  • Explain the value NaN and gradient NaN values that users can now see in their search.sumary files, as these are
    symbptoms of the above kind of issues. This allows us to explain that just cause a likelihood has a good value
    doesnt mean we can assume its gradient is ok.
  • Unit cube vs phyusical, come back o this point from tutorial 1 to explain how it is actually very important when
    we think about how as search sees and therefore explores parameter space
  • In summary, there are so many details we need to think of when we go about inference. OFten, non the above matter
    and we can get a good inference analysis and pipeline going without worry about these details. However, worrying about
    them will often mean inference runs faster, converges on the right solution more often, and there are worst case scdenarions where
    by not worrying about the above you may infer the wrong solution.

Chapter 1, tutorial option, "bayesian formalism."

  • Bayesian Formalism: Now explain that everything they've learned in the previous chapter is Baeysian inference
    and run through how the contnts of tutorials 1 throuh 5 link to formal Bayesiqn equations. Make it clear that
    the point of HowToFit is to make it so you can learn inference without knowing formal maths, but it helps to know
    how to the two fit together.

Context established at filing (2026-09-10)

  • Chapter 1 currently ends with a prose-only tutorial_6_scientific_workflow.py; the
    new tutorials 6 and 7 displace it, so it is renumbered to tutorial 8 and the
    Bayesian formalism tutorial becomes tutorial_optional_bayesian_formalism.py
    (chapter 3 already uses the tutorial_optional_* naming).
  • Chapter 1 never mentions JAX, gradients, the unit cube or posterior predictive
    checks; all are new vocabulary for the chapter.
  • Installed PyAutoFit: Analysis(use_jax=True) swaps self._xp to jax.numpy;
    MultiStartAdam (autodiff MLE), BlackJAXNUTS (HMC MCMC) are the gradient
    searches; LBFGS is finite-difference; Nautilus/Dynesty use JAX only for
    vmap/jit. search.summary carries Value-NaN Lane-Steps / Gradient-NaN Lane-Steps for the multi-start gradient searches only. add_assertion is a
    traced xp.where penalty on the JAX path (PyAutoFit#1583, installed).
    resample_figure_of_merit is hard-coded per search (-inf MLE/MCMC, -1e99
    nested/SMC), not a config key.

Activity

  1. Jammy2211 commented on Sep 10, 2026

    @Jammy2211
    ContributorAuthor

    PR open: #50 (branch feature/howtofit-ch1-gradients-details, commit 406c53b, label pending-release).

    Delivered: tutorial_6_gradients.py (918 lines), tutorial_7_the_details.py (1140 lines), tutorial_optional_bayesian_formalism.py (554 lines); scientific-workflow tutorial renumbered 6 → 8; chapter lists, smoke-profile JAX overrides, notebooks and navigator catalogue updated. Local verification: every new script runs green with real sampling (≈60 s / 70 s / 15 s); the full run_smoke.py suite passes (18 scripts); check_tutorials_complete, check_navigator and the catalogue-idempotence check pass; tutorial 8 notebook remains code-free.

    Heart was YELLOW (organism-scope reasons unrelated to HowToFit); acknowledged in-session and recorded on the Mind row. Merge via /prm once CI is green.

  2. Jammy2211 commented on Sep 10, 2026

    @Jammy2211
    ContributorAuthor

    Shipped

    Merged #50 into main.

    Three new chapter 1 tutorials — tutorial_6_gradients.py, tutorial_7_the_details.py, tutorial_optional_bayesian_formalism.py — plus the renumbering of the prose-only scientific-workflow tutorial to tutorial 8, the chapter navigation lists, smoke-profile JAX overrides for the gradient tutorials, and regenerated notebooks and navigator catalogue. CI (smoke on 3.12/3.13, navigator, tutorials-complete) green on the merged head.

    Follow-ups from the API survey are filed in PyAutoMind as four draft/{bug,refactor}/autofit/ prompts (assertion repr recursion, stale enable_pytrees advice, example Analysis builtin sum, Emcee short-chain crash).

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