You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_torch_stack.py 1.8 kB

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