Elffuss BraidHub

kikocis/ncnn public

master · 2.8 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
18from packaging import version
19
20class Model(nn.Module):
21 def __init__(self):
22 super(Model, self).__init__()
23
24 self.pool_0 = nn.MaxPool1d(kernel_size=3)
25 self.pool_1 = nn.MaxPool1d(kernel_size=4, stride=2, padding=2, dilation=1)
26 self.pool_2 = nn.MaxPool1d(kernel_size=3, stride=1, padding=1, dilation=1, return_indices=False, ceil_mode=False)
27 self.pool_3 = nn.MaxPool1d(kernel_size=5, stride=2, padding=2, dilation=1, return_indices=False, ceil_mode=True)
28 self.pool_4 = nn.MaxPool1d(kernel_size=3, stride=1, padding=1, dilation=2, return_indices=False, ceil_mode=False)
29 self.pool_5 = nn.MaxPool1d(kernel_size=2, stride=1, padding=0, dilation=1, return_indices=True, ceil_mode=True)
30 self.pool_6 = nn.MaxPool1d(kernel_size=5, stride=1, padding=2, dilation=1, return_indices=True, ceil_mode=False)
31
32 def forward(self, x, y):
33 x = self.pool_0(x)
34 x = self.pool_1(x)
35 x = self.pool_2(x)
36 x = self.pool_3(x)
37 x = self.pool_4(x)
38 x, tx = self.pool_5(x)
39 x, indices = self.pool_6(x)
40
41 y = self.pool_0(y)
42 y = self.pool_1(y)
43 y = self.pool_2(y)
44 y = self.pool_3(y)
45 y = self.pool_4(y)
46 if version.parse(torch.__version__) < version.parse('1.10'):
47 y = y.unsqueeze(0)
48 y, ty = self.pool_5(y)
49
50 return x, indices, y
51
52def test():
53 net = Model()
54 net.eval()
55
56 torch.manual_seed(0)
57 x = torch.rand(1, 12, 64)
58 y = torch.rand(12, 64)
59
60 a = net(x, y)
61
62 # export torchscript
63 mod = torch.jit.trace(net, (x, y))
64 mod.save("test_nn_MaxPool1d.pt")
65
66 # torchscript to pnnx
67 import os
68 os.system("../src/pnnx test_nn_MaxPool1d.pt inputshape=[1,12,64],[12,64]")
69
70 # pnnx inference
71 import test_nn_MaxPool1d_pnnx
72 b = test_nn_MaxPool1d_pnnx.test_inference()
73
74 for a0, b0 in zip(a, b):
75 if not torch.equal(a0, b0):
76 return False
77 return True
78
79if __name__ == "__main__":
80 if test():
81 exit(0)
82 else:
83 exit(1)