Skip to content

fix: keep covariance of the z-scored Gaussian prior in NPE-C - #2081

Merged
janfb merged 12 commits into
sbi-dev:mainfrom
aniketpandey05:fix/npe-c-zscored-prior
Oct 27, 2026
Merged

janfb merged 12 commits into
sbi-dev:mainfrom
aniketpandey05:fix/npe-c-zscored-prior

Conversation

@aniketpandey05

@aniketpandey05 aniketpandey05 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

With z-scored theta (the default for mdn), multi-round NPE-C evaluates the prior in standardized space inside the closed-form MoG proposal-posterior loss. For a Gaussian prior N(m, C), z-scoring with shift m_e and scale s_e gives
N((m - m_e) / s_e, C / (s_e s_e^T)).

_set_maybe_z_scored_prior built this as MultivariateNormal(mean, torch.diag(std)), which

  • passes standard deviations where variances are expected, and
  • drops all correlations of the prior.

So the precision that is subtracted in _precisions_proposal_posterior and _means_proposal_posterior was wrong for any correlated or non-unit-scale Gaussian prior. On a 2-D prior with std 2 and correlation 0.9, sbi used
[[0.97, 0], [0, 0.99]] instead of [[0.95, 0.86], [0.86, 0.97]], and the per-sample proposal-posterior log-prob differed by up to 3.1 nats.

This PR builds the covariance as C / outer(s_e, s_e). It also fixes the half-width of the z-scored uniform prior (sqrt(3) * std, was sqrt(3 * std)). That branch is not used in the loss, so it has no effect on training.

Does this close any issues?

No issue was opened, as this is a small bug fix.

Anything else we should know?

mini-sbibm, --bm-mode snpe --bm-estimators mdn --bm-seeds 3:

C2ST before after
linear_mvg_2d 0.514 ± 0.015 0.516 ± 0.009
slcp 0.968 ± 0.010 0.968 ± 0.010
two_moons 0.697 ± 0.029 0.697 ± 0.029

slcp and two_moons have uniform priors, so they are unchanged as expected.
gaussian_linear fails for seeds 0 and 1 both on main and on this branch, with a
non-positive-definite precision in the Cholesky of the proposal posterior
(npe_c.py). That failure exists already and is unrelated to this change.

The correct z-scored prior has a larger precision for strongly correlated priors, so
P_proposal + P_density - P_prior is closer to indefinite when the round-1 posterior is
poorly trained. The new test therefore trains round 1 for 30 epochs.

Checklist

  • I have read the contributing guide.
  • pytest -m "not slow and not gpu" passes for tests/linearGaussian_snpe_test.py
    and tests/inference_with_NaN_simulator_test.py (full suite not run locally).
  • ruff check and ruff format pass on the changed files.
  • uv run pyright sbi passes. My local environment could not resolve torch for
    pyright; relying on CI.
  • I added a test: test_npe_c_z_scored_gaussian_prior_keeps_covariance. It fails
    on main and passes here.
  • I used Google-style docstrings for new or changed public functions.
  • The new test takes about 8.6 s on CPU and is not marked slow.

I used Claude Code to find this bug

With z-scored theta and an MDN, multi-round NPE-C uses the prior in
standardized space in its closed-form proposal-posterior loss. For a
Gaussian prior N(m, C) this is N((m - m_e) / s_e, C / (s_e s_e^T)).

The prior was built as MultivariateNormal(mean, torch.diag(std)), which
passes standard deviations as variances and drops all correlations. The
loss was therefore wrong for any correlated or non-unit-scale Gaussian
prior (up to ~3 nats per sample on a 2-D prior with correlation 0.9).

Build the covariance as C / outer(s_e, s_e). Also fix the half-width of
the z-scored uniform prior, which is sqrt(3) * std, not sqrt(3 * std).
@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f17fee43-128c-493e-a735-6d6a24d339ec
Commits

Reviewing files that changed from the base of the PR and between 37fe544 and c4dd006.

Files selected for processing: 2
  • sbi/inference/trainers/npe/npe_c.py
  • tests/linearGaussian_snpe_test.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Walkthrough

NPE-C stores Gaussian priors using the estimator’s z-scoring parameters. It identifies non-normalizable mixture components, handles them during posterior transformation, and warns after qualifying training runs.

Changes: NPE-C prior and mixture handling

Layer / File(s) Summary
Gaussian prior and posterior transformation
sbi/inference/trainers/npe/npe_c.py, tests/linearGaussian_snpe_test.py
NPE-C stores Gaussian priors with covariance transformed by the estimator’s scale. Tests check posterior transformation with correlated priors and transformed inputs.
Non-normalizable mixture components
sbi/inference/trainers/npe/npe_c.py, tests/linearGaussian_snpe_test.py
The precision helper identifies invalid component pairs and uses identity precision and covariance for intermediate calculations. Posterior transformation assigns invalid pairs very low logits and raises ValueError if a row has no normalizable pair. Qualifying training runs warn when evaluated batches contain invalid pairs. Tests cover these cases.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: janfb

Merge Risk: Minimal · up to c4dd0

Gaussian covariance is preserved, and partially invalid mixtures are handled. No merge-blocking issue is established.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title "fix: keep covariance of the z-scored Gaussian prior in NPE-C" matches the main change. The PR changes how the z-scored Gaussian prior covariance is built for the NPE-C proposal-posterior lo…
Description check Passed The description follows the template sections: What does this PR do, Does this close any issues, Anything else we should know, and the checklist. It explains the bug, the fix, and the validation with …
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within survi…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix: keep covariance of the z-scored Gaussian prior in NPE-C" matches the main change. The PR changes how the z-scored Gaussian prior covariance is built for the NPE-C proposal-posterior loss, replacing the diagonal-std construction. The title is specific and short. It does not mention the secondary changes, such as the zero-weight handling for non-normalizable component pairs, the warning, or the uniform-prior half-width fix. The title does not need to cover those details.

Full details: Description check

Explanation

The description follows the template sections: What does this PR do, Does this close any issues, Anything else we should know, and the checklist. It explains the bug, the fix, and the validation with a benchmark table. It also gives a clear reason for the new test's 30-epoch training. The 'Does this close any issues' section says no issue exists, which is acceptable. Two checklist items are unchecked: pyright was not run locally, and this item is still open. The author states that CI will cover it. The description does not fully match the template's Google-style docstring item, but it marks that item as checked. Overall, the description is mostly complete.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 10 functions across 2 files.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.25%. Comparing base (a1276f2) to head (c4dd006).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2081      +/-   ##
==========================================
+ Coverage   90.22%   90.25%   +0.02%     
==========================================
  Files         142      142              
  Lines       14799    14821      +22     
==========================================
+ Hits        13353    13377      +24     
+ Misses       1446     1444       -2     
Flag Coverage Δ
fast 86.26% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
sbi/inference/trainers/npe/npe_c.py 95.62% <100.00%> (+0.59%) ⬆️

... and 4 files with indirect coverage changes

@aniketpandey05

Copy link
Copy Markdown
Contributor Author

@janfb

janfb added 10 commits October 26, 2026 22:21
…training

With the prior as proposal, the proposal posterior must equal the density estimator. The test builds an MDN with a known z-score transform and a correlated, non-unit-scale Gaussian prior, and checks that identity on _automatic_posterior_transformation. It fails on main and replaces the earlier test, which trained two rounds (about 8 s) and compared private attributes with a copy of the fix's formula.
The comment above the fix still stated the old N(.., s / s_e) formula. One comment now states the pushforward, the uniform branch computes its std where it uses it, and the redundant expand_as is gone (shift and scale are already expanded to input_shape).
…C's MoG loss

process_prior wraps some Gaussian priors, e.g. float64 ones. The MoG loss already unwraps the prior when it decides to use the closed form, but the z-scored prior did not, so a wrapped Gaussian was turned into a BoxUniform and its precision was left out of the loss. In a two-round toy with prior covariance [[4, 3.6], [3.6, 4]], the round-2 posterior variances were 3.04 and 2.17 instead of 1.49.

The z-scored prior is now built from the unwrapped Gaussian, cast to the estimator's dtype. The APT identity test runs with a plain and a wrapped float64 prior; the wrapped case fails without this fix.
…er reads

A uniform prior is constant on its support and drops out of the closed-form loss, which reads the stored prior only when it is Gaussian. The stored prior is now None for non-Gaussian priors.
From round 2 on, the closed-form loss multiplies each component of the density estimator with each component of the proposal and divides by the prior. A pair is a proper Gaussian only if its precision P_proposal + P_estimator - P_prior is positive definite. The APT paper argues this holds because the proposal is narrower than the prior, but that is true for the mixture, not for each component: low-weight components handed over from round 1 are often wider than the prior in some direction. Such a pair has infinite mass, and the Cholesky factorization raised on the first round-2 batch.

This crashed mini-sbibm's gaussian_linear on main for 2 of 3 seeds. With the corrected z-scored prior of this PR it also crashed a correlated 2-D prior with 200 simulations per round in 3 of 10 seeds, because the old prior was too small to expose it.

Such pairs now get zero weight, with identity precision so that every other quantity stays finite. A row without any normalizable pair raises a ValueError. Round-2 training makes all pairs normalizable within 1 to 15 epochs in our runs, and the network returned at the end (the best validation epoch) needs no dropping, so it is trained on the exact APT loss. All crashing seeds now train, with posterior errors in the range of the seeds that never crashed; gaussian_linear reaches C2ST 0.70, as single-round MDN does.
Expand the z-score scale before the outer product again: estimators pickled with sbi <= 0.27 have a 0-dim scale, and torch.outer rejects it (the earlier tidy-up removed the contributor's expand_as).

Trim the new inline comments to constraints, document the ValueError, and drop the uncited advice to use more simulations from its message.

The pair-dropping test now uses an indefinite pair, as round 1 produces them, and checks that every returned precision can be factorized; it fails without the identity substitution. Both MoG-loss tests share their setup.
While a component pair is left out of the MoG loss, the loss is blind to that estimator component: its weight cancels in the normalization and its parameters get no gradient from the pair. In all our runs training made every pair normalizable within 1 to 15 epochs, and the returned network was trained on the exact APT loss. After each round, NPE-C now checks the returned network on the round's simulations and warns if any pair still has infinite mass, so a possibly biased posterior does not go unnoticed. None of the 15 rescued runs (correlated 2-D prior, gaussian_linear) warns.
@janfb

janfb commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

@aniketpandey05 good catch, this bug was in the loss since its first version! As we have limited reviewing capacity, I finished the PR with a few commits on your branch, so here is what changed on top of your fix.

  • Test: I replaced your test with a cheaper one that checks the behaviour instead of the formula. When the proposal is the prior, the proposal posterior must equal the density estimator. It runs in under a second and fails on main.
  • Wrapped priors: a Gaussian prior that process_prior wraps, for example a float64 one, was treated as uniform in the loss. It is now unwrapped first.
  • Uniform prior: the loss never reads the z-scored uniform prior, because a uniform prior drops out of the correction. So I removed that branch instead of fixing its width.
  • The gaussian_linear crash you noted: it is a real problem of this loss. A pair of a proposal component and an estimator component can be wider than the prior in some direction, and then their product has infinite mass. With your fix, this also crashed a correlated prior with 200 simulations per round. Such pairs now get zero weight, and training makes them valid again within a few epochs. NPE-C now warns if any remain after training.

Thanks again for fixing this, Jan

With force_first_round_loss=True a later round trains with maximum likelihood, but the check after training still ran and could warn about pairs the loss never dropped. It now runs only when the round used the MoG loss.

The check moved all of the round's simulations to the training device at once, which defeats storing data on the CPU for a GPU with little memory. It now moves one batch at a time.

The identity used for non-normalizable pairs is created on the right device again instead of being copied from the CPU at every loss evaluation.

A test checks that a round trained with the MoG loss runs the check and a round with force_first_round_loss does not.
@janfb
janfb merged commit 09f0bda into sbi-dev:main Oct 27, 2026
18 checks passed
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.

2 participants