| 1 | # Tencent is pleased to support the open source community by making ncnn available. |
| 2 | # |
| 3 | # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | # |
| 5 | # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 6 | # in compliance with the License. You may obtain a copy of the License at |
| 7 | # |
| 8 | # https://opensource.org/licenses/BSD-3-Clause |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software distributed |
| 11 | # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | # specific language governing permissions and limitations under the License. |
| 14 | |
| 15 | import torch |
| 16 | import torch.nn as nn |
| 17 | import torch.nn.functional as F |
| 18 | from packaging import version |
| 19 | |
| 20 | def hardsigmoid_forward_0(x): |
| 21 | return F.relu6(x + 3., True) / 6. |
| 22 | |
| 23 | def hardsigmoid_forward_1(x): |
| 24 | return x.add_(3.).clamp_(0., 6.).div_(6.) |
| 25 | |
| 26 | class h_sigmoid(nn.Module): |
| 27 | def __init__(self, inplace=True): |
| 28 | super(h_sigmoid, self).__init__() |
| 29 | self.relu = nn.ReLU6(inplace=inplace) |
| 30 | |
| 31 | def forward(self, x): |
| 32 | return self.relu(x + 3) / 6 |
| 33 | |
| 34 | class Model(nn.Module): |
| 35 | def __init__(self): |
| 36 | super(Model, self).__init__() |
| 37 | |
| 38 | self.h_sigmoid = h_sigmoid(); |
| 39 | |
| 40 | def forward(self, x, y, z, w): |
| 41 | x = x * 2 - 1 |
| 42 | y = y * 2 - 1 |
| 43 | z = z * 2 - 1 |
| 44 | w = w * 2 - 1 |
| 45 | x = F.hardsigmoid(x) |
| 46 | y = F.hardsigmoid(y) |
| 47 | z = self.h_sigmoid(z) |
| 48 | w = hardsigmoid_forward_0(w) |
| 49 | w = hardsigmoid_forward_1(w) |
| 50 | return x, y, z, w |
| 51 | |
| 52 | def test(): |
| 53 | if version.parse(torch.__version__) < version.parse('1.10'): |
| 54 | return True |
| 55 | |
| 56 | net = Model() |
| 57 | net.eval() |
| 58 | |
| 59 | torch.manual_seed(0) |
| 60 | x = torch.rand(1, 16) |
| 61 | y = torch.rand(12, 2, 16) |
| 62 | z = torch.rand(1, 3, 12, 16) |
| 63 | w = torch.rand(1, 5, 7, 9, 11) |
| 64 | |
| 65 | a = net(x, y, z, w) |
| 66 | |
| 67 | # export onnx |
| 68 | torch.onnx.export(net, (x, y, z, w), "test_F_hardsigmoid.onnx") |
| 69 | |
| 70 | # onnx to pnnx |
| 71 | import os |
| 72 | os.system("../../src/pnnx test_F_hardsigmoid.onnx inputshape=[1,16],[12,2,16],[1,3,12,16],[1,5,7,9,11]") |
| 73 | |
| 74 | # pnnx inference |
| 75 | import test_F_hardsigmoid_pnnx |
| 76 | b = test_F_hardsigmoid_pnnx.test_inference() |
| 77 | |
| 78 | for a0, b0 in zip(a, b): |
| 79 | if not torch.allclose(a0, b0, 1e-4, 1e-4): |
| 80 | return False |
| 81 | return True |
| 82 | |
| 83 | if __name__ == "__main__": |
| 84 | if test(): |
| 85 | exit(0) |
| 86 | else: |
| 87 | exit(1) |