Elffuss BraidHub

kikocis/ncnn public

master · 2.6 KiBRawPermalink
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
15import torch
16import torch.nn as nn
17import torch.nn.functional as F
18
19class Model(nn.Module):
20 def __init__(self):
21 super(Model, self).__init__()
22
23 self.gru_0_0 = nn.GRU(input_size=32, hidden_size=16)
24 self.gru_0_1 = nn.GRU(input_size=16, hidden_size=16, num_layers=3, bias=False)
25 self.gru_0_2 = nn.GRU(input_size=16, hidden_size=16, num_layers=4, bias=True, bidirectional=True)
26 self.gru_0_3 = nn.GRU(input_size=16, hidden_size=16, num_layers=4, bias=True, bidirectional=True)
27
28 self.gru_1_0 = nn.GRU(input_size=25, hidden_size=16, batch_first=True)
29 self.gru_1_1 = nn.GRU(input_size=16, hidden_size=16, num_layers=3, bias=False, batch_first=True)
30 self.gru_1_2 = nn.GRU(input_size=16, hidden_size=16, num_layers=4, bias=True, batch_first=True, bidirectional=True)
31 self.gru_1_3 = nn.GRU(input_size=16, hidden_size=16, num_layers=4, bias=True, batch_first=True, bidirectional=True)
32
33 def forward(self, x, y):
34 x0, h0 = self.gru_0_0(x)
35 x1, _ = self.gru_0_1(x0)
36 x2, h2 = self.gru_0_2(x1)
37 x3, h3 = self.gru_0_3(x1, h2)
38
39 y0, h4 = self.gru_1_0(y)
40 y1, _ = self.gru_1_1(y0)
41 y2, h6 = self.gru_1_2(y1)
42 y3, h7 = self.gru_1_3(y1, h6)
43 return x2, x3, h0, h2, h3, y2, y3, h4, h6, h7
44
45def test():
46 net = Model()
47 net.eval()
48
49 torch.manual_seed(0)
50 x = torch.rand(10, 1, 32)
51 y = torch.rand(1, 12, 25)
52
53 a = net(x, y)
54
55 # export torchscript
56 mod = torch.jit.trace(net, (x, y))
57 mod.save("test_nn_GRU.pt")
58
59 # torchscript to pnnx
60 import os
61 os.system("../src/pnnx test_nn_GRU.pt inputshape=[10,1,32],[1,12,25]")
62
63 # pnnx inference
64 import test_nn_GRU_pnnx
65 b = test_nn_GRU_pnnx.test_inference()
66
67 for a0, b0 in zip(a, b):
68 if not torch.equal(a0, b0):
69 return False
70 return True
71
72if __name__ == "__main__":
73 if test():
74 exit(0)
75 else:
76 exit(1)