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 T5LayerNorm(nn.Module):
21 def __init__(self, hidden_size, eps=1e-6):
22 super().__init__()
23 self.weight = nn.Parameter(torch.rand(hidden_size))
24 self.variance_epsilon = eps
25
26 def forward(self, x):
27 variance = x.pow(2).mean(-1, keepdim=True)
28 x = x * torch.rsqrt(variance + self.variance_epsilon)
29 return self.weight * x
30
31class Model(nn.Module):
32 def __init__(self):
33 super(Model, self).__init__()
34
35 self.rmsn_0 = T5LayerNorm(26)
36 self.rmsn_1 = T5LayerNorm(21)
37
38 def forward(self, x, y):
39 x = self.rmsn_0(x)
40 y = self.rmsn_1(y)
41 return x, y
42
43def test():
44 if version.parse(torch.__version__) < version.parse('2.4'):
45 return True
46
47 net = Model()
48 net.eval()
49
50 torch.manual_seed(0)
51 x = torch.rand(1, 64, 26)
52 y = torch.rand(3, 15, 15, 21)
53
54 a0, a1 = net(x, y)
55
56 # export onnx
57 torch.onnx.export(net, (x,y), "test.onnx")
58
59 # export torchscript
60 mod = torch.jit.trace(net, (x, y))
61 mod.save("test_pnnx_fuse_rmsnorm.pt")
62
63 # torchscript to pnnx
64 import os
65 os.system("../src/pnnx test_pnnx_fuse_rmsnorm.pt inputshape=[1,64,26],[3,15,15,21]")
66
67 # pnnx inference
68 import test_pnnx_fuse_rmsnorm_pnnx
69 b0, b1 = test_pnnx_fuse_rmsnorm_pnnx.test_inference()
70
71 return torch.allclose(a0, b0, 1e-4, 1e-4) and torch.allclose(a1, b1, 1e-4, 1e-4)
72
73if __name__ == "__main__":
74 if test():
75 exit(0)
76 else:
77 exit(1)