Repository navigation
fix: map priors and proposals with the MDN's z-score in multi-round NPE-A and NPE-C - #2103
Conversation
|
No actionable comments were generated in the recent review.
|
| 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:
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
Possibly related issues
- NPE-A: multi-round proposal correction is wrong for mixture proposals (default num_components=10) #2108: The issue concerns NPE-A proposal correction for multiple Gaussian components; the supplied change summary does not establish that this specific problem is fixed.
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: 
5
-
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
#2081if 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.
Comment @coderabbitai help to get the list of available commands.
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).
eecd6bc to
9375cc4
Compare
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.
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more.
|
dgedon
left a comment
There was a problem hiding this comment.
Great catch and good work! Ready to merge from my side
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.
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 andConditionedMDNuse them. NPE-A and NPE-C also share one function that finds a Gaussian or uniform prior, also behind aprocess_priorwrapper.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:retrain_from_scratch=Truegave 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.build_posterior()gets another density estimator. Now NPE-A maps it from the posterior's z-scored space.TypeErrorfor a prior wrapped byprocess_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=Truein round 2. Linear Gaussian toy with a correlated Gaussian prior, so the true posterior is known. Seeds 1 to 3:mainWith 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.
mainprocess_priorTypeErrorNew tests:
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 exceptNPE_A_Posterior, which keeps working. Other objects now raise aTypeErrorthat points toNPE_A_Posterior(proposal_mog=...).NPE-A now reads a
MoGproposal as a MoG over parameters. A MoG that is already z-scored gets z-scored again, so pass it toNPE_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 andConditionedMDNgive one new error text forz_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.