Repository navigation
Description
🐛 Bug Description
NeuralPosterior._device is a plain string set once in __init__
(sbi/inference/posteriors/base_posterior.py:63). Loading a saved posterior with
torch.load(..., map_location=...) remaps the tensor storages but leaves _device
untouched, so the posterior claims to be on one device while its tensors are on another.
This affects every posterior type, not one in particular, since they all inherit _device
from NeuralPosterior.
The consequence is that any later code path trusting _device (moving new inputs,
constructing tensors, or building a sampler) targets the wrong device. Sampling from a
cpu-mapped posterior that still reports mps:0/cuda:0 can then fail with a device
mismatch, or silently move data back to an accelerator the user deliberately mapped away
from.
🔄 Steps to Reproduce
Needs a machine with CUDA or MPS. Train anywhere, then load onto CPU:
import tempfile
import torch
from torch import eye, zeros
from torch.distributions import MultivariateNormal
from sbi.inference import NPE
from sbi.utils.torchutils import process_device
device = process_device("gpu")
prior = MultivariateNormal(zeros(2).to(device), eye(2).to(device))
theta = prior.sample((200,))
x = theta + 0.1 * torch.randn_like(theta)
trainer = NPE(prior=prior, device=device, show_progress_bars=False)
trainer.append_simulations(theta.cpu(), x.cpu())
estimator = trainer.train(max_num_epochs=1)
posterior = trainer.build_posterior(estimator).set_default_x(zeros(1, 2).to(device))
with tempfile.NamedTemporaryFile(suffix=".pt") as f:
torch.save(posterior, f.name)
loaded = torch.load(f.name, weights_only=False, map_location="cpu")
tensor_devices = {t.device.type for t in loaded.posterior_estimator.parameters()}
print(f"_device attribute: {loaded._device!r}")
print(f"actual tensors on: {tensor_devices}")Output on an MPS machine:
_device attribute: 'mps:0'
actual tensors on: {'cpu'}
The same happens for VIPosterior:
_device attribute: 'mps:0'
actual tensors on: {'cpu'}
✅ Expected Behavior
After a map_location load, posterior._device should agree with where the tensors
actually are — either reconciled during unpickling, or documented as requiring an explicit
posterior.to(device) call.
📌 Additional Context
_deviceis assigned atsbi/inference/posteriors/base_posterior.py:63; each posterior
subclass then defines its ownto()(direct_posterior.py:96,mcmc_posterior.py:172,
vi_posterior.py:239,rejection_posterior.py:75,importance_posterior.py:81,
ensemble_posterior.py:98,vector_field_posterior.py:112).- Pre-existing and long-standing; not introduced by fix: make unconstraining transforms module-owned #1939 or fix: make VIPosterior serialization state-based #1953.
- Workaround: call
posterior.to(device)after loading. - A fix probably belongs in
NeuralPosterior.__setstate__so it covers all posterior types
at once, rather than being added per subclass. Notedocs/how_to_guide/07_save_and_load.ipynb
already documents aCPU_Unpicklerworkaround for loading accelerator-trained posteriors,
so that guide should be updated alongside any fix. - Not currently covered by tests: the device tests in
tests/inference_on_device_test.py
never pickle or deepcopy across devices.
Activity
BHARATH0153 commentedon Jul 28, 2026
@janfb please assign
the problem is just that setstate restores _device from the pickle as-is, but torch.load(..., map_location=...) moves tensors under the hood without touching the string. so the string is stale.
I will fix through
in NeuralPosterior.setstate, after restoring state, check what device the estimator params are actually on and update _device if they disagree
that covers all posteriors without touching each subclass
update the save/load guide — replace the cpu_unpickler workaround with just calling .to(device)
add a test for cross-device pickle roundtrip
the gist of it:
def setstate(self, state):
self.dict = state
m = getattr(self, "posterior_estimator", None)
if m is None:
m = getattr(self, "potential_fn", None)
if m is not None:
p = next(m.parameters(), None)
if p is not None:
self._device = str(p.device)
BHARATH0153 commentedon Jul 29, 2026
@janfb #1954 (comment) if it's OK I will try to make pr in one day after work
janfb commentedon Jul 29, 2026
Thanks for the initiative @BHARATH0153 !
Please note that @waterWang already made a PR. I closed it because I wanted to have a discussion here first. Let's give them the chance to comment here and re-open a PR if they want to.
BHARATH0153 commentedon Jul 30, 2026
@waterWang still you wanna work on it
BHARATH0153 commentedon Jul 30, 2026
@janfb "I think @waterWang has not responded yet." Can work it through his pr
janfb commentedon Jul 30, 2026
Yes, agreed, you can take it @BHARATH0153
please see also #1958 and make sure to use the new
canonical_device()from sbi/utils/torchutils.py for checking the strings.fix: reconcile posterior._device after map_location load (sbi-dev#1954)
fix: reconcile posterior._device after map_location load (sbi-dev#1954)
fix: reconcile posterior._device after map_location load (sbi-dev#1954)
fix: reconcile posterior._device after map_location load (sbi-dev#1954)
BHARATH0153 commentedon Aug 7, 2026
#1972