Elffuss BraidHub

kikocis/ncnn public

master · 2.0 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.linear_0 = nn.Linear(in_features=64, out_features=16, bias=False)
24 self.bn_0 = nn.BatchNorm1d(num_features=16)
25 self.linear_1 = nn.Linear(in_features=16, out_features=3, bias=True)
26 self.bn_1 = nn.BatchNorm1d(num_features=3)
27
28 def forward(self, x, y):
29 x = self.linear_0(x)
30 x = self.bn_0(x)
31 x = self.linear_1(x)
32 x = self.bn_1(x)
33
34 y = self.linear_0(y)
35 y = self.bn_0(y)
36 y = self.linear_1(y)
37 y = self.bn_1(y)
38 return x, y
39
40def test():
41 net = Model()
42 net.eval()
43
44 torch.manual_seed(0)
45 x = torch.rand(1, 64)
46 y = torch.rand(12, 64)
47
48 a0, a1 = net(x, y)
49
50 # export torchscript
51 mod = torch.jit.trace(net, (x, y))
52 mod.save("test_pnnx_fuse_linear_batchnorm1d.pt")
53
54 # torchscript to pnnx
55 import os
56 os.system("../src/pnnx test_pnnx_fuse_linear_batchnorm1d.pt inputshape=[1,64],[12,64]")
57
58 # pnnx inference
59 import test_pnnx_fuse_linear_batchnorm1d_pnnx
60 b0, b1 = test_pnnx_fuse_linear_batchnorm1d_pnnx.test_inference()
61
62 return torch.allclose(a0, b0, 1e-4, 1e-4) and torch.allclose(a1, b1, 1e-4, 1e-4)
63
64if __name__ == "__main__":
65 if test():
66 exit(0)
67 else:
68 exit(1)