| 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 | self.pad_0 = nn.ConstantPad1d(2, 0.0) |
| 24 | self.pad_1 = nn.ReflectionPad1d(4) |
| 25 | self.pad_2 = nn.ReplicationPad1d(3) |
| 26 | |
| 27 | self.conv_0 = nn.Conv1d(in_channels=12, out_channels=14, kernel_size=3) |
| 28 | self.conv_1 = nn.Conv1d(in_channels=14, out_channels=14, kernel_size=1) |
| 29 | self.conv_2 = nn.Conv1d(in_channels=14, out_channels=14, kernel_size=2) |
| 30 | self.conv_3 = nn.Conv1d(in_channels=14, out_channels=12, kernel_size=3, padding=(1,)) |
| 31 | |
| 32 | def forward(self, x): |
| 33 | x = self.pad_0(x) |
| 34 | x = F.pad(x, pad=(1,1)) |
| 35 | x = self.conv_0(x) |
| 36 | |
| 37 | x = self.pad_1(x) |
| 38 | x = self.conv_1(x) |
| 39 | |
| 40 | x = F.pad(x, pad=(3,3), mode='reflect') |
| 41 | x = self.conv_1(x) |
| 42 | |
| 43 | x = self.pad_2(x) |
| 44 | x = self.conv_2(x) |
| 45 | |
| 46 | x = F.pad(x, pad=(1,1), mode='replicate') |
| 47 | x = self.conv_2(x) |
| 48 | |
| 49 | x = F.pad(x, pad=(2,2)) |
| 50 | x = self.conv_3(x) |
| 51 | |
| 52 | return x |
| 53 | |
| 54 | def test(): |
| 55 | net = Model() |
| 56 | net.eval() |
| 57 | |
| 58 | torch.manual_seed(0) |
| 59 | x = torch.rand(1, 12, 13) |
| 60 | |
| 61 | a = net(x) |
| 62 | |
| 63 | # export torchscript |
| 64 | mod = torch.jit.trace(net, x) |
| 65 | mod.save("test_pnnx_pnnx_fuse_pad_conv1d.pt") |
| 66 | |
| 67 | # torchscript to pnnx |
| 68 | import os |
| 69 | os.system("../src/pnnx test_pnnx_pnnx_fuse_pad_conv1d.pt inputshape=[1,12,13]") |
| 70 | |
| 71 | # pnnx inference |
| 72 | import test_pnnx_pnnx_fuse_pad_conv1d_pnnx |
| 73 | b = test_pnnx_pnnx_fuse_pad_conv1d_pnnx.test_inference() |
| 74 | |
| 75 | for a0, b0 in zip(a, b): |
| 76 | if not torch.equal(a0, b0): |
| 77 | return False |
| 78 | return True |
| 79 | |
| 80 | if __name__ == "__main__": |
| 81 | if test(): |
| 82 | exit(0) |
| 83 | else: |
| 84 | exit(1) |