| 1 | # Tencent is pleased to support the open source community by making ncnn available. |
| 2 | # |
| 3 | # Copyright (C) 2023 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 pixel_unshuffle(nn.Module): |
| 20 | def __init__(self, scale=2): |
| 21 | super(pixel_unshuffle, self).__init__() |
| 22 | self.scale = scale |
| 23 | |
| 24 | def forward(self, x): |
| 25 | n, c, h, w = x.shape |
| 26 | x = torch.reshape(x, (n, c, h // self.scale, self.scale, w // self.scale, self.scale)) |
| 27 | x = x.permute((0, 1, 3, 5, 2, 4)) |
| 28 | x = torch.reshape(x, (n, c * self.scale * self.scale, h // self.scale, w // self.scale)) |
| 29 | |
| 30 | return x |
| 31 | |
| 32 | class Model(nn.Module): |
| 33 | def __init__(self): |
| 34 | super(Model, self).__init__() |
| 35 | |
| 36 | self.down_0 = pixel_unshuffle(2) |
| 37 | self.down_1 = pixel_unshuffle(4) |
| 38 | |
| 39 | def forward(self, x): |
| 40 | x = self.down_0(x) |
| 41 | x = self.down_1(x) |
| 42 | return x |
| 43 | |
| 44 | def test(): |
| 45 | net = Model() |
| 46 | net.eval() |
| 47 | |
| 48 | torch.manual_seed(0) |
| 49 | x = torch.rand(1, 3, 128, 128) |
| 50 | |
| 51 | a0 = net(x) |
| 52 | |
| 53 | # export torchscript |
| 54 | mod = torch.jit.trace(net, x) |
| 55 | mod.save("test_pnnx_fuse_pixel_unshuffle.pt") |
| 56 | |
| 57 | # torchscript to pnnx |
| 58 | import os |
| 59 | os.system("../src/pnnx test_pnnx_fuse_pixel_unshuffle.pt inputshape=[1,3,128,128]") |
| 60 | |
| 61 | # pnnx inference |
| 62 | import test_pnnx_fuse_pixel_unshuffle_pnnx |
| 63 | b0 = test_pnnx_fuse_pixel_unshuffle_pnnx.test_inference() |
| 64 | |
| 65 | return torch.equal(a0, b0) |
| 66 | |
| 67 | if __name__ == "__main__": |
| 68 | if test(): |
| 69 | exit(0) |
| 70 | else: |
| 71 | exit(1) |