|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +# pyre-unsafe |
| 8 | + |
| 9 | + |
| 10 | +import torch |
| 11 | +from executorch.backends.test.suite.flow import TestFlow |
| 12 | + |
| 13 | +from executorch.backends.test.suite.operators import ( |
| 14 | + dtype_test, |
| 15 | + operator_test, |
| 16 | + OperatorTest, |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +class ClampModel(torch.nn.Module): |
| 21 | + def __init__(self, min_val=None, max_val=None): |
| 22 | + super().__init__() |
| 23 | + self.min_val = min_val |
| 24 | + self.max_val = max_val |
| 25 | + |
| 26 | + def forward(self, x): |
| 27 | + return torch.clamp(x, min=self.min_val, max=self.max_val) |
| 28 | + |
| 29 | + |
| 30 | +@operator_test |
| 31 | +class TestClamp(OperatorTest): |
| 32 | + @dtype_test |
| 33 | + def test_clamp_dtype(self, flow: TestFlow, dtype) -> None: |
| 34 | + # Test with different dtypes |
| 35 | + model = ClampModel(min_val=-0.5, max_val=0.5).to(dtype) |
| 36 | + self._test_op(model, (torch.rand(10, 10).to(dtype) * 2 - 1,), flow) |
| 37 | + |
| 38 | + def test_clamp_min_only(self, flow: TestFlow) -> None: |
| 39 | + # Test with only min value specified |
| 40 | + self._test_op(ClampModel(min_val=0.0), (torch.randn(10, 10),), flow) |
| 41 | + |
| 42 | + def test_clamp_max_only(self, flow: TestFlow) -> None: |
| 43 | + # Test with only max value specified |
| 44 | + self._test_op(ClampModel(max_val=0.0), (torch.randn(10, 10),), flow) |
| 45 | + |
| 46 | + def test_clamp_shapes(self, flow: TestFlow) -> None: |
| 47 | + # Test with different tensor shapes |
| 48 | + model = ClampModel(min_val=-1.0, max_val=1.0) |
| 49 | + |
| 50 | + # 1D tensor |
| 51 | + self._test_op(model, (torch.randn(20),), flow) |
| 52 | + |
| 53 | + # 2D tensor |
| 54 | + self._test_op(model, (torch.randn(5, 10),), flow) |
| 55 | + |
| 56 | + # 3D tensor |
| 57 | + self._test_op(model, (torch.randn(3, 4, 5),), flow) |
| 58 | + |
| 59 | + def test_clamp_edge_cases(self, flow: TestFlow) -> None: |
| 60 | + # Test edge cases |
| 61 | + |
| 62 | + # Min equals max |
| 63 | + self._test_op( |
| 64 | + ClampModel(min_val=0.0, max_val=0.0), (torch.randn(10, 10),), flow |
| 65 | + ) |
| 66 | + |
| 67 | + # Tensor with infinity |
| 68 | + x = torch.tensor([float("inf"), float("-inf"), 1.0, -1.0]) |
| 69 | + self._test_op( |
| 70 | + ClampModel(min_val=-2.0, max_val=2.0), |
| 71 | + (x,), |
| 72 | + flow, |
| 73 | + generate_random_test_inputs=False, |
| 74 | + ) |
| 75 | + |
| 76 | + # Tensor with NaN |
| 77 | + x = torch.tensor([float("nan"), 1.0, -1.0]) |
| 78 | + self._test_op( |
| 79 | + ClampModel(min_val=-2.0, max_val=2.0), |
| 80 | + (x,), |
| 81 | + flow, |
| 82 | + generate_random_test_inputs=False, |
| 83 | + ) |
0 commit comments