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