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) 2024 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 def forward(self, x, y, z):
25 if version.parse(torch.__version__) >= version.parse('1.13') and version.parse(torch.__version__) < version.parse('2.0'):
26 out0 = torch.slice_scatter(x, y, start=6, step=1)
27 else:
28 out0 = torch.slice_scatter(x, y, start=6)
29 out1 = torch.slice_scatter(x, z, dim=1, start=2, end=6, step=2)
30 return out0, out1
31
32def test():
33 if version.parse(torch.__version__) < version.parse('1.11'):
34 return True
35
36 net = Model()
37 net.eval()
38
39 torch.manual_seed(0)
40 x = torch.rand(8, 8)
41 y = torch.rand(2, 8)
42 z = torch.rand(8, 2)
43
44 a = net(x, y, z)
45
46 # export torchscript
47 mod = torch.jit.trace(net, (x, y, z))
48 mod.save("test_torch_slice_scatter.pt")
49
50 # torchscript to pnnx
51 import os
52 os.system("../src/pnnx test_torch_slice_scatter.pt inputshape=[8,8],[2,8],[8,2]")
53
54 # pnnx inference
55 import test_torch_slice_scatter_pnnx
56 b = test_torch_slice_scatter_pnnx.test_inference()
57
58 for a0, b0 in zip(a, b):
59 if not torch.equal(a0, b0):
60 return False
61 return True
62
63if __name__ == "__main__":
64 if test():
65 exit(0)
66 else:
67 exit(1)