Skip to content

MCMCPosterior fail to pickle due to pytorch bug, this causes problem sampling #1952

Closed

Description

@Liordemarcas

🐛 Bug Description

Thank for inspecting!
If we try to pickle an MCMCPosterior object, it won't save the internal inverse theta transformation. As a result, sampling will fail. Note that this also breaks parallel MCMC sampling (num_workers >1). SBI version 0.26.1, PyTorch version 2.13.0, Python version 3.13.12. Related to the issue I opened: pytorch/pytorch#191197

Minimal Example:

import pickle

import torch
from sbi.inference import NPE, simulate_for_sbi
from sbi.utils import BoxUniform

# ---------------------------------------------------------
# 1. Setup: Toy Simulator and Prior
# ---------------------------------------------------------
prior = BoxUniform(low=torch.tensor([-3.0]), high=torch.tensor([3.0]))

def simulator(theta):
    # Simple linear simulator with Gaussian noise
    return theta + torch.randn_like(theta) * 0.1

# The observed data we want to do inference on
x_o = torch.tensor([1.0])

# Initialize
inference = NPE(prior=prior)
theta1, x1 = simulate_for_sbi(simulator, prior, num_simulations=500)
inference.append_simulations(theta1, x1)
estimator1 = inference.train(max_num_epochs=10)
posterior = inference.build_posterior(estimator1, sample_with="mcmc")

with open("posterior.pkl", "wb") as f:
    pickle.dump(posterior, f)
with open("posterior.pkl", "rb") as f:
    posterior_pickled = pickle.load(f)

print("******************\nBefore pickling:\n", posterior.theta_transform)
print("******************\nAfter pickling:\n", posterior_pickled.theta_transform)

sampled_thetas = posterior.sample((1000,), x=x_o)
sampled_thetas_pickled = posterior_pickled.sample((1000,), x=x_o)

Return:

100%|██████████| 500/500 [00:00<00:00, 186181.82it/s]
 Training neural network. Epochs trained: 11******************
Before pickling:
 Inverse(IndependentTransform(ComposeTransform(
    SigmoidTransform(),
    AffineTransform()
), 1))
******************
After pickling:
 Inverse(None)
Generating 20 MCMC inits via resample strategy: 100%|██████████| 20/20 [00:00<00:00, 22.15it/s]
Running vectorized MCMC with 20 chains: 100%|██████████| 6000/6000 [00:01<00:00, 3652.13it/s]
Generating 20 MCMC inits via resample strategy:   0%|          | 0/20 [00:00<?, ?it/s]
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[19], line 35
     32 print("******************\nAfter pickling:\n", posterior_pickled.theta_transform)
     34 sampled_thetas = posterior.sample((1000,), x=x_o)
---> 35 sampled_thetas_pickled = posterior_pickled.sample((1000,), x=x_o)

File ~/envs/optuna_260217/lib/python3.13/site-packages/sbi/inference/posteriors/mcmc_posterior.py:311, in MCMCPosterior.sample(self, sample_shape, x, method, thin, warmup_steps, num_chains, init_strategy, init_strategy_parameters, num_workers, mp_context, show_progress_bars)
    304 init_strategy_parameters = (
    305     self.init_strategy_parameters
    306     if init_strategy_parameters is None
    307     else init_strategy_parameters
    308 )
    309 self.potential_ = self._prepare_potential(method)  # type: ignore
--> 311 initial_params = self._get_initial_params(
    312     init_strategy,  # type: ignore
    313     num_chains,  # type: ignore
    314     num_workers,
    315     show_progress_bars,
    316     **init_strategy_parameters,
    317 )
    318 num_samples = torch.Size(sample_shape).numel()
    320 track_gradients = method in ("hmc_pyro", "nuts_pyro", "hmc_pymc", "nuts_pymc")

File ~/envs/optuna_260217/lib/python3.13/site-packages/sbi/inference/posteriors/mcmc_posterior.py:625, in MCMCPosterior._get_initial_params(self, init_strategy, num_chains, num_workers, show_progress_bars, **kwargs)
    621     initial_params = torch.cat(initial_params)  # type: ignore
    622 else:
    623     initial_params = torch.cat(
    624         [
--> 625             init_fn()
    626             for _ in tqdm(
    627                 range(num_chains),
    628                 desc=f"Generating {num_chains} MCMC inits via {init_strategy} "
    629                 "strategy",
    630                 disable=not show_progress_bars,
    631             )
    632         ]  # type: ignore
    633     )
    634 assert initial_params.shape[0] == num_chains, "Initial params shape mismatch."
    635 return initial_params

File ~/envs/optuna_260217/lib/python3.13/site-packages/sbi/inference/posteriors/mcmc_posterior.py:559, in MCMCPosterior._build_mcmc_init_fn.<locals>.<lambda>()
    555     return lambda: sir_init(
    556         proposal, potential_fn, transform=transform, **kwargs
    557     )
    558 elif init_strategy == "resample":
--> 559     return lambda: resample_given_potential_fn(
    560         proposal, potential_fn, transform=transform, **kwargs
    561     )
    562 elif init_strategy == "latest_sample":
    563     latest_sample = IterateParameters(self._mcmc_init_params, **kwargs)

File ~/envs/optuna_260217/lib/python3.13/site-packages/sbi/samplers/mcmc/init_strategy.py:114, in resample_given_potential_fn(proposal, potential_fn, transform, num_candidate_samples, num_batches, **kwargs)
    112 idxs = torch.multinomial(probs, 1, replacement=False).cpu()
    113 # Return transformed sample.
--> 114 return transform(init_param_candidates[idxs, :])

File ~/envs/optuna_260217/lib/python3.13/site-packages/torch/distributions/transforms.py:271, in _InverseTransform.__call__(self, x)
    269 def __call__(self, x):
    270     if self._inv is None:
--> 271         raise AssertionError("_inv must not be None")
    272     return self._inv._inv_call(x)

AssertionError: _inv must not be None

Activity

  1. added
    bug
    on Jul 27, 2026
  2. janfb commented on Jul 27, 2026

    @janfb
    Contributor

    Thanks for reporting this @Liordemarcas

    We have a fix for this incoming with #1939 and this will be released in the next days with version 0.27.

  3. added a commit that references this issue on Jul 28, 2026
    1bf329f
  4. added a commit that references this issue on Aug 1, 2026
    4a94f9b
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