Elffuss BraidHub

kikocis/ncnn public

master · 2.5 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.w3 = nn.Parameter(torch.rand(16))
24 self.b3 = nn.Parameter(torch.rand(16))
25 self.w4 = nn.Parameter(torch.rand(12))
26 self.b4 = nn.Parameter(torch.rand(12))
27 self.w5 = nn.Parameter(torch.rand(32))
28 self.b5 = nn.Parameter(torch.rand(32))
29
30 def forward(self, x, y, z, w0, b0, w1, b1, w2, b2):
31 x = F.group_norm(x, 2, w0, b0)
32 x = F.group_norm(x, 1, None, None)
33 x = F.group_norm(x, 4, self.w3, self.b3)
34
35 y = F.group_norm(y, 3, w1, b1, eps=1e-4)
36 y = F.group_norm(y, 4, None, None)
37 y = F.group_norm(y, 6, self.w4, self.b4)
38
39 z = F.group_norm(z, 32, w2, b2)
40 z = F.group_norm(z, 4, None, None, eps=1e-2)
41 z = F.group_norm(z, 8, self.w5, self.b5)
42 return x, y, z
43
44def test():
45 net = Model()
46 net.eval()
47
48 torch.manual_seed(0)
49 x = torch.rand(1, 16)
50 y = torch.rand(12, 12, 16)
51 z = torch.rand(1, 32, 12, 16)
52 w0 = torch.rand(16)
53 b0 = torch.rand(16)
54 w1 = torch.rand(12)
55 b1 = torch.rand(12)
56 w2 = torch.rand(32)
57 b2 = torch.rand(32)
58
59 a0, a1, a2 = net(x, y, z, w0, b0, w1, b1, w2, b2)
60
61 # export torchscript
62 mod = torch.jit.trace(net, (x, y, z, w0, b0, w1, b1, w2, b2))
63 mod.save("test_F_group_norm.pt")
64
65 # torchscript to pnnx
66 import os
67 os.system("../src/pnnx test_F_group_norm.pt inputshape=[1,16],[12,12,16],[1,32,12,16],[16],[16],[12],[12],[32],[32]")
68
69 # pnnx inference
70 import test_F_group_norm_pnnx
71 b0, b1, b2 = test_F_group_norm_pnnx.test_inference()
72
73 return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2)
74
75if __name__ == "__main__":
76 if test():
77 exit(0)
78 else:
79 exit(1)