| 1 | # Tencent is pleased to support the open source community by making ncnn available. |
| 2 | # |
| 3 | # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | # 2023 Xiaomi Corp. (author: Fangjun Kuang) |
| 5 | # |
| 6 | # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 7 | # in compliance with the License. You may obtain a copy of the License at |
| 8 | # |
| 9 | # https://opensource.org/licenses/BSD-3-Clause |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software distributed |
| 12 | # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 13 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 14 | # specific language governing permissions and limitations under the License. |
| 15 | |
| 16 | import torch |
| 17 | import torch.nn as nn |
| 18 | import torch.nn.functional as F |
| 19 | |
| 20 | class Model(nn.Module): |
| 21 | def __init__(self): |
| 22 | super(Model, self).__init__() |
| 23 | |
| 24 | def forward(self, x, y, z): |
| 25 | # x - 3d |
| 26 | # y - 2d |
| 27 | # z - 1d |
| 28 | x0 = torch.cumsum(x, dim=0) |
| 29 | x1 = torch.cumsum(x, dim=1) |
| 30 | x2 = torch.cumsum(x, dim=2) |
| 31 | |
| 32 | y0 = torch.cumsum(y, dim=0) |
| 33 | y1 = torch.cumsum(y, dim=1) |
| 34 | |
| 35 | z0 = torch.cumsum(z, dim=0) |
| 36 | return x0, x1, x2, y0, y1, z0 |
| 37 | |
| 38 | def test(): |
| 39 | net = Model() |
| 40 | net.eval() |
| 41 | |
| 42 | torch.manual_seed(0) |
| 43 | x = torch.rand(2, 3, 16) |
| 44 | y = torch.rand(5, 9) |
| 45 | z = torch.rand(14) |
| 46 | |
| 47 | a = net(x, y, z) |
| 48 | |
| 49 | # export torchscript |
| 50 | mod = torch.jit.trace(net, (x, y, z)) |
| 51 | mod.save("test_torch_cumsum.pt") |
| 52 | |
| 53 | # torchscript to pnnx |
| 54 | import os |
| 55 | os.system("../src/pnnx test_torch_cumsum.pt inputshape=[2,3,16],[5,9],[14]") |
| 56 | |
| 57 | # pnnx inference |
| 58 | import test_torch_cumsum_pnnx |
| 59 | b = test_torch_cumsum_pnnx.test_inference() |
| 60 | |
| 61 | for a0, b0 in zip(a, b): |
| 62 | if not torch.equal(a0, b0): |
| 63 | return False |
| 64 | return True |
| 65 | |
| 66 | if __name__ == "__main__": |
| 67 | if test(): |
| 68 | exit(0) |
| 69 | else: |
| 70 | exit(1) |