Skip to content

fix: align Emcee and Zeus log posteriors with the thinned sample chain - #1629

Merged
Jammy2211 merged 1 commit into
mainfrom
feature/emcee-log-prob-alignment
Sep 14, 2026
Merged

Jammy2211 merged 1 commit into
mainfrom
feature/emcee-log-prob-alignment

Conversation

@Jammy2211

Copy link
Copy Markdown
Collaborator

Closes #1628.

The bug

Emcee.samples_via_internal_from built each sample's likelihood from two arrays that were not in correspondence:

samples_after_burn_in = search_internal.get_chain(discard=discard, thin=thin, flat=True)
parameter_lists = samples_after_burn_in.tolist()
total_samples = len(parameter_lists)
log_posterior_list = search_internal.get_log_prob(flat=True)[-total_samples - 1 : -1].tolist()

The parameters are the chain after burn-in discard and thinning. The log posteriors are a contiguous tail slice of the raw, unthinned, undiscarded flat array, plus an unexplained one-element offset. Sample i's likelihood belonged to a different sample.

Zeus had the same defect in a different form — get_log_prob(flat=True) against a possibly-thinned chain, after which zip() silently truncated to the shorter list, hiding the length mismatch entirely.

Impact

  • result.max_log_likelihood_instance / samples.max_log_likelihood() returned the argmax of a scrambled array — effectively a random post-burn-in draw, not the maximum likelihood sample.
  • The "Maximum Log Likelihood" line of every Emcee and Zeus result.info was wrong.
  • log_likelihood_list was wrong per-sample, so anything derived from it inherited the error.

Nested sampling and the MLE searches were never affected.

The error scales with how much the post-burn-in samples differ from one another, so a poorly converged chain is punished hardest — exactly the case where a trustworthy maximum-likelihood sample matters most.

Verification

Reproduced on a 1D Gaussian fit with af.Emcee(nwalkers=20, nsteps=500), comparing the reported likelihood against the same Analysis recomputed from the reported instance:

reported actual delta
before 188.9628 188.8337 0.129
before (worse chain) 188.34 176.52 11.82
after 188.992757 188.992757 0.000e+00

After the fix, three consecutive runs gave a worst-case delta of exactly 0.000e+00.

The fix

Both searches request log posteriors under the same discard and thin as the chain. discard/thin are now bound in both branches of the test-mode conditional (test mode previously inlined discard=5, thin=5 into its get_chain call), and Zeus's empty-chain fallback resets them to 0/1 to match the get_chain(flat=True) it falls back to.

Both now raise exc.SamplesException when the two lengths disagree, so a future mismatch fails loudly rather than truncating — the old Zeus zip() is precisely the silent-guard pattern this repo's conventions forbid.

API semantics were introspected, not assumed. emcee 3.1.6's get_chain and get_log_prob both delegate to the same get_value(name, flat=False, thin=1, discard=0), which applies [discard + thin - 1 : iteration : thin] and flattens identically. zeus 2.5.4's two methods carry identical explicit signatures, the same fractional-discard handling, and matching [discard:index:thin] slices. No library-specific asymmetry, so no asymmetric handling was needed.

Unchanged: discard/thin values, the auto-correlation logic, nested sampling, the MLE searches.

Tests

Added to the existing MCMC test modules, matching their fixtures and conventions (no JAX, seeded, af.ex.Gaussian + af.ex.Analysis). The Zeus test is guarded by importlib.util.find_spec("zeus") since zeus is an [optional] extra, following the requires_nautilus pattern.

They assert the invariant, not a pinned number: samples.max_log_likelihood_sample.log_likelihood must equal the Analysis likelihood recomputed from samples.max_log_likelihood(), plus the two list lengths must match and be non-zero.

Confirmed to actually catch the bug — each was run against the reverted source:

with fix with bug restored
emcee PASSED FAILED — stored -1247.252566 vs true -1247.482800
zeus PASSED FAILED — stored -1244.796028 vs true -1245.091243

Both tests need AutoCorrelationsSettings(check_for_convergence=False, check_size=5, required_length=2): with the default check_size=100 against a 10-step test-mode chain, auto_correlations_from slices to an empty array and emcee.autocorr raises IndexError before samples are built. Pre-existing, see below.

Suite

pytest test_autofit -q → 2852 passed, 2 skipped, zero failures.

Pinned values

None exist, so nothing else moved. Grepped PyAutoFit (*.py, *.rst, *.ipynb, *.md, *.yaml) for Emcee/Zeus references co-occurring with likelihood numbers or pytest.approx, and checked autofit_workspace too. The only hit is a comment naming the two searches as log-posterior searches, with no number. No test mocks get_log_prob outside the two files changed here.

Found but not fixed (follow-ups)

  1. thin can be 0. thin = int(np.max(auto_correlations.times) / 2.0) is 0 whenever the largest auto-correlation time is below 2.0, and a zero slice step raises ValueError: slice step cannot be zero in both get_chain and get_log_prob. Pre-existing and unchanged here — the old code hit it on get_chain first. Clamping it would change thin values, which is a separate decision.
  2. check_size=100 versus short chains. auto_correlations_from raises IndexError from emcee.autocorr when the chain is shorter than check_size, which is always true under PYAUTO_TEST_MODE=1 (nsteps=10). Zeus guards its equivalent with except IndexError; Emcee does not. Worked around in the tests rather than changed in the library.
  3. black --check still reports findings in zeus/search.py and both test files. Every one is pre-existing on origin/main (verified by piping git show origin/main:<file> through black) and none is in a hunk added here. Left alone — AGENTS.md records no black gate, and fixing them would add unrelated noise.

Origin

Found while calibrating HowToFit tutorial 3's MCMC budget (PyAutoLabs/HowToFit#59, PR PyAutoLabs/HowToFit#60). That tutorial work does not depend on this fix and ships independently.

🤖 Generated with Claude Code

https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG

`Emcee.samples_via_internal_from` took its parameters from the chain after
burn-in discard and thinning, but its log posteriors from a contiguous tail
slice of the raw, unthinned, undiscarded array:

    samples_after_burn_in = search_internal.get_chain(
        discard=discard, thin=thin, flat=True
    )
    total_samples = len(parameter_lists)
    log_posterior_list = search_internal.get_log_prob(flat=True)[
        -total_samples - 1 : -1
    ].tolist()

The two are not in correspondence, so sample `i`'s reported likelihood belonged
to a different sample. `result.max_log_likelihood_instance` was therefore the
argmax of a scrambled array — effectively a random post-burn-in draw rather than
the maximum likelihood sample — and the "Maximum Log Likelihood" line of every
Emcee `result.info` was wrong. The slice also carried an unexplained one-element
offset.

`Zeus` had the same defect in a different form: `get_log_prob(flat=True)` against
a possibly-thinned chain, with the following `zip()` silently truncating to the
shorter list.

Both now request log posteriors under the same `discard` and `thin` as the
chain. `discard`/`thin` are bound in both branches of the test-mode conditional,
and Zeus's empty-chain fallback resets them to `0`/`1` to match the
`get_chain(flat=True)` it falls back to. Both searches now raise
`exc.SamplesException` if the two lengths disagree, so a future mismatch fails
loudly instead of truncating.

emcee's `get_chain` and `get_log_prob` both delegate to the same
`get_value(name, flat, thin, discard)`, and zeus's carry identical explicit
signatures, so the discard/thin semantics are provably identical between the
two calls in each library.

Regression tests assert the invariant rather than a pinned number: the reported
maximum likelihood must equal the `Analysis` likelihood recomputed from the
reported instance. Both were confirmed to fail against the old code and pass
against the new.

No `discard`/`thin` values, auto-correlation logic, nested sampling or MLE
search behaviour changed.

Closes #1628

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0132v5TNVbbvBBESAefHwnwG
@Jammy2211
Jammy2211 merged commit 08a2446 into main Sep 14, 2026
4 checks passed
@Jammy2211
Jammy2211 deleted the feature/emcee-log-prob-alignment branch September 14, 2026 22:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: Emcee/Zeus pair thinned parameters with unthinned log-probabilities

1 participant