# API Reference¶

## Inference¶

### sbi.inference.base.infer(simulator, prior, method, num_simulations, num_workers=1)¶

Runs simulation-based inference and returns the posterior.

This function provides a simple interface to run sbi. Inference is run for a single round and hence the returned posterior $$p(\theta|x)$$ can be sampled and evaluated for any $$x$$ (i.e. it is amortized).

The scope of this function is limited to the most essential features of sbi. For more flexibility (e.g. multi-round inference, different density estimators) please use the flexible interface described here: https://www.mackelab.org/sbi/tutorial/02_flexible_interface/

Parameters:

Name Type Description Default
simulator Callable

A function that takes parameters $$\theta$$ and maps them to simulations, or observations, x, $$\mathrm{sim}(\theta)\to x$$. Any regular Python callable (i.e. function or class with __call__ method) can be used.

required
prior Distribution

A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. Any object with .log_prob()and .sample() (for example, a PyTorch distribution) can be used.

required
method str

What inference method to use. Either of SNPE, SNLE or SNRE.

required
num_simulations int

Number of simulation calls. More simulations means a longer runtime, but a better posterior estimate.

required
num_workers int

Number of parallel workers to use for simulations.

1
Source code in sbi/inference/base.py
 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 def infer( simulator: Callable, prior: Distribution, method: str, num_simulations: int, num_workers: int = 1, ) -> NeuralPosterior: r"""Runs simulation-based inference and returns the posterior. This function provides a simple interface to run sbi. Inference is run for a single round and hence the returned posterior $p(\theta|x)$ can be sampled and evaluated for any $x$ (i.e. it is amortized). The scope of this function is limited to the most essential features of sbi. For more flexibility (e.g. multi-round inference, different density estimators) please use the flexible interface described here: https://www.mackelab.org/sbi/tutorial/02_flexible_interface/ Args: simulator: A function that takes parameters $\theta$ and maps them to simulations, or observations, x, $\mathrm{sim}(\theta)\to x$. Any regular Python callable (i.e. function or class with __call__ method) can be used. prior: A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. Any object with .log_prob()and .sample() (for example, a PyTorch distribution) can be used. method: What inference method to use. Either of SNPE, SNLE or SNRE. num_simulations: Number of simulation calls. More simulations means a longer runtime, but a better posterior estimate. num_workers: Number of parallel workers to use for simulations. Returns: Posterior over parameters conditional on observations (amortized). """ try: method_fun: Callable = getattr(sbi.inference, method.upper()) except AttributeError: raise NameError( "Method not available. method must be one of 'SNPE', 'SNLE', 'SNRE'." ) simulator, prior = prepare_for_sbi(simulator, prior) inference = method_fun(prior=prior) theta, x = simulate_for_sbi( simulator=simulator, proposal=prior, num_simulations=num_simulations, num_workers=num_workers, ) _ = inference.append_simulations(theta, x).train() posterior = inference.build_posterior() return posterior 

### sbi.utils.user_input_checks.prepare_for_sbi(simulator, prior)¶

Prepare simulator and prior for usage in sbi.

NOTE: This is a wrapper around process_prior and process_simulator which can be used in isolation as well.

Attempts to meet the following requirements by reshaping and type-casting:

• the simulator function receives as input and returns a Tensor.
• the simulator can simulate batches of parameters and return batches of data.
• the prior does not produce batches and samples and evaluates to Tensor.
• the output shape is a torch.Size((1,N)) (i.e, has a leading batch dimension 1).

If this is not possible, a suitable exception will be raised.

Parameters:

Name Type Description Default
simulator Callable

Simulator as provided by the user.

required
prior

Prior as provided by the user.

required

Returns:

Type Description
Tuple[Callable, Distribution]

Tuple (simulator, prior) checked and matching the requirements of sbi.

Source code in sbi/utils/user_input_checks.py
 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 def prepare_for_sbi(simulator: Callable, prior) -> Tuple[Callable, Distribution]: """Prepare simulator and prior for usage in sbi. NOTE: This is a wrapper around process_prior and process_simulator which can be used in isolation as well. Attempts to meet the following requirements by reshaping and type-casting: - the simulator function receives as input and returns a Tensor.
- the simulator can simulate batches of parameters and return batches of data.
- the prior does not produce batches and samples and evaluates to Tensor.
- the output shape is a torch.Size((1,N)) (i.e, has a leading batch dimension 1). If this is not possible, a suitable exception will be raised. Args: simulator: Simulator as provided by the user. prior: Prior as provided by the user. Returns: Tuple (simulator, prior) checked and matching the requirements of sbi. """ # Check prior, return PyTorch prior. prior, _, prior_returns_numpy = process_prior(prior) # Check simulator, returns PyTorch simulator able to simulate batches. simulator = process_simulator(simulator, prior, prior_returns_numpy) # Consistency check after making ready for sbi. check_sbi_inputs(simulator, prior) return simulator, prior 

### sbi.inference.base.simulate_for_sbi(simulator, proposal, num_simulations, num_workers=1, simulation_batch_size=1, show_progress_bar=True)¶

Returns ($$\theta, x$$) pairs obtained from sampling the proposal and simulating.

This function performs two steps:

• Sample parameters $$\theta$$ from the proposal.
• Simulate these parameters to obtain $$x$$.

Parameters:

Name Type Description Default
simulator Callable

A function that takes parameters $$\theta$$ and maps them to simulations, or observations, x, $$\text{sim}(\theta)\to x$$. Any regular Python callable (i.e. function or class with __call__ method) can be used.

required
proposal Any

Probability distribution that the parameters $$\theta$$ are sampled from.

required
num_simulations int

Number of simulations that are run.

required
num_workers int

Number of parallel workers to use for simulations.

1
simulation_batch_size int

Number of parameter sets that the simulator maps to data x at once. If None, we simulate all parameter sets at the same time. If >= 1, the simulator has to process data of shape (simulation_batch_size, parameter_dimension).

1
show_progress_bar bool

Whether to show a progress bar for simulating. This will not affect whether there will be a progressbar while drawing samples from the proposal.

True
Source code in sbi/inference/base.py
 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 def simulate_for_sbi( simulator: Callable, proposal: Any, num_simulations: int, num_workers: int = 1, simulation_batch_size: int = 1, show_progress_bar: bool = True, ) -> Tuple[Tensor, Tensor]: r"""Returns ($\theta, x$) pairs obtained from sampling the proposal and simulating. This function performs two steps: - Sample parameters $\theta$ from the proposal. - Simulate these parameters to obtain $x$. Args: simulator: A function that takes parameters $\theta$ and maps them to simulations, or observations, x, $\text{sim}(\theta)\to x$. Any regular Python callable (i.e. function or class with __call__ method) can be used. proposal: Probability distribution that the parameters $\theta$ are sampled from. num_simulations: Number of simulations that are run. num_workers: Number of parallel workers to use for simulations. simulation_batch_size: Number of parameter sets that the simulator maps to data x at once. If None, we simulate all parameter sets at the same time. If >= 1, the simulator has to process data of shape (simulation_batch_size, parameter_dimension). show_progress_bar: Whether to show a progress bar for simulating. This will not affect whether there will be a progressbar while drawing samples from the proposal. Returns: Sampled parameters $\theta$ and simulation-outputs $x$. """ theta = proposal.sample((num_simulations,)) x = simulate_in_batches( simulator, theta, simulation_batch_size, num_workers, show_progress_bar ) return theta, x 

### sbi.inference.snpe.snpe_a.SNPE_A¶

Bases: PosteriorEstimator

Source code in sbi/inference/snpe/snpe_a.py
  24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 class SNPE_A(PosteriorEstimator): def __init__( self, prior: Optional[Distribution] = None, density_estimator: Union[str, Callable] = "mdn_snpe_a", num_components: int = 10, device: str = "cpu", logging_level: Union[int, str] = "WARNING", summary_writer: Optional[TensorboardSummaryWriter] = None, show_progress_bars: bool = True, ): r"""SNPE-A [1]. [1] _Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation_, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376. This class implements SNPE-A. SNPE-A trains across multiple rounds with a maximum-likelihood-loss. This will make training converge to the proposal posterior instead of the true posterior. To correct for this, SNPE-A applies a post-hoc correction after training. This correction has to be performed analytically. Thus, SNPE-A is limited to Gaussian distributions for all but the last round. In the last round, SNPE-A can use a Mixture of Gaussians. Args: prior: A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. Any object with .log_prob()and .sample() (for example, a PyTorch distribution) can be used. density_estimator: If it is a string (only "mdn_snpe_a" is valid), use a pre-configured mixture of densities network. Alternatively, a function that builds a custom neural network can be provided. The function will be called with the first batch of simulations (theta, x), which can thus be used for shape inference and potentially for z-scoring. It needs to return a PyTorch nn.Module implementing the density estimator. The density estimator needs to provide the methods .log_prob and .sample(). Note that until the last round only a single (multivariate) Gaussian component is used for training (see Algorithm 1 in [1]). In the last round, this component is replicated num_components times, its parameters are perturbed with a very small noise, and then the last training round is done with the expanded Gaussian mixture as estimator for the proposal posterior. num_components: Number of components of the mixture of Gaussians in the last round. This overrides the num_components value passed to posterior_nn(). device: Training device, e.g., "cpu", "cuda" or "cuda:{0, 1, ...}". logging_level: Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. summary_writer: A tensorboard SummaryWriter to control, among others, log file location (default is /logs.) show_progress_bars: Whether to show a progressbar during training. """ # Catch invalid inputs. if not ((density_estimator == "mdn_snpe_a") or callable(density_estimator)): raise TypeError( "The density_estimator passed to SNPE_A needs to be a " "callable or the string 'mdn_snpe_a'!" ) # num_components will be used to replicate the Gaussian in the last round. self._num_components = num_components self._ran_final_round = False # WARNING: sneaky trick ahead. We proxy the parent's train here, # requiring the signature to have num_atoms, save it for use below, and # continue. It's sneaky because we are using the object (self) as a namespace # to pass arguments between functions, and that's implicit state management. kwargs = utils.del_entries( locals(), entries=("self", "__class__", "num_components"), ) super().__init__(**kwargs) def train( self, final_round: bool = False, training_batch_size: int = 50, learning_rate: float = 5e-4, validation_fraction: float = 0.1, stop_after_epochs: int = 20, max_num_epochs: int = 2**31 - 1, clip_max_norm: Optional[float] = 5.0, calibration_kernel: Optional[Callable] = None, resume_training: bool = False, retrain_from_scratch: bool = False, show_train_summary: bool = False, dataloader_kwargs: Optional[Dict] = None, component_perturbation: float = 5e-3, ) -> nn.Module: r"""Return density estimator that approximates the proposal posterior. [1] _Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation_, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376. Training is performed with maximum likelihood on samples from the latest round, which leads the algorithm to converge to the proposal posterior. Args: final_round: Whether we are in the last round of training or not. For all but the last round, Algorithm 1 from [1] is executed. In last the round, Algorithm 2 from [1] is executed once. training_batch_size: Training batch size. learning_rate: Learning rate for Adam optimizer. validation_fraction: The fraction of data to use for validation. stop_after_epochs: The number of epochs to wait for improvement on the validation set before terminating training. max_num_epochs: Maximum number of epochs to run. If reached, we stop training even when the validation loss is still decreasing. Otherwise, we train until validation loss increases (see also stop_after_epochs). clip_max_norm: Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. calibration_kernel: A function to calibrate the loss with respect to the simulations x. See Lueckmann, Gonçalves et al., NeurIPS 2017. resume_training: Can be used in case training time is limited, e.g. on a cluster. If True, the split between train and validation set, the optimizer, the number of epochs, and the best validation log-prob will be restored from the last time .train() was called. force_first_round_loss: If True, train with maximum likelihood, i.e., potentially ignoring the correction for using a proposal distribution different from the prior. retrain_from_scratch: Whether to retrain the conditional density estimator for the posterior from scratch each round. Not supported for SNPE-A. show_train_summary: Whether to print the number of epochs and validation loss and leakage after the training. dataloader_kwargs: Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) component_perturbation: The standard deviation applied to all weights and biases when, in the last round, the Mixture of Gaussians is build from a single Gaussian. This value can be problem-specific and also depends on the number of mixture components. Returns: Density estimator that approximates the distribution $p(\theta|x)$. """ assert not retrain_from_scratch, """Retraining from scratch is not supported in SNPE-A yet. The reason for this is that, if we reininitialized the density estimator, the z-scoring would change, which would break the posthoc correction. This is a pure implementation issue.""" kwargs = utils.del_entries( locals(), entries=("self", "__class__", "final_round", "component_perturbation"), ) # SNPE-A always discards the prior samples. kwargs["discard_prior_samples"] = True kwargs["force_first_round_loss"] = True self._round = max(self._data_round_index) if final_round: # If there is (will be) only one round, train with Algorithm 2 from [1]. if self._round == 0: self._build_neural_net = partial( self._build_neural_net, num_components=self._num_components ) # Run Algorithm 2 from [1]. elif not self._ran_final_round: # Now switch to the specified number of components. This method will # only be used if retrain_from_scratch=True. Otherwise, # the MDN will be built from replicating the single-component net for # num_component times (via _expand_mog()). self._build_neural_net = partial( self._build_neural_net, num_components=self._num_components ) # Extend the MDN to the originally desired number of components. self._expand_mog(eps=component_perturbation) else: warnings.warn( "You have already run SNPE-A with final_round=True. Running it" "again with this setting will not allow computing the posthoc" "correction applied in SNPE-A. Thus, you will get an error when " "calling .build_posterior() after training.", UserWarning, ) else: # Run Algorithm 1 from [1]. # Wrap the function that builds the MDN such that we can make # sure that there is only one component when running. self._build_neural_net = partial(self._build_neural_net, num_components=1) if final_round: self._ran_final_round = True return super().train(**kwargs) def correct_for_proposal( self, density_estimator: Optional[TorchModule] = None, ) -> "SNPE_A_MDN": r"""Build mixture of Gaussians that approximates the posterior. Returns a SNPE_A_MDN object, which applies the posthoc-correction required in SNPE-A. Args: density_estimator: The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained. Returns: Posterior $p(\theta|x)$ with .sample() and .log_prob() methods. """ if density_estimator is None: density_estimator = deepcopy( self._neural_net ) # PosteriorEstimator.train() also returns a deepcopy, mimic this here # If internal net is used device is defined. device = self._device else: # Otherwise, infer it from the device of the net parameters. device = str(next(density_estimator.parameters()).device) # Set proposal of the density estimator. # This also evokes the z-scoring correction if necessary. if ( self._proposal_roundwise[-1] is self._prior or self._proposal_roundwise[-1] is None ): proposal = self._prior assert isinstance( proposal, (MultivariateNormal, utils.BoxUniform) ), """Prior must be torch.distributions.MultivariateNormal or sbi.utils. BoxUniform""" else: assert isinstance( self._proposal_roundwise[-1], DirectPosterior ), """The proposal you passed to append_simulations is neither the prior nor a DirectPosterior. SNPE-A currently only supports these scenarios. """ proposal = self._proposal_roundwise[-1] # Create the SNPE_A_MDN wrapped_density_estimator = SNPE_A_MDN( flow=density_estimator, proposal=proposal, prior=self._prior, device=device ) return wrapped_density_estimator def build_posterior( self, density_estimator: Optional[TorchModule] = None, prior: Optional[Distribution] = None, ) -> "DirectPosterior": r"""Build posterior from the neural density estimator. This method first corrects the estimated density with correct_for_proposal and then returns a DirectPosterior. Args: density_estimator: The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained. prior: Prior distribution. Returns: Posterior $p(\theta|x)$ with .sample() and .log_prob() methods. """ if prior is None: assert ( self._prior is not None ), """You did not pass a prior. You have to pass the prior either at initialization inference = SNPE_A(prior) or to .build_posterior (prior=prior).""" prior = self._prior wrapped_density_estimator = self.correct_for_proposal( density_estimator=density_estimator ) self._posterior = DirectPosterior( posterior_estimator=wrapped_density_estimator, prior=prior, ) return deepcopy(self._posterior) def _log_prob_proposal_posterior( self, theta: Tensor, x: Tensor, masks: Tensor, proposal: Optional[Any], ) -> Tensor: """Return the log-probability of the proposal posterior. For SNPE-A this is the same as self._neural_net.log_prob(theta, x) in _loss() to be found in snpe_base.py. Args: theta: Batch of parameters θ. x: Batch of data. masks: Mask that is True for prior samples in the batch in order to train them with prior loss. proposal: Proposal distribution. Returns: Log-probability of the proposal posterior. """ return self._neural_net.log_prob(theta, x) def _expand_mog(self, eps: float = 1e-5): """ Replicate a singe Gaussian trained with Algorithm 1 before continuing with Algorithm 2. The weights and biases of the associated MDN layers are repeated num_components times, slightly perturbed to break the symmetry such that the gradients in the subsequent training are not all identical. Args: eps: Standard deviation for the random perturbation. """ assert isinstance(self._neural_net._distribution, MultivariateGaussianMDN) # Increase the number of components self._neural_net._distribution._num_components = self._num_components # Expand the 1-dim Gaussian. for name, param in self._neural_net.named_parameters(): if any( key in name for key in ["logits", "means", "unconstrained", "upper"] ): if "bias" in name: param.data = param.data.repeat(self._num_components) param.data.add_(torch.randn_like(param.data) * eps) param.grad = None # let autograd construct a new gradient elif "weight" in name: param.data = param.data.repeat(self._num_components, 1) param.data.add_(torch.randn_like(param.data) * eps) param.grad = None # let autograd construct a new gradient 

#### __init__(prior=None, density_estimator='mdn_snpe_a', num_components=10, device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True)¶

SNPE-A [1].

[1] Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376.

This class implements SNPE-A. SNPE-A trains across multiple rounds with a maximum-likelihood-loss. This will make training converge to the proposal posterior instead of the true posterior. To correct for this, SNPE-A applies a post-hoc correction after training. This correction has to be performed analytically. Thus, SNPE-A is limited to Gaussian distributions for all but the last round. In the last round, SNPE-A can use a Mixture of Gaussians.

Parameters:

Name Type Description Default
prior Optional[Distribution]

A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. Any object with .log_prob()and .sample() (for example, a PyTorch distribution) can be used.

None
density_estimator Union[str, Callable]

If it is a string (only “mdn_snpe_a” is valid), use a pre-configured mixture of densities network. Alternatively, a function that builds a custom neural network can be provided. The function will be called with the first batch of simulations (theta, x), which can thus be used for shape inference and potentially for z-scoring. It needs to return a PyTorch nn.Module implementing the density estimator. The density estimator needs to provide the methods .log_prob and .sample(). Note that until the last round only a single (multivariate) Gaussian component is used for training (see Algorithm 1 in [1]). In the last round, this component is replicated num_components times, its parameters are perturbed with a very small noise, and then the last training round is done with the expanded Gaussian mixture as estimator for the proposal posterior.

'mdn_snpe_a'
num_components int

Number of components of the mixture of Gaussians in the last round. This overrides the num_components value passed to posterior_nn().

10
device str

Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”.

'cpu'
logging_level Union[int, str]

Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL.

'WARNING'
summary_writer Optional[TensorboardSummaryWriter]

A tensorboard SummaryWriter to control, among others, log file location (default is <current working directory>/logs.)

None
show_progress_bars bool

Whether to show a progressbar during training.

True
Source code in sbi/inference/snpe/snpe_a.py
 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 def __init__( self, prior: Optional[Distribution] = None, density_estimator: Union[str, Callable] = "mdn_snpe_a", num_components: int = 10, device: str = "cpu", logging_level: Union[int, str] = "WARNING", summary_writer: Optional[TensorboardSummaryWriter] = None, show_progress_bars: bool = True, ): r"""SNPE-A [1]. [1] _Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation_, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376. This class implements SNPE-A. SNPE-A trains across multiple rounds with a maximum-likelihood-loss. This will make training converge to the proposal posterior instead of the true posterior. To correct for this, SNPE-A applies a post-hoc correction after training. This correction has to be performed analytically. Thus, SNPE-A is limited to Gaussian distributions for all but the last round. In the last round, SNPE-A can use a Mixture of Gaussians. Args: prior: A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. Any object with .log_prob()and .sample() (for example, a PyTorch distribution) can be used. density_estimator: If it is a string (only "mdn_snpe_a" is valid), use a pre-configured mixture of densities network. Alternatively, a function that builds a custom neural network can be provided. The function will be called with the first batch of simulations (theta, x), which can thus be used for shape inference and potentially for z-scoring. It needs to return a PyTorch nn.Module implementing the density estimator. The density estimator needs to provide the methods .log_prob and .sample(). Note that until the last round only a single (multivariate) Gaussian component is used for training (see Algorithm 1 in [1]). In the last round, this component is replicated num_components times, its parameters are perturbed with a very small noise, and then the last training round is done with the expanded Gaussian mixture as estimator for the proposal posterior. num_components: Number of components of the mixture of Gaussians in the last round. This overrides the num_components value passed to posterior_nn(). device: Training device, e.g., "cpu", "cuda" or "cuda:{0, 1, ...}". logging_level: Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. summary_writer: A tensorboard SummaryWriter to control, among others, log file location (default is /logs.) show_progress_bars: Whether to show a progressbar during training. """ # Catch invalid inputs. if not ((density_estimator == "mdn_snpe_a") or callable(density_estimator)): raise TypeError( "The density_estimator passed to SNPE_A needs to be a " "callable or the string 'mdn_snpe_a'!" ) # num_components will be used to replicate the Gaussian in the last round. self._num_components = num_components self._ran_final_round = False # WARNING: sneaky trick ahead. We proxy the parent's train here, # requiring the signature to have num_atoms, save it for use below, and # continue. It's sneaky because we are using the object (self) as a namespace # to pass arguments between functions, and that's implicit state management. kwargs = utils.del_entries( locals(), entries=("self", "__class__", "num_components"), ) super().__init__(**kwargs) 

#### build_posterior(density_estimator=None, prior=None)¶

Build posterior from the neural density estimator.

This method first corrects the estimated density with correct_for_proposal and then returns a DirectPosterior.

Parameters:

Name Type Description Default
density_estimator Optional[TorchModule]

The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained.

None
prior Optional[Distribution]

Prior distribution.

None

Returns:

Type Description
DirectPosterior

Posterior $$p(\theta|x)$$ with .sample() and .log_prob() methods.

Source code in sbi/inference/snpe/snpe_a.py
 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 def build_posterior( self, density_estimator: Optional[TorchModule] = None, prior: Optional[Distribution] = None, ) -> "DirectPosterior": r"""Build posterior from the neural density estimator. This method first corrects the estimated density with correct_for_proposal and then returns a DirectPosterior. Args: density_estimator: The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained. prior: Prior distribution. Returns: Posterior $p(\theta|x)$ with .sample() and .log_prob() methods. """ if prior is None: assert ( self._prior is not None ), """You did not pass a prior. You have to pass the prior either at initialization inference = SNPE_A(prior) or to .build_posterior (prior=prior).""" prior = self._prior wrapped_density_estimator = self.correct_for_proposal( density_estimator=density_estimator ) self._posterior = DirectPosterior( posterior_estimator=wrapped_density_estimator, prior=prior, ) return deepcopy(self._posterior) 

#### correct_for_proposal(density_estimator=None)¶

Build mixture of Gaussians that approximates the posterior.

Returns a SNPE_A_MDN object, which applies the posthoc-correction required in SNPE-A.

Parameters:

Name Type Description Default
density_estimator Optional[TorchModule]

The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained.

None

Returns:

Type Description
SNPE_A_MDN

Posterior $$p(\theta|x)$$ with .sample() and .log_prob() methods.

Source code in sbi/inference/snpe/snpe_a.py
 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 def correct_for_proposal( self, density_estimator: Optional[TorchModule] = None, ) -> "SNPE_A_MDN": r"""Build mixture of Gaussians that approximates the posterior. Returns a SNPE_A_MDN object, which applies the posthoc-correction required in SNPE-A. Args: density_estimator: The density estimator that the posterior is based on. If None, use the latest neural density estimator that was trained. Returns: Posterior $p(\theta|x)$ with .sample() and .log_prob() methods. """ if density_estimator is None: density_estimator = deepcopy( self._neural_net ) # PosteriorEstimator.train() also returns a deepcopy, mimic this here # If internal net is used device is defined. device = self._device else: # Otherwise, infer it from the device of the net parameters. device = str(next(density_estimator.parameters()).device) # Set proposal of the density estimator. # This also evokes the z-scoring correction if necessary. if ( self._proposal_roundwise[-1] is self._prior or self._proposal_roundwise[-1] is None ): proposal = self._prior assert isinstance( proposal, (MultivariateNormal, utils.BoxUniform) ), """Prior must be torch.distributions.MultivariateNormal or sbi.utils. BoxUniform""" else: assert isinstance( self._proposal_roundwise[-1], DirectPosterior ), """The proposal you passed to append_simulations is neither the prior nor a DirectPosterior. SNPE-A currently only supports these scenarios. """ proposal = self._proposal_roundwise[-1] # Create the SNPE_A_MDN wrapped_density_estimator = SNPE_A_MDN( flow=density_estimator, proposal=proposal, prior=self._prior, device=device ) return wrapped_density_estimator 

#### train(final_round=False, training_batch_size=50, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, calibration_kernel=None, resume_training=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None, component_perturbation=0.005)¶

Return density estimator that approximates the proposal posterior.

[1] Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376.

Training is performed with maximum likelihood on samples from the latest round, which leads the algorithm to converge to the proposal posterior.

Parameters:

Name Type Description Default
final_round bool

Whether we are in the last round of training or not. For all but the last round, Algorithm 1 from [1] is executed. In last the round, Algorithm 2 from [1] is executed once.

False
training_batch_size int

Training batch size.

50
learning_rate float

0.0005
validation_fraction float

The fraction of data to use for validation.

0.1
stop_after_epochs int

The number of epochs to wait for improvement on the validation set before terminating training.

20
max_num_epochs int

Maximum number of epochs to run. If reached, we stop training even when the validation loss is still decreasing. Otherwise, we train until validation loss increases (see also stop_after_epochs).

2 ** 31 - 1
clip_max_norm Optional[float]

Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping.

5.0
calibration_kernel Optional[Callable]

A function to calibrate the loss with respect to the simulations x. See Lueckmann, Gonçalves et al., NeurIPS 2017.

None
resume_training bool

Can be used in case training time is limited, e.g. on a cluster. If True, the split between train and validation set, the optimizer, the number of epochs, and the best validation log-prob will be restored from the last time .train() was called.

False
force_first_round_loss

If True, train with maximum likelihood, i.e., potentially ignoring the correction for using a proposal distribution different from the prior.

required
retrain_from_scratch bool

Whether to retrain the conditional density estimator for the posterior from scratch each round. Not supported for SNPE-A.

False
show_train_summary bool

Whether to print the number of epochs and validation loss and leakage after the training.

False
dataloader_kwargs Optional[Dict]

Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn)

None
component_perturbation float

The standard deviation applied to all weights and biases when, in the last round, the Mixture of Gaussians is build from a single Gaussian. This value can be problem-specific and also depends on the number of mixture components.

0.005

Returns:

Type Description
nn.Module

Density estimator that approximates the distribution $$p(\theta|x)$$.

Source code in sbi/inference/snpe/snpe_a.py
  98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 def train( self, final_round: bool = False, training_batch_size: int = 50, learning_rate: float = 5e-4, validation_fraction: float = 0.1, stop_after_epochs: int = 20, max_num_epochs: int = 2**31 - 1, clip_max_norm: Optional[float] = 5.0, calibration_kernel: Optional[Callable] = None, resume_training: bool = False, retrain_from_scratch: bool = False, show_train_summary: bool = False, dataloader_kwargs: Optional[Dict] = None, component_perturbation: float = 5e-3, ) -> nn.Module: r"""Return density estimator that approximates the proposal posterior. [1] _Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation_, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376. Training is performed with maximum likelihood on samples from the latest round, which leads the algorithm to converge to the proposal posterior. Args: final_round: Whether we are in the last round of training or not. For all but the last round, Algorithm 1 from [1] is executed. In last the round, Algorithm 2 from [1] is executed once. training_batch_size: Training batch size. learning_rate: Learning rate for Adam optimizer. validation_fraction: The fraction of data to use for validation. stop_after_epochs: The number of epochs to wait for improvement on the validation set before terminating training. max_num_epochs: Maximum number of epochs to run. If reached, we stop training even when the validation loss is still decreasing. Otherwise, we train until validation loss increases (see also stop_after_epochs). clip_max_norm: Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. calibration_kernel: A function to calibrate the loss with respect to the simulations x. See Lueckmann, Gonçalves et al., NeurIPS 2017. resume_training: Can be used in case training time is limited, e.g. on a cluster. If True, the split between train and validation set, the optimizer, the number of epochs, and the best validation log-prob will be restored from the last time .train() was called. force_first_round_loss: If True, train with maximum likelihood, i.e., potentially ignoring the correction for using a proposal distribution different from the prior. retrain_from_scratch: Whether to retrain the conditional density estimator for the posterior from scratch each round. Not supported for SNPE-A. show_train_summary: Whether to print the number of epochs and validation loss and leakage after the training. dataloader_kwargs: Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) component_perturbation: The standard deviation applied to all weights and biases when, in the last round, the Mixture of Gaussians is build from a single Gaussian. This value can be problem-specific and also depends on the number of mixture components. Returns: Density estimator that approximates the distribution $p(\theta|x)$. """ assert not retrain_from_scratch, """Retraining from scratch is not supported in SNPE-A yet. The reason for this is that, if we reininitialized the density estimator, the z-scoring would change, which would break the posthoc correction. This is a pure implementation issue.""" kwargs = utils.del_entries( locals(), entries=("self", "__class__", "final_round", "component_perturbation"), ) # SNPE-A always discards the prior samples. kwargs["discard_prior_samples"] = True kwargs["force_first_round_loss"] = True self._round = max(self._data_round_index) if final_round: # If there is (will be) only one round, train with Algorithm 2 from [1]. if self._round == 0: self._build_neural_net = partial( self._build_neural_net, num_components=self._num_components ) # Run Algorithm 2 from [1]. elif not self._ran_final_round: # Now switch to the specified number of components. This method will # only be used if retrain_from_scratch=True. Otherwise, # the MDN will be built from replicating the single-component net for # num_component times (via _expand_mog()). self._build_neural_net = partial( self._build_neural_net, num_components=self._num_components ) # Extend the MDN to the originally desired number of components. self._expand_mog(eps=component_perturbation) else: warnings.warn( "You have already run SNPE-A with final_round=True. Running it" "again with this setting will not allow computing the posthoc" "correction applied in SNPE-A. Thus, you will get an error when " "calling .build_posterior() after training.", UserWarning, ) else: # Run Algorithm 1 from [1]. # Wrap the function that builds the MDN such that we can make # sure that there is only one component when running. self._build_neural_net = partial(self._build_neural_net, num_components=1) if final_round: self._ran_final_round = True return super().train(**kwargs) 

### sbi.inference.snpe.snpe_c.SNPE_C¶

Bases: PosteriorEstimator

Source code in sbi/inference/snpe/snpe_c.py
  27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 class SNPE_C(PosteriorEstimator): def __init__( self, prior: Optional[Distribution] = None, density_estimator: Union[str, Callable] = "maf", device: str = "cpu", logging_level: Union[int, str] = "WARNING", summary_writer: Optional[TensorboardSummaryWriter] = None, show_progress_bars: bool = True, ): r"""SNPE-C / APT [1]. [1] _Automatic Posterior Transformation for Likelihood-free Inference_, Greenberg et al., ICML 2019, https://arxiv.org/abs/1905.07488. This class implements two loss variants of SNPE-C: the non-atomic and the atomic version. The atomic loss of SNPE-C can be used for any density estimator, i.e. also for normalizing flows. However, it suffers from leakage issues. On the other hand, the non-atomic loss can only be used only if the proposal distribution is a mixture of Gaussians, the density estimator is a mixture of Gaussians, and the prior is either Gaussian or Uniform. It does not suffer from leakage issues. At the beginning of each round, we print whether the non-atomic or the atomic version is used. In this codebase, we will automatically switch to the non-atomic loss if the following criteria are fulfilled:
- proposal is a DirectPosterior with density_estimator mdn, as built with utils.sbi.posterior_nn().
- the density estimator is a mdn, as built with utils.sbi.posterior_nn().