Skip to content

feat(mdn): implement transform_to_unconstrained z-scoring for MDN - #1888

Merged
janfb merged 12 commits into
sbi-dev:mainfrom
BHARATH0153:main
Jun 26, 2026
Merged

janfb merged 12 commits into
sbi-dev:mainfrom
BHARATH0153:main

Conversation

@BHARATH0153

@BHARATH0153 BHARATH0153 commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Remove all vector field estimator changes from this PR. Keep only the transform_to_unconstrained z-scoring for MDN.

Changes

  • MixtureDensityEstimator: Added prior_transform parameter for change-of-variables via mcmc_transform. log_prob includes the Jacobian correction (log_prob(z) + log|det J⁻¹|). sample applies the inverse transform to map back to constrained space. The mutual-exclusion guard transform_input ↔ prior_transform ensures only one is active.
  • build_mdn: Wires prior_transform = mcmc_transform(x_dist) when z_score_x="transform_to_unconstrained". Added x_dist as explicit parameter.
  • Bugfix: Fixed double-sum in _log_det_jacobian — the IndependentTransform(reinterpreted_batch_ndims=1) already sums over the event dimension, so the explicit .sum(dim=-1) was duplicating the sum.
  • Naming: Renamed from input_transform → prior_transform to avoid confusion with the existing transform_input parameter.
  • Docs: Restored omitted docstrings for has_input_transform, _transform_input, _inverse_transform_input, _log_det_jacobian_forward.
  • Type hints: Uses TorchTransform from sbi.sbi_types.
  • Tests: Added test_mdn_transform_to_unconstrained that 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

@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb please review at your convenience thanks!

@BHARATH0153 BHARATH0153 changed the title feat(mdn): implement transform_to_unconstrained z-scoring for MDN feat: implement transform_to_unconstrained z-scoring for MDN and vector field estimators Jun 23, 2026
@janfb

janfb commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

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, mcmc_transform direction, the change-of-variables in log_prob, the inverse on sample, and the transform_input/input_transform mutual-exclusion guard are all good. There's one correctness bug and a test gap (details inline). Both are small; if you fix them this half is mergeable.

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

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.57143% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.86%. Comparing base (c444a92) to head (2545833).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
sbi/inference/trainers/npe/npe_a.py 0.00% 2 Missing ⚠️
sbi/inference/trainers/npe/npe_c.py 50.00% 1 Missing ⚠️
...eural_nets/estimators/mixture_density_estimator.py 93.33% 1 Missing ⚠️
sbi/neural_nets/net_builders/mdn.py 85.71% 1 Missing ⚠️
sbi/utils/conditional_density_utils.py 50.00% 1 Missing ⚠️
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     
Flag Coverage Δ
fast 81.39% <78.57%> (?)

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

Files with missing lines Coverage Δ
sbi/inference/posteriors/npe_a_posterior.py 56.81% <ø> (ø)
sbi/inference/trainers/npe/npe_c.py 93.20% <50.00%> (-0.55%) ⬇️
...eural_nets/estimators/mixture_density_estimator.py 91.76% <93.33%> (-0.12%) ⬇️
sbi/neural_nets/net_builders/mdn.py 96.42% <85.71%> (-3.58%) ⬇️
sbi/utils/conditional_density_utils.py 92.72% <50.00%> (-0.53%) ⬇️
sbi/inference/trainers/npe/npe_a.py 77.70% <0.00%> (-1.65%) ⬇️

@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 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!

Comment thread tests/sbiutils_test.py Resolved
Comment thread sbi/neural_nets/net_builders/mdn.py Resolved
@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb thanks for the review by today 12 I will make all changes as per review thanks for the review again

@BHARATH0153 BHARATH0153 changed the title feat: implement transform_to_unconstrained z-scoring for MDN and vector field estimators feat(mdn): implement transform_to_unconstrained z-scoring for MDN Jun 24, 2026
- 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
@BHARATH0153

BHARATH0153 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor Author

@janfb as requested all changes are done please review thanks!

@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb please rerun the checks all are resolved thanks!

@janfb

janfb commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Thanks for the quick quixes, @BHARATH0153! The MDN estimator itself now looks right: the Jacobian fix is correct (I verified log_prob returns the right shape), the prior_transform rename is clean, the docstrings are back, and the new test is also in 👍

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:

  1. _log_det_jacobian_forward now takes a required transformed_input, but npe_a_posterior.py:173 still calls it with one argument. That's an unconditional TypeError in NPE-A's corrected log_prob — and note it breaks the default affine z-scoring too, not just the new option. To reproduce, try: NPE_A(prior).append_simulations(theta, x).train(); post.log_prob(theta, x=x_o) → TypeError: ... missing 1 required positional argument: 'transformed_input'.

  2. has_input_transform now returns True for the prior_transform path, but _transform_shift/_transform_scale are None there. npe_a.py:~358, npe_c.py (_set_maybe_z_scored_prior), and conditional_density_utils.py:~196 all read those buffers when has_input_transform is true. And this leads to a TypeError: unsupported operand type(s) for -: 'Tensor' and 'NoneType'. The property used to mean "affine z-score is on" (since Refactor MDN implementation: port MDN from pyknos, improve numerical stability #1724) and those three consumers rely on that.

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 mcmc_transform in closed form. So the right fix isn't to make those paths handle prior_transform; it's to let them raise a clear error, and keep transform_to_unconstrained scoped to what the MDN can do correctly on its own: direct log_prob/sample and single-round NPE (those go through the estimator's own methods and already work).

So, I'd suggest:

  • fix the npe_a_posterior.py caller (one line),
  • add a narrow has_affine_z_score property and have the three analytic consumers gate on it, raising NotImplementedError for the prior_transform case,
  • plus the device/buffer point and a ruff pass (inline).

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.

@BHARATH0153

BHARATH0153 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@janfb done I implemented once re check please at your convenience and please commit if anything going wrong

and thanks for the great review
So the right fix isn't to make those paths handle prior_transform; it's to let them raise a clear error, and keep transform_to_unconstrained scoped to what the MDN can do correctly on its own: direct log_prob/sample and single-round NPE (those go through the estimator's own methods and already work). and this is true and I have fixed by your suggestion thanks please commit if you have any thing

@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 again @BHARATH0153 , I made specific suggestions to fix the new bugs. let me know how it goes.

@janfb

janfb commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

@janfb done I implemented once re check please at your convenience and please commit if anything going wrong

@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.

@BHARATH0153

BHARATH0153 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@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

@BHARATH0153
BHARATH0153 requested a review from janfb June 25, 2026 10:05
@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb now all tests are passing tested locally

@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.

Converging! one last fix and we are good to merge @BHARATH0153 🚀

@BHARATH0153
BHARATH0153 requested a review from janfb June 25, 2026 15:34
@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb done please check thanks!

@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.

All good, well done @BHARATH0153! First PR merged 🎉

@janfb
janfb merged commit dbf432b into sbi-dev:main Jun 26, 2026
9 checks passed
janfb added a commit to pawank925/sbi that referenced this pull request Aug 17, 2026
`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.
janfb added a commit that referenced this pull request Aug 17, 2026
…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]>
janfb added a commit that referenced this pull request Oct 1, 2026
* 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.
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.

bug: transform_to_unconstrained z-scoring is a silent no-op for nflows flows

2 participants