Elffuss BraidHub

kikocis/ncnn public

master · 1.8 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2023 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 def forward(self, x, y, z):
24 out0 = torch.narrow(x, 0, 0, 2)
25 out1 = torch.narrow(x, 1, 1, 2)
26 out2 = torch.narrow(y, 0, 0, 2)
27 out3 = torch.narrow(y, 1, 1, 2)
28 out4 = torch.narrow(z, 0, 0, 2)
29 out5 = torch.narrow(z, 1, 1, 2)
30 return out0, out1, out2, out3, out4, out5
31
32def test():
33 net = Model()
34 net.eval()
35
36 torch.manual_seed(0)
37 x = torch.rand(3, 3)
38 y = torch.rand(5, 3)
39 z = torch.rand(3, 5)
40 a = net(x, y, z)
41
42 # export torchscript
43 mod = torch.jit.trace(net, (x, y, z))
44 mod.save("test_torch_narrow.pt")
45
46 # torchscript to pnnx
47 import os
48 os.system("../src/pnnx test_torch_narrow.pt inputshape=[3,3],[5,3],[3,5]")
49
50 # pnnx inference
51 import test_torch_narrow_pnnx
52 b = test_torch_narrow_pnnx.test_inference()
53
54 for a0, b0 in zip(a, b):
55 if not torch.equal(a0, b0):
56 return False
57 return True
58
59if __name__ == "__main__":
60 if test():
61 exit(0)
62 else:
63 exit(1)