Skip to content
Merged
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
9 changes: 9 additions & 0 deletions pytensor/link/pytorch/dispatch/scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from pytensor.link.pytorch.dispatch.basic import pytorch_funcify
from pytensor.scalar.basic import (
Cast,
Clip,
Invert,
ScalarOp,
)
Expand Down Expand Up @@ -71,6 +72,14 @@ def pytorch_funcify_Softplus(op, node, **kwargs):
return torch.nn.Softplus()


@pytorch_funcify.register(Clip)
def pytorch_funcify_Clip(op, node, **kwargs):
def clip(x, min_val, max_val):
return torch.where(x < min_val, min_val, torch.where(x > max_val, max_val, x))

return clip


@pytorch_funcify.register(ScalarLoop)
def pytorch_funicify_ScalarLoop(op, node, **kwargs):
update = pytorch_funcify(op.fgraph, **kwargs)
Expand Down
13 changes: 13 additions & 0 deletions tests/link/pytorch/test_elemwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,19 @@ def test_cast():
assert res.dtype == np.int32


@pytest.mark.parametrize(
"x_val, min_val, max_val",
[
(np.array([5.0], dtype=config.floatX), 0.0, 10.0),
(np.array([-5.0], dtype=config.floatX), 0.0, 10.0),
],
)
def test_clip(x_val, min_val, max_val):
x = pt.tensor("x", shape=x_val.shape, dtype=config.floatX)
out = pt.clip(x, min_val, max_val)
compare_pytorch_and_py([x], [out], [x_val])


def test_vmap_elemwise():
from pytensor.link.pytorch.dispatch.basic import pytorch_funcify

Expand Down
Loading