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 torchvision
17import torchvision.models as models
18from packaging import version
19
20def test():
21 if version.parse(torchvision.__version__) < version.parse('0.12'):
22 return True
23
24 if version.parse(torch.__version__) >= version.parse('2.0') and version.parse(torch.__version__) < version.parse('2.1'):
25 return True
26
27 net = models.vit_b_32()
28 net.eval()
29
30 torch.manual_seed(0)
31 x = torch.rand(1, 3, 224, 224)
32
33 a = net(x)
34
35 # export onnx
36 torch.onnx.export(net, (x,), "test_vit_b_32.onnx")
37
38 # onnx to pnnx
39 import os
40 os.system("../../src/pnnx test_vit_b_32.onnx inputshape=[1,3,224,224]")
41
42 # pnnx inference
43 import test_vit_b_32_pnnx
44 b = test_vit_b_32_pnnx.test_inference()
45
46 if not torch.allclose(a, b, 1e-4, 1e-4):
47 return False
48
49 if version.parse(torch.__version__) < version.parse('2.5'):
50 return True
51
52 # export dynamo onnx
53 torch.onnx.dynamo_export(net, x).save("test_vit_b_32_dynamo.onnx")
54
55 # onnx to pnnx
56 os.system("../../src/pnnx test_vit_b_32_dynamo.onnx inputshape=[1,3,224,224]")
57
58 # pnnx inference
59 import test_vit_b_32_dynamo_pnnx
60 b = test_vit_b_32_dynamo_pnnx.test_inference()
61
62 return torch.allclose(a, b, 1e-4, 1e-4)
63
64if __name__ == "__main__":
65 if test():
66 exit(0)
67 else:
68 exit(1)