Fix radd rsub
This commit is contained in:
parent
065c6a0f29
commit
6445563268
3 changed files with 50 additions and 2 deletions
Binary file not shown.
|
|
@ -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()
|
||||
|
|
|
|||
2
test.py
2
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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue