unify negative shape creation to raise ValueError (#5817)

[run_process_replay]
This commit is contained in:
chenyu
2024-07-30 13:42:59 -04:00
committed by GitHub
parent 6742a4789a
commit defd89e8e0
3 changed files with 12 additions and 11 deletions
+10 -10
View File
@@ -113,24 +113,24 @@ class TestOps(unittest.TestCase):
]
for method in creation_methods:
with self.assertRaises(RuntimeError): method(-3, 2)
with self.assertRaises(RuntimeError): method((2, -3))
with self.assertRaises(RuntimeError): method((2, -3, 0))
with self.assertRaises(ValueError): method(-3, 2)
with self.assertRaises(ValueError): method((2, -3))
with self.assertRaises(ValueError): method((2, -3, 0))
def test_negative_dims_full(self):
with self.assertRaises(RuntimeError): Tensor.full(-3, 2)
with self.assertRaises(RuntimeError): Tensor.full((2, -3), 4)
with self.assertRaises(RuntimeError): Tensor.full((2, -3, 0), 4)
with self.assertRaises(ValueError): Tensor.full(-3, 2)
with self.assertRaises(ValueError): Tensor.full((2, -3), 4)
with self.assertRaises(ValueError): Tensor.full((2, -3, 0), 4)
def test_negative_dims_eye(self):
with self.assertRaises(RuntimeError): Tensor.eye(-3, 3)
with self.assertRaises(AssertionError): Tensor.eye(3, -3)
with self.assertRaises(RuntimeError): Tensor.eye(-3, -3)
with self.assertRaises(ValueError): Tensor.eye(-3, 3)
with self.assertRaises(ValueError): Tensor.eye(3, -3)
with self.assertRaises(ValueError): Tensor.eye(-3, -3)
def test_negative_dims_kaiming(self):
creation_methods = [Tensor.kaiming_uniform, Tensor.kaiming_normal]
for method in creation_methods:
with self.assertRaises(RuntimeError): method(-3, 3)
with self.assertRaises(ValueError): method(-3, 3)
with self.assertRaises(ValueError): method((-3, 3), 3)
with self.assertRaises(ValueError): method((-3, -3), 3)
+1 -1
View File
@@ -99,7 +99,7 @@ class View:
@staticmethod
@functools.lru_cache(maxsize=None)
def create(shape:Tuple[sint, ...], strides:Optional[Tuple[sint, ...]]=None, offset:sint=0, mask:Optional[Tuple[Tuple[sint, sint], ...]]=None):
if not all(s >= 0 for s in shape): raise RuntimeError(f"Trying to create View with negative dimension: {shape=}")
if not all(s >= 0 for s in shape): raise ValueError(f"Trying to create View with negative dimension: {shape=}")
strides = canonicalize_strides(shape, strides) if strides else strides_for_shape(shape)
# canonicalize 0 in shape
if 0 in shape: return View(shape, (0,) * len(shape), offset=0, mask=None, contiguous=True)
+1
View File
@@ -525,6 +525,7 @@ class Tensor:
print(Tensor.eye(2, 4).numpy())
```
"""
if n < 0 or (m is not None and m < 0): raise ValueError(f"cannot have negative {n=}, {m=}")
return Tensor.ones((n,1),**kwargs).pad((None,(0,n))).flatten().shrink(((0,n*n),)).reshape(n,n)._slice((None,(0,n if m is None else m)))
def full_like(self, fill_value:ConstType, **kwargs):