Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions leanpass/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ def __rmul__(self, other):

def __truediv__(self, other):
other = other if isinstance(other, Tensor) else Tensor(other)
if np.any(other.data == 0):
raise ZeroDivisionError("Tensor division by zero")
out = self._create_child(self.data / other.data, "/", (self, other))

def _backward():
Expand Down
8 changes: 8 additions & 0 deletions tests/test_leanpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,11 @@ def test_tensor_gelu_backward():
assert x.grad.shape == x.data.shape
assert np.all(np.isfinite(x.grad))
assert np.all(x.grad != 0)


def test_truediv_raises_on_zero_divisor():
import pytest
x = Tensor([1.0, 2.0], requires_grad=True)
y = Tensor([1.0, 0.0], requires_grad=False)
with pytest.raises(ZeroDivisionError):
_ = x / y