Skip to content

fix: process_prior failing for independent priors with non-float32 types - #2064

Merged
janfb merged 3 commits into
sbi-dev:mainfrom
ThomasGesseyJonesPX:fix/shape_in_return_type_wrapper
Oct 14, 2026
Merged

janfb merged 3 commits into
sbi-dev:mainfrom
ThomasGesseyJonesPX:fix/shape_in_return_type_wrapper

Conversation

@ThomasGesseyJonesPX

Copy link
Copy Markdown
Contributor

What does this PR do?

process_prior currently throws an error when it is given multiple independent priors (as a list) with non-float32 dtypes. This is because the batch_shape and event_shape of each of the component independent priors is not passed to its PytorchReturnTypeWrapper, e.g., it becomes a scalar, which leads to an assertion error when these are encapsulated in MultipleIndependent. This PR addresses this by having PytorchReturnTypeWrapper default to the batch_shape and event_shape of the given prior rather than torch.Size().

A minimal example of the issue can be seen with the following code

import torch
from torch.distributions import Normal
from sbi.utils.user_input_checks import process_prior

def one_d_prior(dtype):  # 1-D prior, using the shape recommended by the error message
    return Normal(torch.zeros(1, dtype=dtype), torch.ones(1, dtype=dtype))

process_prior([one_d_prior(torch.float32), one_d_prior(torch.float32)])  # Works nicely 
process_prior([one_d_prior(torch.float64), one_d_prior(torch.float64)])  # Fails 

which outputs an AssertionError which incorrectly points the user toward an issue with them using scalar distributions.

AssertionError: One of the distributions you passed is defined over a scalar only. Make
        sure pass distributions with one of event_shape or batch_shape > 0: For example
            - instead of Uniform(0.0, 1.0) pass Uniform(torch.zeros(1), torch.ones(1))
            - instead of Beta(1.0, 2.0) pass Beta(tensor([1.0]), tensor([2.0])).

Does this close any issues?

No, I could not find any matching issues.

Anything else we should know?

The proposed fix works by changing the default behaviour of PytorchReturnTypeWrapper. This can be avoided by manually passing the batch_shape and event_shape within process_pytorch_prior. I believe this is the only place its actually used, so I felt changing the default behaviour made more intuitive sense, but would be keen to get a maintainers opinion on which of the two approaches would be better.

The test added to avoid regressions intentionally does not use Uniform as the conversion to BoxUniform converts these priors to float32 and avoids the bug as a result.

Checklist

Put an x in the boxes that apply. If you are unsure about any of them, just
ask - we are happy to help.

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

AI usage declaration: the bug was originally encountered by a colleague of mine, who then used Claude to trace this to the sbi package and to provide me with instructions for replication and the minimal example. All the code in this PR to address the issue was manually written.

@coderabbitai

coderabbitai Bot commented Oct 13, 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: 8b8ddfc0-cfe5-4494-879a-a2ab3eb21653
📥 Commits

Reviewing files that changed from the base of the PR and between abbc8fc and 8b48da6.

📒 Files selected for processing: 3
  • sbi/utils/user_input_checks.py
  • sbi/utils/user_input_checks_utils.py
  • tests/user_input_checks_test.py
🚧 Files skipped from review as they are similar to previous changes: 1
  • sbi/utils/user_input_checks_utils.py

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

📝 Walkthrough

PytorchReturnTypeWrapper now uses the wrapped prior’s batch and event shapes when callers omit those arguments. Prior processing checks sample dtype before issuing its existing warning and keeps the float32 conversion behavior. Tests cover non-float32 and mixed-dtype priors.

Changes: Prior shape handling

Layer / File(s) Summary
Wrapper defaults and prior-processing coverage
sbi/utils/user_input_checks_utils.py, sbi/utils/user_input_checks.py, tests/user_input_checks_test.py
Omitted shape arguments now inherit the corresponding shapes from the prior, while explicit shapes remain in effect. Prior processing checks the sample dtype before warning. Tests cover independent priors with float64 Gamma distributions, mixed dtypes, and a float64 MultivariateNormal whose processed samples are float32 and whose event shape and parameter dimension are retained.

Priority: ⬇️ Low

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

Change: Bug fix

Suggested reviewers: janfb

Merge Risk: ⚪ Minimal · up to 8b48d

The change preserves prior shapes while standardizing processed outputs to float32, with regression cases for mixed and non-float32 priors. No concrete merge-blocking risk is established in the reviewed context.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: fixing process_prior for independent priors with non-float32 types. It is concise and specific.
Description check Passed The description follows the repository template. It explains the problem and solution, documents issue status, provides a reproduction example, records test results, completes the checklist, and discl…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · 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 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.91%. Comparing base (29af137) to head (8b48da6).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2064      +/-   ##
==========================================
+ Coverage   89.89%   89.91%   +0.01%     
==========================================
  Files         142      142              
  Lines       14646    14650       +4     
==========================================
+ Hits        13166    13172       +6     
+ Misses       1480     1478       -2     
Flag Coverage Δ
fast 85.50% <100.00%> (?)

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

Files with missing lines Coverage Δ
sbi/utils/user_input_checks.py 79.78% <100.00%> (+0.75%) ⬆️
sbi/utils/user_input_checks_utils.py 93.71% <100.00%> (+0.54%) ⬆️

… shape defaults

Warn once per prior that sbi casts non-float32 priors to float32, so users do not expect float64 precision. Add mixed-dtype and multivariate cases, a shape and warning test, and document the None defaults of PytorchReturnTypeWrapper.
@janfb

janfb commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

@ThomasGesseyJonesPX thanks a lot for fixing this, and for the clear reproducer and the honest AI note!

To your question: I like changing the default of the wrapper. It also fixes a quiet bug for single priors, where a float64 multivariate prior came out with the wrong event shape.

I added a small commit on top. sbi casts the samples and log probs of non-float32 priors to float32. Until now this happened silently, so users could think they get float64 precision. It now warns when it casts. I also added tests for mixed dtypes and multivariate priors, and documented the new defaults in the wrapper docstring.

While checking this I found a separate bug: the combined prior returns the wrong shape for sample((2, 3)), with float32 priors as well. I will open an issue for it, so it stays out of this PR.

Thanks again for fixing this, Jan

@ThomasGesseyJonesPX

ThomasGesseyJonesPX commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

@janfb thanks for the speedy review response. With this problem resolved, we have encountered a second issue when using float64 priors but I cannot see an immediate clean fix for this one so I will raise an issue - #2066

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

2 participants