Elffuss BraidHub

kikocis/ncnn public

master · 2.3 KiBRawPermalink
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
15import torch
16import torch.nn as nn
17import torch.nn.functional as F
18from packaging import version
19
20def hardswish_forward_0(x):
21 return x * F.hardsigmoid(x)
22
23def hardswish_forward_1(x):
24 return x * F.hardtanh(x + 3, 0., 6.) / 6.
25
26def hardswish_forward_2(x):
27 out = F.relu6(x + 3., True) / 6.
28 return out * x
29
30def hardswish_forward_3(x):
31 return x * F.relu6(x + 3, inplace=True) / 6
32
33class Model(nn.Module):
34 def __init__(self):
35 super(Model, self).__init__()
36
37 def forward(self, x, y, z, w):
38 x = x * 2 - 1
39 y = y * 2 - 1
40 z = z * 2 - 1
41 w = w * 2 - 1
42 x = F.hardswish(x)
43 y = hardswish_forward_0(y)
44 z = hardswish_forward_1(z)
45 w = hardswish_forward_2(w)
46 w = hardswish_forward_3(w)
47 return x, y, z, w
48
49def test():
50 if version.parse(torch.__version__) < version.parse('1.10'):
51 return True
52
53 net = Model()
54 net.eval()
55
56 torch.manual_seed(0)
57 x = torch.rand(1, 16)
58 y = torch.rand(12, 2, 16)
59 z = torch.rand(1, 3, 12, 16)
60 w = torch.rand(1, 5, 7, 9, 11)
61
62 a = net(x, y, z, w)
63
64 # export onnx
65 torch.onnx.export(net, (x, y, z, w), "test_F_hardswish.onnx")
66
67 # onnx to pnnx
68 import os
69 os.system("../../src/pnnx test_F_hardswish.onnx inputshape=[1,16],[12,2,16],[1,3,12,16],[1,5,7,9,11]")
70
71 # pnnx inference
72 import test_F_hardswish_pnnx
73 b = test_F_hardswish_pnnx.test_inference()
74
75 for a0, b0 in zip(a, b):
76 if not torch.allclose(a0, b0, 1e-4, 1e-4):
77 return False
78 return True
79
80if __name__ == "__main__":
81 if test():
82 exit(0)
83 else:
84 exit(1)