Elffuss BraidHub

kikocis/ncnn public

master · 2.0 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 mish_forward_0(x):
21 return x * F.softplus(x).tanh()
22
23def mish_forward_1(x):
24 return x.mul(torch.tanh(F.softplus(x)))
25
26class Model(nn.Module):
27 def __init__(self):
28 super(Model, self).__init__()
29
30 def forward(self, x, y, z, w):
31 x = x * 2 - 1
32 y = y * 2 - 1
33 z = z * 2 - 1
34 w = w * 2 - 1
35 x = F.mish(x)
36 y = F.mish(y)
37 z = mish_forward_0(z)
38 w = mish_forward_1(w)
39 return x, y, z, w
40
41def test():
42 if version.parse(torch.__version__) < version.parse('1.9'):
43 return True
44
45 net = Model()
46 net.eval()
47
48 torch.manual_seed(0)
49 x = torch.rand(1, 16)
50 y = torch.rand(12, 2, 16)
51 z = torch.rand(1, 3, 12, 16)
52 w = torch.rand(1, 5, 7, 9, 11)
53
54 a = net(x, y, z, w)
55
56 # export onnx
57 torch.onnx.export(net, (x, y, z, w), "test_F_mish.onnx")
58
59 # onnx to pnnx
60 import os
61 os.system("../../src/pnnx test_F_mish.onnx inputshape=[1,16],[12,2,16],[1,3,12,16],[1,5,7,9,11]")
62
63 # pnnx inference
64 import test_F_mish_pnnx
65 b = test_F_mish_pnnx.test_inference()
66
67 for a0, b0 in zip(a, b):
68 if not torch.allclose(a0, b0, 1e-4, 1e-4):
69 return False
70 return True
71
72if __name__ == "__main__":
73 if test():
74 exit(0)
75 else:
76 exit(1)