| 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 | |
| 19 | class Model(nn.Module): |
| 20 | def __init__(self): |
| 21 | super(Model, self).__init__() |
| 22 | |
| 23 | def forward(self, x, y, z, w): |
| 24 | out0 = torch.stack((x, y), dim=0) |
| 25 | out1 = torch.stack((x, y), dim=2) |
| 26 | out2 = torch.stack((z, w), dim=2) |
| 27 | out3 = torch.stack((z, w), dim=-1) |
| 28 | return out0, out1, out2, out3 |
| 29 | |
| 30 | def test(): |
| 31 | net = Model() |
| 32 | net.eval() |
| 33 | |
| 34 | torch.manual_seed(0) |
| 35 | x = torch.rand(3, 16) |
| 36 | y = torch.rand(3, 16) |
| 37 | z = torch.rand(5, 9, 3) |
| 38 | w = torch.rand(5, 9, 3) |
| 39 | |
| 40 | a = net(x, y, z, w) |
| 41 | |
| 42 | # export onnx |
| 43 | torch.onnx.export(net, (x, y, z, w), "test_torch_stack.onnx") |
| 44 | |
| 45 | # onnx to pnnx |
| 46 | import os |
| 47 | os.system("../../src/pnnx test_torch_stack.onnx inputshape=[3,16],[3,16],[5,9,3],[5,9,3]") |
| 48 | |
| 49 | # pnnx inference |
| 50 | import test_torch_stack_pnnx |
| 51 | b = test_torch_stack_pnnx.test_inference() |
| 52 | |
| 53 | for a0, b0 in zip(a, b): |
| 54 | if not torch.equal(a0, b0): |
| 55 | return False |
| 56 | return True |
| 57 | |
| 58 | if __name__ == "__main__": |
| 59 | if test(): |
| 60 | exit(0) |
| 61 | else: |
| 62 | exit(1) |