You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
process_prior's casting can lead to a type mismatch between the .support and samples of the output prior #2066
process_prior wraps non-float32torch.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
importtorchfromtorch.distributionsimportParetofromsbi.utils.sbiutilsimportmcmc_transformfromsbi.utils.user_input_checksimportprocess_priorone=torch.ones(1, dtype=torch.float64)
prior, _, _=process_prior(Pareto(one, one)) # support on x >= 1.0mcmc_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.
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.
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.
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
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.
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:
importtorchfrompyro.distributionsimportStableWithLogProbfromsbi.utils.user_input_checks_utilsimportmove_distribution_to_devicex=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 rebuildsprint(stable.coords, moved.coords) # S S0, now a different conventionprint(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
@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.
Activity
janfb commentedon Oct 14, 2026
@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 float64UniformorBoxUniformworks, becauseprocess_prioralready turns it into a float32BoxUniform.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). AnIndependentneeds 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,MultivariateNormaland a few others. All of them came out ofprocess_prioras float32, andmcmc_transformworked for each.Would you like to take this on in a PR, once PR #2064 is merged? A test with your
Paretoexample and anIndependentcase would cover it.ThomasGesseyJonesPX commentedon Oct 15, 2026
@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
YashDoesCode commentedon Oct 27, 2026
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!
ThomasGesseyJonesPX commentedon Oct 27, 2026
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
YashDoesCode commentedon Oct 28, 2026
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!
ThomasGesseyJonesPX commentedon Oct 30, 2026
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
ParetoandIndependentcases 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_deviceand is exposed to the public API throughprocess_prior.The function
move_distribution_to_deviceassumes that all the required arguments to rebuild the distribution can be extracted from thedist.arg_constraintsproperty. This is true for many inbuilttorchandpyrodistributions. 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
Multinomialdue to itstotal_countparameter, though that is possibly unlikely for someone to use as a prior. A more realistic case being theStableWithLogProbfrompyrowhich has acoordsparameter which controls which of two conventions is used, with one option being the default.Here is a code snippet of this issue in action:
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
janfb commentedon Oct 31, 2026
@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(andvalidate_args). Everything else, likecoordsorMultinomial'stotal_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,IndependentandStableWithLogProbexamples.Thanks, Jan
Test the constructor check with the Stable prior from the issue
fix: rebuild float64 priors in float32 and keep their constructor arg…