-
Notifications
You must be signed in to change notification settings - Fork 27
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
Add PyTorch dataloader #25
Merged
Merged
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1c5febf
[loaders refactor] initial commit
94519b3
add torch to dev environment
04480ba
fix mypy checks
6104bf3
add torch accessor
ed8aa66
Merge branch 'main' into loader/torch
86c8560
lint
2bbf2df
additional test coverage for torch loaders
69909b4
update pre-commit
8bcd870
update docs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
# type: ignore | ||
import pytest | ||
|
||
|
||
|
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 |
---|---|---|
@@ -1,3 +1,4 @@ | ||
pytest | ||
torch | ||
coverage | ||
-r requirements.txt |
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 |
---|---|---|
@@ -1,4 +1,5 @@ | ||
#!/usr/bin/env python | ||
# type: ignore | ||
import os | ||
|
||
from setuptools import find_packages, setup | ||
|
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
Empty file.
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 |
---|---|---|
@@ -0,0 +1,83 @@ | ||
from typing import Any, Callable, Optional, Tuple | ||
|
||
import torch | ||
|
||
# Notes: | ||
# This module includes two PyTorch datasets. | ||
# - The MapDataset provides an indexable interface | ||
# - The IterableDataset provides a simple iterable interface | ||
# Both can be provided as arguments to the the Torch DataLoader | ||
# Assumptions made: | ||
# - Each dataset takes pre-configured X/y xbatcher generators (may not always want two generators ina dataset) | ||
# TODOs: | ||
# - sort out xarray -> numpy pattern. Currently there is a hardcoded variable name for x/y | ||
# - need to test with additional dataset parameters (e.g. transforms) | ||
|
||
|
||
class MapDataset(torch.utils.data.Dataset): | ||
def __init__( | ||
self, | ||
X_generator, | ||
y_generator, | ||
transform: Optional[Callable] = None, | ||
target_transform: Optional[Callable] = None, | ||
) -> None: | ||
''' | ||
PyTorch Dataset adapter for Xbatcher | ||
|
||
Parameters | ||
---------- | ||
X_generator : xbatcher.BatchGenerator | ||
y_generator : xbatcher.BatchGenerator | ||
transform : callable, optional | ||
A function/transform that takes in an array and returns a transformed version. | ||
target_transform : callable, optional | ||
A function/transform that takes in the target and transforms it. | ||
''' | ||
self.X_generator = X_generator | ||
self.y_generator = y_generator | ||
self.transform = transform | ||
self.target_transform = target_transform | ||
|
||
def __len__(self) -> int: | ||
return len(self.X_generator) | ||
|
||
def __getitem__(self, idx) -> Tuple[Any, Any]: | ||
if torch.is_tensor(idx): | ||
idx = idx.tolist() | ||
assert len(idx) == 1 | ||
|
||
# TODO: figure out the dataset -> array workflow | ||
# currently hardcoding a variable name | ||
X_batch = self.X_generator[idx]['x'].torch.to_tensor() | ||
y_batch = self.y_generator[idx]['y'].torch.to_tensor() | ||
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. flagging that we can't use named tensors here while we wait for pytorch/pytorch#29010 |
||
|
||
if self.transform: | ||
X_batch = self.transform(X_batch) | ||
|
||
if self.target_transform: | ||
y_batch = self.target_transform(y_batch) | ||
return X_batch, y_batch | ||
|
||
|
||
class IterableDataset(torch.utils.data.IterableDataset): | ||
def __init__( | ||
self, | ||
X_generator, | ||
y_generator, | ||
) -> None: | ||
''' | ||
PyTorch Dataset adapter for Xbatcher | ||
|
||
Parameters | ||
---------- | ||
X_generator : xbatcher.BatchGenerator | ||
y_generator : xbatcher.BatchGenerator | ||
''' | ||
|
||
self.X_generator = X_generator | ||
self.y_generator = y_generator | ||
|
||
def __iter__(self): | ||
for xb, yb in zip(self.X_generator, self.y_generator): | ||
yield (xb['x'].torch.to_tensor(), yb['y'].torch.to_tensor()) |
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 |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import numpy as np | ||
import pytest | ||
import xarray as xr | ||
|
||
torch = pytest.importorskip('torch') | ||
|
||
from xbatcher import BatchGenerator | ||
from xbatcher.loaders.torch import IterableDataset, MapDataset | ||
|
||
|
||
@pytest.fixture(scope='module') | ||
def ds_xy(): | ||
n_samples = 100 | ||
n_features = 5 | ||
ds = xr.Dataset( | ||
{ | ||
'x': ( | ||
['sample', 'feature'], | ||
np.random.random((n_samples, n_features)), | ||
), | ||
'y': (['sample'], np.random.random(n_samples)), | ||
}, | ||
) | ||
return ds | ||
|
||
|
||
def test_map_dataset(ds_xy): | ||
|
||
x = ds_xy['x'] | ||
y = ds_xy['y'] | ||
|
||
x_gen = BatchGenerator(x, {'sample': 10}) | ||
y_gen = BatchGenerator(y, {'sample': 10}) | ||
|
||
dataset = MapDataset(x_gen, y_gen) | ||
|
||
# test __getitem__ | ||
x_batch, y_batch = dataset[0] | ||
assert len(x_batch) == len(y_batch) | ||
assert isinstance(x_batch, torch.Tensor) | ||
|
||
# test __len__ | ||
assert len(dataset) == len(x_gen) | ||
|
||
# test integration with torch DataLoader | ||
loader = torch.utils.data.DataLoader(dataset) | ||
|
||
for x_batch, y_batch in loader: | ||
assert len(x_batch) == len(y_batch) | ||
assert isinstance(x_batch, torch.Tensor) | ||
|
||
# TODO: why does pytorch add an extra dimension (length 1) to x_batch | ||
assert x_gen[-1]['x'].shape == x_batch.shape[1:] | ||
# TODO: also need to revisit the variable extraction bits here | ||
assert np.array_equal(x_gen[-1]['x'], x_batch[0, :, :]) | ||
|
||
|
||
def test_iterable_dataset(ds_xy): | ||
|
||
x = ds_xy['x'] | ||
y = ds_xy['y'] | ||
|
||
x_gen = BatchGenerator(x, {'sample': 10}) | ||
y_gen = BatchGenerator(y, {'sample': 10}) | ||
|
||
dataset = IterableDataset(x_gen, y_gen) | ||
|
||
# test integration with torch DataLoader | ||
loader = torch.utils.data.DataLoader(dataset) | ||
|
||
for x_batch, y_batch in loader: | ||
assert len(x_batch) == len(y_batch) | ||
assert isinstance(x_batch, torch.Tensor) | ||
|
||
# TODO: why does pytorch add an extra dimension (length 1) to x_batch | ||
assert x_gen[-1]['x'].shape == x_batch.shape[1:] | ||
# TODO: also need to revisit the variable extraction bits here | ||
assert np.array_equal(x_gen[-1]['x'], x_batch[0, :, :]) |
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.
Flagging this as something so discuss / work out a design for. It feels quite important that we are able to generate arbitrary batches on the fly. The current implementation eagerly generates batches which will not scale well. However, the pure generator approach doesn't work if you need to randomly access batches (eg via getitem).