Repository navigation
feat(mdn): implement transform_to_unconstrained z-scoring for MDN - #1888
Conversation
|
@janfb please review at your convenience thanks! |
|
Thanks for picking this up, @BHARATH0153! I suggest to split this into two PRs, because the two halves are at very different stages: 1. MDN: The structure is clean, 2. Vector field (deferred). Please drop the vector-field changes from this PR for now. I checked it locally and it currently crashes at sampling, and more importantly it overlaps with #1884 (composed standardization for scale-equivariant FMPE/NPSE), which changes the same standardization path. I'm assigned to #1885 and will take the VF part myself once #1884 is settled and the ODE-space design is worked out. So overall, please trim this PR to MDN-only with the fix + a test below, and we can get it in. Thanks again, this is a useful contribution! |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #1888 +/- ##
==========================================
- Coverage 87.90% 87.86% -0.04%
==========================================
Files 143 143
Lines 13366 13387 +21
==========================================
+ Hits 11749 11763 +14
- Misses 1617 1624 +7
Flags with carried forward coverage won't be shown. Click here to find out more.
|
janfb
left a comment
There was a problem hiding this comment.
Thanks again for the PR @BHARATH0153 . Here the inline review.
Please revert all changes to the vector field related methods. And please revert the removed docstrings. The remaining todos are variable naming and testing issues, and the jac summing bug.
Looking forward to your fixes!
|
@janfb thanks for the review by today 12 I will make all changes as per review thanks for the review again |
- Add prior_transform parameter to MixtureDensityEstimator - Implement log_prob Jacobian correction and sample inverse transform - Wire transform_to_unconstrained in build_mdn via mcmc_transform - Fix double-sum bug in _log_det_jacobian_forward - Rename parameter to prior_transform (distinct from transform_input) - Add test for MDN transform_to_unconstrained correctness - Add x_dist as explicit parameter to build_mdn
|
@janfb as requested all changes are done please review thanks! |
|
@janfb please rerun the checks all are resolved thanks! |
|
Thanks for the quick quixes, @BHARATH0153! The MDN estimator itself now looks right: the Jacobian fix is correct (I verified When reviewing this again I found two two more blocking bugs, both from the same root cause: the PR changes two things that the MDN shares with the NPE-A / NPE-C machinery, without updating the other side. They don't show up in the diff because the broken code is in files the PR doesn't touch. Details inline, summary here:
The reason bug 2 hides is that the analytic NPE-A / NPE-C correction is mathematically only valid for an affine z-score, it can't represent a nonlinear So, I'd suggest:
More generally, this is now reaching into the NPE-A/NPE-C correction internals, which is a bit beyond where I wanted this PR to go. Do let me know if you prefer that I implement those fixes, I can commit to your branch. |
|
@janfb done I implemented once re check please at your convenience and please commit if anything going wrong and thanks for the great review |
janfb
left a comment
There was a problem hiding this comment.
Thanks again @BHARATH0153 , I made specific suggestions to fix the new bugs. let me know how it goes.
@BHARATH0153 you were too fast, I posted my inline comments just know and I suggest to not use a new property, but just raise an error in the caller sites. |
|
@janfb sorry I had terrible network and trying to do fast by the data finish and two comments are adressed dint used a new property sorry for using before |
|
@janfb now all tests are passing tested locally |
janfb
left a comment
There was a problem hiding this comment.
Converging! one last fix and we are good to merge @BHARATH0153 🚀
|
@janfb done please check thanks! |
janfb
left a comment
There was a problem hiding this comment.
All good, well done @BHARATH0153! First PR merged 🎉
`build_mdn` has supported `z_score_x="transform_to_unconstrained"` since sbi-dev#1888, which shipped in 0.27.0, but the error from the nflows builders still sent users to the zuko models only. Name `mdn` as well, and correct the same claim in the guard's docstring. The message stays as it is for the classifier, vector field and unconditional builders, which never named an alternative model. Documenting the estimator classes also turns on RST parsing for docstrings that nothing parsed before. That surfaced 19 warnings: shape tuples such as `(sample_dim, batch_dim, *input_shape)` without backticks, display equations indented below the prose, and two footnotes with no citation in the class docstring. The SDE in `ConditionalScoreEstimator` rendered glued to the sentence before it and is now a `.. math::` block. The branch builds with 56 warnings, one fewer than main. No control flow changes. The only runtime change is the error message.
…gs (#1990) * docs: fix broken links, orphaned FAQ page, and add estimator API reference * docs: finish the #1982 documentation fixes Builds on @pawank925's commit. - Replace the absolute readthedocs URLs in the reStructuredText pages with `:doc:` roles. Sphinx resolves those at build time and warns when a target moves, which is what the dead `sbi.html` link needed. Six notebook cells used the same dead target and now point at api_reference.html. The notebooks keep absolute URLs, because readers also open them on GitHub and in Colab, where MyST roles do not render. - Give the estimators their own page. Each section of the landing page pairs with a page in the toctree. The entries went into `api_reference/neural_nets`, so the sidebar filed the classes under "Neural nets". Also add `ConditionalVectorFieldEstimator`, which is the base class of the score and flow matching estimators and the type that `vector_field_estimator_based_potential` takes, plus `FlowMatchingEstimator` and `MixedDensityEstimator` for the FMPE, MNLE and MNPE methods that the Training section already lists. - Fix the FAQ page that becomes visible with the toctree entry. The code sample was missing a comma and raised a SyntaxError. The title was not phrased as a question like the other entries. The first sentence assumed the reader arrived from the leakage entry. The page also described the transform as zuko-only, although `mdn` supports it. Renumber the file to 04, because questions 04 to 07 went away in #1519. * fix: correct the transform_to_unconstrained message and docstrings `build_mdn` has supported `z_score_x="transform_to_unconstrained"` since #1888, which shipped in 0.27.0, but the error from the nflows builders still sent users to the zuko models only. Name `mdn` as well, and correct the same claim in the guard's docstring. The message stays as it is for the classifier, vector field and unconditional builders, which never named an alternative model. Documenting the estimator classes also turns on RST parsing for docstrings that nothing parsed before. That surfaced 19 warnings: shape tuples such as `(sample_dim, batch_dim, *input_shape)` without backticks, display equations indented below the prose, and two footnotes with no citation in the class docstring. The SDE in `ConditionalScoreEstimator` rendered glued to the sentence before it and is now a `.. math::` block. The branch builds with 56 warnings, one fewer than main. No control flow changes. The only runtime change is the error message. * fix: render the mean_t and std_t maths instead of a MathJax error MathJax rejects an underscore inside `\text{}`. `\text{mean_t}` therefore printed "'_' allowed only in math mode" where the equation should be. Write the subscript properly, as `\text{mean}_t`. Five of the seven were already in `mean_t_fn` and `std_t_fn` in `base.py`. Nothing rendered those docstrings before this branch documented the estimator classes, so the broken output was invisible. The other two are in `ConditionalScoreEstimator`, where the previous commit moved two plain-text equations into `.. math::` blocks. As plain text the underscores were harmless; as maths they were not. Sphinx reports no warning for this, because it is MathJax that rejects the TeX in the browser. Checked with a browser: both display equations on the ConditionalScoreEstimator page typeset, and none of the seven estimator pages has a MathJax error. * docs: correct the estimator docstring contracts and equations Follows a CodeRabbit review. All five findings were valid. Three are older mistakes in docstrings that this branch renders for the first time. Two are in text this branch added. - `combine_theta_and_x` and `unnormalized_log_ratio` documented `theta` with a sample dimension and `x` without one. `_get_shape_prefix` compares the two prefixes exactly and states that it does not broadcast, so the documented shapes raise a `ValueError`. Document the contract that the code enforces. - The perturbation kernel read `N(mean_t, std_t)` in `mean_t_fn` and `N(mean_t, std_t^2)` in `std_fn`. `std_fn` returns a standard deviation, and the marginal variance adds `std_fn(t)**2`, so the variance form is the correct one. Use it in both, and in the SDE marginal. - The flow matching score equations subtracted `\theta_0`, but `score()` subtracts `input`, which is `\theta_t`. Substituting the interpolation into the code gives `-\theta_1/t`, the score of `p(\theta_t|\theta_0)`, so the code is right and the symbol was wrong. - The FAQ example used `prior` without defining it. Define it, so the example runs as it is. - The FAQ claimed the transform works with the `zuko_*` estimators. The unconditional (marginal) zuko builder rejects it, so limit the claim to the conditional ones. --------- Co-authored-by: Jan <[email protected]>
* docs: limit API reference class pages to the sbi API The autosummary class template passed a bare `:inherited-members:`. Sphinx reads that as "stop at `object`", so every class page documented the full `torch.nn.Module` surface. The `CNNEmbedding` page listed 54 members, one of which was sbi's. Pass `Module` instead, so the walk stops there. Members that come from sbi's own base classes stay. `training` needs a separate exclusion, because it is an annotation on `nn.Module`, and `:inherited-members:` only filters members that a class defines. 16 pages change, from 954 documented members to 104. The other 67 pages do not change, and neither does the Sphinx warning count. * docs: document the members the API reference shows Five members survive the inherited-members filter without a docstring, so they render as bare names. `CNNEmbedding.forward` is the only member on its page. `RatioEstimator.loss` overrode a documented base method with a bare `raise NotImplementedError()`. That dropped the inherited text and left no hint at runtime. Name the reason in the docstring and in the error. Also state the shape contract of `combine_theta_and_x` and `unnormalized_log_ratio` once, in the arguments, instead of twice. * refactor: share the transform_to_unconstrained suggestion per module The nflows builders passed the same suggestion string at four call sites, and the classifier builders at three. That duplication is why the nflows message still named the zuko models only, two releases after `build_mdn` gained support for the option in #1888. Define the string once per module, so the models it names cannot go stale in one copy and not the others. * docs: remove stale and redundant comments - `tests/sbiutils_test.py` still said `transform_to_unconstrained` is implemented for the conditional zuko builders only, and that mdn raises. The test's own `model != "mdn"` guard and `test_mdn_transform_to_unconstrained` in the same file say otherwise. Keep only the part that the code does not state, the factory's z-score mapping. - The FAQ example carried two comments. One restated the value beside it, the other repeated the note below the snippet. - "The second argument of N is the variance, which matches `std_fn`" reads as if the variance equals `std_fn`. It is the square. * docs: correct the shape and mask contracts - The CNN forward docstrings named `input_shape`, but in those classes that name holds `self.input_shape`, which prepends the channel. A reader of `forward` reads it as the constructor argument, and under that meaning the single-channel clause was wrong. Name `in_channels` and `input_shape` as the constructor takes them. Checked against the builder: `(batch_dim, *input_shape)` is accepted for one channel and raises for three. - `causal_mask` skips the `triu` call when `sequence_length` is 1 and returns `min_dtype` everywhere, so "0 elsewhere" did not hold. State the case, and state why it changes nothing: a softmax over one position returns one. * docs: point MixedDensityEstimator.forward to log_prob too The docstring and the error sent every caller to `sample`. A caller who wants to evaluate a density needs `log_prob`. Name both methods. The error message was a triple-quoted string, so it also carried line breaks and indentation, and it had a typo. * docs: exclude the other annotated nn.Module attributes With Sphinx 8.1 on Python 3.10, which Read the Docs uses, the FlowMatchingEstimator page still listed `call_super_init` and `dump_patches`. Sphinx 9.1 on Python 3.12 did not. Like `training`, both are annotated attributes of `nn.Module`. Exclude them by name.
Summary
Remove all vector field estimator changes from this PR. Keep only the
transform_to_unconstrainedz-scoring for MDN.Changes
MixtureDensityEstimator: Addedprior_transformparameter for change-of-variables viamcmc_transform.log_probincludes the Jacobian correction (log_prob(z) + log|det J⁻¹|).sampleapplies the inverse transform to map back to constrained space. The mutual-exclusion guardtransform_input↔prior_transformensures only one is active.build_mdn: Wiresprior_transform = mcmc_transform(x_dist)whenz_score_x="transform_to_unconstrained". Addedx_distas explicit parameter._log_det_jacobian— theIndependentTransform(reinterpreted_batch_ndims=1)already sums over the event dimension, so the explicit.sum(dim=-1)was duplicating the sum.input_transform→prior_transformto avoid confusion with the existingtransform_inputparameter.has_input_transform,_transform_input,_inverse_transform_input,_log_det_jacobian_forward.TorchTransformfromsbi.sbi_types.test_mdn_transform_to_unconstrainedthat tests the change-of-variables formula directly against the underlying MoG.Closes #1885
The VF estimator changes will be pursued in a separate PR by @janfb