Elffuss BraidHub

kikocis/ncnn public

master · 2.2 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
18from packaging import version
19
20class Model(nn.Module):
21 def __init__(self):
22 super(Model, self).__init__()
23
24 self.in_0 = nn.InstanceNorm1d(num_features=12, affine=True)
25 self.in_0.weight = nn.Parameter(torch.rand(12))
26 self.in_0.bias = nn.Parameter(torch.rand(12))
27 self.in_1 = nn.InstanceNorm1d(num_features=12, eps=1e-2, affine=False)
28 if version.parse(torch.__version__) < version.parse('1.10'):
29 self.in_2 = nn.InstanceNorm1d(num_features=12, eps=1e-4, affine=True, track_running_stats=False)
30 else:
31 self.in_2 = nn.InstanceNorm1d(num_features=12, eps=1e-4, affine=True, track_running_stats=True)
32 self.in_2.weight = nn.Parameter(torch.rand(12))
33 self.in_2.bias = nn.Parameter(torch.rand(12))
34
35 def forward(self, x):
36 x = self.in_0(x)
37 x = self.in_1(x)
38 x = self.in_2(x)
39 return x
40
41def test():
42 net = Model()
43 net.eval()
44
45 torch.manual_seed(0)
46 x = torch.rand(1, 12, 24)
47
48 a = net(x)
49
50 # export onnx
51 torch.onnx.export(net, (x,), "test_nn_InstanceNorm1d.onnx")
52
53 # onnx to pnnx
54 import os
55 os.system("../../src/pnnx test_nn_InstanceNorm1d.onnx inputshape=[1,12,24]")
56
57 # pnnx inference
58 import test_nn_InstanceNorm1d_pnnx
59 b = test_nn_InstanceNorm1d_pnnx.test_inference()
60
61 return torch.equal(a, b)
62
63if __name__ == "__main__":
64 if test():
65 exit(0)
66 else:
67 exit(1)