Repository navigation
Description
The .to() method in multiple posterior classes has a fragile design pattern: it calls super().__init__() which erases internal state (particularly self._x - the default observation), and then has to manually restore that state afterwards. This pattern is error-prone, adds boilerplate, and indicates a design problem in the base posterior class.
The pattern looks like this:
def to(self, device):
# Capture x_o before it's lost
if self._x is not None:
x_o = self._x.to(device)
else:
x_o = None
# ... capture other state that will be lost ...
# Call super().__init__() which ERASES self._x
super().__init__(
self.potential_fn,
# ... other args ...
)
# Restore the lost state
# super().__init__ erases the self._x, so we need to set it again
if x_o is not None:
self.set_default_x(x_o)
# ... restore other state ...This pattern exists in at least 6 files:
- sbi/inference/posteriors/mcmc_posterior.py
- sbi/inference/posteriors/direct_posterior.py
- sbi/inference/posteriors/vector_field_posterior.py
- sbi/inference/posteriors/rejection_posterior.py
- sbi/inference/posteriors/importance_posterior.py
- sbi/inference/posteriors/ensemble_posterior.py
Why this is a problem:
- Boilerplate: Each subclass has to duplicate this capture-restore pattern
- Error-prone: If any state is forgotten, it gets silently lost
- Fragile: Adding new state to the base class requires updating all subclasses
- Unclear contract: It's not obvious what state needs to be preserved
The root cause is in base_posterior.py. The base posterior's __init__ sets up internal state like self._x = None, potential_fn, etc. When a subclass calls super().__init__(...) in its .to() method, it re-runs all this initialization, resetting self._x to None.
Note: The potentials' .to() method does NOT have this problem - it only moves tensors to the device without calling __init__. The issue is specific to posteriors.
Proposed solution:
Make the base posterior's .to() method non-destructive. Instead of calling super().__init__(), manually move only the attributes that need to change, without resetting state:
def to(self, device):
device = process_device(device)
self.device = device
# Move only the things that need moving, don't reset state
if self._x is not None:
self._x = self._x.to(device)
self.potential_fn = self.potential_fn.to(device)
if self.prior is not None:
self.prior = move_distribution_to_device(self.prior, device)
# Don't call `super().__init__()` at all - no state reset
return selfThen subclasses just call super().to() without any capture-restore.
Testing:
- Test that .to() preserves _x / default observation
- Test that .to() preserves prior
- Test that .to() preserves potential_fn
- Test that chained operations work: .to(device).sample(...)
Potentially related to #1970
Activity
janfb commentedon Sep 3, 2026
Hi Jocho, I created #2004 as a follow up for #1972 and noticed that it is solved with what you proposed here:
The mapped-load path in
__setstate__reconciles the device state by hand, because the posteriorto()methods raise for plain torch priors and re-run__init__. Your proposal here fixes both, so I redirected #2004 to this issue. One PR can close both.Here is how I think a minimal and complete version looks.
The base class gets a
to()that moves the shared state in place: the device strings, the potential, the transform, the default x and the cached MAP. Moving the potential also moves the estimator, because both hold the same object. The prior or proposal needs one rule: if it is the potential's prior, point to that object again after the move; if it is another posterior, as in multi-round NLE or NRE, call its ownto(); otherwise move it the way the potentials do. The transform can be moved in place with the helper we already have for that, no rebuild needed. Return self.The subclasses then only call the base method and handle their own state, which is mostly resetting caches. Two classes are easy to miss because they inherit from DirectPosterior: the filtered direct posterior holds context tensors, and the NPE-A posterior holds its two mixtures. VI keeps its own part for the variational distributions and the link transform.
Then
__setstate__just callsto(). Please keep the early return for the case where the device already matches. Without it every same-device load and every deepcopy would rebuild the prior and trigger the MPS side effects.RestrictedPrior needs a small
to()as well, including the classifier and its threshold inside the accept-reject function. The RestrictionEstimator is a trainer and stays out.For tests I would add one parametrized CPU test over all posterior types with a BoxUniform and a plain torch prior, plus one case where the proposal is a previous-round posterior. It checks that
to()does not raise, keeps the MAP, keeps prior and potential in sync, and that sampling and the potential still work. Extend the GPUto()test with the plain torch prior and run the gpu tests on MPS before you open the PR.Out of scope: process_device, the constructors, RestrictionEstimator and #1994.
No rush from my side. If it does not fit into your remaining time, say so and I take it.
Thanks, Jan
janfb commentedon Sep 24, 2026
Since #2013, the MCMC, rejection and importance posteriors type their proposal as
Proposal, which only declaressample()andlog_prob(). Theirto()methods callself.proposal.to(device)andmcmc_transform(self.proposal), which needs aDistribution. CI does not see this because our pyright config turns off the attribute and argument checks. The proposal rule in the newto()should narrow the type first: callto()on a posterior, move aDistributionlike the potentials do. That fixes the runtime error for plain torch priors and the typing at the same time.janfb commentedon Oct 27, 2026
Hi @Jocho-Smith, I will take this one over now, as it has been quiet since September and is assigned to me. Thanks for opening it, and for the
bind()work it builds on.cheers, Jan
Jocho-Smith commentedon Nov 4, 2026
Hey @janfb , sry for the inactivity. I'm deep into my PhD work currently after having a lucky discovery, so I'll not be able to contribute to sbi for probably a couple of months now - I would still like to contribute more if "logistics" allows for it. So probably it is best to not include me into issues for now - I'll let you know, if I'm available again.
Thanks for the patience on this one and thanks for the
bind()project.All the best
Jocho
fix: move posteriors to another device in place and keep their state (s…