PySyft icon indicating copy to clipboard operation
PySyft copied to clipboard

Backward function not called for torch.autograd.function

Open DanyEle opened this issue 7 years ago • 16 comments

Describe the bug The backward function of a custom class in PySyft inherited from the torch.autograd.function is not invoked when running the backward() method on remote tensors. This feature is essential for my current research work based on PySyft.

To Reproduce Just run this code:

import torch
import torch.autograd as autograd
import torch.nn as nn
import syft as sy

class MyFun(torch.autograd.Function):
    def forward(self, inp):
        return inp

    def backward(self, grad_out):
        grad_input = grad_out.clone()
        print('Custom backward called!')
        return grad_input

class MyMod(nn.Module):
    def forward(self, x):
        return MyFun()(x)

#local version - the backward method is indeed invoked. 
mod = MyMod()
y = autograd.Variable(torch.randn(1), requires_grad=True)
z = mod(y)
z.backward()

#remote version - the backward method is not invoked.
hook = sy.TorchHook(torch)
worker = sy.VirtualWorker(hook, id="alice")
y_remote = y.send(worker)
z_remote = z.send(worker)
z_remote.backward()

Expected behavior I would expect the backward() method from the custom class to be actually called.

Desktop (please complete the following information):

  • OS: Ubuntu 18.04 LTS

Additional context I believe the problem lies in the fact that the torch.autograd.function is not implemented in PySyft, and hence the backward method of a custom class is not invoked.

DanyEle avatar Jun 28 '19 09:06 DanyEle

As discussed with @DanyEle one reason for this can be: Regarding nn.Modules operated on remote data, the forward pass method is run by the client (ie the local instance) and then all ops inside (like nn.relu or nn.Linear) are hooked and a message is sent for each of them to the workers which holds the data. Therefore, the remote worker doesn't have the big picture of your nn.module model. However, when you call backward, the cmd backward() is sent directly to the remote worker. In this case, as it doesn't have the big picture of your nn.module model, it doesn't see the custom backward of yours and just performs the default backward.

LaRiffle avatar Jun 28 '19 11:06 LaRiffle

Thank you for the response @LaRiffle . Any idea on how to possibly fix this issue and introduce support for the backward propagation function for the torch.autograd.function in PySyft over remote tensors?

DanyEle avatar Jun 28 '19 15:06 DanyEle

hey @DanyEle On another note, how does this behave if you call y.send() before you call the mod on it?

robert-wagner avatar Jun 28 '19 18:06 robert-wagner

hey @DanyEle On another note, how does this behave if you call y.send() before you call the mod on it?

Just tried it and did not notice any difference. The backward method from the MyMod class is still not invoked.

DanyEle avatar Jun 28 '19 19:06 DanyEle

The core issue is that when we serialize objects we don't serialize their graph as well. In other words, when you call .send() on a tensor, we don't send the whole graph, we only send that tensor.

However, the fix should be easy. If you send everything BEFORE the forward pass it should work.

TODO: we should add support for someone to send a dynamic graph

iamtrask avatar Jul 01 '19 14:07 iamtrask

@LaRiffle - shouldn't it be possible to do what he's trying to do using AutogradTensor? Is there a way to call .send() on a graph and keep the graph local but just send the tensor to a remote machine so that when you call .backward() it does backprop locally but executes it remotely?

Aka - how does he create a custom op for AutogradTensor?

iamtrask avatar Jul 01 '19 16:07 iamtrask

As suggested by @iamtrask , I currently trying to use "AutogradTensor" from Pull Request #2293 , however I have not yet managed to get it working with a custom class.

Any ideas on how to combine custom classes in combination with an AutogradTensor?

This is the code I tried with the AutoGradTensor:

import torch.autograd as autograd
import torch.nn as nn
import syft as sy

class MyFun(torch.autograd.Function):
    def forward(self, inp):
        return inp
    
    def backward(self, grad_out):
        grad_input = grad_out.clone()
        print('Custom backward called!')
        return grad_input

class MyMod(nn.Module):
    def forward(self, x):
        return MyFun()(x)

#local version - the backward method is indeed invoked. 
mod_test = MyFun()

mod = MyMod()



y = autograd.Variable(torch.randn(1), requires_grad=True)
z = mod(y)
#z.backward()
#remote version - the backward method is not invoked.
hook = sy.TorchHook(torch)
worker = sy.VirtualWorker(hook, id="alice")

y_remote = y.send(worker)
y_autograd = sy.AutogradTensor().on(y_remote)
#y_auto_remote = y_auto.send(worker)
z_remote = z.send(worker)
z_autograd = sy.AutogradTensor().on(z_remote)

z_remote.backward()```



However, it says 'ValueError: The gradient for one of the command you used was not found. Check gradients.py to see if it's missing.'

DanyEle avatar Jul 09 '19 12:07 DanyEle

Hey! So there are many things here,

  • Currently with AutogradTensor, you need to specify the gradient for all operations that you use, and in particular you need to explain how the backward is supposed to be computed, so you cant' just add a print statement to some multiplication function, you also need to re-state how to differentiate it. Of course this is not a pb for a function which doesn't modify the data. One awesome thing would be to be able to call the native backward for a function, which might not be always available especially if you don't have access to the graph of computation grad_fn.
  • To specify a custom function with a forward and backward, which are understood by Autograd, you currently need to add this function in gradient.py, would be good to offer a way for user to add more functions directly in the code just like @DanyEle tries to do

LaRiffle avatar Jul 10 '19 07:07 LaRiffle

The easiest way to do would be to work in the second direction, and the piece of code that we'd like to work would be:

import torch
import torch.autograd as autograd
import torch.nn as nn

import syft as sy
hook = sy.TorchHook(torch)
worker = sy.VirtualWorker(hook, id="alice")

class MyFunction(torch.autograd.Function):
    def forward(self, x):
        print("Custom forward called")
        return x
    
    def backward(self, grad_out):
        grad_input = grad_out.clone()
        print('Custom backward called!')
        return grad_input


x = torch.tensor([1.5], requires_grad=True)
x = x.send(worker, local_autograd=True)

y = MyFunction(x)

y.backward()

Would this address your usecase?

LaRiffle avatar Jul 10 '19 08:07 LaRiffle

Thank you for the example @LaRiffle . I tried running your code, but got the following error:

y.backward()

TypeError: backward() missing 1 required positional argument: 'grad_out'

Instead, when running

y.backward(x)

This does seem to be working as expected and the backward method is indeed invoked from the custom class. I have yet to verify whether this would work for my particular case though.

DanyEle avatar Jul 10 '19 10:07 DanyEle

So I would say the sample of code I suggetsed is not supposed to work right now, but we should do the appropriate imprvements in autograd to have it working. It's more a target to achieve :)

LaRiffle avatar Jul 10 '19 13:07 LaRiffle

I'm trying to adapt your suggestion @LaRiffle , and running your example with my more concrete case:

#Perform forward pass
 output, hidden = remote_model_cpu_train(data_remote, hidden_repackaged, worker)
#Resize the output
output_viewed = output.view(-1, ntokens)
#Compute the loss
loss = criterion(output_viewed, targets_remote)
#Let's backpropagate over here!
loss.backward(hidden) 

However, I get the following error in the loss.backward(hidden) step:

image

image

DanyEle avatar Jul 12 '19 12:07 DanyEle

Perhaps no serialization mechanism are implemented for AutogradTensor objects? Not super sure.. I'm trying to look into it.

EDIT: After talking to @LaRiffle , it turns out that serialization is not yet implemented for AutogradTensor objects. So, I'm currently trying to implement serialization for it.

Thèo suggested that it should be sufficient to add proper simplify anddetail methods to the autograd.py and add AutogradTensor to to OBJ_SIMPLIFIER_AND_DETAILERS in serde.py

DanyEle avatar Jul 12 '19 12:07 DanyEle

I believe this should be a working implemenetation for the simplify and detail methods, but I get a missing gradient error during the backpropagation. Is there anything missing for the data being sent over? Like some part of the gradient?

from autograd.py

  @staticmethod
    def simplify(tensor: "AutogradTensor") -> tuple:
        """Takes the attributes of an AutogradTensor and saves them in a tuple.

        Args:
            tensor: an AutogradTensor.

        Returns:
            tuple: a tuple holding the unique attributes of the AutogradTensor.
        """
        print("Simplify AutogradTensor")
        chain = None
        #send the child over
        if hasattr(tensor, "child"):
            chain = syft.serde._simplify(tensor.child)

        return (
            tensor.owner,
            syft.serde._simplify(tensor.id),
            chain,
            tensor.requires_grad,
            tensor.preinitialize_grad,
            tensor.grad_fn,
            syft.serde._simplify(tensor.tags),
            syft.serde._simplify(tensor.description),
        )
        

    @staticmethod
    def detail(worker: AbstractTensor, tensor_tuple: tuple) -> "AutogradTensor":
        """
            This function reconstructs an AutogradTensors given its attributes in form of a tuple.
            Args:
                worker: the worker doing the deserialization
                tensor_tuple: a tuple holding the attributes of the AutogradTensor
            Returns:
                AutogradTensor: an AutogradTensor
            Examples:
                shared_tensor = detail(data)
            """
        print("Detail AutogradTensor")
        owner, tensor_id, chain, requires_grad, preinitialize_grad, grad_fn, tags, description = tensor_tuple

        
        if chain is not None:
            chain = syft.serde._detail(worker, chain)
            
    
        tensor = AutogradTensor(
            owner=owner,
            id=syft.serde._detail(worker, tensor_id),
            preinitialize_grad=preinitialize_grad,
            grad_fn = grad_fn,
            data = chain, #pass the de-serialized data
            tags = syft.serde._detail(worker, tags),
            description = syft.serde._detail(worker, description),
        )
        
        #tensor.child = chain

        return tensor
    

DanyEle avatar Jul 12 '19 14:07 DanyEle

I successfully managed to implement the serialization and deserialization procedures for AutogradTensor. Nevertheless, my issue with remote backpropagation using a custom class still persists, and a [0,0,0,..0] gradient is produced in all model's parameters.

DanyEle avatar Jul 14 '19 13:07 DanyEle

Moved issue to #2361

DanyEle avatar Jul 17 '19 06:07 DanyEle