Elffuss BraidHub

kikocis/ncnn public

master · 2.4 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2023 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
20class Model(nn.Module):
21 def __init__(self):
22 super(Model, self).__init__()
23
24 self.w0 = nn.Parameter(torch.rand(12, 15))
25 self.w1 = nn.Parameter(torch.rand(12, 15))
26 self.w2 = nn.Parameter(torch.rand(12, 15))
27 self.w3 = nn.Parameter(torch.rand(12, 15))
28 self.w4 = nn.Parameter(torch.rand(12, 15))
29 self.w5 = nn.Parameter(torch.rand(12, 15))
30 self.c0 = nn.Parameter(torch.ones(1))
31 self.c1 = nn.Parameter(torch.ones(3) + 0.2)
32
33 def forward(self, x):
34 c10, c11, _ = torch.unbind(self.c1)
35 x0 = x * 10 + self.c0 - c11
36 x = x + self.w0 + x0
37 x = x - self.w1 + x0.float()
38 x = x * self.w2 + x0
39 x = x / self.w3 + x0
40 x = x // self.w4 + x0
41 if version.parse(torch.__version__) >= version.parse('2.0'):
42 x = x % self.w5 + x0
43 else:
44 x = torch.fmod(x, self.w5) + x0
45 y = x.int()
46 return x, y & 3, y | 3, y ^ 3, y << 3, y >> 3
47
48def test():
49 net = Model()
50 net.eval()
51
52 torch.manual_seed(0)
53 x = torch.rand(12, 15)
54
55 a = net(x)
56
57 # export torchscript
58 mod = torch.jit.trace(net, x)
59 mod.save("test_pnnx_expression.pt")
60
61 # torchscript to pnnx
62 import os
63 os.system("../src/pnnx test_pnnx_expression.pt inputshape=[12,15]")
64
65 # pnnx inference
66 import test_pnnx_expression_pnnx
67 b = test_pnnx_expression_pnnx.test_inference()
68
69 for a0, b0 in zip(a, b):
70 if not torch.equal(a0, b0):
71 return False
72 return True
73
74if __name__ == "__main__":
75 if test():
76 exit(0)
77 else:
78 exit(1)