Skip to content

fix: MoG.condition for free dims after fixed dims - #2039

Merged
janfb merged 2 commits into
mainfrom
fix/mog-condition-dim-order
Oct 20, 2026
Merged

janfb merged 2 commits into
mainfrom
fix/mog-condition-dim-order

Conversation

@janfb

@janfb janfb commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Summary

MoG.condition gave wrong conditional means, covariances and mixture weights when a free dimension comes after a fixed one. It took sub-blocks of the upper-triangular precision factor U. That is only exact when all free dims come before all fixed dims. Now it reorders the columns of U to (free, fixed) and makes the factor triangular again with a QR decomposition. Then the sub-blocks are exact again.

 condition(y, dims_to_sample)
-  R = U
+  R = qr(U[:, free + fixed]).R                   # R^T R = P in (free, fixed) order
+  flip rows of R to a positive diagonal
   precision factor of x | y = R_xx
   marginal precision of y   = R_yy^T R_yy
-  mean = mu_x - P_xx^{-1} P_xy (y - mu_y)
+  mean = mu_x - R_xx^{-1} R_xy (y - mu_y)
   weights = softmax(logits + log N(y; mu_y, (R_yy^T R_yy)^{-1}))

ConditionedMDN calls MoG.condition since #2026, so this also fixes conditioned MDN posteriors, also when they are passed to conditional_pairplot or conditional_corrcoeff.

Evidence

New test TestMoGCondition::test_condition_matches_analytic_gaussian. It compares the conditional means, covariances (from the precisions and from the factors) and log-weights with the analytic Gaussian conditional. D=4, K=3, batch size 2, float64.

  • Before: [0] passes. [1], [2] and [1, 3] fail. The max errors are up to 18 in the means, 5.8 in the covariances and 19 in the log-weights.
  • After: all four pass. The max errors are below 1e-13.

Merge Danger

Door: two-way

Blast Radius: results

The fix changes results without a warning when a free dim comes after a fixed dim and the components are correlated. Conditioned MDN samples, densities and plots then differ from before. Before, they were wrong. Other layouts give the same results as before, up to rounding.

Closes #2038

Written with the help of Claude Code, reviewed locally with GPT Sol 6.1.

@janfb janfb added the bug Something isn't working label Oct 5, 2026
@janfb janfb self-assigned this Oct 5, 2026
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

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: b2102f0a-ff27-4b63-ac90-6485dea0cc7e
📥 Commits

Reviewing files that changed from the base of the PR and between 6372998 and 6d863cb.

📒 Files selected for processing: 2
  • sbi/neural_nets/estimators/mog.py
  • tests/mog_test.py
🚧 Files skipped from review as they are similar to previous changes: 1
  • sbi/neural_nets/estimators/mog.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

MoG.condition now reorders and QR-factorizes precision factors before extracting conditional and marginal blocks. It computes conditional means with triangular solves. Tests compare results with analytic Gaussian conditionals across four retained-dimension selections.

Changes: MoG conditioning

Layer / File(s) Summary
Conditioning factorization and validation
sbi/neural_nets/estimators/mog.py, tests/mog_test.py
The conditioning code reorders precision-factor dimensions, applies QR re-triangularization, normalizes diagonal signs, and uses triangular solves for conditional means. Parameterized tests validate means, covariances, precision factors, normalized component log-weights, and mixture log probabilities against analytic Gaussian conditionals.

Priority: ➖ Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: dgedon

Merge Risk: ⚪ Minimal · up to 6d863

The conditioning update is ready to merge based on the covered analytic layouts and absence of a new actionable defect.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main fix to MoG.condition when free dimensions follow fixed dimensions.
Description check Passed The description explains the bug, implementation, affected paths, tests, results, issue reference, and AI assistance. It does not use every template heading or complete the checklist, but it provides …
Linked Issues check Passed Issue [#2038] requires correct conditioning when a free dimension follows a fixed dimension, plus an analytic test. MoG.condition now reorders factor columns to free-then-fixed order, applies QR re-…
Out of Scope Changes check Passed The changes are limited to MoG.condition and its focused analytic conditioning test. The implementation and test directly support issue [#2038]. No unrelated change is shown.
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 3 functions across 2 files.
Full details: Description check

Explanation

The description explains the bug, implementation, affected paths, tests, results, issue reference, and AI assistance. It does not use every template heading or complete the checklist, but it provides the key information needed to review the change.

Full details: Linked Issues check

Explanation

Issue [#2038] requires correct conditioning when a free dimension follows a fixed dimension, plus an analytic test. MoG.condition now reorders factor columns to free-then-fixed order, applies QR re-triangularization, normalizes diagonal signs, and uses the resulting blocks for conditional means, covariances, and mixture weights. The new double-precision test covers [1], [2], and [1, 3] against analytic Gaussian results. ConditionedMDN uses this corrected path.

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

@codecov

codecov Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.71%. Comparing base (f83e9c7) to head (6d863cb).
⚠️ Report is 13 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2039      +/-   ##
==========================================
- Coverage   89.84%   89.71%   -0.14%     
==========================================
  Files         142      142              
  Lines       14680    15783    +1103     
==========================================
+ Hits        13189    14159     +970     
- Misses       1491     1624     +133     
Flag Coverage Δ
fast 85.72% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/neural_nets/estimators/mog.py 94.15% <100.00%> (+0.14%) ⬆️

... and 19 files 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.

Math checks out. Two non-blocking suggestions inline.

Comment thread sbi/neural_nets/estimators/mog.py Resolved
Comment thread tests/mog_test.py Resolved
…r complement

The analytic test only checked sign-invariant quantities, so dropping the sign flip after QR (with abs() in the weights) passed while cond_mog.log_prob returned NaN. Assert a positive factor diagonal and compare log_prob with the analytic mixture.

Note in condition() that R_yy^T R_yy is the marginal precision of y (Schur complement), not the yy-block of P.
@janfb
janfb merged commit 03f35c2 into main Oct 20, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MoG conditioning is wrong when a free dimension comes after a fixed one

2 participants