| 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 | |
| 15 | import torch |
| 16 | import torch.nn as nn |
| 17 | import torch.nn.functional as F |
| 18 | |
| 19 | class Model(nn.Module): |
| 20 | def __init__(self): |
| 21 | super(Model, self).__init__() |
| 22 | |
| 23 | def forward(self, x, y, z, w): |
| 24 | x0, x1, x2 = torch.tensor_split(x, (12, 13)) |
| 25 | y0, y1 = torch.tensor_split(y, 2, dim=0) |
| 26 | y2, y3, y4 = torch.tensor_split(y, 3, dim=1) |
| 27 | z0, z1 = torch.tensor_split(z, (3,), dim=0) |
| 28 | z2, z3 = torch.tensor_split(z, (1,), dim=1) |
| 29 | z4, z5, z6 = torch.tensor_split(z, 3, dim=2) |
| 30 | w0, w1, w2 = torch.tensor_split(w, (2, 4), dim=0) |
| 31 | w3, w4 = torch.tensor_split(w, 2, dim=1) |
| 32 | w5, w6, w7 = torch.tensor_split(w, (1, 5), dim=2) |
| 33 | w8, w9, wa, wb, wc = torch.tensor_split(w, (1, 3, 7, 17), dim=3) |
| 34 | return x0, x1, x2, y0, y1, y2, y3, y4, z0, z1, z2, z3, z4, z5, z6, w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, wa, wb, wc |
| 35 | |
| 36 | def test(): |
| 37 | net = Model() |
| 38 | net.eval() |
| 39 | |
| 40 | torch.manual_seed(0) |
| 41 | x = torch.rand(100) |
| 42 | y = torch.rand(3, 16) |
| 43 | z = torch.rand(5, 9, 3) |
| 44 | w = torch.rand(6, 13, 6, 22) |
| 45 | |
| 46 | a = net(x, y, z, w) |
| 47 | |
| 48 | # export torchscript |
| 49 | mod = torch.jit.trace(net, (x, y, z, w)) |
| 50 | mod.save("test_torch_tensor_split.pt") |
| 51 | |
| 52 | # torchscript to pnnx |
| 53 | import os |
| 54 | os.system("../src/pnnx test_torch_tensor_split.pt inputshape=[100],[3,16],[5,9,3],[6,13,6,22]") |
| 55 | |
| 56 | # pnnx inference |
| 57 | import test_torch_tensor_split_pnnx |
| 58 | b = test_torch_tensor_split_pnnx.test_inference() |
| 59 | |
| 60 | for a0, b0 in zip(a, b): |
| 61 | if not torch.equal(a0, b0): |
| 62 | return False |
| 63 | return True |
| 64 | |
| 65 | if __name__ == "__main__": |
| 66 | if test(): |
| 67 | exit(0) |
| 68 | else: |
| 69 | exit(1) |