You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I find Dask very useful, and would like to use it to accelerate some pytorch models I am working on. A function to be accelerated would be the forward() function. I started doing some tests, but I get errors like these:
File "/home/muammar/.local/lib/python3.7/site-packages/distributed/protocol/serialize.py", line 81, in serialization_error_loads
raise TypeError(msg)
TypeError: Could not serialize object of type Tensor.
Traceback (most recent call last):
File "/home/muammar/.local/lib/python3.7/site-packages/distributed/protocol/serialize.py", line 144, in serialize
header, frames = dumps(x, context=context) if wants_context else dumps(x)
File "/home/muammar/.local/lib/python3.7/site-packages/distributed/protocol/serialize.py", line 38, in dask_dumps
header, frames = dumps(x)
File "/home/muammar/.local/lib/python3.7/site-packages/distributed/protocol/torch.py", line 10, in serialize_torch_Tensor
header, frames = serialize(t.numpy())
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
If I detach the variable, then pytorch does not work with numpy arrays. My question would be -- what is the state of pytorch support? If it is of any help, I would be more than happy to try any code (or even write something if it is under my capabilities) because it would be very useful to have this support in Dask. Thanks for this great python module.
My question would be -- what is the state of pytorch support?
It's been as supported as people have made support :) I'm not sure anyone has seen the issue that you've raised here. If you're able to isolate it that would help. I encourage you to find some minimal reproducible example that reproduces the error above. Ideally this looks like the following:
fromdistributed.protocolimportserialize, deserializet=# make some pytorch tensordeserialize(*serialize(t))
That works for most pytorch tensors that we've seen so far (see tests in distributed/protocol/torch.py), so presumably your tensors are different in some way. It would be good to find out how.
Thanks for your reply. I should have inspected in more details the distributed.protocol modules.
It's been as supported as people have made support :)
Yes, this is true :).
I'm not sure anyone has seen the issue that you've raised here. If you're able to isolate it that would help. I encourage you to find some minimal reproducible example that reproduces the error above. Ideally this looks like the following:
I can reproduce the error above with this minimal script:
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)
deserialize(*serialize(t))
Tensors going in forward() usually have requires_grad=True to make pytorch keep track of them when computing gradients to perform backward propagation for neural networks. Changing requires_grad=False makes dask's serialize, deserialize mechanisms to work. How could it be possible to serialize/deserialize a tensor that has requires_grad=True?
Another thing to understand is -- what detach() is actually doing. Like I wonder if this would affect the graphs and perform pytorch computations correctly. I will try to do some experiments about that. Regarding performance, I don't know exactly how that would be affected.
Regarding performance, I don't know exactly how that would be affected.
I don't see how performance would be effected either. Well, not re-attaching the gradient would provide faster computation but would return an incorrect result because the gradients wouldn't be recorded.
[how] detach ... affect the graphs and perform pytorch computations correctly.
I think a better method would be to call the requires_grad_ function on the Tensor:
To serialize we should .detach_() instead of .detach().
diff --git a/distributed/protocol/torch.py b/distributed/protocol/torch.py
index c25b1549..46c93812 100644
--- a/distributed/protocol/torch.py
+++ b/distributed/protocol/torch.py
@@ -1,5 +1,5 @@
from .serialize import (serialize, dask_serialize, dask_deserialize,
- register_generic)
+ register_generic)
import torch
import numpy as np
@@ -7,7 +7,7 @@ import numpy as np
@dask_serialize.register(torch.Tensor)
def serialize_torch_Tensor(t):
- header, frames = serialize(t.numpy())
+ header, frames = serialize(t.detach_().numpy())
if t.grad is not None:
grad_header, grad_frames = serialize(t.grad.numpy())
header['grad'] = {'header': grad_header, 'start': len(frames)}
@@ -22,7 +22,8 @@ def deserialize_torch_Tensor(header, frames):
if header.get('grad', False):
i = header['grad']['start']
frames, grad_frames = frames[:i], frames[i:]
- grad = dask_deserialize.dispatch(np.ndarray)(header['grad']['header'], grad_frames)
+ grad = dask_deserialize.dispatch(np.ndarray)(header['grad']['header'],
+ grad_frames)
else:
grad = None
Now, in deserialize_torch_Tensor I see .requires_grad_ is already being used when device == 'cpu' or we set requires_grad=header['requires_grad'] otherwise.
I will go ahead and prepare a PR where .detach_() is used to create a leaf.
After applying #2586, I am able to use dask.delayed in the forward() function of my package. However, the pytorch computational graph breaks (note that loss function and metric error are constant) :
I am investigating why that is. Basically, the autograd is not tracking the gradient of the outputs.
In the picture above, I was doing something very naive -- I just abstracted from forward() a function that I decorated as @dask.delayed. It seems to me that the pytorch optimizer(?) is not aware of what is going on.
I also did another naive attempt that would be related to training in batches (using chunks). I just stashed the changes that created the problem above, and I decorated forward() as @dask.delayed and using just one batch, I was able to see that the computations returned from forward() for that batch seemed correct but loss function does not change at each epoch because again either autograd or the optimizer do not track them :(. I have to look at dask_ml.Incremental to understand how the optimizer can be transferred.
I had my project public, but in the national lab where I work, I was told I have to first discuss the terms of licensing and those stuff before putting it public again. However, I have something in this gist so that you have an idea!
I never heard about using a parameter server! that sounds interesting. I will read it. Thank you very much for these discussions, I really appreciate.
I think that using Dask to bootstrap PyTorch's distributed computing platform is likely a highly pragmatic approach. As @TomAugspurger this was done for tensorflow. It was also done for XGBoost in dask-xgboost, and is currently being upstreamed in dmlc/xgboost#4473 .
Rather than use submit and map I encourage people to step a little bit outside of the task scheduling framework and use run to ensure that all workers participate and that they participate evenly. If someone wants to take this on I would encourage them to look at the existing solutions and then speak up early about early work. I think that people here will be happy to advise.
In the next few days I will try to do something less hardcoded and test other things. If anyone has any idea on how to improve the Dask part, ping me :)
@muammar Well, the method I proposed should be more scalable: If I understood correctly, with your method you are using Dask workers to compute gradients. These gradients are then aggregated by the master, computed new weights and then sent back to workers to update the model, am I right?
Just for the sake of clarification, what the method above does is:
Split the data in chunks.
Send to each worker a batch of data with the model.
forward/backward passes in the workers, accumulate the gradients and return them to master.
I use a client.gather to get them and sum them up.
Update the gradient parameters in master.
Finally .optimizer.step().
Repeat until convergence.
If the answer is positive, then what you are doing is "implementing a single parameter server" (kind of) and this can be a bottleneck.
The other method is using ring-all-reduce (implemented in distributedDataParallel in pytorch) to aggregate weight, hence no communication with the master node is involved.
Also you are not using Dask to comunicate weight, because all the communications between workers are managed by Pytorch dist module, which is highly optimized.
Concerning the model: this should fix it, because you are creating models inside workers, am I wrong? I not, consider that you are sending your model/weights to workers at most once, that is when you first instantiate the model.
Please tell me if I said something really stupid, because this is very likely.
It makes sense. Let me know how I could help with this. I am working in a package for chemistry and materials science where I implemented the distributed training method discussed previously. I would be glad to implement this new approach and make tests but I might have some questions :). In this way, we could get something done to be added in dask distributed! What do you think?
By the way, will the diagnostic dashboard be able to show the status of things?
By the way, will the diagnostic dashboard be able to show the status of things?
I think that'd be useful too (for train/test score, etc). In the decentralized/ring-all-reduce case I think it could be done (maybe with bit of delay) with the per-worker resource plugin
I like what you did here. Basically you are implementing torch.distributed using Dask, am I right? It would be great to compare the performance of this two approaches.
@stsievert and @mrocklin I am submitting a paper about a package I built for ML in atomistic simulations and as you helped me getting the PyTorch model working with dask, I would like to add you in the acknowledgment section. Is that ok with you? If you do not want me to add your name I understand. Best.
@muammar - would you be interested in sharing this on the dask blog? We sometimes have posts on that sort of thing, and I think it'd be interesting for many people (here's a post on Dask with Pytorch Nick wrote earlier this year).
(I'm going to close this issue, since it seems you have it working well now, but that won't stop you being able to leave comments on the conversation here, fyi)
Activity
mrocklin commentedon Mar 29, 2019
It's been as supported as people have made support :) I'm not sure anyone has seen the issue that you've raised here. If you're able to isolate it that would help. I encourage you to find some minimal reproducible example that reproduces the error above. Ideally this looks like the following:
That works for most pytorch tensors that we've seen so far (see tests in distributed/protocol/torch.py), so presumably your tensors are different in some way. It would be good to find out how.
muammar commentedon Mar 29, 2019
Thanks for your reply. I should have inspected in more details the
distributed.protocolmodules.Yes, this is true :).
I can reproduce the error above with this minimal script:
Tensors going in
forward()usually haverequires_grad=Trueto make pytorch keep track of them when computing gradients to perform backward propagation for neural networks. Changingrequires_grad=Falsemakes dask'sserialize,deserializemechanisms to work. How could it be possible to serialize/deserialize a tensor that hasrequires_grad=True?muammar commentedon Mar 29, 2019
I was inspecting this: https://github.com/dask/distributed/blob/177dfb891089cc872bab34fb8369d75cae13bc0a/distributed/protocol/torch.py I clearly see that tensors with gradients should be taken care of. I will install dask from sources to do some printing and understand better why this happens.
Just for the record:
mrocklin commentedon Mar 29, 2019
Thanks for the minimal script. That's very helpful to have, even if we can't find a good fix soon.
Yes, I was just about to point you to that file and ask if you had time to investigate. Glad to see that you're a step ahead of me :)
muammar commentedon Mar 29, 2019
Thanks for being so responsive. Yes, I will go ahead and look into it. I hope I can make it work.
muammar commentedon Mar 29, 2019
This seems to fix it:
Should I prepare a PR for this?
mrocklin commentedon Mar 29, 2019
Sure! Do we know if this has any negative impact, for example on performance?
cc @stsievert
muammar commentedon Mar 29, 2019
Another thing to understand is -- what
detach()is actually doing. Like I wonder if this would affect the graphs and perform pytorch computations correctly. I will try to do some experiments about that. Regarding performance, I don't know exactly how that would be affected.stsievert commentedon Mar 29, 2019
I don't see how performance would be effected either. Well, not re-attaching the gradient would provide faster computation but would return an incorrect result because the gradients wouldn't be recorded.
I think a better method would be to call the
requires_grad_function on the Tensor:These return
self, sox is x.detach_().muammar commentedon Mar 29, 2019
@stsievert I was finishing reading this https://pytorch.org/docs/stable/autograd.html#torch.Tensor.detach and I think I agree with you.
To serialize we should
.detach_()instead of.detach().Now, in
deserialize_torch_TensorI see.requires_grad_is already being used whendevice == 'cpu'or we setrequires_grad=header['requires_grad']otherwise.I will go ahead and prepare a PR where
.detach_()is used to create aleaf..detach_() pytorch tensor to serialize data as numpy array.
muammar commentedon Mar 29, 2019
After applying #2586, I am able to use
dask.delayedin theforward()function of my package. However, the pytorch computational graph breaks (note that loss function and metric error are constant) :I am investigating why that is. Basically, the autograd is not tracking the gradient of the outputs.
[-]Using dask with PyTorch[/-][+]Using dask with PyTorch (train a model)[/+]stsievert commentedon Mar 29, 2019
How are you performing the distributed optimization? I'm familiar with two choices:
dask_ml.Incremental)What does your optimization code look like?
muammar commentedon Mar 29, 2019
In the picture above, I was doing something very naive -- I just abstracted from
forward()a function that I decorated as@dask.delayed. It seems to me that the pytorch optimizer(?) is not aware of what is going on.I also did another naive attempt that would be related to training in batches (using chunks). I just stashed the changes that created the problem above, and I decorated
forward()as@dask.delayedand using just one batch, I was able to see that the computations returned fromforward()for that batch seemed correct but loss function does not change at each epoch because again either autograd or the optimizer do not track them :(. I have to look atdask_ml.Incrementalto understand how the optimizer can be transferred.I had my project public, but in the national lab where I work, I was told I have to first discuss the terms of licensing and those stuff before putting it public again. However, I have something in this gist so that you have an idea!
I never heard about using a parameter server! that sounds interesting. I will read it. Thank you very much for these discussions, I really appreciate.
24 remaining items
mrocklin commentedon May 22, 2019
I think that using Dask to bootstrap PyTorch's distributed computing platform is likely a highly pragmatic approach. As @TomAugspurger this was done for tensorflow. It was also done for XGBoost in dask-xgboost, and is currently being upstreamed in dmlc/xgboost#4473 .
Rather than use
submitandmapI encourage people to step a little bit outside of the task scheduling framework and userunto ensure that all workers participate and that they participate evenly. If someone wants to take this on I would encourage them to look at the existing solutions and then speak up early about early work. I think that people here will be happy to advise.muammar commentedon May 22, 2019
Just for the sake of clarification, what the method above does is:
client.gatherto get them and sum them up..optimizer.step().It makes sense. Let me know how I could help with this. I am working in a package for chemistry and materials science where I implemented the distributed training method discussed previously. I would be glad to implement this new approach and make tests but I might have some questions :). In this way, we could get something done to be added in dask distributed! What do you think?
By the way, will the diagnostic dashboard be able to show the status of things?
Mmiglio commentedon May 22, 2019
I would love to create a package with this :)
To be honest I don't know the answer, but tomorrow I will try and see if something happens.
stsievert commentedon May 22, 2019
I'd love to see this too! This sounds pragmatically useful.
Depends on the problem. For large models, certainly. But wouldn't this be managed by PyTorch? All Dask would do is setup the network, right?
I have a draft implementation of the parameter server/ring-all-reduce schemes above for Dask at https://github.com/stsievert/dask-ps (though they're referred to as "centralized" and "decentralized" respectively, and also far too general).
I think that'd be useful too (for train/test score, etc). In the decentralized/ring-all-reduce case I think it could be done (maybe with bit of delay) with the per-worker resource plugin
Mmiglio commentedon May 23, 2019
Indeed with the method I proposed everything would be managed by PyTorch. As you said what Dask would do is set up the network and partition data.
I like what you did here. Basically you are implementing torch.distributed using Dask, am I right? It would be great to compare the performance of this two approaches.
muammar commentedon Mar 4, 2020
@stsievert and @mrocklin I am submitting a paper about a package I built for ML in atomistic simulations and as you helped me getting the PyTorch model working with dask, I would like to add you in the acknowledgment section. Is that ok with you? If you do not want me to add your name I understand. Best.
stsievert commentedon Mar 4, 2020
@muammar no objections here! Thank you.
mrocklin commentedon Mar 4, 2020
Thank you for thinking of us @muammar . Are you able to share the article?
muammar commentedon Mar 4, 2020
I have shared it with you and @stsievert. You should have it in your emails.
sribkain commentedon Mar 17, 2020
@muammar Can I get a copy too please?
muammar commentedon Mar 17, 2020
The preprint can be found here: https://chemrxiv.org/articles/ML4Chem_A_Machine_Learning_Package_for_Chemistry_and_Materials_Science/11952516 :)
GenevieveBuckley commentedon Oct 19, 2021
And @muammar's github repository with the ML4Chem library is here: https://github.com/muammar/ml4chem
@muammar - would you be interested in sharing this on the dask blog? We sometimes have posts on that sort of thing, and I think it'd be interesting for many people (here's a post on Dask with Pytorch Nick wrote earlier this year).
GenevieveBuckley commentedon Oct 19, 2021
(I'm going to close this issue, since it seems you have it working well now, but that won't stop you being able to leave comments on the conversation here, fyi)