- Notifications
You must be signed in to change notification settings - Fork194
Refactorsimulate_for_sbi
location#1253
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes from1 commit
Commits
Show all changes
4 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
Added to utilis, Fixed Typos
Signed-off-by: samadpls <abdulsamadsid1@gmail.com>
- Loading branch information
Uh oh!
There was an error while loading.Please reload this page.
commitfc1ecdfc1b0ec3a5ffee51b38f7e73808b732915
There are no files selected for viewing
119 changes: 119 additions & 0 deletionssbi/utils/simulation_utils.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed | ||
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/> | ||
from typing import Any, Callable, Optional, Tuple, Union | ||
import numpy as np | ||
import torch | ||
from joblib import Parallel, delayed | ||
from numpy import ndarray | ||
from torch import Tensor, float32 | ||
from tqdm.auto import tqdm | ||
from sbi.utils.sbiutils import seed_all_backends | ||
# Refactoring following #1175. tl:dr: letting joblib iterate over numpy arrays | ||
# allows for a roughly 10x performance gain. The resulting casting necessity | ||
# (cfr. user_input_checks.wrap_as_joblib_efficient_simulator) introduces | ||
# considerable overhead. The simulating pipeline should, therefore, be further | ||
# restructured in the future (PR #1188). | ||
def simulate_for_sbi( | ||
simulator: Callable, | ||
proposal: Any, | ||
num_simulations: int, | ||
num_workers: int = 1, | ||
simulation_batch_size: Union[int, None] = 1, | ||
seed: Optional[int] = None, | ||
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. Note that the simulator should be able to handle numpy | ||
arrays for efficient parallelization. You can use | ||
`process_simulator` to ensure this. | ||
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 of shape | ||
(simulation_batch_size, parameter_dimension) that the simulator | ||
receives per call. If None, we set | ||
simulation_batch_size=num_simulations and simulate all parameter | ||
sets with one call. Otherwise, we construct batches of parameter | ||
sets and distribute them among num_workers. | ||
seed: Seed for reproducibility. | ||
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$. | ||
""" | ||
if num_simulations == 0: | ||
theta = torch.tensor([], dtype=float32) | ||
x = torch.tensor([], dtype=float32) | ||
else: | ||
# Cast theta to numpy for better joblib performance (seee #1175) | ||
seed_all_backends(seed) | ||
theta = proposal.sample((num_simulations,)) | ||
# Parse the simulation_batch_size logic | ||
if simulation_batch_size is None: | ||
simulation_batch_size = num_simulations | ||
else: | ||
simulation_batch_size = min(simulation_batch_size, num_simulations) | ||
if num_workers != 1: | ||
# For multiprocessing, we want to switch to numpy arrays. | ||
# The batch size will be an approximation, since np.array_split does | ||
# not take as argument the size of the batch but their total. | ||
num_batches = num_simulations // simulation_batch_size | ||
batches = np.array_split(theta.numpy(), num_batches, axis=0) | ||
batch_seeds = np.random.randint(low=0, high=1_000_000, size=(len(batches),)) | ||
# define seeded simulator. | ||
def simulator_seeded(theta: ndarray, seed: int) -> Tensor: | ||
seed_all_backends(seed) | ||
return simulator(theta) | ||
try: # catch TypeError to give more informative error message | ||
simulation_outputs: list[Tensor] = [ # pyright: ignore | ||
xx | ||
for xx in tqdm( | ||
Parallel(return_as="generator", n_jobs=num_workers)( | ||
delayed(simulator_seeded)(batch, seed) | ||
for batch, seed in zip(batches, batch_seeds) | ||
), | ||
total=num_simulations, | ||
disable=not show_progress_bar, | ||
) | ||
] | ||
except TypeError as err: | ||
raise TypeError( | ||
"For multiprocessing, we switch to numpy arrays. Make sure to " | ||
"preprocess your simulator with `process_simulator` to handle numpy" | ||
" arrays." | ||
) from err | ||
else: | ||
simulation_outputs: list[Tensor] = [] | ||
batches = torch.split(theta, simulation_batch_size) | ||
for batch in tqdm(batches, disable=not show_progress_bar): | ||
simulation_outputs.append(simulator(batch)) | ||
# Correctly format the output | ||
x = torch.cat(simulation_outputs, dim=0) | ||
theta = torch.as_tensor(theta, dtype=float32) | ||
return theta, x |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.