Elffuss BraidHub

kikocis/ncnn public

pnnx2ncnn convert torch.roll with one or two shifts (#5623)

Changesete5ca598b9f4c8f3b04b149e6b0a181757e25cd3b17767de0b77853ffafda0dff
Authornihui <nihuini@tencent.com> · 2024-08-12 19:33 +08:00
CommitterGitHub <noreply@github.com> · 2024-08-12 19:33 +08:00
Parents690deb1b4c95

Browse the files at this changeset

8 files changed

modified tools/pnnx/src/CMakeLists.txt +1 −0
@@ -572,6 +572,7 @@
572572 pass_ncnn/torch_mm.cpp
573573 pass_ncnn/torch_norm.cpp
574574 pass_ncnn/torch_prod.cpp
575+ pass_ncnn/torch_roll.cpp
575576 pass_ncnn/torch_slice_scatter.cpp
576577 pass_ncnn/torch_squeeze.cpp
577578 pass_ncnn/torch_sum.cpp
added tools/pnnx/src/pass_ncnn/torch_roll.cpp +193 −0
@@ -0,0 +1,193 @@
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_ncnn.h"
16+
17+namespace pnnx {
18+
19+namespace ncnn {
20+
21+class torch_roll : public GraphRewriterPass
22+{
23+public:
24+ const char* match_pattern_graph() const
25+ {
26+ return R"PNNXIR(7767517
27+3 2
28+pnnx.Input input 0 1 input
29+torch.roll op_0 1 1 input out dims=%dims shifts=%shifts
30+pnnx.Output output 1 0 out
31+)PNNXIR";
32+ }
33+
34+ const char* replace_pattern_graph() const
35+ {
36+ return R"PNNXIR(7767517
37+4 3
38+pnnx.Input input 0 1 input
39+Slice slice 1 2 input a b
40+Concat concat 2 1 b a out
41+pnnx.Output output 1 0 out
42+)PNNXIR";
43+ }
44+
45+ bool match(const std::map<std::string, Parameter>& captured_params) const
46+ {
47+ if (captured_params.at("dims").type != 5)
48+ return false;
49+
50+ if (captured_params.at("dims").ai.size() != 1)
51+ return false;
52+
53+ if (captured_params.at("shifts").type != 5)
54+ return false;
55+
56+ if (captured_params.at("shifts").ai.size() != 1)
57+ return false;
58+
59+ return true;
60+ }
61+
62+ void write(const std::map<std::string, Operator*>& ops, const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& captured_attrs) const
63+ {
64+ GraphRewriterPass::write(ops, captured_params, captured_attrs);
65+
66+ const Operand* in = ops.at("slice")->inputs[0];
67+
68+ const int batch_index = in->params.at("__batch_index").i;
69+
70+ int axis = captured_params.at("dims").ai[0];
71+ if (axis == batch_index)
72+ {
73+ fprintf(stderr, "roll along batch axis %d is not supported\n", batch_index);
74+ }
75+
76+ if (axis < 0)
77+ {
78+ int input_rank = in->shape.size();
79+ axis = input_rank + axis;
80+ }
81+
82+ if (axis > batch_index)
83+ axis -= 1;
84+
85+ ops.at("slice")->params["1"] = axis;
86+
87+ ops.at("concat")->params["0"] = axis;
88+
89+ const int shift = captured_params.at("shifts").ai[0];
90+ ops.at("slice")->params["2"] = std::vector<int>{-shift};
91+ }
92+};
93+
94+REGISTER_GLOBAL_PNNX_NCNN_GRAPH_REWRITER_PASS(torch_roll, 20)
95+
96+class torch_roll_1 : public GraphRewriterPass
97+{
98+public:
99+ const char* match_pattern_graph() const
100+ {
101+ return R"PNNXIR(7767517
102+3 2
103+pnnx.Input input 0 1 input
104+torch.roll op_0 1 1 input out dims=%dims shifts=%shifts
105+pnnx.Output output 1 0 out
106+)PNNXIR";
107+ }
108+
109+ const char* replace_pattern_graph() const
110+ {
111+ return R"PNNXIR(7767517
112+8 7
113+pnnx.Input input 0 1 input
114+Slice slice 1 2 input a b
115+Slice slice_a 1 2 a a0 a1
116+Slice slice_b 1 2 b b0 b1
117+Concat concat_a 2 1 a1 a0 a10
118+Concat concat_b 2 1 b1 b0 b10
119+Concat concat 2 1 b10 a10 out
120+pnnx.Output output 1 0 out
121+)PNNXIR";
122+ }
123+
124+ bool match(const std::map<std::string, Parameter>& captured_params) const
125+ {
126+ if (captured_params.at("dims").type != 5)
127+ return false;
128+
129+ if (captured_params.at("dims").ai.size() != 2)
130+ return false;
131+
132+ if (captured_params.at("shifts").type != 5)
133+ return false;
134+
135+ if (captured_params.at("shifts").ai.size() != 2)
136+ return false;
137+
138+ return true;
139+ }
140+
141+ void write(const std::map<std::string, Operator*>& ops, const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& captured_attrs) const
142+ {
143+ GraphRewriterPass::write(ops, captured_params, captured_attrs);
144+
145+ const Operand* in = ops.at("slice")->inputs[0];
146+
147+ const int batch_index = in->params.at("__batch_index").i;
148+
149+ int axis0 = captured_params.at("dims").ai[0];
150+ int axis1 = captured_params.at("dims").ai[1];
151+ if (axis0 == batch_index || axis1 == batch_index)
152+ {
153+ fprintf(stderr, "roll along batch axis %d is not supported\n", batch_index);
154+ }
155+
156+ if (axis0 < 0)
157+ {
158+ int input_rank = in->shape.size();
159+ axis0 = input_rank + axis0;
160+ }
161+
162+ if (axis0 > batch_index)
163+ axis0 -= 1;
164+
165+ if (axis1 < 0)
166+ {
167+ int input_rank = in->shape.size();
168+ axis1 = input_rank + axis1;
169+ }
170+ if (axis1 > batch_index)
171+ axis1 -= 1;
172+
173+ ops.at("slice")->params["1"] = axis0;
174+ ops.at("slice_a")->params["1"] = axis1;
175+ ops.at("slice_b")->params["1"] = axis1;
176+
177+ ops.at("concat_a")->params["0"] = axis1;
178+ ops.at("concat_b")->params["0"] = axis1;
179+ ops.at("concat")->params["0"] = axis0;
180+
181+ const int shift0 = captured_params.at("shifts").ai[0];
182+ const int shift1 = captured_params.at("shifts").ai[1];
183+ ops.at("slice")->params["2"] = std::vector<int>{-shift0};
184+ ops.at("slice_a")->params["2"] = std::vector<int>{-shift1};
185+ ops.at("slice_b")->params["2"] = std::vector<int>{-shift1};
186+ }
187+};
188+
189+REGISTER_GLOBAL_PNNX_NCNN_GRAPH_REWRITER_PASS(torch_roll_1, 20)
190+
191+} // namespace ncnn
192+
193+} // namespace pnnx
modified tools/pnnx/tests/CMakeLists.txt +1 −0
@@ -234,6 +234,7 @@
234234 pnnx_add_test(torch_positive)
235235 pnnx_add_test(torch_prod)
236236 pnnx_add_test(torch_repeat_interleave)
237+pnnx_add_test(torch_roll)
237238 pnnx_add_test(torch_scatter_add)
238239 pnnx_add_test(torch_slice_scatter)
239240 pnnx_add_test(torch_sum)
modified tools/pnnx/tests/ncnn/CMakeLists.txt +1 −0
@@ -162,6 +162,7 @@
162162 pnnx_ncnn_add_test(torch_mm)
163163 pnnx_ncnn_add_test(torch_norm)
164164 pnnx_ncnn_add_test(torch_prod)
165+pnnx_ncnn_add_test(torch_roll)
165166 pnnx_ncnn_add_test(torch_slice_scatter)
166167 pnnx_ncnn_add_test(torch_sum)
167168 pnnx_ncnn_add_test(torch_squeeze)
added tools/pnnx/tests/ncnn/test_torch_roll.py +64 −0
@@ -0,0 +1,64 @@
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+
19+class Model(nn.Module):
20+ def __init__(self):
21+ super(Model, self).__init__()
22+
23+ def forward(self, x, y, z):
24+ x = torch.roll(x, 3, 1)
25+ y = torch.roll(y, -2, -1)
26+ z = torch.roll(z, shifts=(2,1), dims=(0,1))
27+ return x, y, z
28+
29+def test():
30+ net = Model()
31+ net.eval()
32+
33+ torch.manual_seed(0)
34+ x = torch.rand(3, 16)
35+ y = torch.rand(5, 9, 11)
36+ z = torch.rand(8, 5, 9, 10)
37+
38+ a = net(x, y, z)
39+
40+ # export torchscript
41+ mod = torch.jit.trace(net, (x, y, z))
42+ mod.save("test_torch_roll.pt")
43+
44+ # torchscript to ncnn
45+ import os
46+ os.system("../../src/pnnx test_torch_roll.pt inputshape=[3,16],[5,9,11],[8,5,9,10]")
47+
48+ # ncnn inference
49+ import test_torch_roll_ncnn
50+ b = test_torch_roll_ncnn.test_inference()
51+
52+ print(x)
53+ for a0, b0 in zip(a, b):
54+ if not torch.equal(a0, b0):
55+ print(a0)
56+ print(b0)
57+ return False
58+ return True
59+
60+if __name__ == "__main__":
61+ if test():
62+ exit(0)
63+ else:
64+ exit(1)
modified tools/pnnx/tests/onnx/CMakeLists.txt +1 −0
@@ -145,6 +145,7 @@
145145 pnnx_onnx_add_test(torch_min)
146146 pnnx_onnx_add_test(torch_minimum)
147147 pnnx_onnx_add_test(torch_prod)
148+pnnx_onnx_add_test(torch_roll)
148149 pnnx_onnx_add_test(torch_split)
149150 pnnx_onnx_add_test(torch_squeeze)
150151 pnnx_onnx_add_test(torch_stack)
added tools/pnnx/tests/onnx/test_torch_roll.py +64 −0
@@ -0,0 +1,64 @@
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+ def forward(self, x, y, z):
25+ x = torch.roll(x, 3, -1)
26+ y = torch.roll(y, -2, -1)
27+ z = torch.roll(z, shifts=(2,1), dims=(0,1))
28+ return x, y, z
29+
30+def test():
31+ if version.parse(torch.__version__) < version.parse('1.10'):
32+ return True
33+
34+ net = Model()
35+ net.eval()
36+
37+ torch.manual_seed(0)
38+ x = torch.rand(1, 3, 16)
39+ y = torch.rand(1, 5, 9, 11)
40+ z = torch.rand(14, 8, 5, 9, 10)
41+
42+ a = net(x, y, z)
43+
44+ # export onnx
45+ torch.onnx.export(net, (x, y, z), "test_torch_roll.onnx")
46+
47+ # onnx to pnnx
48+ import os
49+ os.system("../../src/pnnx test_torch_roll.onnx inputshape=[1,3,16],[1,5,9,11],[14,8,5,9,10]")
50+
51+ # pnnx inference
52+ import test_torch_roll_pnnx
53+ b = test_torch_roll_pnnx.test_inference()
54+
55+ for a0, b0 in zip(a, b):
56+ if not torch.equal(a0, b0):
57+ return False
58+ return True
59+
60+if __name__ == "__main__":
61+ if test():
62+ exit(0)
63+ else:
64+ exit(1)
added tools/pnnx/tests/test_torch_roll.py +61 −0
@@ -0,0 +1,61 @@
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+
19+class Model(nn.Module):
20+ def __init__(self):
21+ super(Model, self).__init__()
22+
23+ def forward(self, x, y, z):
24+ x = torch.roll(x, 3)
25+ y = torch.roll(y, -2, -1)
26+ z = torch.roll(z, shifts=(2,1), dims=(0,1))
27+ return x, y, z
28+
29+def test():
30+ net = Model()
31+ net.eval()
32+
33+ torch.manual_seed(0)
34+ x = torch.rand(1, 3, 16)
35+ y = torch.rand(1, 5, 9, 11)
36+ z = torch.rand(14, 8, 5, 9, 10)
37+
38+ a = net(x, y, z)
39+
40+ # export torchscript
41+ mod = torch.jit.trace(net, (x, y, z))
42+ mod.save("test_torch_roll.pt")
43+
44+ # torchscript to pnnx
45+ import os
46+ os.system("../src/pnnx test_torch_roll.pt inputshape=[1,3,16],[1,5,9,11],[14,8,5,9,10]")
47+
48+ # pnnx inference
49+ import test_torch_roll_pnnx
50+ b = test_torch_roll_pnnx.test_inference()
51+
52+ for a0, b0 in zip(a, b):
53+ if not torch.equal(a0, b0):
54+ return False
55+ return True
56+
57+if __name__ == "__main__":
58+ if test():
59+ exit(0)
60+ else:
61+ exit(1)