Skip to content

fix: normalize condition_mog mixture weights in log space - #2026

Merged
janfb merged 3 commits into
sbi-dev:mainfrom
BHARATH0153:fix/condition-mog-logsumexp
Oct 5, 2026
Merged

janfb merged 3 commits into
sbi-dev:mainfrom
BHARATH0153:fix/condition-mog-logsumexp

Conversation

@BHARATH0153

@BHARATH0153 BHARATH0153 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

changes

condition_mog renormalized the updated mixture weights in probability space, which underflows to exactly 0 in float32 whenever the condition is not close to the component means. The result is -inf (if some components underflow, so log(0)) or NaN (if all of them do, so 0/0), and MoG.__post_init__ then rejects it with ValueError: logits contains NaN or Inf values.

This makes the public sbi.analysis.ConditionedMDN fail 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-D NPE + MDN posterior I trained here fails even at the posterior mode, while the linear-Gaussian MDN in tests/linearGaussian_snpe_test.py does not fail at the condition it uses.

MoG.condition (sbi/neural_nets/estimators/mog.py) computes the identical update and already normalizes it correctly with torch.logsumexp. This PR switches condition_mog to the same form, so there is one correct implementation of that normalization in the codebase.

Tests

tests/mog_test.py gains a TestConditionMoG class:

  • test_logits_stay_finite_far_from_component_means — the regression: logits must stay finite for distant conditions
  • test_matches_mog_condition — cross-check against MoG.condition, which already did this correctly
  • test_weights_are_a_proper_distribution — the log-weights exponentiate to a valid distribution

7 of the 8 new test cases fail on main and pass with the fix. Existing tests are unaffected: tests/mog_test.py, tests/analysis_test.py, tests/linearGaussian_mdn_test.py and tests/linearGaussian_snpe_test.py -k condition all pass (35 tests).

tests/linearGaussian_snpe_test.py::test_mdn_conditional_density only 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

  • I have read the contributing guide.
  • uv run pytest -n auto -m "not slow and not gpu" passes.
  • uv run pre-commit run --all-files passes (ruff and formatting).
  • uv run pyright sbi passes.
  • I added or updated tests for the changed behavior.
  • I used Google-style docstrings for new or changed public functions.
  • (If applicable) I reported how long new tests run and marked slow ones with pytest.mark.slow.

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (2)
docs/contributing.md — auto-discovered
AGENTS.md — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a6ae728b-05e8-49ac-824c-5c3da6ddf09f
📥 Commits

Reviewing files that changed from the base of the PR and between 825b5d4 and dd521c6.

📒 Files selected for processing (3)
  • sbi/analysis/conditional_density.py
  • sbi/utils/conditional_density_utils.py
  • tests/mog_test.py
💤 Files with no reviewable changes (1)
  • sbi/utils/conditional_density_utils.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

Walkthrough

ConditionedMDN now creates a MoG from the extracted mixture parameters and delegates conditioning to MoG.condition. The standalone condition_mog helper and its Gaussian log-probability helper were removed. A parameterized test checks conditioned component logits for three observation values.

Changes

Conditioned MDN construction

Layer / File(s) Summary
Delegate conditioning and verify component logits
sbi/analysis/conditional_density.py, sbi/utils/conditional_density_utils.py, tests/mog_test.py
ConditionedMDN passes the extracted mixture parameters to MoG and calls MoG.condition. The standalone conditioning helpers and the unused numpy import were removed. A parameterized test checks component logits for observations 0.0, 4.0, and 10.0.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: janfb

Merge Risk: ⚪ Minimal · up to dd521

The conditioning change is ready to merge after normal checks; no actionable issue was found in the supported workflow.

Security Architecture Review

Security architecture risk: ⚪ Minimal · up to dd521

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Within the inspected changed path, caller-controlled conditions and dimension selections affect in-process numerical distribution construction. Delegation does not introduce a privileged operation or expand access to another service, tenant, or data store.

Resilience and Maintainability Implications

  • observed — MoG.condition computes a new distribution without modifying the input mixture. The caller stores the result only after computation and validation succeed, so failure in this new step does not publish a partially conditioned distribution or require shared-state rollback.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the log-space normalization fix. The final implementation delegates conditioning to MoG.condition and removes condition_mog, but the title still accurately describes t…
Description check ✅ Passed The description explains the problem, links the issue, and includes tests, AI usage, and a completed checklist. Some implementation and test details are outdated: the final changes remove `condition_m…
Linked Issues check ✅ Passed Issue [#2025] requires ConditionedMDN to produce valid conditional mixture logits when component likelihoods underflow. ConditionedMDN.__init__ now delegates conditioning to MoG.condition, which…
Out of Scope Changes check ✅ Passed The PR removes condition_mog and its copied helper after replacing their only described use with MoG.condition. This removes duplicated conditioning logic and directly supports issue [#2025]. The …
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. Analyzed 5 functions across 3 files.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@BHARATH0153
BHARATH0153 marked this pull request as draft September 30, 2026 15:53
@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.14%. Comparing base (1807051) to head (dd521c6).
⚠️ Report is 14 commits behind head on main.

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     
Flag Coverage Δ
fast 84.97% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/analysis/conditional_density.py 93.33% <100.00%> (-0.11%) ⬇️
sbi/utils/conditional_density_utils.py 78.69% <ø> (-10.59%) ⬇️

... and 31 files with indirect coverage changes

`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
@BHARATH0153

BHARATH0153 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@coderabbitai review and check the correctness

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

@BHARATH0153, the last commit was already reviewed. I’ll rerun the full review to check the log-space normalization and regression tests for correctness.

✅ Action performed

Full review finished.

@BHARATH0153
BHARATH0153 marked this pull request as draft October 1, 2026 14:03
@BHARATH0153
BHARATH0153 marked this pull request as ready for review October 1, 2026 14:03
@BHARATH0153 BHARATH0153 closed this Oct 2, 2026
@BHARATH0153 BHARATH0153 reopened this Oct 2, 2026
janfb added 2 commits October 5, 2026 11:47
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.
@janfb

janfb commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

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 condition_mog and MoG.condition both remained, and the bug came from the two copies drifting apart. So I pushed two commits on top: ConditionedMDN now calls MoG.condition directly, condition_mog and its copied helper are removed, and one test checks the conditioned weights against the analytic values far from the component means.

I will merge this once CI is green.

cheers, Jan

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this fix @BHARATH0153 👍

@janfb
janfb merged commit f83e9c7 into sbi-dev:main Oct 5, 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.

ConditionedMDN crashes with "logits contains NaN or Inf values"

2 participants