Elffuss BraidHub

kikocis/ncnn public

pnnx convert nn.RMSNorm F.rms_norm (#5628)

Changesetcd5603efda533c80f83670ced1321ccf4023bbc884c8b589cf44d1bcab441b34
Authornihui <nihuini@tencent.com> · 2024-08-14 15:51 +08:00
CommitterGitHub <noreply@github.com> · 2024-08-14 15:51 +08:00
Parentsdf9a7627276d

Browse the files at this changeset

10 files changed

modified tools/pnnx/src/CMakeLists.txt +3 −0
@@ -77,6 +77,7 @@
7777 pass_level1/nn_ReplicationPad1d.cpp
7878 pass_level1/nn_ReplicationPad2d.cpp
7979 pass_level1/nn_ReplicationPad3d.cpp
80+ pass_level1/nn_RMSNorm.cpp
8081 pass_level1/nn_RNN.cpp
8182 pass_level1/nn_RReLU.cpp
8283 pass_level1/nn_SELU.cpp
@@ -163,6 +164,7 @@
163164 pass_level2/F_prelu.cpp
164165 pass_level2/F_relu.cpp
165166 pass_level2/F_relu6.cpp
167+ pass_level2/F_rms_norm.cpp
166168 pass_level2/F_rrelu.cpp
167169 pass_level2/F_scaled_dot_product_attention.cpp
168170 pass_level2/F_selu.cpp
@@ -383,6 +385,7 @@
383385 pass_level5/fuse_static_layernorm.cpp
384386 pass_level5/fuse_static_linear.cpp
385387 pass_level5/fuse_static_prelu.cpp
388+ pass_level5/fuse_static_rmsnorm.cpp
386389 pass_level5/normalize_einsum_equation.cpp
387390 pass_level5/unroll_rnn_op.cpp
388391 )
added tools/pnnx/src/pass_level1/nn_RMSNorm.cpp +51 −0
@@ -0,0 +1,51 @@
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 "pass_level1.h"
16+
17+#include "../utils.h"
18+
19+namespace pnnx {
20+
21+class RMSNorm : public FuseModulePass
22+{
23+public:
24+ const char* match_type_str() const
25+ {
26+ return "__torch__.torch.nn.modules.normalization.RMSNorm";
27+ }
28+
29+ const char* type_str() const
30+ {
31+ return "nn.RMSNorm";
32+ }
33+
34+ void write(Operator* op, const std::shared_ptr<torch::jit::Graph>& graph, const torch::jit::Module& mod) const
35+ {
36+ const torch::jit::Node* rmsn = find_node_by_kind(graph, "aten::rms_norm");
37+
38+ op->params["normalized_shape"] = rmsn->namedInput("normalized_shape");
39+ op->params["eps"] = rmsn->namedInput("eps");
40+ op->params["elementwise_affine"] = mod.hasattr("weight") && mod.hasattr("bias");
41+
42+ if (mod.hasattr("weight"))
43+ {
44+ op->attrs["weight"] = mod.attr("weight").toTensor();
45+ }
46+ }
47+};
48+
49+REGISTER_GLOBAL_PNNX_FUSE_MODULE_PASS(RMSNorm)
50+
51+} // namespace pnnx
added tools/pnnx/src/pass_level2/F_rms_norm.cpp +43 −0
@@ -0,0 +1,43 @@
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 "pass_level2.h"
16+
17+namespace pnnx {
18+
19+class F_rms_norm : public GraphRewriterPass
20+{
21+public:
22+ const char* match_pattern_graph() const
23+ {
24+ return R"PNNXIR(7767517
25+6 5
26+pnnx.Input input_0 0 1 input
27+pnnx.Input input_1 0 1 weight
28+pnnx.Input input_2 0 1 normalized_shape
29+prim::Constant op_0 0 1 eps value=%eps
30+aten::rms_norm op_1 4 1 input normalized_shape weight eps out
31+pnnx.Output output 1 0 out
32+)PNNXIR";
33+ }
34+
35+ const char* type_str() const
36+ {
37+ return "F.rms_norm";
38+ }
39+};
40+
41+REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_rms_norm, 10)
42+
43+} // namespace pnnx
modified tools/pnnx/src/pass_level5.cpp +2 −0
@@ -60,6 +60,7 @@
6060 #include "pass_level5/fuse_static_layernorm.h"
6161 #include "pass_level5/fuse_static_linear.h"
6262 #include "pass_level5/fuse_static_prelu.h"
63+#include "pass_level5/fuse_static_rmsnorm.h"
6364 #include "pass_level5/normalize_einsum_equation.h"
6465 #include "pass_level4/dead_code_elimination.h"
6566 #include "pass_level4/canonicalize.h"
@@ -102,6 +103,7 @@
102103 fuse_static_groupnorm(g);
103104 fuse_static_instancenorm(g);
104105 fuse_static_layernorm(g);
106+ fuse_static_rmsnorm(g);
105107
106108 fuse_static_conv(g);
107109 fuse_static_convtranspose(g);
added tools/pnnx/src/pass_level5/fuse_static_rmsnorm.cpp +57 −0
@@ -0,0 +1,57 @@
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_static_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_static_Frmsnorm_pass : public GraphRewriterPass
25+{
26+public:
27+ const char* match_pattern_graph() const
28+ {
29+ return R"PNNXIR(7767517
30+4 3
31+pnnx.Input input 0 1 input
32+pnnx.Attribute op_weight 0 1 weight @data
33+F.rms_norm op_0 2 1 input weight out normalized_shape=%normalized_shape eps=%eps
34+pnnx.Output output 1 0 out
35+)PNNXIR";
36+ }
37+
38+ const char* replace_pattern_graph() const
39+ {
40+ return R"PNNXIR(7767517
41+3 2
42+pnnx.Input input 0 1 input
43+nn.RMSNorm rmsn 1 1 input out normalized_shape=%normalized_shape eps=%eps elementwise_affine=True @weight=%op_weight.data
44+pnnx.Output output 1 0 out
45+)PNNXIR";
46+ }
47+};
48+
49+void fuse_static_rmsnorm(Graph& graph)
50+{
51+ fuse_static_Frmsnorm_pass a;
52+ int opindex = 0;
53+
54+ pnnx_graph_rewrite(graph, &a, opindex);
55+}
56+
57+} // namespace pnnx
added tools/pnnx/src/pass_level5/fuse_static_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_static_rmsnorm(Graph& graph);
20+
21+} // namespace pnnx
modified tools/pnnx/src/pass_ncnn/solve_batch_index.cpp +4 −0
@@ -46,6 +46,7 @@
4646 "F.group_norm",
4747 "F.instance_norm",
4848 "F.interpolate",
49+ "F.layer_norm",
4950 "F.linear",
5051 "F.local_response_norm",
5152 "F.lp_pool1d",
@@ -56,6 +57,7 @@
5657 "F.pixel_shuffle",
5758 "F.pixel_unshuffle",
5859 "F.prelu",
60+ "F.rms_norm",
5961 "F.scaled_dot_product_attention",
6062 "F.unfold",
6163 "F.upsample_bilinear",
@@ -91,6 +93,7 @@
9193 "nn.InstanceNorm2d",
9294 "nn.InstanceNorm3d",
9395 "nn.LocalResponseNorm",
96+ "nn.LayerNorm",
9497 "nn.LPPool1d",
9598 "nn.LPPool2d",
9699 "nn.MaxPool1d",
@@ -104,6 +107,7 @@
104107 "nn.ReplicationPad1d",
105108 "nn.ReplicationPad2d",
106109 "nn.ReplicationPad3d",
110+ "nn.RMSNorm",
107111 "nn.Softmax2d",
108112 "nn.Unfold",
109113 "nn.Upsample",
modified tools/pnnx/tests/CMakeLists.txt +2 −0
@@ -61,6 +61,7 @@
6161 pnnx_add_test(F_prelu)
6262 pnnx_add_test(F_relu)
6363 pnnx_add_test(F_relu6)
64+pnnx_add_test(F_rms_norm)
6465 pnnx_add_test(F_rrelu)
6566 pnnx_add_test(F_scaled_dot_product_attention)
6667 pnnx_add_test(F_selu)
@@ -145,6 +146,7 @@
145146 pnnx_add_test(nn_ReplicationPad1d)
146147 pnnx_add_test(nn_ReplicationPad2d)
147148 pnnx_add_test(nn_ReplicationPad3d)
149+pnnx_add_test(nn_RMSNorm)
148150 pnnx_add_test(nn_RNN)
149151 pnnx_add_test(nn_RReLU)
150152 pnnx_add_test(nn_SELU)
added tools/pnnx/tests/test_F_rms_norm.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 Model(nn.Module):
21+ def __init__(self):
22+ super(Model, self).__init__()
23+
24+ self.w3 = nn.Parameter(torch.rand(24))
25+ self.w4 = nn.Parameter(torch.rand(12, 16))
26+ self.w5 = nn.Parameter(torch.rand(24))
27+
28+ def forward(self, x, y, z, w0, w1, w2):
29+ x = F.rms_norm(x, (24,), w0)
30+ x = F.rms_norm(x, (12,24), None)
31+ x = F.rms_norm(x, (24,), self.w3)
32+
33+ y = F.rms_norm(y, (16,), None, eps=1e-3)
34+ y = F.rms_norm(y, (12,16), w1)
35+ y = F.rms_norm(y, (12,16), self.w4)
36+
37+ z = F.rms_norm(z, (24,), w2)
38+ z = F.rms_norm(z, (12,16,24), None, eps=1e-2)
39+ z = F.rms_norm(z, (24,), self.w5)
40+ return x, y, z
41+
42+def test():
43+ if version.parse(torch.__version__) < version.parse('2.4'):
44+ return True
45+
46+ net = Model()
47+ net.eval()
48+
49+ torch.manual_seed(0)
50+ x = torch.rand(1, 12, 24)
51+ y = torch.rand(2, 3, 12, 16)
52+ z = torch.rand(1, 10, 12, 16, 24)
53+ w0 = torch.rand(24)
54+ w1 = torch.rand(12, 16)
55+ w2 = torch.rand(24)
56+
57+ a0, a1, a2 = net(x, y, z, w0, w1, w2)
58+
59+ # export torchscript
60+ mod = torch.jit.trace(net, (x, y, z, w0, w1, w2))
61+ mod.save("test_F_rms_norm.pt")
62+
63+ # torchscript to pnnx
64+ import os
65+ os.system("../src/pnnx test_F_rms_norm.pt inputshape=[1,12,24],[2,3,12,16],[1,10,12,16,24],[24],[12,16],[24]")
66+
67+ # pnnx inference
68+ import test_F_rms_norm_pnnx
69+ b0, b1, b2 = test_F_rms_norm_pnnx.test_inference()
70+
71+ return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2)
72+
73+if __name__ == "__main__":
74+ if test():
75+ exit(0)
76+ else:
77+ exit(1)
added tools/pnnx/tests/test_nn_RMSNorm.py +71 −0
@@ -0,0 +1,71 @@
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 Model(nn.Module):
21+ def __init__(self):
22+ super(Model, self).__init__()
23+
24+ self.rmsn_0 = nn.RMSNorm(64)
25+ self.rmsn_0.weight = nn.Parameter(torch.rand(64))
26+ self.rmsn_1 = nn.RMSNorm(normalized_shape=(24,64), eps=1e-2, elementwise_affine=False)
27+
28+ def forward(self, x, y, z):
29+ x = self.rmsn_0(x)
30+ x = self.rmsn_1(x)
31+
32+ y = self.rmsn_0(y)
33+ y = self.rmsn_1(y)
34+
35+ z = self.rmsn_0(z)
36+ z = self.rmsn_1(z)
37+ return x, y, z
38+
39+def test():
40+ if version.parse(torch.__version__) < version.parse('2.4'):
41+ return True
42+
43+ net = Model()
44+ net.eval()
45+
46+ torch.manual_seed(0)
47+ x = torch.rand(1, 24, 64)
48+ y = torch.rand(1, 12, 24, 64)
49+ z = torch.rand(1, 12, 16, 24, 64)
50+
51+ a0, a1, a2 = net(x, y, z)
52+
53+ # export torchscript
54+ mod = torch.jit.trace(net, (x, y, z))
55+ mod.save("test_nn_RMSNorm.pt")
56+
57+ # torchscript to pnnx
58+ import os
59+ os.system("../src/pnnx test_nn_RMSNorm.pt inputshape=[1,24,64],[1,12,24,64],[1,12,16,24,64]")
60+
61+ # pnnx inference
62+ import test_nn_RMSNorm_pnnx
63+ b0, b1, b2 = test_nn_RMSNorm_pnnx.test_inference()
64+
65+ return torch.equal(a0, b0) and torch.equal(a1, b1) and torch.equal(a2, b2)
66+
67+if __name__ == "__main__":
68+ if test():
69+ exit(0)
70+ else:
71+ exit(1)