-
Notifications
You must be signed in to change notification settings - Fork 155
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes to how data is stored #685
Merged
michaeldeistler
merged 18 commits into
sbi-dev:main
from
tbmiller-astro:data_loader_changes
Jun 29, 2022
Merged
Changes from 17 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
5200ee0
Initial testing of get_dataloaders
750fb65
Minor typo
178e3d1
Changes to SNPE append_simulations and get_dataloaders.
tbmiller-astro e1f7fd3
Minor bug fix
tbmiller-astro d77bed7
Minor bugfix when using multiple rounds
tbmiller-astro ba69f8d
Merge branch 'mackelab:main' into main
tbmiller-astro 1d0d625
Merge branch 'mackelab:main' into main
tbmiller-astro 48ace32
Added to SNRE and SNLE
tbmiller-astro 713398b
Trying to fix whitespace issue
tbmiller-astro 0d16766
new_branch
tbmiller-astro 1767ec8
Renormalize - fixes line endings
tbmiller-astro d14fec3
Ran isort, made sure _round is updated correctly
tbmiller-astro 2c87aa2
Fixed bug with indicies
tbmiller-astro 7eb4551
Changes to tests to match new syntax
tbmiller-astro 980a95b
Now compatible with black and pyright
tbmiller-astro 52addc1
Merge branch 'mackelab:main' into data_loader_changes
tbmiller-astro 4198a82
Reverted to storing data as tensors in list
tbmiller-astro 0cbc4fa
Use all data to initialize NN
tbmiller-astro File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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 |
---|---|---|
|
@@ -21,8 +21,11 @@ | |
from sbi.utils import ( | ||
check_estimator_arg, | ||
check_prior, | ||
handle_invalid_x, | ||
mask_sims_from_prior, | ||
validate_theta_and_x, | ||
warn_if_zscoring_changes_data, | ||
warn_on_invalid_x, | ||
x_shape_from_simulation, | ||
) | ||
|
||
|
@@ -83,6 +86,7 @@ def append_simulations( | |
theta: Tensor, | ||
x: Tensor, | ||
from_round: int = 0, | ||
data_device: Optional[str] = None, | ||
) -> "LikelihoodEstimator": | ||
r"""Store parameters and simulation outputs to use them for later training. | ||
|
||
|
@@ -99,16 +103,34 @@ def append_simulations( | |
With default settings, this is not used at all for `SNLE`. Only when | ||
the user later on requests `.train(discard_prior_samples=True)`, we | ||
use these indices to find which training data stemmed from the prior. | ||
|
||
data_device: Where to store the data, default is on the same device where | ||
the training is happening. If training a large dataset on a GPU with not | ||
much VRAM can set to 'cpu' to store data on system memory instead. | ||
Returns: | ||
NeuralInference object (returned so that this function is chainable). | ||
""" | ||
|
||
theta, x = validate_theta_and_x(theta, x, training_device=self._device) | ||
is_valid_x, num_nans, num_infs = handle_invalid_x(x, True) # Hardcode to True | ||
|
||
x = x[is_valid_x] | ||
theta = theta[is_valid_x] | ||
|
||
# Check for problematic z-scoring | ||
warn_if_zscoring_changes_data(x) | ||
warn_on_invalid_x(num_nans, num_infs, True) | ||
|
||
if data_device is None: | ||
data_device = self._device | ||
theta, x = validate_theta_and_x( | ||
theta, x, data_device=data_device, training_device=self._device | ||
) | ||
|
||
prior_masks = mask_sims_from_prior(int(from_round), theta.size(0)) | ||
|
||
self._theta_roundwise.append(theta) | ||
self._x_roundwise.append(x) | ||
self._prior_masks.append(mask_sims_from_prior(int(from_round), theta.size(0))) | ||
self._prior_masks.append(prior_masks) | ||
|
||
self._data_round_index.append(int(from_round)) | ||
|
||
return self | ||
|
@@ -121,7 +143,6 @@ def train( | |
stop_after_epochs: int = 20, | ||
max_num_epochs: int = 2**31 - 1, | ||
clip_max_norm: Optional[float] = 5.0, | ||
exclude_invalid_x: bool = True, | ||
resume_training: bool = False, | ||
discard_prior_samples: bool = False, | ||
retrain_from_scratch: bool = False, | ||
|
@@ -131,8 +152,6 @@ def train( | |
r"""Train the density estimator to learn the distribution $p(x|\theta)$. | ||
|
||
Args: | ||
exclude_invalid_x: Whether to exclude simulation outputs `x=NaN` or `x=±∞` | ||
during training. Expect errors, silent or explicit, when `False`. | ||
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 | ||
|
@@ -150,20 +169,13 @@ def train( | |
Returns: | ||
Density estimator that has learned the distribution $p(x|\theta)$. | ||
""" | ||
|
||
# Starting index for the training set (1 = discard round-0 samples). | ||
start_idx = int(discard_prior_samples and self._round > 0) | ||
# Load data from most recent round. | ||
self._round = max(self._data_round_index) | ||
theta, x, _ = self.get_simulations( | ||
start_idx, exclude_invalid_x, warn_on_invalid=True | ||
) | ||
|
||
# Dataset is shared for training and validation loaders. | ||
dataset = data.TensorDataset(theta, x) | ||
# Starting index for the training set (1 = discard round-0 samples). | ||
start_idx = int(discard_prior_samples and self._round > 0) | ||
|
||
train_loader, val_loader = self.get_dataloaders( | ||
dataset, | ||
start_idx, | ||
training_batch_size, | ||
validation_fraction, | ||
resume_training, | ||
|
@@ -176,10 +188,14 @@ def train( | |
# This is passed into NeuralPosterior, to create a neural posterior which | ||
# can `sample()` and `log_prob()`. The network is accessible via `.net`. | ||
if self._neural_net is None or retrain_from_scratch: | ||
|
||
# Get theta,x from dataset to initialize NN | ||
theta, x, _ = self.get_simulations() | ||
self._neural_net = self._build_neural_net( | ||
theta[self.train_indices], x[self.train_indices] | ||
theta[:training_batch_size].to("cpu"), x[:training_batch_size].to("cpu") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the |
||
) | ||
self._x_shape = x_shape_from_simulation(x) | ||
self._x_shape = x_shape_from_simulation(x[:training_batch_size].to("cpu")) | ||
del theta, x | ||
assert ( | ||
len(self._x_shape) < 3 | ||
), "SNLE cannot handle multi-dimensional simulator output." | ||
|
@@ -257,8 +273,8 @@ def train( | |
self._summarize( | ||
round_=self._round, | ||
x_o=None, | ||
theta_bank=theta, | ||
x_bank=x, | ||
theta_bank=None, | ||
x_bank=None, | ||
) | ||
|
||
# Update description for progress bar. | ||
|
This file contains 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should be