Skip to content

.detach_() pytorch tensor to serialize data as numpy array. - #2586

Merged
mrocklin merged 9 commits into
dask:masterfrom
muammar:master
Apr 8, 2019
Merged

mrocklin merged 9 commits into
dask:masterfrom
muammar:master

Conversation

@muammar

@muammar muammar commented Mar 29, 2019

Copy link
Copy Markdown
Contributor

This commit is related to #2581. Tensors with requires_grad=True cannot
be converted to numpy unless they are detached from the computational
graph first. To fix that, the tensor has to be detached as a leaf using
the .detach_() method. For more information see:

https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach_

This commit is related to dask#2581. Tensors with requires_grad=True cannot
be converted to numpy unless they are detached from the computational
graph first. To fix that, the tensor has to be detached as a leaf using
the .detach_() method. For more information see:

https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach_
@mrocklin

Copy link
Copy Markdown
Member

Thanks for the PR @muammar !

Can I ask you to include your example in the issue as a small test? See https://github.com/dask/distributed/blob/master/distributed/protocol/tests/test_torch.py for examples.

Also cc @stsievert

@muammar

muammar commented Mar 29, 2019

Copy link
Copy Markdown
Contributor Author

I hope I did this correctly. Running py.test called the function correctly.

@stsievert

Copy link
Copy Markdown
Member

I'd like to see requires_grad tested. Something like

x = torch.tensor([0, 0, 0], requires_grad=True)
y = deserialize(*serialize(x))
assert y.requires_grad

What's the motivation behind this PR? Are models being trained with PyTorch and Dask?

torch.set_printoptions(precision=10)
a = np.random.rand(8, 1)
t = torch.tensor(a, requires_grad=True, dtype=torch.float)
deserialize(*serialize(t))

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.

The result of this line should be a PyTorch tensor that is mostly equivalent to t. Is there some check we can run to verify that we have recreated an equivalent tensor object?

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.

By doing this:

import torch
import numpy as np
from distributed.protocol import serialize, deserialize

a = np.random.rand(8, 1)

t = torch.tensor(a, requires_grad=True, dtype=torch.float)

t2 = deserialize(*serialize(t))
print(a)
print(t2.numpy())

I get:

[[0.90611823]
 [0.57207592]
 [0.14868348]
 [0.24763735]
 [0.25475143]
 [0.71949837]
 [0.19011521]
 [0.3211044 ]]
[[0.9061182 ]
 [0.5720759 ]
 [0.14868347]
 [0.24763735]
 [0.25475144]
 [0.7194984 ]
 [0.19011521]
 [0.3211044 ]]

They slightly differ on the 8th decimal. assert will thorw an error because of that and I thought that setting larger precission would help.

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.

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.

They slightly differ on the 8th decimal

I use np.allclose in these situations.

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.

@stsievert that worked. Thanks for the suggestion.

@muammar

muammar commented Mar 29, 2019

Copy link
Copy Markdown
Contributor Author

@stsievert that is correct. I am trying to train a model using pytorch and dask.

@muammar

muammar commented Mar 29, 2019

Copy link
Copy Markdown
Contributor Author

I'd like to see requires_grad tested. Something like

x = torch.tensor([0, 0, 0], requires_grad=True)
y = deserialize(*serialize(x))
assert y.requires_grad

Thanks for bringing this up. The data is being serialized/deserialized correctly. However, .detach_() creates a copy of the tensor with requires_grad=False. Shouldn't we use .detach() instead? because how else we could verify the tensor requires grad.

muammar added 2 commits March 29, 2019 11:57
- assert t2.requires_grad to verify that requires_grad=True.
- assert a.all() == t2.all() to verify data consistency.
- Use of .detach() instead of .detach_() in protocol/torch.py
@stsievert

Copy link
Copy Markdown
Member

.detach_() creates a copy of the tensor with requires_grad=False. Shouldn't we use .detach() instead? because how else we could verify the tensor requires grad.

The requires_grad information will need be encoded, probably in the header. Maybe

def serialize_torch(x):
    # ...
    if x.requires_grad:
	    kwargs["requires_grad"] = True
        x.requires_grad_()
    header, frames = serialize(x.numpy())
    header.update(kwargs)
    # ...

with a matching thing for deserialize that looks at the header.

I am trying to train a model using pytorch and dask.

I've had a good experience training using PyTorch models with Dask when using skorch (the official wrapper ignite might work too, but I'm not sure).

@muammar

muammar commented Mar 29, 2019

Copy link
Copy Markdown
Contributor Author

.detach_() creates a copy of the tensor with requires_grad=False. Shouldn't we use .detach() instead? because how else we could verify the tensor requires grad.

The requires_grad information will need be encoded, probably in the header. Maybe

def serialize_torch(x):
    # ...
    if x.requires_grad:
	    kwargs["requires_grad"] = True
        x.requires_grad_()
    header, frames = serialize(x.numpy())
    header.update(kwargs)
    # ...

with a matching thing for deserialize that looks at the header.

Inspired by your comment I came up with d9143a0. It works correctly for requires_grad true and false.

I am trying to train a model using pytorch and dask.

I've had a good experience training using PyTorch models with Dask when using skorch (the official wrapper ignite might work too, but I'm not sure).

Thanks for sharing!. I will look into it, but would be very glad if I would not need to add another dependency.

muammar added 3 commits March 31, 2019 09:56
* upstream/master:
  bump version to 1.26.1
* upstream/master:
  Use ensure_dict instead of dict (dask#2594)
  Specify protocol in LocalCluster (dask#2489)
@mrocklin

mrocklin commented Apr 8, 2019

Copy link
Copy Markdown
Member

@stsievert does this look ok to you? If so, I'm going to merge this in.

@stsievert

Copy link
Copy Markdown
Member

does this look ok to you?

Yes. This PR more accurately represents the tensor that's communicated. The require_grad flag specifies that the gradients should be recorded when performing loss.backwards().

The gradients do eventually need to be connected to an optimizer. @muammar implemented a parameter server for that (#2581 (comment)).

@mrocklin
mrocklin merged commit af1cbdb into dask:master Apr 8, 2019
@mrocklin

mrocklin commented Apr 8, 2019

Copy link
Copy Markdown
Member

Thanks @muammar . This is in!

Also, I notice that this is your first code contribution to this repository. Welcome!

@muammar

muammar commented Apr 8, 2019

Copy link
Copy Markdown
Contributor Author

Thanks @muammar . This is in!

Also, I notice that this is your first code contribution to this repository. Welcome!

You are right, this is my first contribution to dask!! thanks for accepting the PR.

darindf pushed a commit to darindf/distributed that referenced this pull request Apr 11, 2019
This commit is related to dask#2581. Tensors with requires_grad=True cannot
be converted to numpy unless they are detached from the computational
graph first. To fix that, the tensor has to be detached as a leaf using
the .detach_() method. For more information see:

https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach_
muammar added a commit to muammar/distributed that referenced this pull request Apr 12, 2019
* upstream/master:
  Add RabbitMQ SchedulerPlugin example (dask#2604)
  add resources to scheduler update_graph plugin (dask#2603)
  Use ensure_bytes in serialize_error (dask#2588)
  Specify data storage explicitly from Worker constructor (dask#2600)
  Change bokeh port keywords to dashboard_address (dask#2589)
  .detach_() pytorch tensor to serialize data as numpy array. (dask#2586)
  Add warning if creating scratch directories takes a long time (dask#2561)
  Fix typo in pub-sub doc. (dask#2599)
  Allow return_when='FIRST_COMPLETED' in wait (dask#2598)
  Forward kwargs through Nanny to Worker (dask#2596)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants