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) 2021 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
18import torchvision
19
20class Model(nn.Module):
21 def __init__(self):
22 super(Model, self).__init__()
23
24 self.conv_0 = nn.Conv2d(in_channels=12, out_channels=2*3*3, kernel_size=3)
25 self.conv_1 = torchvision.ops.DeformConv2d(in_channels=12, out_channels=16, kernel_size=3)
26
27 self.conv_2 = nn.Conv2d(in_channels=12, out_channels=3*3, kernel_size=3)
28 self.conv_3 = torchvision.ops.DeformConv2d(in_channels=12, out_channels=16, kernel_size=3)
29
30 def forward(self, x):
31 offset = self.conv_0(x)
32 x1 = self.conv_1(x, offset)
33
34 mask = F.sigmoid(self.conv_2(x))
35 x2 = self.conv_3(x, offset, mask)
36 return x1, x2
37
38def test():
39 net = Model()
40 net.eval()
41
42 torch.manual_seed(0)
43 x = torch.rand(1, 12, 64, 64)
44
45 a0, a1 = net(x)
46
47 # export torchscript
48 mod = torch.jit.trace(net, x)
49 mod.save("test_torchvision_DeformConv2d.pt")
50
51 # torchscript to pnnx
52 import os
53 os.system("../src/pnnx test_torchvision_DeformConv2d.pt inputshape=[1,12,64,64]")
54
55 # pnnx inference
56 import test_torchvision_DeformConv2d_pnnx
57 b0, b1 = test_torchvision_DeformConv2d_pnnx.test_inference()
58
59 return torch.equal(a0, b0) and torch.equal(a1, b1)
60
61if __name__ == "__main__":
62 if test():
63 exit(0)
64 else:
65 exit(1)