Elffuss BraidHub

kikocis/ncnn public

master · 2.5 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2022 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.pad_0 = nn.ConstantPad2d(2, 0.0)
24 self.pad_1 = nn.ReflectionPad2d(4)
25 self.pad_2 = nn.ReplicationPad2d(3)
26 self.pad_3 = nn.ZeroPad2d((1,1,0,0))
27
28 self.conv_0 = nn.Conv2d(in_channels=12, out_channels=14, kernel_size=3)
29 self.conv_1 = nn.Conv2d(in_channels=14, out_channels=14, kernel_size=1)
30 self.conv_2 = nn.Conv2d(in_channels=14, out_channels=14, kernel_size=2)
31 self.conv_3 = nn.Conv2d(in_channels=14, out_channels=12, kernel_size=3, padding=(1,1))
32
33 def forward(self, x):
34 x = self.pad_0(x)
35 x = F.pad(x, pad=(1,1))
36 x = self.conv_0(x)
37
38 x = self.pad_1(x)
39 x = self.conv_1(x)
40
41 x = F.pad(x, pad=(3,3,2,2), mode='reflect')
42 x = self.conv_1(x)
43
44 x = self.pad_2(x)
45 x = self.conv_2(x)
46
47 x = F.pad(x, pad=(1,1,1,1), mode='replicate')
48 x = self.conv_2(x)
49
50 x = self.pad_3(x)
51 x = F.pad(x, pad=(2,2,0,0))
52 x = self.conv_3(x)
53
54 return x
55
56def test():
57 net = Model()
58 net.eval()
59
60 torch.manual_seed(0)
61 x = torch.rand(1, 12, 13, 13)
62
63 a = net(x)
64
65 # export torchscript
66 mod = torch.jit.trace(net, x)
67 mod.save("test_pnnx_pnnx_fuse_pad_conv2d.pt")
68
69 # torchscript to pnnx
70 import os
71 os.system("../src/pnnx test_pnnx_pnnx_fuse_pad_conv2d.pt inputshape=[1,12,13,13]")
72
73 # pnnx inference
74 import test_pnnx_pnnx_fuse_pad_conv2d_pnnx
75 b = test_pnnx_pnnx_fuse_pad_conv2d_pnnx.test_inference()
76
77 for a0, b0 in zip(a, b):
78 if not torch.equal(a0, b0):
79 return False
80 return True
81
82if __name__ == "__main__":
83 if test():
84 exit(0)
85 else:
86 exit(1)