support passing None to Tensor.clip (#5319)

passing None for no upper bound or no lower bound
This commit is contained in:
chenyu
2024-07-07 13:04:22 -04:00
committed by GitHub
parent 296a1a36bb
commit 2029cb7047
2 changed files with 9 additions and 3 deletions

View File

@@ -1698,7 +1698,10 @@ class TestOps(unittest.TestCase):
helper_test_op([(45,65)], lambda x: x.clip(10, 100))
helper_test_op([(45,65)], lambda x: x.clip(0, 0.1))
helper_test_op([(45,65)], lambda x: x.clip(-0.3, -0.2))
helper_test_op([(45,65)], lambda x: x.clip(3, 0))
helper_test_op([(45,65)], lambda x: x.clip(3, 0)) # min > max
helper_test_op([(45,65)], lambda x: x.clip(None, 0))
helper_test_op([(45,65)], lambda x: x.clip(0, None))
self.helper_test_exception([(45,65)], lambda x: x.clip(None, None), lambda x: x.clip(None, None), RuntimeError)
def test_matvecmat(self):
helper_test_op([(1,128), (128,128), (128,128)], lambda x,y,z: (x@y).relu()@z)

View File

@@ -2063,15 +2063,18 @@ class Tensor:
```
"""
return self*self
def clip(self, min_, max_):
def clip(self, min_=None, max_=None):
"""
Clips (clamps) the values in the tensor between `min_` and `max_` element-wise.
If `min_` is `None`, there is no lower bound. If `max_` is None, there is no upper bound.
```python exec="true" source="above" session="tensor" result="python"
print(Tensor([-3., -2., -1., 0., 1., 2., 3.]).clip(-1, 1).numpy())
```
"""
return self.maximum(min_).minimum(max_)
if min_ is None and max_ is None: raise RuntimeError("at least one of 'min_' or 'max_' must not be None")
ret = self.maximum(min_) if min_ is not None else self
return ret.minimum(max_) if max_ is not None else ret
def sign(self):
"""
Returns the sign of the tensor element-wise.