Elffuss BraidHub

kikocis/ncnn public

pnnx fuse t5-layernorm as rmsnorm (#5675)

Changeset9be260ac29b77bf8e04af86821a9e42eb86a7ccff352f406d58798fd1acf5a65
Authornihui <nihuini@tencent.com> · 2024-09-04 14:29 +08:00
CommitterGitHub <noreply@github.com> · 2024-09-04 14:29 +08:00
Parentsf7c12eb584c0

Browse the files at this changeset

8 files changed

modified tools/pnnx/src/CMakeLists.txt +1 −0
@@ -369,6 +369,7 @@
369369 pass_level5/fuse_pixel_unshuffle.cpp
370370 pass_level5/fuse_layernorm.cpp
371371 pass_level5/fuse_multiheadattention.cpp
372+ pass_level5/fuse_rmsnorm.cpp
372373 pass_level5/fuse_scaled_dot_product_attention.cpp
373374 pass_level5/fuse_select_to_unbind.cpp
374375 pass_level5/fuse_silu.cpp
modified tools/pnnx/src/pass_level5.cpp +2 −0
@@ -44,6 +44,7 @@
4444 #include "pass_level5/fuse_multiheadattention.h"
4545 #include "pass_level5/fuse_pad_conv1d.h"
4646 #include "pass_level5/fuse_pad_conv2d.h"
47+#include "pass_level5/fuse_rmsnorm.h"
4748 #include "pass_level5/fuse_scaled_dot_product_attention.h"
4849 #include "pass_level5/fuse_select_to_unbind.h"
4950 #include "pass_level5/fuse_silu.h"
@@ -145,6 +146,7 @@
145146
146147 fuse_channel_shuffle(g);
147148 fuse_layernorm(g);
149+ fuse_rmsnorm(g);
148150 fuse_multiheadattention(g);
149151 fuse_scaled_dot_product_attention(g);
150152
added tools/pnnx/src/pass_level5/fuse_rmsnorm.cpp +97 −0
@@ -0,0 +1,97 @@
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+
15+#include "fuse_rmsnorm.h"
16+
17+#include "pass_level2.h"
18+
19+#include <math.h>
20+#include <string.h>
21+
22+namespace pnnx {
23+
24+class fuse_rmsnorm_pass : public GraphRewriterPass
25+{
26+public:
27+ const char* match_pattern_graph() const
28+ {
29+ return R"PNNXIR(7767517
30+6 5
31+pnnx.Input input 0 1 input
32+pnnx.Attribute op_0 0 1 weight @data #weight=(%c)f32
33+pnnx.Expression op_1 1 1 input sq expr=pow(@0,2)
34+torch.mean op_2 1 1 sq sqmean dim=(-1) keepdim=True
35+pnnx.Expression op_3 3 1 weight input sqmean out expr=mul(@0,mul(@1,rsqrt(add(@2,%eps))))
36+pnnx.Output output 1 0 out
37+)PNNXIR";
38+ }
39+
40+ const char* replace_pattern_graph() const
41+ {
42+ return R"PNNXIR(7767517
43+3 2
44+pnnx.Input input 0 1 input
45+nn.RMSNorm rmsnorm 1 1 input out elementwise_affine=True eps=%eps normalized_shape=(%c) @weight=%op_0.data
46+pnnx.Output output 1 0 out
47+)PNNXIR";
48+ }
49+};
50+
51+class fuse_rmsnorm_pass_1 : public fuse_rmsnorm_pass
52+{
53+public:
54+ const char* match_pattern_graph() const
55+ {
56+ return R"PNNXIR(7767517
57+6 5
58+pnnx.Input input 0 1 input
59+pnnx.Attribute op_0 0 1 weight @data #weight=(%c)f32
60+pnnx.Expression op_1 1 1 input sq expr=pow(@0,2.000000e+00)
61+torch.mean op_2 1 1 sq sqmean dim=(-1) keepdim=True
62+pnnx.Expression op_3 3 1 weight input sqmean out expr=mul(@0,mul(@1,reciprocal(sqrt(add(@2,%eps)))))
63+pnnx.Output output 1 0 out
64+)PNNXIR";
65+ }
66+};
67+
68+class fuse_rmsnorm_pass_onnx : public fuse_rmsnorm_pass
69+{
70+public:
71+ const char* match_pattern_graph() const
72+ {
73+ return R"PNNXIR(7767517
74+6 5
75+pnnx.Input input 0 1 input
76+pnnx.Attribute op_0 0 1 weight @data #weight=(%c)f32
77+pnnx.Expression op_1 1 1 input sq expr=pow(@0,2.000000e+00)
78+torch.mean op_2 1 1 sq sqmean dim=(-1) keepdim=True
79+pnnx.Expression op_3 3 1 weight input sqmean out expr=mul(@0,mul(@1,div(1.000000e+00,sqrt(add(@2,%eps)))))
80+pnnx.Output output 1 0 out
81+)PNNXIR";
82+ }
83+};
84+
85+void fuse_rmsnorm(Graph& graph)
86+{
87+ fuse_rmsnorm_pass a;
88+ fuse_rmsnorm_pass_1 a1;
89+ fuse_rmsnorm_pass_onnx b;
90+ int opindex = 0;
91+
92+ pnnx_graph_rewrite(graph, &a, opindex);
93+ pnnx_graph_rewrite(graph, &a1, opindex);
94+ pnnx_graph_rewrite(graph, &b, opindex);
95+}
96+
97+} // namespace pnnx
added tools/pnnx/src/pass_level5/fuse_rmsnorm.h +21 −0
@@ -0,0 +1,21 @@
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+
15+#include "ir.h"
16+
17+namespace pnnx {
18+
19+void fuse_rmsnorm(Graph& graph);
20+
21+} // namespace pnnx
modified tools/pnnx/tests/CMakeLists.txt +1 −0
@@ -346,6 +346,7 @@
346346 pnnx_add_test(pnnx_fuse_layernorm)
347347 pnnx_add_test(pnnx_fuse_linear_batchnorm1d)
348348 pnnx_add_test(pnnx_fuse_multiheadattention)
349+pnnx_add_test(pnnx_fuse_rmsnorm)
349350 pnnx_add_test(pnnx_fuse_scaled_dot_product_attention)
350351 pnnx_add_test(pnnx_fuse_select_to_unbind)
351352 pnnx_add_test(pnnx_fuse_slice_to_tensor_split)
modified tools/pnnx/tests/ncnn/test_F_rms_norm.py +1 −1
@@ -57,7 +57,7 @@
5757 b = test_F_rms_norm_ncnn.test_inference()
5858
5959 for a0, b0 in zip(a, b):
60- if not torch.allclose(a0, b0, 1e-4, 1e-4):
60+ if not torch.allclose(a0, b0, 1e-3, 1e-3):
6161 return False
6262 return True
6363
modified tools/pnnx/tests/ncnn/test_nn_RMSNorm.py +1 −1
@@ -57,7 +57,7 @@
5757 b = test_nn_RMSNorm_ncnn.test_inference()
5858
5959 for a0, b0 in zip(a, b):
60- if not torch.allclose(a0, b0, 1e-4, 1e-4):
60+ if not torch.allclose(a0, b0, 1e-3, 1e-3):
6161 return False
6262 return True
6363
added tools/pnnx/tests/test_pnnx_fuse_rmsnorm.py +77 −0
@@ -0,0 +1,77 @@
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+
15+import torch
16+import torch.nn as nn
17+import torch.nn.functional as F
18+from packaging import version
19+
20+class 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+
31+class 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+
43+def 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+
73+if __name__ == "__main__":
74+ if test():
75+ exit(0)
76+ else:
77+ exit(1)