Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions distributed/protocol/tests/test_torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,22 @@ def test_tensor():
assert (x == t2.numpy()).all()


def test_grad():
@pytest.mark.parametrize("requires_grad", [True, False])
def test_grad(requires_grad):
x = np.arange(10)
t = torch.Tensor(x)
t.grad = torch.zeros_like(t) + 1
t = torch.tensor(x, dtype=torch.float, requires_grad=requires_grad)

if requires_grad:
t.grad = torch.zeros_like(t) + 1

t2 = deserialize(*serialize(t))
assert (t2.numpy() == x).all()
assert (t2.grad.numpy() == 1).all()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would test that serialization and de-serialization does not modify t.requires_grad. Adding this line below the serialization would test that:

assert t.requires_grad == requires_grad

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, too.

assert t2.requires_grad is requires_grad
assert t.requires_grad is requires_grad
assert np.allclose(t2.detach().numpy(), x)

if requires_grad:
assert np.allclose(t2.grad.numpy(), 1)


def test_resnet():
Expand Down
7 changes: 6 additions & 1 deletion distributed/protocol/torch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
@dask_serialize.register(torch.Tensor)
def serialize_torch_Tensor(t):
requires_grad_ = t.requires_grad
header, frames = serialize(t.detach_().numpy())

if requires_grad_:
header, frames = serialize(t.detach().numpy())
else:
header, frames = serialize(t.numpy())
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not an use an if-statement instead? It's known when the error will be thrown: when t.requires_grad is true.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed this block to use an if-statement.


if t.grad is not None:
grad_header, grad_frames = serialize(t.grad.numpy())
header["grad"] = {"header": grad_header, "start": len(frames)}
Expand Down