Elffuss BraidHub

kikocis/ncnn public

master · 13.7 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2021 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#include <math.h>
18#include <string.h>
19
20#include <set>
21#include <iostream>
22#include <sstream>
23#include <algorithm>
24#include <stack>
25
26namespace pnnx {
27
28namespace ncnn {
29
30static bool token_is_argument(const std::string& t)
31{
32 if (t[0] != '@' || t.size() < 2)
33 return false;
34
35 for (size_t i = 1; i < t.size(); i++)
36 {
37 if (t[i] < '0' || t[i] > '9')
38 return false;
39 }
40
41 return true;
42}
43
44static bool token_is_complex(const std::string& t)
45{
46 // 2.000000e+00+3.000000e+00j
47 if (t[t.size() - 1] != 'j')
48 return false;
49
50 return true;
51}
52
53static bool token_is_literal(const std::string& t)
54{
55 if (token_is_complex(t))
56 return true;
57
58 std::istringstream iss(t);
59 float f;
60 iss >> std::noskipws >> f;
61 return iss.eof() && !iss.fail();
62}
63
64static std::string expand_expression(Graph& graph, const Operator* op, int& pnnx_expr_index)
65{
66 std::string expr = op->params.at("expr").s;
67
68 // fprintf(stderr, "ncnn expand_expression %s\n", expr.c_str());
69
70 // split into tokens
71 std::vector<std::string> tokens;
72 {
73 std::string t;
74 for (size_t i = 0; i < expr.size(); i++)
75 {
76 char ch = expr[i];
77
78 if (ch == '[') // list
79 {
80 t += ch;
81 tokens.push_back(t);
82 t.clear();
83 }
84 else if (ch == '(' || ch == ')' || ch == ',' || ch == ']')
85 {
86 if (!t.empty())
87 {
88 tokens.push_back(t);
89 t.clear();
90 }
91 }
92 else
93 {
94 t += ch;
95 }
96 }
97
98 if (!t.empty())
99 {
100 tokens.push_back(t);
101 }
102 }
103
104 // scan and stack
105 std::stack<std::string> exprstack;
106 for (int i = (int)tokens.size() - 1; i >= 0; i--)
107 {
108 const std::string& t = tokens[i];
109
110 if (t == "size")
111 {
112 // not supported
113 return std::string();
114 }
115 else if (t == "int")
116 {
117 // not supported
118 return std::string();
119 }
120 else if (t == "abs"
121 || t == "acos"
122 || t == "asin"
123 || t == "atan"
124 || t == "ceil"
125 || t == "cos"
126 || t == "exp"
127 || t == "floor"
128 || t == "log"
129 || t == "log10"
130 || t == "neg"
131 || t == "reciprocal"
132 || t == "round"
133 || t == "rsqrt"
134 || t == "sign"
135 || t == "sin"
136 || t == "sqrt"
137 || t == "square"
138 || t == "tan"
139 || t == "tanh"
140 || t == "trunc")
141 {
142 std::string a = exprstack.top();
143 exprstack.pop();
144
145 std::string r = t + "(" + (token_is_argument(a) ? op->inputs[std::stoi(a.substr(1))]->name : a) + ")";
146 exprstack.push(r);
147
148 Operator* op_unary = graph.new_operator_before("UnaryOp", t + "_" + std::to_string(pnnx_expr_index++), op);
149
150 if (t == "abs") op_unary->params["0"] = 0;
151 if (t == "acos") op_unary->params["0"] = 13;
152 if (t == "asin") op_unary->params["0"] = 12;
153 if (t == "atan") op_unary->params["0"] = 14;
154 if (t == "ceil") op_unary->params["0"] = 3;
155 if (t == "cos") op_unary->params["0"] = 10;
156 if (t == "exp") op_unary->params["0"] = 7;
157 if (t == "floor") op_unary->params["0"] = 2;
158 if (t == "log") op_unary->params["0"] = 8;
159 if (t == "log10") op_unary->params["0"] = 17;
160 if (t == "neg") op_unary->params["0"] = 1;
161 if (t == "reciprocal") op_unary->params["0"] = 15;
162 if (t == "round") op_unary->params["0"] = 18;
163 if (t == "rsqrt") op_unary->params["0"] = 6;
164 if (t == "sign") fprintf(stderr, "UnaryOp sign not supported yet\n"); // TODO
165 if (t == "sin") op_unary->params["0"] = 9;
166 if (t == "sqrt") op_unary->params["0"] = 5;
167 if (t == "square") op_unary->params["0"] = 4;
168 if (t == "tan") op_unary->params["0"] = 11;
169 if (t == "tanh") op_unary->params["0"] = 16;
170 if (t == "trunc") op_unary->params["0"] = 19;
171
172 Operand* op_unary_in = token_is_argument(a) ? op->inputs[std::stoi(a.substr(1))] : graph.get_operand(op->name + "_" + a);
173 op_unary_in->consumers.push_back(op_unary);
174
175 Operand* op_unary_out = graph.new_operand(op->name + "_" + r);
176 op_unary_out->producer = op_unary;
177
178 op_unary_out->shape = op_unary_in->shape;
179
180 op_unary->inputs.push_back(op_unary_in);
181 op_unary->outputs.push_back(op_unary_out);
182 }
183 else if (t == "add"
184 || t == "atan2"
185 || t == "div"
186 || t == "floor_divide"
187 || t == "fmod"
188 || t == "logaddexp"
189 || t == "max"
190 || t == "maximum"
191 || t == "min"
192 || t == "minimum"
193 || t == "mul"
194 || t == "pow"
195 || t == "remainder"
196 || t == "sub")
197 {
198 std::string a = exprstack.top();
199 exprstack.pop();
200 std::string b = exprstack.top();
201 exprstack.pop();
202
203 std::string r = t + "(" + (token_is_argument(a) ? op->inputs[std::stoi(a.substr(1))]->name : a) + "," + (token_is_argument(b) ? op->inputs[std::stoi(b.substr(1))]->name : b) + ")";
204 exprstack.push(r);
205
206 Operator* op_binary = graph.new_operator_before("BinaryOp", t + "_" + std::to_string(pnnx_expr_index++), op);
207
208 // default todo type mark :[
209 op_binary->params["0"] = -1;
210
211 if (t == "add") op_binary->params["0"] = 0;
212 if (t == "sub") op_binary->params["0"] = 1;
213 if (t == "mul") op_binary->params["0"] = 2;
214 if (t == "div") op_binary->params["0"] = 3;
215 if (t == "logaddexp") fprintf(stderr, "BinaryOp logaddexp not supported yet\n"); // TODO
216 if (t == "max" || t == "maximum") op_binary->params["0"] = 4;
217 if (t == "min" || t == "minimum") op_binary->params["0"] = 5;
218 if (t == "floor_divide") fprintf(stderr, "BinaryOp floor_divide not supported yet\n"); // TODO
219 if (t == "fmod") fprintf(stderr, "BinaryOp fmod not supported yet\n"); // TODO
220 if (t == "remainder") fprintf(stderr, "BinaryOp remainder not supported yet\n"); // TODO
221 if (t == "pow") op_binary->params["0"] = 6;
222 if (t == "atan2") op_binary->params["0"] = 10;
223
224 if (token_is_literal(a))
225 {
226 if (t == "sub") op_binary->params["0"] = 7;
227 if (t == "div") op_binary->params["0"] = 8;
228 if (t == "pow") op_binary->params["0"] = 9;
229 if (t == "atan2") op_binary->params["0"] = 11;
230
231 Operand* op_binary_inb = token_is_argument(b) ? op->inputs[std::stoi(b.substr(1))] : graph.get_operand(op->name + "_" + b);
232 op_binary_inb->consumers.push_back(op_binary);
233
234 op_binary->params["1"] = 1; // with_scalar
235 op_binary->params["2"] = std::stof(a);
236
237 Operand* op_binary_out = graph.new_operand(op->name + "_" + r);
238 op_binary_out->producer = op_binary;
239
240 op_binary_out->shape = op_binary_inb->shape;
241
242 op_binary->inputs.push_back(op_binary_inb);
243 op_binary->outputs.push_back(op_binary_out);
244 }
245 else if (token_is_literal(b))
246 {
247 Operand* op_binary_ina = token_is_argument(a) ? op->inputs[std::stoi(a.substr(1))] : graph.get_operand(op->name + "_" + a);
248 op_binary_ina->consumers.push_back(op_binary);
249
250 op_binary->params["1"] = 1; // with_scalar
251 op_binary->params["2"] = std::stof(b);
252
253 if (t == "pow" && std::stof(b) == 2)
254 {
255 // replace pow 2 with square
256 op_binary->type = "UnaryOp";
257 op_binary->params.clear();
258 op_binary->params["0"] = 4;
259 }
260
261 Operand* op_binary_out = graph.new_operand(op->name + "_" + r);
262 op_binary_out->producer = op_binary;
263
264 op_binary_out->shape = op_binary_ina->shape;
265
266 op_binary->inputs.push_back(op_binary_ina);
267 op_binary->outputs.push_back(op_binary_out);
268 }
269 else
270 {
271 Operand* op_binary_ina = token_is_argument(a) ? op->inputs[std::stoi(a.substr(1))] : graph.get_operand(op->name + "_" + a);
272 op_binary_ina->consumers.push_back(op_binary);
273
274 Operand* op_binary_inb = token_is_argument(b) ? op->inputs[std::stoi(b.substr(1))] : graph.get_operand(op->name + "_" + b);
275 op_binary_inb->consumers.push_back(op_binary);
276
277 Operand* op_binary_out = graph.new_operand(op->name + "_" + r);
278 op_binary_out->producer = op_binary;
279
280 // resolve out shape
281 std::vector<int> out_shape;
282 {
283 std::vector<int> a_shape = op_binary_ina->shape;
284 std::vector<int> b_shape = op_binary_inb->shape;
285 int outrank = (int)std::max(a_shape.size(), b_shape.size());
286 for (int k = (int)a_shape.size(); k < outrank; k++)
287 {
288 a_shape.insert(a_shape.begin(), 1);
289 }
290 for (int k = (int)b_shape.size(); k < outrank; k++)
291 {
292 b_shape.insert(b_shape.begin(), 1);
293 }
294 out_shape.resize(outrank);
295 for (int k = 0; k < outrank; k++)
296 {
297 out_shape[k] = std::max(a_shape[k], b_shape[k]);
298 }
299 }
300 op_binary_out->shape = out_shape;
301
302 op_binary->inputs.push_back(op_binary_ina);
303 op_binary->inputs.push_back(op_binary_inb);
304 op_binary->outputs.push_back(op_binary_out);
305 }
306 }
307 else if (t == "[") // list
308 {
309 // not supported
310 return std::string();
311 }
312 else if (t[0] == '@')
313 {
314 exprstack.push(t);
315 }
316 else
317 {
318 // literal
319 exprstack.push(t);
320 }
321 }
322
323 std::string r = exprstack.top();
324 exprstack.pop();
325
326 // fprintf(stderr, "expand_expression return %s\n", r.c_str());
327
328 return r;
329}
330
331void expand_expression(Graph& graph)
332{
333 int pnnx_expr_index = 0;
334
335 std::set<Operator*> nonsupported_expr_ops;
336
337 while (1)
338 {
339 bool matched = false;
340
341 for (size_t i = 0; i < graph.ops.size(); i++)
342 {
343 Operator* op = graph.ops[i];
344 if (op->type != "pnnx.Expression")
345 continue;
346
347 if (nonsupported_expr_ops.find(op) != nonsupported_expr_ops.end())
348 continue;
349
350 matched = true;
351
352 std::string outname = expand_expression(graph, op, pnnx_expr_index);
353
354 if (outname.empty())
355 {
356 // not supported expr
357 nonsupported_expr_ops.insert(op);
358 break;
359 }
360
361 // link new output
362 Operand* old_output_operand = op->outputs[0];
363 Operand* new_output_operand = graph.get_operand(op->name + "_" + outname);
364
365 if (!new_output_operand)
366 {
367 // not supported expr
368 nonsupported_expr_ops.insert(op);
369 break;
370 }
371
372 for (auto r : op->inputs)
373 {
374 r->remove_consumer(op);
375 }
376
377 for (auto& x : old_output_operand->consumers)
378 {
379 new_output_operand->consumers.push_back(x);
380
381 for (size_t j = 0; j < x->inputs.size(); j++)
382 {
383 if (x->inputs[j] == old_output_operand)
384 {
385 x->inputs[j] = new_output_operand;
386 }
387 }
388 }
389
390 new_output_operand->type = old_output_operand->type;
391 new_output_operand->shape = old_output_operand->shape;
392 new_output_operand->params = old_output_operand->params;
393
394 old_output_operand->producer = 0;
395 old_output_operand->consumers.clear();
396
397 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op));
398 delete op;
399
400 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), old_output_operand));
401 delete old_output_operand;
402
403 break;
404 }
405
406 if (!matched)
407 break;
408 }
409}
410
411} // namespace ncnn
412
413} // namespace pnnx