Repository navigation
fix: keep covariance of the z-scored Gaussian prior in NPE-C - #2081
Conversation
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).
|
No actionable comments were generated in the recent review.
|
| 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:
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: 
5
-
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.
Comment @coderabbitai help to get the list of available commands.
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
…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.
…e MoG-loss changes
|
@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.
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.
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 givesN((m - m_e) / s_e, C / (s_e s_e^T)).
_set_maybe_z_scored_priorbuilt this asMultivariateNormal(mean, torch.diag(std)), whichSo the precision that is subtracted in
_precisions_proposal_posteriorand_means_proposal_posteriorwas 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, wassqrt(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:slcp and two_moons have uniform priors, so they are unchanged as expected.
gaussian_linearfails for seeds 0 and 1 both onmainand on this branch, with anon-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_prioris closer to indefinite when the round-1 posterior ispoorly trained. The new test therefore trains round 1 for 30 epochs.
Checklist
pytest -m "not slow and not gpu"passes fortests/linearGaussian_snpe_test.pyand
tests/inference_with_NaN_simulator_test.py(full suite not run locally).uv run pyright sbipasses. My local environment could not resolvetorchforpyright; relying on CI.
test_npe_c_z_scored_gaussian_prior_keeps_covariance. It failson
mainand passes here.I used Claude Code to find this bug