Skip to content

fix: map priors and proposals with the MDN's z-score in multi-round NPE-A and NPE-C - #2103

Merged
janfb merged 22 commits into
mainfrom
mdn-z-score-transform
Oct 28, 2026
Merged

janfb merged 22 commits into
mainfrom
mdn-z-score-transform

Conversation

@janfb

@janfb janfb commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Multi-round NPE-A and NPE-C with an MDN combine the MDN's mixture of Gaussians (MoG) with the prior and the proposal in closed form. The MDN fits its MoG in a z-scored space, so the prior and the proposal must be in that space too. Three places did this mapping themselves, and PR #2081 had to fix one copy that had drifted.

Now the MDN itself maps a MoG into its z-scored space, back to parameters, and from the z-scored space of another MDN. No other code reads its shift and scale. The maps raise for z_score_theta="transform_to_unconstrained", because they need an affine z-score. NPE-A, NPE-C and ConditionedMDN use them. NPE-A and NPE-C also share one function that finds a Gaussian or uniform prior, also behind a process_prior wrapper.

The maps stay exact in float32. They subtract the shift before they divide by the scale. The map between two z-scored spaces uses the relative shift and scale, so it keeps small offsets at a large shift and does not overflow at a large scale.

This fixes four bugs that are in main:

  • NPE-C with an MDN and retrain_from_scratch=True gave wrong posteriors. The new network has its own z-score, but the prior and the proposal stayed in the z-scored space of the old network. Now NPE-C maps both into the new network's space after it builds the network.
  • NPE-A used a Gaussian or MoG proposal without z-scoring it.
  • NPE-A used the MoG of an earlier NPE-A posterior in that posterior's z-scored space. This is wrong when build_posterior() gets another density estimator. Now NPE-A maps it from the posterior's z-scored space.
  • From round 2 on, NPE-A raised a TypeError for a prior wrapped by process_prior, e.g. a float64 Gaussian. A float64 prior without the wrapper gave float64 samples.

This matters for everyone who runs NPE-A, or NPE-C with an MDN, for more than one round.

Evidence

NPE-C with an MDN, 2 rounds of 1000 simulations, retrain_from_scratch=True in round 2. Linear Gaussian toy with a correlated Gaussian prior, so the true posterior is known. Seeds 1 to 3:

round-2 posterior vs. the true one main this PR this PR, without retraining
mean error, in posterior sd 1.1 to 2.6 0.14 to 0.16 0.11 to 0.19
std ratio 1.5 to 12.8 0.97 to 1.51 0.96 to 1.14
covariance error (true 0.30) 0.9 to 3.1 0.04 to 0.39 0.05 to 0.08

With retraining, the result varies more between seeds than without it. The spread gets smaller with more simulations.

NPE-A, 2 rounds, with a Gaussian proposal that is equal to the prior. Then prior / proposal is 1, so the corrected density must equal the network's density.

NPE-A, round 2 main this PR
largest change of the log-density 0.53 0.0001
prior wrapped by process_prior TypeError runs, float32 samples

New tests:

MDN: a MoG mapped to parameters has the MDN's log_prob, the two maps invert each other,
     a float64 MoG comes back as float32
MDN: at a large shift, a MoG is z-scored like the inputs, and the map between two equal
     z-scored spaces keeps small offsets; at a scale of 1e20 it keeps the precisions
MDN: a MoG mapped from another MDN's z-scored space equals the way through parameters
MDN: all three maps raise for a non-affine z-score
NPE-A: a Gaussian proposal equal to the prior keeps the density           fails on main
NPE-C: retrain_from_scratch=True gives the true round-2 moments (slow)     fails on main

Merge Danger

Door: two-way. The new MDN maps and MoG.standardize() / MoG.unstandardize() are public, but nothing else depends on them yet.

Blast Radius: multi-round NPE-A and NPE-C with an MDN.

NPE-A no longer accepts any object with a get_mog_params() method as a proposal. It used the MoG of such an object without z-scoring it. No class in sbi has this method except NPE_A_Posterior, which keeps working. Other objects now raise a TypeError that points to NPE_A_Posterior(proposal_mog=...).

NPE-A now reads a MoG proposal as a MoG over parameters. A MoG that is already z-scored gets z-scored again, so pass it to NPE_A_Posterior(proposal_mog=...) instead.

NPE-A now accepts every uniform prior, not only BoxUniform, and gives a new error text for other priors. NPE-A, NPE-C and ConditionedMDN give one new error text for z_score_theta="transform_to_unconstrained". NPE-C computes the proposal's MoG once per round instead of once per training batch. MoG.to() takes an optional dtype, and NPE-C casts the prior to the network's dtype also without a z-score.

@coderabbitai

coderabbitai Bot commented Oct 27, 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: ca437d36-94e7-4135-896d-eae28d72f073
Commits

Reviewing files that changed from the base of the PR and between 5c68685 and 56b069b.

Files selected for processing: 1
  • sbi/inference/trainers/npe/npe_c.py

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

Walkthrough

The changes add affine MoG transformations between estimator spaces and update NPE-A and NPE-C to use z-scored proposal and prior MoGs. MoG extraction uses estimator inverse transformations. Tests cover transformation behavior and multi-round inference cases.

Changes: MoG proposal correction

Layer / File(s) Summary
MoG space transformations
sbi/neural_nets/estimators/mog.py, sbi/neural_nets/estimators/mixture_density_estimator.py, sbi/utils/conditional_density_utils.py, tests/mixture_density_estimator_test.py
MoG gains device and dtype conversion options and affine standardization methods. MixtureDensityEstimator gains methods to map MoGs between input and estimator spaces. MoG extraction uses the estimator’s inverse transformation. Tests cover mapping behavior, numerical cases, and non-affine transforms.
NPE-A prior and proposal MoGs
sbi/inference/trainers/npe/npe_base.py, sbi/inference/trainers/npe/npe_a.py, sbi/inference/posteriors/npe_a_posterior.py, tests/linearGaussian_snpe_test.py
A shared helper converts supported priors to z-scored MoGs. NPE-A maps supported proposals into the current estimator’s space and uses the shared prior helper. The custom proposal-object branch is removed.
NPE-C stored proposal and prior MoGs
sbi/inference/trainers/npe/npe_c.py, tests/linearGaussian_snpe_test.py, tests/sbiutils_test.py
NPE-C stores proposal and prior MoGs in z-scored space and uses the stored values in warning checks and loss calculations. Tests update prior-state setup and cover multi-round NPE-C and NPE-A behavior.

Priority: Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant NPEC as NPE-C trainer
  participant ProposalEstimator
  participant CurrentEstimator
  participant MoGLoss as MoG loss
  NPEC->>ProposalEstimator: Extract proposal MoG at default_x
  ProposalEstimator-->>NPEC: Return proposal MoG
  NPEC->>CurrentEstimator: Transform proposal MoG into current estimator space
  CurrentEstimator-->>NPEC: Return transformed MoG
  NPEC->>MoGLoss: Use stored proposal and prior MoGs
Loading

Possibly related issues

Possibly related PRs

  • sbi-dev/sbi#2045: It changes the estimator transform contract, MoG extraction, and NPE-A proposal-MoG handling.
  • sbi-dev/sbi#2104: It changes NPE-C proposal-MoG evaluation, which this PR restructures to cache in transformed space.
  • sbi-dev/sbi#2081: It changes NPE-C prior precision handling, which this PR replaces with stored prior-MoG state.

Suggested reviewers: satwiksps, bharath0153

Merge Risk: Minimal · up to 56b06

No actionable merge-blocking risk is established by the reviewed evidence.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the main change: NPE-A and NPE-C multi-round training now map priors and proposals with the MDN's z-score. The changeset adds MDN MoG mapping helpers (transform_mog, inverse_transform_…
Description check Passed The description follows the template well. It has a Summary with the problem and fix, a Evidence section with toy-experiment tables and new tests, and a Merge Danger section that lists breaking behavi…
Docstring Coverage Passed Docstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
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 names the main change: NPE-A and NPE-C multi-round training now map priors and proposals with the MDN's z-score. The changeset adds MDN MoG mapping helpers (transform_mog, inverse_transform_mog, transform_mog_from), uses them in NPE-A and NPE-C, and fixes the retrain_from_scratch and proposal z-scoring bugs. The title is fully related to the main change and follows the conventional-commit style. It is 83 characters, which is slightly long but readable.

Full details: Description check

Explanation

The description follows the template well. It has a Summary with the problem and fix, a Evidence section with toy-experiment tables and new tests, and a Merge Danger section that lists breaking behavior changes. It addresses the linked PR context but has no 'Does this close any issues?' entry, which the template asks for. The Checklist section is missing, so the author did not state whether the test suite, pre-commit, pyright, or docstring requirements pass. The description also does not say whether AI assistance was used, which the template asks for. These gaps are non-critical, so the description is mostly complete.

Resolution

Optional improvements: add a 'Does this close any issues?' entry (for example, a link to the related issues or to PR #2081 if it is related), add the Checklist from the template with the boxes checked, and state whether an AI assistant was used for a substantial part of the PR.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • 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.

janfb added 18 commits October 27, 2026 17:44
MixtureDensityEstimator gets transform_mog() and inverse_transform_mog(). They hold the only check that the input transform is affine, and transform_mog() casts the MoG to the estimator's device and dtype. MoG gets affine() for the pushforward and a dtype argument in to().
extract_and_transform_mog() uses inverse_transform_mog() instead of its own copy of the math.
…ts wrapper

NPE-A builds its z-scored Gaussian prior with transform_mog() instead of its own copy of the z-score math. The prior is now cast to the estimator's dtype, so a float64 Gaussian prior no longer gives float64 posterior samples.
The check that the z-score is affine moves into ProposalCorrectedMDN, because the analytic correction assumes it for every prior. This also covers an NPE_A_Posterior that is built directly with a proposal MoG.
…ulti-round NPE-A

From round 2 on, NPE-A raised a TypeError for a prior that process_prior had wrapped, e.g. a float64 Gaussian. It now finds the Gaussian or uniform prior with check_dist_class, as NPE-C does.
The new test also covers the float64 Gaussian prior without a wrapper, whose round-2 samples were float64 before the previous commit.
…round NPE-A

The NPE-A correction works in the estimator's z-scored space, but a MultivariateNormal or MoG proposal went into it unmapped, in parameter space. With the default z-scoring this gave a wrong posterior: for a proposal equal to the prior, which must leave the density unchanged, the log-probs moved by up to 0.5.
The trainer now maps these proposals with the estimator's transform_mog(). Proposals from an NPE_A_Posterior are already in the z-scored space and stay as they are.
NPE-C builds its z-scored Gaussian prior with transform_mog() instead of its own copy of the z-score math, so NPE-A, NPE-C and the conditional density share one implementation.
…ound NPE-C

With an MDN and train(retrain_from_scratch=True), multi-round NPE-C gave badly wrong posteriors: in a 2-round linear Gaussian toy the mean was off by 1 to 2 posterior standard deviations and the covariance by a factor of 2 to 10.
NPE-C built the z-scored prior before the network was rebuilt, so it used the old network's z-score. The proposal's MoG also stayed in the z-scored space of the proposal's network, while theta and the new network use the new one.
NPE-C now sets the state of the MoG loss after the network is (re)built, and maps the proposal's MoG through parameter space into the network's z-scored space, once per round instead of once per batch. The mapping also checks that the z-score is affine, so NPE-C's own check goes.
MoG.affine() computed the z-scored means as m / scale - shift / scale. For a large offset relative to the scale this cancels in float32: with shift 1e4 and scale 3e-3, a prior centred at the shift got the z-scored mean 0.25 instead of 0, so the prior and proposal sat in other coordinates than the training inputs.
MoG now has standardize() and unstandardize(), which mirror the MDN's input transform and its inverse. Tests: the large-offset case, and that both maps raise for a non-affine transform.
NPE-A and NPE-C each found the Gaussian or uniform prior behind the process_prior wrapper and mapped it into the MDN's z-scored space. NPE-A had already drifted: it missed the wrapper until a few commits ago. Both now call one helper in npe_base.
NPE-C keeps the prior as a MoG instead of rebuilding a MultivariateNormal from it, declares the state of its MoG loss in __init__, and its check for non-normalizable pairs reuses the stored proposal MoG.
…lper

Prior detection now lives in the helper that the wrapped-prior NPE-C test already runs, and the MDN test checks the dtype cast. A wrong detection raises.
NPE-A accepted any object with get_mog_params() as a proposal and used its MoG without mapping or casting it, although nothing stated which space that MoG is in. No class in sbi other than NPE_A_Posterior, which has its own branch, provides the method.
Such proposals now raise a TypeError that points to the documented route: NPE_A_Posterior(proposal_mog=...) with the MoG in the estimator's z-scored space.
Over 19 seeds the retrained posterior has mean errors up to 0.26 sd, std ratios up to 1.51 and covariance errors up to 0.39; the bug gave at least 1.06 sd, 1.83 and 0.93. The bounds now sit between the two.
NPE-C moved the proposal's MoG into the network's z-scored space through parameter space. With a large shift relative to the scale, adding the shift and subtracting it again lost small offsets in float32, also when both networks share the z-score: with shift 1e4 and scale 3e-3, a proposal mean of 0.13 became 0.
The MDN now has transform_mog_from(), which maps a MoG from another MDN's z-scored space through the difference of the two shifts. NPE-C uses it.
The attribute _prior_mog no longer shares its name with the helper that builds it. The retrain test's comment keeps only the constraint.
…s used

The product was stored next to the prior MoG and set and checked with it. The MoG loss now computes it from the stored MoG, like the proposal's and the estimator's products.
Their names and signatures say what the Args and Returns sections said.
Both check that a large shift does not cancel small offsets, so they share one estimator.
…d space

NPE-A used the MoG of a previous NPE_A_Posterior proposal as it was, in the z-scored space of that posterior's estimator. This is only right if the trained estimator has the same z-score, which fails when build_posterior() gets another density_estimator. The proposal's MoG now goes through transform_mog_from(), like the NPE-C proposal.
…train spread from below

_set_state_for_mog_proposal() only sets the prior state since the proposal moved to _initialize_neural_network(), so it is now _set_prior_state(). The retrain test also fails for a collapsed posterior (std ratio below 0.7; the lowest measured is 0.92).
@janfb
janfb force-pushed the mdn-z-score-transform branch from eecd6bc to 9375cc4 Compare October 27, 2026 16:57
@janfb
janfb changed the base branch from refactor/npe-a-corrected-estimator to main October 27, 2026 16:57
janfb added 3 commits October 27, 2026 18:09
The map from another estimator's z-scored space went through input space. At an input scale above about 1.85e19, the squared scale in the precisions overflows float32 and the proposal precisions become wrong, so a two-round NPE-C run with BoxUniform([0, 0], [1e20, 1e20]) failed with NaN logits. The map now applies the relative shift and scale in one step, which never forms the squared input scale.
… from the proposal type

ProposalCorrectedMDN repeated the MDN's check for an affine z-score with its own message, which NPE-A users never saw because the MDN's check runs first in build_posterior(). The wrapper now calls the MDN's check, so there is one message, and it keeps the hint to use a different method.

The proposal type of NPE-A's _get_proposal_mog still listed Any from the removed duck-typed proposal.
MoG.standardize() and unstandardize() divided the precisions by the outer product of the scale. For a scale far from 1, e.g. 1e20, that product overflows float32 and the precisions silently became 0 while the precision factors stayed finite. Dividing the rows and the columns separately gives the representable result.
@janfb
janfb marked this pull request as ready for review October 27, 2026 17:19
@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.78947% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.40%. Comparing base (395cbab) to head (56b069b).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
sbi/inference/trainers/npe/npe_a.py 77.77% 2 Missing ⚠️
sbi/inference/trainers/npe/npe_base.py 90.90% 1 Missing ⚠️
...eural_nets/estimators/mixture_density_estimator.py 96.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2103      +/-   ##
==========================================
+ Coverage   90.24%   90.40%   +0.16%     
==========================================
  Files         142      142              
  Lines       14845    14837       -8     
==========================================
+ Hits        13397    13414      +17     
+ Misses       1448     1423      -25     
Flag Coverage Δ
fast 86.48% <95.78%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/posteriors/npe_a_posterior.py 100.00% <ø> (ø)
sbi/inference/trainers/npe/npe_c.py 95.95% <100.00%> (+0.32%) ⬆️
sbi/neural_nets/estimators/mog.py 94.91% <100.00%> (+0.15%) ⬆️
sbi/utils/conditional_density_utils.py 88.00% <100.00%> (+1.13%) ⬆️
sbi/inference/trainers/npe/npe_base.py 95.42% <90.90%> (-0.38%) ⬇️
...eural_nets/estimators/mixture_density_estimator.py 91.02% <96.66%> (+1.75%) ⬆️
sbi/inference/trainers/npe/npe_a.py 86.04% <77.77%> (+12.31%) ⬆️

... and 1 file with indirect coverage changes

@dgedon dgedon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch and good work! Ready to merge from my side

Comment thread sbi/inference/trainers/npe/npe_c.py Resolved
NPE-C kept its own z_score_theta flag, set in _set_prior_state(), to decide whether to z-score theta in the MoG loss. The MDN's _transform_input() already returns theta unchanged without a z-score, so the loss now calls it directly, and the flag and _maybe_z_score_theta() are gone. A non-affine z-score cannot reach the loss, because mapping the proposal into the network's z-scored space raises before training.
@janfb
janfb merged commit a8fecc2 into main Oct 28, 2026
21 checks passed
@janfb
janfb deleted the mdn-z-score-transform branch October 28, 2026 09:19
@janfb
janfb restored the mdn-z-score-transform branch October 28, 2026 09:21
@janfb
janfb deleted the mdn-z-score-transform branch October 28, 2026 09:22
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