Elffuss BraidHub

kikocis/ncnn public

master · 2.1 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2021 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 torchscript
57 mod = torch.jit.trace(net, (x, y, z, w))
58 mod.save("test_F_mish.pt")
59
60 # torchscript to pnnx
61 import os
62 os.system("../src/pnnx test_F_mish.pt inputshape=[1,16],[12,2,16],[1,3,12,16],[1,5,7,9,11]")
63
64 # pnnx inference
65 import test_F_mish_pnnx
66 b = test_F_mish_pnnx.test_inference()
67
68 for a0, b0 in zip(a, b):
69 if not torch.allclose(a0, b0, 1e-4, 1e-4):
70 return False
71 return True
72
73if __name__ == "__main__":
74 if test():
75 exit(0)
76 else:
77 exit(1)