Skip to content

process_prior's casting can lead to a type mismatch between the .support and samples of the output prior #2066

Closed

Description

@ThomasGesseyJonesPX

Bug description

process_prior wraps non-float32 torch.Distributions in a PytorchReturnTypeWrapper so that the output samples are float32. However, there is no casting of the Constraint output by .support. Some distributions including the torch inbuilt Pareto distribution have tensors in their support / Constraint definitions. The subsequent type mismatch then can cause downstream RuntimeErrors in code expecting these to be of the same type. For example in mcmc_transform.

Minimal code example

import torch
from torch.distributions import Pareto

from sbi.utils.sbiutils import mcmc_transform
from sbi.utils.user_input_checks import process_prior

one = torch.ones(1, dtype=torch.float64)
prior, _, _ = process_prior(Pareto(one, one))  # support on x >= 1.0
mcmc_transform(prior)

Error message or traceback

Traceback (most recent call last):
  File "/Users/thomasgesseyjones/Documents/04_research/XX_other/sbi/mwe.py", line 9, in <module>
    mcmc_transform(prior)  # RuntimeError: Float did not match Double
    ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/thomasgesseyjones/Documents/04_research/XX_other/sbi/sbi/utils/sbiutils.py", line 1023, in mcmc_transform
    check_transform(prior, transform)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/thomasgesseyjones/Documents/04_research/XX_other/sbi/sbi/utils/sbiutils.py", line 1049, in check_transform
    assert torch.allclose(
           ^^^^^^^^^^^^^^^
RuntimeError: Float did not match Double

sbi version

0.27.0

Python version

Python 3.12.4

Device

CPU

Inference method

Not method-specific

Single-round or multi-round

Not applicable

Additional context

At first casting the tensors within the Constraint object return by the wrapped Distribution.support within PytorchReturnTypeWrapper.support seemed like an obvious fix. But, digging into this further doing so is non-trivial due to the interaction of Constraints with Independent and constraint.cat leading to the tensors a Constraint depends on being potentially within complex nested data structures, and its unclear to me if there are edge cases a recursive traversal of these structures would still miss.

Activity

  1. added
    bug
    on Oct 14, 2026
  2. janfb commented on Oct 14, 2026

    @janfb
    Contributor

    @ThomasGesseyJonesPX thanks for the clear report, I can reproduce it.

    It hits priors whose support stores tensors and that sbi does not rebuild anyway: Pareto, Independent(Uniform(...)), and lists that contain them. A float64 Uniform or BoxUniform works, because process_prior already turns it into a float32 BoxUniform.

    I agree that casting the constraints is fragile. I think the cleaner fix is to stop wrapping where we can: rebuild the distribution from its own parameters, cast to float32. Then the support, mean and variance are float32 by construction, and nothing needs a cast.

    sbi already rebuilds distributions this way to move them to another device (get_distribution_parameters). An Independent needs one extra step for its base distribution. Distributions that cannot be rebuilt, such as custom subclasses, would keep the current wrapper as a fallback.

    I tried this quickly for Pareto, Independent(Uniform), Gamma, Beta, LogNormal, MultivariateNormal and a few others. All of them came out of process_prior as float32, and mcmc_transform worked for each.

    Would you like to take this on in a PR, once PR #2064 is merged? A test with your Pareto example and an Independent case would cover it.

  3. ThomasGesseyJonesPX commented on Oct 15, 2026

    @ThomasGesseyJonesPX
    ContributorAuthor

    @janfb thanks for the suggestion, that does sound like a much cleaner approach. Very happy to take this on and raise a PR in the next couple of days

  4. YashDoesCode commented on Oct 27, 2026

    @YashDoesCode
    Contributor

    Hey @ThomasGesseyJonesPX ! Hope you're doing well.

    I came across issue #2066 and saw that you were planning to work on the fix. I found the problem interesting and would be happy to contribute to it, particularly the approach Jan suggested for rebuilding distributions with their parameters cast to float32.

    Just wanted to check if you're still planning to take this up. If you are, no worries at all. I don't want to overlap with your work. If your plans have changed, I'd be glad to take it forward, provided Jan is okay with that.

    Thanks!

  5. ThomasGesseyJonesPX commented on Oct 27, 2026

    @ThomasGesseyJonesPX
    ContributorAuthor

    Hi @YashDoesCode,
    Thanks for the nudge on this. I have completed some preliminary research on this, but no code development yet. I was planning to work on this on Friday morning but if its blocking for you I can try and bring it forward, or can detail below the anticipated difficulties for you to be aware of before you attempt it yourself

  6. YashDoesCode commented on Oct 28, 2026

    @YashDoesCode
    Contributor

    Hey @ThomasGesseyJonesPX, thanks for getting back to me!

    It's not blocking me, so please don't feel you need to bring it forward just for my sake. Since you've already done some preliminary research, I'd be interested to hear about the anticipated difficulties you mentioned. That would help me understand the edge cases and the scope of the fix better.

    I'm happy to let you take the lead on this. I'd also be glad to help investigate or test any tricky cases if that would be useful.

    Thanks again!

  7. ThomasGesseyJonesPX commented on Oct 30, 2026

    @ThomasGesseyJonesPX
    ContributorAuthor

    Hi @janfb,

    I have spent most of the day working on this. I have managed to resolve many of the edge cases I came across but there remains one rather nasty one I was hoping to get your input on as a maintainer.

    For the rebuilding of the distributions I followed the approach that already existed when changing devices that you alluded to. This plus the wrapper back-up works nicely for the Pareto and Independent cases we discussed.

    However, when using Claude to do an automatic review of my code before creating the PR it pointed out a further edge case that also exists in the current move_distribution_to_device and is exposed to the public API through process_prior.

    The function move_distribution_to_device assumes that all the required arguments to rebuild the distribution can be extracted from the dist.arg_constraints property. This is true for many inbuilt torch and pyro distributions. If its not true and the missing parameters are required then it fails, and the recursive tensor move backup is triggered. However, there is a third case where its not true, and the missing parameter has a default.

    In which case a distribution is rebuilt but with that missing parameter set to its default which may not be the same as the value in the user's input, leading to the rebuilt distribution being a mathematically different distribution to the input one. This can happen in the torch inbuilt Multinomial due to its total_count parameter, though that is possibly unlikely for someone to use as a prior. A more realistic case being the StableWithLogProb from pyro which has a coords parameter which controls which of two conventions is used, with one option being the default.

    Here is a code snippet of this issue in action:

    import torch
    from pyro.distributions import StableWithLogProb
    
    from sbi.utils.user_input_checks_utils import move_distribution_to_device
    
    x = torch.tensor([[0.0], [2.0]])
    
    stable = StableWithLogProb(torch.tensor([1.5]), torch.tensor([0.9]), coords="S")
    moved = move_distribution_to_device(stable, "cpu")  # same device, but still rebuilds
    print(stable.coords, moved.coords)  # S S0, now a different convention
    print(stable.log_prob(x).squeeze(), moved.log_prob(x).squeeze())  # so pdfs are not the same

    As you can imagine this is potentially a rather horrid bug for a user as its silent. They get a valid distribution back, its just not the distribution they put in.

    cc. @YashDoesCode as you were interested to hear more about some of the difficulties faced in implementing this

  8. janfb commented on Oct 31, 2026

    @janfb
    Contributor

    @ThomasGesseyJonesPX good catch, thanks! A rebuilt prior that is silently a different distribution is exactly what we want to avoid, so please fix it in the same PR.

    I think the simplest rule is: rebuild only when the constructor takes no arguments other than the parameters in arg_constraints (and validate_args). Everything else, like coords or Multinomial's total_count, goes to the existing fallback. This covers the device move as well.

    Please keep the PR concise: the rebuild, this check, and small tests with your Pareto, Independent and StableWithLogProb examples.

    Thanks, Jan

  9. added a commit that references this issue on Nov 16, 2026
    f8ef4a9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions