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) 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
18
19class Model(nn.Module):
20 def __init__(self):
21 super(Model, self).__init__()
22
23 self.act_0 = nn.LogSoftmax(dim=1)
24 self.act_1 = nn.LogSoftmax(dim=1)
25 self.act_2 = nn.LogSoftmax(dim=0)
26 self.act_3 = nn.LogSoftmax(dim=2)
27
28 def forward(self, x, y, z, w):
29 x = x * 2 - 1
30 y = y * 2 - 1
31 z = z * 2 - 1
32 w = w * 2 - 1
33 x = self.act_0(x)
34 y = self.act_1(y)
35 z = self.act_2(z)
36 w = self.act_3(w)
37 return x, y, z, w
38
39def test():
40 net = Model()
41 net.eval()
42
43 torch.manual_seed(0)
44 x = torch.rand(1, 12)
45 y = torch.rand(1, 12, 64)
46 z = torch.rand(1, 12, 24, 64)
47 w = torch.rand(1, 12, 24, 32, 64)
48
49 a0, a1, a2, a3 = net(x, y, z, w)
50
51 # export torchscript
52 mod = torch.jit.trace(net, (x, y, z, w))
53 mod.save("test_nn_LogSoftmax.pt")
54
55 # torchscript to pnnx
56 import os
57 os.system("../src/pnnx test_nn_LogSoftmax.pt inputshape=[1,12],[1,12,64],[1,12,24,64],[1,12,24,32,64]")
58
59 # pnnx inference
60 import test_nn_LogSoftmax_pnnx
61 b0, b1, b2, b3 = test_nn_LogSoftmax_pnnx.test_inference()
62
63 return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2) and torch.equal(a3, b3)
64
65if __name__ == "__main__":
66 if test():
67 exit(0)
68 else:
69 exit(1)