Elffuss BraidHub

kikocis/ncnn public

master · 2.1 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 def forward(self, x, y, z, w):
24 x = x.clone()
25 y = y.clone()
26 z = z.clone()
27 w = w.clone()
28 xx = x[8]
29 x[2:10,...] += 1
30 xx[...,1] = xx[...,-1] * 3
31 x1 = x.clone()
32 xxx = x[2:-1,11,...]
33 x[:,:,3,::2].clamp_(0, 0.5)
34 xx[:,3,::2] = xx[:,4,1::2].exp_()
35 x[:,:,::2,:] = x1[:,:,::2,:].pow(2)
36 xxx[:,:,:] /= 2
37 y[...,-1,-5:-1] = y[...,-4,1:5] - 11
38 z[:1] = z[-1:] * z[3:4]
39 w[80::2] = w[4:84:4] + 23
40 return x, y, z, w
41
42def test():
43 net = Model()
44 net.eval()
45
46 torch.manual_seed(0)
47 x = torch.rand(18, 15, 19, 20)
48 y = torch.rand(15, 19, 20)
49 z = torch.rand(19, 20)
50 w = torch.rand(120)
51
52 a = net(x, y, z, w)
53
54 # export torchscript
55 mod = torch.jit.trace(net, (x, y, z, w))
56 mod.save("test_Tensor_slice_copy.pt")
57
58 # torchscript to pnnx
59 import os
60 os.system("../src/pnnx test_Tensor_slice_copy.pt inputshape=[18,15,19,20],[15,19,20],[19,20],[120]")
61
62 # pnnx inference
63 import test_Tensor_slice_copy_pnnx
64 b = test_Tensor_slice_copy_pnnx.test_inference()
65
66 for a0, b0 in zip(a, b):
67 if not torch.equal(a0, b0):
68 return False
69 return True
70
71if __name__ == "__main__":
72 if test():
73 exit(0)
74 else:
75 exit(1)