Repository navigation
fix: normalize condition_mog mixture weights in log space - #2026
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 🧰 Additional context used📚 Code guidelines (2)No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (3)
💤 Files with no reviewable changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthrough
ChangesConditioned MDN construction
Priority: ➖ Normal Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix · Severity of issue fixed: Medium Suggested reviewers: Merge Risk: ⚪ Minimal · up to The conditioning change is ready to merge after normal checks; no actionable issue was found in the supported workflow. Security Architecture ReviewSecurity architecture risk: ⚪ Minimal · up to The change is contained within numerical distribution construction. It preserves the public constructor interface and validation while using stable log-space normalization. No introduced security concern was identified in the inspected change. Retained concerns Security review detailsSecurity Blast Radius
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2026 +/- ##
==========================================
- Coverage 89.50% 89.14% -0.36%
==========================================
Files 142 142
Lines 14641 16197 +1556
==========================================
+ Hits 13104 14439 +1335
- Misses 1537 1758 +221
Flags with carried forward coverage won't be shown. Click here to find out more.
|
`condition_mog` renormalized the updated mixture weights in probability
space:
new_mcs = torch.exp(logits + log_prob_y)
new_mcs = new_mcs / new_mcs.sum()
cond_logits = torch.log(new_mcs)
`log_prob_y` is a per-component log density. Once the condition is not
close to the component means it becomes very negative, so
`torch.exp(log_prob_y)` underflows to exactly 0 in float32. If some
components underflow, their normalized weight is 0 and `torch.log(0)`
returns -inf; if all of them do, the sum is 0 and the division is 0/0,
giving NaN. Either way `cond_logits` is not a valid log-weight vector,
and `MoG.__post_init__` rejects it with "logits contains NaN or Inf
values".
This made `sbi.analysis.ConditionedMDN` unusable for ordinary inputs: a
plainly trained `NPE` + MDN posterior conditioned on `torch.zeros(num_dim)`,
i.e. the posterior mode itself, already raised.
`MoG.condition` performs the identical update and already does it
correctly with `logsumexp`, so switch `condition_mog` to the same form.
The result is unchanged wherever the old code was already correct (max
absolute difference 3.8e-06, i.e. float32 rounding) and finite where it
previously returned -inf or NaN.
Fixes sbi-dev#2025
b4b3092 to
825b5d4
Compare
|
@coderabbitai review and check the correctness |
|
|
✅ Action performedFull review finished. |
condition_mog duplicated MoG.condition, including a copy of its per-component log-prob helper. The underflow in sbi-dev#2025 came from the two copies drifting apart. ConditionedMDN now builds a MoG and calls MoG.condition, and condition_mog and the copied helper are removed.
Replace the condition_mog tests with one test of MoG.condition against the analytic conditional log-weights, at conditions where the probability-space normalization underflowed.
|
Thanks @BHARATH0153, good catch, and the reproduction in #2025 made it easy to check. Your log-space fix is correct. The PR body says there is now one correct implementation, but I will merge this once CI is green. cheers, Jan |
janfb
left a comment
There was a problem hiding this comment.
Thanks for this fix @BHARATH0153 👍
changes
condition_mogrenormalized the updated mixture weights in probability space, which underflows to exactly0in float32 whenever the condition is not close to the component means. The result is-inf(if some components underflow, solog(0)) orNaN(if all of them do, so0/0), andMoG.__post_init__then rejects it withValueError: logits contains NaN or Inf values.This makes the public
sbi.analysis.ConditionedMDNfail whenever the condition lands far enough from the mixture component means. How far that is depends on the fitted precision factors, so the threshold is model-dependent: a 3-DNPE+ MDN posterior I trained here fails even at the posterior mode, while the linear-Gaussian MDN intests/linearGaussian_snpe_test.pydoes not fail at the condition it uses.MoG.condition(sbi/neural_nets/estimators/mog.py) computes the identical update and already normalizes it correctly withtorch.logsumexp. This PR switchescondition_mogto the same form, so there is one correct implementation of that normalization in the codebase.Tests
tests/mog_test.pygains aTestConditionMoGclass:test_logits_stay_finite_far_from_component_means— the regression: logits must stay finite for distant conditionstest_matches_mog_condition— cross-check againstMoG.condition, which already did this correctlytest_weights_are_a_proper_distribution— the log-weights exponentiate to a valid distribution7 of the 8 new test cases fail on
mainand pass with the fix. Existing tests are unaffected:tests/mog_test.py,tests/analysis_test.py,tests/linearGaussian_mdn_test.pyandtests/linearGaussian_snpe_test.py -k conditionall pass (35 tests).tests/linearGaussian_snpe_test.py::test_mdn_conditional_densityonly passed before because its linear-Gaussian MDN has component means close to the observation, so it never reached the underflow region — that is what the new tests cover.Fixes #2025
AI USAGE
tested and made changes locally
description written by Claude
PR Checklist
uv run pytest -n auto -m "not slow and not gpu"passes.uv run pre-commit run --all-filespasses (ruff and formatting).uv run pyright sbipasses.pytest.mark.slow.