Elffuss BraidHub

kikocis/ncnn public

master · 2.1 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2023 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 LayerNorm2d(nn.Module):
20 def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
21 super().__init__()
22 self.weight = nn.Parameter(torch.ones(num_channels))
23 self.bias = nn.Parameter(torch.zeros(num_channels))
24 self.eps = eps
25
26 def forward(self, x: torch.Tensor) -> torch.Tensor:
27 u = x.mean(1, keepdim=True)
28 s = (x - u).pow(2).mean(1, keepdim=True)
29 x = (x - u) / torch.sqrt(s + self.eps)
30 x = self.weight[:, None, None] * x + self.bias[:, None, None]
31 return x
32
33class Model(nn.Module):
34 def __init__(self):
35 super(Model, self).__init__()
36
37 self.ln_0 = LayerNorm2d(64)
38
39 def forward(self, x):
40 x = self.ln_0(x)
41 return x
42
43def test():
44 net = Model()
45 net.eval()
46
47 torch.manual_seed(0)
48 x = torch.rand(1, 64, 16, 16)
49
50 a0 = net(x)
51
52 # export torchscript
53 mod = torch.jit.trace(net, x)
54 mod.save("test_pnnx_fuse_layernorm.pt")
55
56 # torchscript to pnnx
57 import os
58 os.system("../src/pnnx test_pnnx_fuse_layernorm.pt inputshape=[1,64,16,16]")
59
60 # pnnx inference
61 import test_pnnx_fuse_layernorm_pnnx
62 b0 = test_pnnx_fuse_layernorm_pnnx.test_inference()
63
64 return torch.allclose(a0, b0, 1e-4, 1e-4)
65
66if __name__ == "__main__":
67 if test():
68 exit(0)
69 else:
70 exit(1)