-
Notifications
You must be signed in to change notification settings - Fork 9
Add neural network modules, tests, and test utils #33
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
Open
kevinchern
wants to merge
12
commits into
dwavesystems:main
Choose a base branch
from
kevinchern:feature/nn
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
621fd0a
Add neural network modules, tests, and test utils
kevinchern a42973c
Use decorator to store configs and add module test
kevinchern c85393e
Add docstrings
kevinchern 495851c
Address review comments
kevinchern 0a99594
Store nested configs and cite ResNet
kevinchern e2f9986
Improve docstrings and fix typos
kevinchern 9467786
Refactor nn.py into a module
kevinchern 7ca53f2
Remove leading underscore for test functions
kevinchern c7028d4
Apply suggestions from code review
kevinchern a72e07a
Address PR comments
kevinchern 9b53973
Fix typo
kevinchern 7062a11
Separate tests and add more store_config tests
kevinchern 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 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,118 @@ | ||
| import inspect | ||
| from functools import wraps | ||
| from types import MappingProxyType | ||
|
|
||
| import torch | ||
| from torch import nn | ||
|
|
||
|
|
||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| def store_config(fn): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| @wraps(fn) | ||
| def wrapper(self, *args, **kwargs): | ||
| # Get signature of function and match the arguments with their names | ||
| sig = inspect.signature(fn) | ||
| bound = sig.bind(self, *args, **kwargs) | ||
| # Use default values if the args/kwargs were not supplied | ||
| bound.apply_defaults() | ||
| config = {k: v for k, v in bound.arguments.items() if k != 'self'} | ||
| config['module_name'] = bound.args[0].__class__.__name__ | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.config = MappingProxyType(config) | ||
| fn(self, *args, **kwargs) | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return wrapper | ||
|
|
||
|
|
||
| class Identity(nn.Module): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| @store_config | ||
| def __init__(self): | ||
| """An identity module. | ||
|
|
||
| This module is useful for handling cases where a neural network module is expected, but no | ||
| effect is desired.""" | ||
| super().__init__() | ||
|
|
||
| def forward(self, x) -> torch.Tensor: | ||
| """Input | ||
|
|
||
| Args: | ||
| x (torch.Tensor): The input and the output. | ||
|
|
||
| Returns: | ||
| torch.Tensor: The input and the output. | ||
| """ | ||
| return x | ||
|
|
||
|
|
||
| class SkipLinear(nn.Module): | ||
|
|
||
| @store_config | ||
| def __init__(self, din, dout) -> None: | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Applies a linear transformation to the incoming data: :math:`y = xA^T`. | ||
|
|
||
| This module is identity when `din == dout`, otherwise, it is a linear transformation, i.e., | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| no bias term. | ||
|
|
||
| Args: | ||
| din (int): Size of each input sample. | ||
| dout (int): Size of each output sample. | ||
| """ | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| super().__init__() | ||
| if din == dout: | ||
| self.linear = Identity() | ||
| else: | ||
| self.linear = nn.Linear(din, dout, bias=False) | ||
|
|
||
| def forward(self, x) -> torch.Tensor: | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Apply a linear transformation to the input variable `x`. | ||
|
|
||
| Args: | ||
| x (torch.Tensor): the input tensor. | ||
|
|
||
| Returns: | ||
| torch.Tensor: the linearly-transformed tensor of `x`. | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| return self.linear(x) | ||
|
|
||
|
|
||
| class LinearBlock(nn.Module): | ||
| @store_config | ||
| def __init__(self, din, dout, p) -> None: | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """A linear block consisting of normalizations, linear transformations, dropout, relu, and a skip connection. | ||
|
|
||
| The module is composed of (in order): | ||
| 1. a first layer norm, | ||
| 2. a first linear transformation, | ||
| 3. a dropout, | ||
| 4. a relu activation, | ||
| 5. a second layer norm, | ||
| 6. a second linear layer, and, finally, | ||
| 7. a skip connection from initial input to output. | ||
|
|
||
| Args: | ||
| din (int): Size of each input sample | ||
| dout (int): Size of each output sample | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| p (float): Dropout probability. | ||
| """ | ||
| super().__init__() | ||
| self.skip = SkipLinear(din, dout) | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| linear_1 = nn.Linear(din, dout) | ||
| linear_2 = nn.Linear(dout, dout) | ||
| self.block = nn.Sequential( | ||
| nn.LayerNorm(din), | ||
| linear_1, | ||
| nn.Dropout(p), | ||
| nn.ReLU(), | ||
| nn.LayerNorm(dout), | ||
| linear_2, | ||
| ) | ||
|
|
||
| def forward(self, x) -> torch.Tensor: | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Transforms the input `x` with the modules. | ||
|
|
||
| Args: | ||
| x (torch.Tensor): An input tensor. | ||
|
|
||
| Returns: | ||
| torch.Tensor: Output tensor. | ||
| """ | ||
| return self.block(x) + self.skip(x) | ||
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,5 @@ | ||
| --- | ||
| features: | ||
| - Add the python module `dwave.plugins.torch.nn` | ||
| - Add ``LinearBlock`` and ``SkipLinear` modules | ||
| - Add utilities for testing modules | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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,52 @@ | ||
| import unittest | ||
|
|
||
| import torch | ||
| from parameterized import parameterized | ||
|
|
||
| from dwave.plugins.torch.nn import LinearBlock, SkipLinear, store_config | ||
| from tests.utils import model_probably_good | ||
|
|
||
|
|
||
| class TestNN(unittest.TestCase): | ||
| """The tests in this class is, generally, concerned with two characteristics of the output. | ||
| 1. Module outputs, probably, do not end with an activation function, and | ||
| 2. the output tensor shapes are as expected. | ||
| """ | ||
|
|
||
| def test_store_config(self): | ||
kevinchern marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # Check the Module stores configs as expected. | ||
| class MyModel(torch.nn.Module): | ||
| @store_config | ||
| def __init__(self, a, b=1, *, x=4, y='hello'): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return x | ||
| model = MyModel(a=123, x=5) | ||
| self.assertDictEqual(dict(model.config), | ||
| {"a": 123, "b": 1, "x": 5, "y": "hello", | ||
| "module_name": "MyModel"}) | ||
|
|
||
| @parameterized.expand([0, 0.5, 1]) | ||
| def test_LinearBlock(self, p): | ||
| din = 32 | ||
| dout = 177 | ||
| model = LinearBlock(din, dout, p) | ||
| self.assertTrue(model_probably_good(model, (din,), (dout,))) | ||
|
|
||
| def test_SkipLinear(self): | ||
| din = 33 | ||
| dout = 99 | ||
| model = SkipLinear(din, dout) | ||
| self.assertTrue(model_probably_good(model, (din,), (dout, ))) | ||
| with self.subTest("Check identity for `din == dout`"): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| dim = 123 | ||
| model = SkipLinear(dim, dim) | ||
| x = torch.randn((dim,)) | ||
| y = model(x) | ||
| self.assertTrue((x == y).all()) | ||
| self.assertTrue(model_probably_good(model, (dim,), (dim, ))) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
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,143 @@ | ||
| import unittest | ||
|
|
||
| import torch | ||
| from parameterized import parameterized | ||
|
|
||
| from dwave.plugins.torch.nn import store_config | ||
| from tests import utils | ||
|
|
||
|
|
||
| class TestTestUtils(unittest.TestCase): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def test_probably_unconstrained(self): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| x = torch.randn((1000, 10, 10)) | ||
| self.assertTrue(utils._probably_unconstrained(x)) | ||
|
|
||
| # Activate | ||
| self.assertFalse(utils._probably_unconstrained(x.sigmoid())) | ||
| self.assertFalse(utils._probably_unconstrained(x.relu())) | ||
| self.assertFalse(utils._probably_unconstrained(x.tanh())) | ||
|
|
||
| def test__are_all_spins(self): | ||
| # Scalar case | ||
| self.assertTrue(utils._are_all_spins(torch.tensor([1]))) | ||
| self.assertTrue(utils._are_all_spins(torch.tensor([-1]))) | ||
| self.assertFalse(utils._are_all_spins(torch.tensor([0]))) | ||
|
|
||
| # Zeros | ||
| self.assertFalse(utils._are_all_spins(torch.tensor([0, 1]))) | ||
| self.assertFalse(utils._are_all_spins(torch.tensor([0, -1]))) | ||
| self.assertFalse(utils._are_all_spins(torch.tensor([0, 0]))) | ||
| # Nonzeros | ||
| self.assertFalse(utils._are_all_spins(torch.tensor([1, 1.2]))) | ||
| self.assertFalse(utils._are_all_spins(-torch.tensor([1, 1.2]))) | ||
|
|
||
| # All spins | ||
| self.assertTrue(utils._are_all_spins(torch.tensor([-1, 1]))) | ||
| self.assertTrue(utils._are_all_spins(torch.tensor([-1.0, 1.0]))) | ||
|
|
||
| def test__has_zeros(self): | ||
| # Scalar | ||
| self.assertFalse(utils._has_zeros(torch.tensor([1]))) | ||
| self.assertTrue(utils._has_zeros(torch.tensor([0]))) | ||
| self.assertTrue(utils._has_zeros(torch.tensor([-0]))) | ||
|
|
||
| # Tensor | ||
| self.assertTrue(utils._has_zeros(torch.tensor([0, 1]))) | ||
|
|
||
| def test__has_mixed_signs(self): | ||
| # Single entries cannot have mixed signs | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([-0]))) | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([0]))) | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([1]))) | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([-1]))) | ||
|
|
||
| # Zeros are unsigned | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([0, 0]))) | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([0, 1.2]))) | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([0, -1.2]))) | ||
|
|
||
| # All entries have same sign | ||
| self.assertFalse(utils._has_mixed_signs(torch.tensor([0.4, 1.2]))) | ||
| self.assertFalse(utils._has_mixed_signs(-torch.tensor([0.4, 1.2]))) | ||
|
|
||
| # Finally! | ||
| self.assertTrue(utils._has_mixed_signs(torch.tensor([-0.1, 1.2]))) | ||
|
|
||
| def test__bounded_in_plus_minus_one(self): | ||
| # Violation on one end | ||
| self.assertFalse(utils._bounded_in_plus_minus_one(torch.tensor([1.2]))) | ||
| self.assertFalse(utils._bounded_in_plus_minus_one(torch.tensor([-1.2]))) | ||
| self.assertFalse(utils._bounded_in_plus_minus_one(torch.tensor([1.2, 0]))) | ||
| self.assertFalse(utils._bounded_in_plus_minus_one(torch.tensor([-1.2, 0]))) | ||
|
|
||
| # Boundary | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([1]))) | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([-1]))) | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([1, -1]))) | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([1, 0]))) | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([0, 1]))) | ||
|
|
||
| # Correct | ||
| self.assertTrue(utils._bounded_in_plus_minus_one(torch.tensor([0.5, 0.9, -0.2]))) | ||
|
|
||
| @parameterized.expand([[dict(a=1, x=4)], [dict(a="hello")]]) | ||
| def test__has_correct_config(self, kwargs): | ||
| class MyModel(torch.nn.Module): | ||
| @store_config | ||
| def __init__(self, a, b=2, *, x=4, y=5): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return torch.ones(5) | ||
| model = MyModel(**kwargs) | ||
| self.assertTrue(utils._has_correct_config(model)) | ||
| self.assertFalse(utils._has_correct_config(torch.nn.Linear(5, 3))) | ||
|
|
||
| def test__shapes_match(self): | ||
| shape = (123, 456) | ||
| x = torch.randn(shape) | ||
| self.assertTrue(utils._shapes_match(x, shape)) | ||
| self.assertFalse(utils._shapes_match(x, (1, 2, 3))) | ||
|
|
||
| def test_model_probably_good(self): | ||
| with self.subTest("Model should be good"): | ||
| class MyModel(torch.nn.Module): | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| @store_config | ||
| def __init__(self, a, b=2, *, x=4, y=5): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return 2*x | ||
| self.assertTrue(utils.model_probably_good(MyModel("hello"), (500, ), (500,))) | ||
kevinchern marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| with self.subTest("Model should be bad: config not stored"): | ||
| class MyModel(torch.nn.Module): | ||
| def __init__(self, a, b=2, *, x=4, y=5): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return 2*x | ||
| self.assertFalse(utils.model_probably_good(MyModel("hello"), (500, ), (500,))) | ||
|
|
||
| with self.subTest("Model should be bad: shape mismatch"): | ||
| class MyModel(torch.nn.Module): | ||
| def __init__(self, a, b=2, *, x=4, y=5): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return torch.randn(500) | ||
| self.assertFalse(utils.model_probably_good(MyModel("hello"), (123, ), (123,))) | ||
|
|
||
| with self.subTest("Model should be bad: constrained output"): | ||
| class MyModel(torch.nn.Module): | ||
| def __init__(self, a, b=2, *, x=4, y=5): | ||
| super().__init__() | ||
|
|
||
| def forward(self, x): | ||
| return torch.ones_like(x) | ||
| self.assertFalse(utils.model_probably_good(MyModel("hello"), (123, ), (123,))) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
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.
Uh oh!
There was an error while loading. Please reload this page.