Repository: openmined/pysyft
Issue: Garbage Collection issue with in-place methods on tensors

This triggers a KeyError. I suspect unexpected garbage collection.
```
buf = torch.tensor([[1., 2], [4., 2]]).send(bob)
buf.add_(buf)
buf.get()
```

Changed files:
syft/frameworks/torch/hook.py, syft/frameworks/torch/torch_attributes.py, syft/workers/base.py, test/torch/tensors/test_gc.py

diff --git a/syft/frameworks/torch/hook.py b/syft/frameworks/torch/hook.py
index 33ecd0c23..dc07585bf 100644
--- a/syft/frameworks/torch/hook.py
+++ b/syft/frameworks/torch/hook.py
@@ -524,7 +524,7 @@ class TorchHook:
 
         return overloaded_syft_method
 
-    def get_hooked_method(hook_self, attr):
+    def get_hooked_method(hook_self, method_name):
         """
         Hook a method in order to replace all args/kwargs syft/torch tensors with
         their child attribute if they exist
@@ -535,45 +535,47 @@ class TorchHook:
         :return: the hooked method
         """
 
-        @wraps(attr)
+        @wraps(method_name)
         def overloaded_native_method(self, *args, **kwargs):
             """
             Operate the hooking
             """
 
             if not hasattr(self, "child"):  # means that it's not a wrapper
-                cmd = getattr(self, f"native_{attr}")
+                method = getattr(self, f"native_{method_name}")
                 # Run the native function with the new args
 
                 try:
-
                     if isinstance(args, tuple):
-                        response = cmd(*args)
+                        response = method(*args)
                     else:
-                        response = cmd(args)
+                        response = method(args)
 
                 except BaseException as e:
                     # we can make some errors more descriptive with this method
                     raise route_method_exception(e, self, args, kwargs)
 
             else:  # means that there is a wrapper to remove
-
                 try:
                     # Replace all torch tensor with their child attribute
                     new_self, new_args = syft.frameworks.torch.hook_args.hook_method_args(
-                        attr, self, args
+                        method_name, self, args
                     )
                 except BaseException as e:
                     # we can make some errors more descriptive with this method
                     raise route_method_exception(e, self, args, kwargs)
 
                 # Send the new command to the appropriate class and get the response
-                cmd = getattr(new_self, attr)
-                response = cmd(*new_args, **kwargs)
+                method = getattr(new_self, method_name)
+                response = method(*new_args, **kwargs)
+
+                # For inplace methods, just directly return self
+                if syft.torch.is_inplace_method(method_name):
+                    return self
 
                 # Put back the wrappers where needed
                 response = syft.frameworks.torch.hook_args.hook_response(
-                    attr, response, wrap_type=type(self), new_self=self
+                    method_name, response, wrap_type=type(self), new_self=self
                 )
 
             return response
diff --git a/syft/frameworks/torch/torch_attributes.py b/syft/frameworks/torch/torch_attributes.py
index a6f40857c..f8fb47ae2 100644
--- a/syft/frameworks/torch/torch_attributes.py
+++ b/syft/frameworks/torch/torch_attributes.py
@@ -112,7 +112,6 @@ class TorchAttributes(object):
             "is_tensor",
             "isfinite",
             "load",
-            "zeros_like",
             "randperm",
         ]
 
@@ -159,6 +158,9 @@ class TorchAttributes(object):
 
         self.command_guard = self._command_guard
 
+        # Dict {method_name: <is_inplace:bool>
+        self.inplace_methods = {}
+
     def _command_guard(
         self, command: str, torch_domain: str, get_native: bool = False
     ) -> Union[Callable[..., Any], str]:
@@ -232,6 +234,19 @@ class TorchAttributes(object):
         native_func_name = ".".join(parts)
         return native_func_name
 
+    def is_inplace_method(self, method_name):
+        """
+        Says if a method is inplace or not by test if it ends by _ and is not a __xx__
+        :param method_name: the name for the method
+        :return: boolean
+        """
+        try:
+            return self.inplace_methods[method_name]
+        except KeyError:
+            is_inplace = method_name[-1] == "_" and "__" not in method_name
+            self.inplace_methods[method_name] = is_inplace
+            return is_inplace
+
     @staticmethod
     def apply_fix16922(torch):
         """
diff --git a/syft/workers/base.py b/syft/workers/base.py
index 34544bb22..6cfe768a1 100644
--- a/syft/workers/base.py
+++ b/syft/workers/base.py
@@ -264,8 +264,11 @@ class BaseWorker(AbstractWorker):
         command = command.decode("utf-8")
         # Handle methods
         if _self is not None:
-
-            tensor = getattr(_self, command)(*args, **kwargs)
+            if sy.torch.is_inplace_method(command):
+                getattr(_self, command)(*args, **kwargs)
+                return
+            else:
+                tensor = getattr(_self, command)(*args, **kwargs)
         # Handle functions
         else:
             # At this point, the command is ALWAYS a path to a
@@ -304,7 +307,6 @@ class BaseWorker(AbstractWorker):
                 ptr_id=tensor.id,
                 garbage_collect_data=False,
             )
-
             return pointer
 
     def send_command(self, recipient, message):
diff --git a/test/torch/tensors/test_gc.py b/test/torch/tensors/test_gc.py
index 43b61f980..6724682b3 100644
--- a/test/torch/tensors/test_gc.py
+++ b/test/torch/tensors/test_gc.py
@@ -132,6 +132,18 @@ def test_implicit_garbage_collect_double_pointer(workers):
     # assert x.id not in workers["alice"]._objects
 
 
+# TESTING IN PLACE METHODS
+
+
+def test_inplace_method_on_pointer(workers):
+    bob = workers["bob"]
+    tensor = torch.tensor([[1.0, 2], [4.0, 2]])
+    pointer = tensor.send(bob)
+    pointer.add_(pointer)
+    tensor_back = pointer.get()
+    assert (tensor * 2 == tensor_back).all()
+
+
 # TESTING LOGGING TENSORS