Skip to content

Commit

Permalink
autograd: return self for += and -=. (OpenMined#3872)
Browse files Browse the repository at this point in the history
Co-authored-by: Justin Harris <justindharris@gmail.com>
  • Loading branch information
juharris and Justin Harris committed Jul 18, 2020
1 parent 1ee5007 commit 96f0709
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions syft/frameworks/torch/tensors/interpreters/autograd.py
Expand Up @@ -90,6 +90,7 @@ def __iadd__(self, other):
result = self.add(other)
self.child = result.child
self.grad_fn = result.grad_fn
return self

def __sub__(self, other):
if isinstance(self, AutogradTensor) and not isinstance(other, AutogradTensor):
Expand All @@ -100,6 +101,7 @@ def __isub__(self, other):
result = self.sub(other)
self.child = result.child
self.grad_fn = result.grad_fn
return self

def __mul__(self, other):
if isinstance(self, AutogradTensor) and not isinstance(other, AutogradTensor):
Expand Down
28 changes: 28 additions & 0 deletions test/generic/test_autograd.py
Expand Up @@ -22,6 +22,34 @@ def test_wrap():
assert isinstance(x.child.child, torch.Tensor)


def test_iadd():
"""
Test += AutogradTensor
"""

a = AutogradTensor(torch.Tensor([1, 2, 3]))
b = AutogradTensor(torch.Tensor([4, 5, 6]))
expected = AutogradTensor(torch.Tensor([5, 7, 9]))

a += b
assert a is not None
assert torch.equal(a, expected)


def test_isub():
"""
Test -= AutogradTensor
"""

a = AutogradTensor(torch.Tensor([1, 2, 3]))
b = AutogradTensor(torch.Tensor([4, 5, 6]))
expected = AutogradTensor(torch.Tensor([-3, -3, -3]))

a -= b
assert a is not None
assert torch.equal(a, expected)


@pytest.mark.parametrize("cmd", ["__add__", "__sub__", "__mul__", "__matmul__"])
@pytest.mark.parametrize("backward_one", [True, False])
def test_backward_for_binary_cmd_with_autograd(cmd, backward_one):
Expand Down

0 comments on commit 96f0709

Please sign in to comment.