diff --git a/norch/__pycache__/tensor.cpython-38.pyc b/norch/__pycache__/tensor.cpython-38.pyc index e230121..77de118 100644 Binary files a/norch/__pycache__/tensor.cpython-38.pyc and b/norch/__pycache__/tensor.cpython-38.pyc differ diff --git a/norch/tensor.py b/norch/tensor.py index 633b8ae..91b6e2f 100644 --- a/norch/tensor.py +++ b/norch/tensor.py @@ -224,10 +224,34 @@ class Tensor: return result_data + def __radd__(self, other): + if isinstance(other, (int, float)): + other = other * self.ones_like() + + if self.shape != other.shape: + raise ValueError("Tensors must have the same shape for addition") + + Tensor._C.add_tensor.argtypes = [ctypes.POINTER(CTensor), ctypes.POINTER(CTensor)] + Tensor._C.add_tensor.restype = ctypes.POINTER(CTensor) + + result_tensor_ptr = Tensor._C.add_tensor(other.tensor, self.tensor) + + result_data = Tensor() + result_data.tensor = result_tensor_ptr + result_data.shape = self.shape.copy() + result_data.ndim = self.ndim + result_data.device = self.device + + result_data.requires_grad = self.requires_grad or other.requires_grad + if result_data.requires_grad: + result_data.grad_fn = AddBackward(other, self) + + return result_data + def __sub__(self, other): if isinstance(other, (int, float)): other = other * self.ones_like() - + if self.shape != other.shape: raise ValueError("Tensors must have the same shape for subtraction") @@ -248,6 +272,30 @@ class Tensor: return result_data + def __rsub__(self, other): + if isinstance(other, (int, float)): + other = other * self.ones_like() + + if self.shape != other.shape: + raise ValueError("Tensors must have the same shape for subtraction") + + Tensor._C.sub_tensor.argtypes = [ctypes.POINTER(CTensor), ctypes.POINTER(CTensor)] + Tensor._C.sub_tensor.restype = ctypes.POINTER(CTensor) + + result_tensor_ptr = Tensor._C.sub_tensor(other.tensor, self.tensor) + + result_data = Tensor() + result_data.tensor = result_tensor_ptr + result_data.shape = self.shape.copy() + result_data.ndim = self.ndim + result_data.device = self.device + + result_data.requires_grad = self.requires_grad or other.requires_grad + if result_data.requires_grad: + result_data.grad_fn = SubBackward(other, self) + + return result_data + def __mul__(self, other): if isinstance(other, (int, float)): result_data = Tensor() diff --git a/test.py b/test.py index e473a71..a490bd6 100644 --- a/test.py +++ b/test.py @@ -75,7 +75,7 @@ if __name__ == "__main__": [[19, 20], [21, 22], [23, 24]], [[25, 26], [27, 28], [29, 30]]], requires_grad=True) - result = 2 ** tensor1 + result = (-10) - tensor1 result = result.sum() result.backward() print(tensor1.grad)