| 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 | # |
| 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 | from packaging import version |
| 19 | |
| 20 | class Model(nn.Module): |
| 21 | def __init__(self): |
| 22 | super(Model, self).__init__() |
| 23 | |
| 24 | self.w2 = nn.Parameter(torch.rand(12, 6, 4)) |
| 25 | self.b2 = nn.Parameter(torch.rand(12)) |
| 26 | self.w3 = nn.Parameter(torch.rand(6, 4, 3)) |
| 27 | |
| 28 | def forward(self, x, w0, w1, b1, y): |
| 29 | x = F.conv1d(x, w0, None, stride=2, padding=1) |
| 30 | if version.parse(torch.__version__) < version.parse('1.9'): |
| 31 | x = F.conv1d(x, w1, b1, stride=1, padding=1, dilation=2, groups=2) |
| 32 | else: |
| 33 | x = F.conv1d(x, w1, b1, stride=1, padding='same', dilation=2, groups=2) |
| 34 | |
| 35 | y = F.conv1d(y, self.w2, self.b2, stride=2, padding=2) |
| 36 | y = F.conv1d(y, self.w3, None, stride=2, padding=1, groups=3) |
| 37 | return x, y |
| 38 | |
| 39 | def test(): |
| 40 | net = Model() |
| 41 | net.eval() |
| 42 | |
| 43 | torch.manual_seed(0) |
| 44 | x = torch.rand(1, 12, 52) |
| 45 | w0 = torch.rand(16, 12, 3) |
| 46 | w1 = torch.rand(16, 8, 5) |
| 47 | b1 = torch.rand(16) |
| 48 | y = torch.rand(1, 6, 25) |
| 49 | |
| 50 | a0, a1 = net(x, w0, w1, b1, y) |
| 51 | |
| 52 | # export torchscript |
| 53 | mod = torch.jit.trace(net, (x, w0, w1, b1, y)) |
| 54 | mod.save("test_F_conv1d.pt") |
| 55 | |
| 56 | # torchscript to pnnx |
| 57 | import os |
| 58 | os.system("../src/pnnx test_F_conv1d.pt inputshape=[1,12,52],[16,12,3],[16,8,5],[16],[1,6,25]") |
| 59 | |
| 60 | # pnnx inference |
| 61 | import test_F_conv1d_pnnx |
| 62 | b0, b1 = test_F_conv1d_pnnx.test_inference() |
| 63 | |
| 64 | return torch.equal(a0, b0) and torch.equal(a1, b1) |
| 65 | |
| 66 | if __name__ == "__main__": |
| 67 | if test(): |
| 68 | exit(0) |
| 69 | else: |
| 70 | exit(1) |