Elffuss BraidHub

kikocis/ncnn public

master · 3.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 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 if version.parse(torch.__version__) < version.parse('1.12'):
25 self.up_0 = nn.UpsamplingNearest2d(size=60)
26 self.up_1 = nn.UpsamplingNearest2d(scale_factor=2)
27 self.up_2 = nn.UpsamplingNearest2d(size=(40,40))
28 self.up_3 = nn.UpsamplingNearest2d(scale_factor=(4,4))
29 self.up_4 = nn.UpsamplingNearest2d(size=(60,40))
30 self.up_5 = nn.UpsamplingNearest2d(scale_factor=(2,3))
31 else:
32 self.up_0 = nn.UpsamplingNearest2d(size=16)
33 self.up_1 = nn.UpsamplingNearest2d(scale_factor=2)
34 self.up_2 = nn.UpsamplingNearest2d(size=(20,20))
35 self.up_3 = nn.UpsamplingNearest2d(scale_factor=(4,4))
36 self.up_4 = nn.UpsamplingNearest2d(size=(16,24))
37 self.up_5 = nn.UpsamplingNearest2d(scale_factor=(2,3))
38
39 self.up_w = nn.UpsamplingNearest2d(scale_factor=(2.976744,2.976744))
40
41 def forward(self, x, w):
42 if version.parse(torch.__version__) < version.parse('1.12'):
43 x0 = self.up_0(x)
44 x0 = self.up_1(x0)
45 x1 = self.up_2(x)
46 x1 = self.up_3(x1)
47 x2 = self.up_4(x)
48 x2 = self.up_5(x2)
49
50 w = self.up_w(w)
51 return x0, x1, x2, w
52 else:
53 x = self.up_0(x)
54 x = self.up_1(x)
55 x = self.up_2(x)
56 x = self.up_3(x)
57 x = self.up_4(x)
58 x = self.up_5(x)
59
60 w = self.up_w(w)
61 return x, w
62
63def test():
64 net = Model()
65 net.eval()
66
67 torch.manual_seed(0)
68 x = torch.rand(1, 3, 32, 32)
69 w = torch.rand(1, 8, 86, 86)
70
71 a = net(x, w)
72
73 # export onnx
74 torch.onnx.export(net, (x, w), "test_nn_UpsamplingNearest2d.onnx")
75
76 # onnx to pnnx
77 import os
78 os.system("../../src/pnnx test_nn_UpsamplingNearest2d.onnx inputshape=[1,3,32,32],[1,8,86,86]")
79
80 # pnnx inference
81 import test_nn_UpsamplingNearest2d_pnnx
82 b = test_nn_UpsamplingNearest2d_pnnx.test_inference()
83
84 for a0, b0 in zip(a, b):
85 if not torch.equal(a0, b0):
86 return False
87 return True
88
89if __name__ == "__main__":
90 if test():
91 exit(0)
92 else:
93 exit(1)