Elffuss BraidHub

kikocis/ncnn public

master · 2.3 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2024 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.gn_0 = nn.GroupNorm(num_groups=4, num_channels=12)
24 self.gn_0.weight = nn.Parameter(torch.rand(12))
25 self.gn_0.bias = nn.Parameter(torch.rand(12))
26 self.gn_1 = nn.GroupNorm(num_groups=12, num_channels=12, eps=1e-2, affine=False)
27 self.gn_2 = nn.GroupNorm(num_groups=1, num_channels=12, eps=1e-4, affine=True)
28 self.gn_2.weight = nn.Parameter(torch.rand(12))
29 self.gn_2.bias = nn.Parameter(torch.rand(12))
30
31 def forward(self, x, y, z):
32 x = self.gn_0(x)
33 x = self.gn_1(x)
34 x = self.gn_2(x)
35
36 y = self.gn_0(y)
37 y = self.gn_1(y)
38 y = self.gn_2(y)
39
40 z = self.gn_0(z)
41 z = self.gn_1(z)
42 z = self.gn_2(z)
43 return x, y, z
44
45def test():
46 net = Model()
47 net.eval()
48
49 torch.manual_seed(0)
50 x = torch.rand(1, 12, 64)
51 y = torch.rand(1, 12, 24, 64)
52 z = torch.rand(1, 12, 24, 32, 64)
53
54 a0, a1, a2 = net(x, y, z)
55
56 # export onnx
57 torch.onnx.export(net, (x, y, z), "test_nn_GroupNorm.onnx")
58
59 # onnx to pnnx
60 import os
61 os.system("../../src/pnnx test_nn_GroupNorm.onnx inputshape=[1,12,64],[1,12,24,64],[1,12,24,32,64]")
62
63 # pnnx inference
64 import test_nn_GroupNorm_pnnx
65 b0, b1, b2 = test_nn_GroupNorm_pnnx.test_inference()
66
67 return torch.allclose(a0, b0, 1e-4, 1e-4) and torch.allclose(a1, b1, 1e-4, 1e-4) and torch.allclose(a2, b2, 1e-4, 1e-4)
68
69if __name__ == "__main__":
70 if test():
71 exit(0)
72 else:
73 exit(1)