| 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 | |
| 15 | import torch |
| 16 | import torch.nn as nn |
| 17 | import torch.nn.functional as F |
| 18 | from packaging import version |
| 19 | |
| 20 | class 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.12'): |
| 26 | x = x[:,:12,1:14:1] |
| 27 | else: |
| 28 | x = x[:,:12,1:14:2] |
| 29 | x = x[...,1:] |
| 30 | if version.parse(torch.__version__) >= version.parse('1.10'): |
| 31 | x = x[:,:,:x.size(2)-1] |
| 32 | y = y[0:,1:,5:,3:] |
| 33 | if version.parse(torch.__version__) < version.parse('1.12'): |
| 34 | y = y[:,:,1:13:1,:14] |
| 35 | else: |
| 36 | y = y[:,:,1:13:2,:14] |
| 37 | if version.parse(torch.__version__) >= version.parse('1.10'): |
| 38 | y = y[:1,:y.size(1):,:,:] |
| 39 | z = z[4:] |
| 40 | if version.parse(torch.__version__) < version.parse('1.12'): |
| 41 | z = z[:2,:,:,:,2:-2:1] |
| 42 | else: |
| 43 | z = z[:2,:,:,:,2:-2:3] |
| 44 | if version.parse(torch.__version__) >= version.parse('1.10'): |
| 45 | z = z[:,:,:,z.size(3)-3:,:] |
| 46 | return x, y, z |
| 47 | |
| 48 | def test(): |
| 49 | net = Model() |
| 50 | net.eval() |
| 51 | |
| 52 | torch.manual_seed(0) |
| 53 | x = torch.rand(1, 13, 26) |
| 54 | y = torch.rand(1, 15, 19, 21) |
| 55 | z = torch.rand(14, 18, 15, 19, 20) |
| 56 | |
| 57 | a = net(x, y, z) |
| 58 | |
| 59 | # export onnx |
| 60 | torch.onnx.export(net, (x, y, z), "test_Tensor_slice.onnx") |
| 61 | |
| 62 | # onnx to pnnx |
| 63 | import os |
| 64 | os.system("../../src/pnnx test_Tensor_slice.onnx inputshape=[1,13,26],[1,15,19,21],[14,18,15,19,20]") |
| 65 | |
| 66 | # pnnx inference |
| 67 | import test_Tensor_slice_pnnx |
| 68 | b = test_Tensor_slice_pnnx.test_inference() |
| 69 | |
| 70 | for a0, b0 in zip(a, b): |
| 71 | if not torch.equal(a0, b0): |
| 72 | return False |
| 73 | return True |
| 74 | |
| 75 | if __name__ == "__main__": |
| 76 | if test(): |
| 77 | exit(0) |
| 78 | else: |
| 79 | exit(1) |