Skip to content

posterior._device goes stale after loading with torch.load(map_location=...) #1954

Closed

Description

@janfb

🐛 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

  • _device is assigned at sbi/inference/posteriors/base_posterior.py:63; each posterior
    subclass then defines its own to() (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. Note docs/how_to_guide/07_save_and_load.ipynb
    already documents a CPU_Unpickler workaround 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

  1. added
    bug
    on Jul 28, 2026
  2. BHARATH0153 commented on Jul 28, 2026

    @BHARATH0153
    Contributor

    @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)

  3. BHARATH0153 commented on Jul 29, 2026

    @BHARATH0153
    Contributor

    @janfb #1954 (comment) if it's OK I will try to make pr in one day after work

  4. janfb commented on Jul 29, 2026

    @janfb
    ContributorAuthor

    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.

  5. BHARATH0153 commented on Jul 30, 2026

    @BHARATH0153
    Contributor

    @waterWang still you wanna work on it

  6. BHARATH0153 commented on Jul 30, 2026

    @BHARATH0153
    Contributor

    @janfb "I think @waterWang has not responded yet." Can work it through his pr

  7. janfb commented on Jul 30, 2026

    @janfb
    ContributorAuthor

    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.

  8. BHARATH0153 commented on Aug 7, 2026

    @BHARATH0153
    Contributor
  9. added
    posteriors
    gpu
    on Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

buggpuposteriors

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions