Elffuss BraidHub

kikocis/ncnn public

master · 17.0 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 <torch/csrc/jit/passes/quantization/helper.h>
16#include <torch/csrc/api/include/torch/version.h>
17
18#include "pass_level1.h"
19
20namespace pnnx {
21
22FuseModulePass::~FuseModulePass()
23{
24}
25
26void FuseModulePass::write(Operator* /*op*/, const std::shared_ptr<torch::jit::Graph>& /*graph*/) const
27{
28}
29
30void FuseModulePass::write(Operator* op, const std::shared_ptr<torch::jit::Graph>& graph, const torch::jit::Module& /*mod*/) const
31{
32 write(op, graph);
33}
34
35static std::vector<const FuseModulePass*> g_global_pnnx_fuse_module_passes;
36
37const std::vector<const FuseModulePass*>& get_global_pnnx_fuse_module_passes()
38{
39 return g_global_pnnx_fuse_module_passes;
40}
41
42FuseModulePassRegister::FuseModulePassRegister(const FuseModulePass* _pass)
43 : pass(_pass)
44{
45 g_global_pnnx_fuse_module_passes.push_back(pass);
46}
47
48FuseModulePassRegister::~FuseModulePassRegister()
49{
50 delete pass;
51}
52
53static void fuse_moduleop_unpack(Graph& graph, const std::vector<std::string>& module_operators)
54{
55 while (1)
56 {
57 bool matched = false;
58
59 for (size_t i = 0; i < graph.ops.size(); i++)
60 {
61 Operator* op = graph.ops[i];
62
63 if (std::find(module_operators.begin(), module_operators.end(), op->type) == module_operators.end())
64 continue;
65
66 if (op->outputs.size() != 1)
67 continue;
68
69 if (op->outputs[0]->consumers.size() != 1)
70 continue;
71
72 Operator* op2 = op->outputs[0]->consumers[0];
73 if (op2->type != "prim::TupleUnpack")
74 continue;
75
76 matched = true;
77
78 op->outputs[0]->producer = 0;
79 op->outputs[0]->remove_consumer(op2);
80
81 for (auto& x : op2->outputs)
82 {
83 x->producer = op;
84 }
85
86 op->outputs = op2->outputs;
87
88 op2->inputs.clear();
89 op2->outputs.clear();
90
91 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op2));
92
93 delete op2;
94
95 break;
96 }
97
98 if (!matched)
99 break;
100 }
101}
102
103void pass_level1(const torch::jit::Module& mod, const std::shared_ptr<torch::jit::Graph>& g, const std::vector<std::string>& module_operators, Graph& pg)
104{
105 for (int i = 1; i < (int)g->inputs().size(); i++)
106 {
107 const auto& in = g->inputs()[i];
108
109 char name[32];
110 sprintf(name, "pnnx_input_%d", i - 1);
111
112 Operator* op = pg.new_operator("pnnx.Input", name);
113 Operand* r = pg.new_operand(in);
114 r->producer = op;
115 op->outputs.push_back(r);
116 }
117
118 std::map<std::string, std::string> class_type_to_names;
119 int pnnx_unknown_index = 0;
120
121 for (const auto& n : g->block()->nodes())
122 {
123 if (n->kind() == c10::prim::GetAttr)
124 {
125 // pass
126 std::string name = n->s(torch::jit::attr::name);
127 // std::string name = n->debugName();
128
129 auto class_type = n->output(0)->type()->cast<torch::jit::ClassType>();
130
131 if (class_type)
132 {
133 std::string class_type_str = class_type->str();
134 class_type_to_names[class_type_str] = name;
135 // class_type_to_names[class_type_str] = class_type_str + "." + name;
136 }
137 else
138 {
139 // Tensor from some class
140 // Operator* op = pg.new_operator(n->kind().toDisplayString(), name);
141 Operator* op = pg.new_operator("pnnx.Attribute", name);
142
143 for (int i = 0; i < (int)n->outputs().size(); i++)
144 {
145 const auto& on = n->output(i);
146 Operand* r = pg.new_operand(on);
147 r->producer = op;
148 op->outputs.push_back(r);
149 }
150
151 std::deque<std::string> module_names; // = split(n->input(0)->node()->s(torch::jit::attr::name), '.');
152 {
153 auto np = n->input(0)->node();
154 while (np->hasAttribute(torch::jit::attr::name))
155 {
156 module_names.push_front(np->s(torch::jit::attr::name));
157 np = np->input(0)->node();
158 }
159 }
160
161 std::string wrapped_name;
162 auto sub_mod = mod;
163 for (auto module_name : module_names)
164 {
165 if (wrapped_name.size() > 0)
166 wrapped_name = wrapped_name + "." + module_name;
167 else
168 wrapped_name = module_name;
169 sub_mod = sub_mod.attr(module_name).toModule();
170 }
171
172 if (wrapped_name.empty())
173 {
174 // top-level module
175 wrapped_name = name;
176 }
177
178 op->name = wrapped_name;
179
180 // op->params["this"] = n->input(i)
181
182 // sub_mod.dump(true, true, true);
183
184 op->attrs["data"] = sub_mod.attr(name).toTensor();
185 op->outputs[0]->type = op->attrs["data"].type;
186 op->outputs[0]->shape = op->attrs["data"].shape;
187 }
188 }
189 else if (n->kind() == c10::prim::Constant) // || n->kind() == c10::prim::ListConstruct)
190 {
191 char name[32];
192 sprintf(name, "pnnx_%d", pnnx_unknown_index++);
193
194 Operator* op = pg.new_operator(n->kind().toDisplayString(), name);
195
196 for (int i = 0; i < (int)n->inputs().size(); i++)
197 {
198 const auto& in = n->input(i);
199 Operand* r = pg.get_operand(in->debugName());
200 r->consumers.push_back(op);
201 op->inputs.push_back(r);
202 }
203
204 for (int i = 0; i < (int)n->outputs().size(); i++)
205 {
206 const auto& on = n->output(i);
207 Operand* r = pg.new_operand(on);
208 r->producer = op;
209 op->outputs.push_back(r);
210 }
211
212 op->params["value"] = n;
213
214 if (op->params["value"].type == 8)
215 {
216 op->type = "pnnx.Attribute";
217
218 op->params.erase("value");
219
220 op->attrs["data"] = n->t(torch::jit::attr::value);
221 }
222 }
223 else if (n->kind() == c10::prim::CallMethod)
224 {
225 auto class_type = n->input(0)->type()->cast<torch::jit::ClassType>();
226 // const std::string& name = n->s(torch::jit::attr::name);
227
228 // fprintf(stderr, "call %s\n", class_type->str().c_str());
229
230 std::string name = class_type_to_names[class_type->str()];
231
232 std::string class_type_str = torch::jit::removeTorchMangle(class_type->str());
233
234 std::string class_type_str_no_torch_prefix = class_type_str.substr(10);
235
236 std::string optypename = class_type_str;
237
238 for (const auto& ow : get_global_pnnx_fuse_module_passes())
239 {
240 if (class_type_str != ow->match_type_str())
241 continue;
242
243 optypename = ow->type_str();
244 break;
245 }
246
247 if (optypename == class_type_str)
248 {
249 optypename = class_type_str_no_torch_prefix;
250 }
251
252 Operator* op = pg.new_operator(optypename, name);
253
254 for (int i = 1; i < (int)n->inputs().size(); i++)
255 {
256 const auto& in = n->input(i);
257 Operand* r = pg.get_operand(in->debugName());
258 r->consumers.push_back(op);
259 op->inputs.push_back(r);
260 }
261
262 for (int i = 0; i < (int)n->outputs().size(); i++)
263 {
264 const auto& on = n->output(i);
265 Operand* r = pg.new_operand(on);
266 r->producer = op;
267 op->outputs.push_back(r);
268 }
269
270 // module operator
271 if (std::find(module_operators.begin(), module_operators.end(), class_type_str_no_torch_prefix) != module_operators.end())
272 {
273 const std::string& function_name = n->s(torch::jit::attr::name);
274 torch::jit::Function& function = class_type->getMethod(function_name);
275 if (function.isGraphFunction())
276 {
277#if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 11)
278 torch::jit::Block* moduleop_block = toGraphFunction(function).graph()->block();
279#else
280 torch::jit::Block* moduleop_block = function.graph()->block();
281#endif
282
283 std::map<size_t, torch::jit::Node*> constant_attr_nodes;
284 for (const auto& mn : moduleop_block->nodes())
285 {
286 if (mn->kind() == c10::prim::GetAttr)
287 {
288 std::string name = mn->s(torch::jit::attr::name);
289 // std::string name = mn->debugName();
290
291 auto class_type = mn->output(0)->type()->cast<torch::jit::ClassType>();
292
293 if (!class_type)
294 {
295 std::deque<std::string> module_names; // = split(mn->input(0)->node()->s(torch::jit::attr::name), '.');
296 {
297 auto np = n->input(0)->node();
298 while (np->hasAttribute(torch::jit::attr::name))
299 {
300 module_names.push_front(np->s(torch::jit::attr::name));
301 np = np->input(0)->node();
302 }
303 }
304 std::deque<std::string> module_names2;
305 {
306 auto np = mn->input(0)->node();
307 while (np->hasAttribute(torch::jit::attr::name))
308 {
309 module_names2.push_front(np->s(torch::jit::attr::name));
310 np = np->input(0)->node();
311 }
312 }
313 for (auto x : module_names2)
314 {
315 module_names.push_back(x);
316 }
317
318 auto sub_mod = mod;
319 for (auto module_name : module_names)
320 {
321 sub_mod = sub_mod.attr(module_name).toModule();
322 }
323
324 std::string wrapped_name;
325 for (auto module_name : module_names2)
326 {
327 if (wrapped_name.size() > 0)
328 wrapped_name = wrapped_name + "." + module_name;
329 else
330 wrapped_name = module_name;
331 }
332
333 if (wrapped_name.empty())
334 {
335 // top-level module
336 wrapped_name = name;
337 }
338 else
339 {
340 wrapped_name = wrapped_name + "." + name;
341 }
342
343 op->attrs[wrapped_name] = sub_mod.attr(name).toTensor();
344 }
345 }
346 else if (mn->kind() == c10::prim::Constant)
347 {
348 Parameter p(mn);
349
350 if (p.type == 8)
351 {
352 size_t unique_id = mn->output(0)->unique();
353 constant_attr_nodes[unique_id] = mn;
354 }
355 }
356 }
357
358 int pnnx_moduleop_unknown_index = 0;
359 for (auto attr : constant_attr_nodes)
360 {
361 char name[32];
362 sprintf(name, "pnnx_%02d", pnnx_moduleop_unknown_index);
363 op->attrs[name] = attr.second->t(torch::jit::attr::value);
364 pnnx_moduleop_unknown_index++;
365 }
366 }
367 }
368 else
369 {
370 for (const auto& ow : get_global_pnnx_fuse_module_passes())
371 {
372 if (class_type_str != ow->match_type_str())
373 continue;
374
375 auto class_type = n->input(0)->type()->cast<torch::jit::ClassType>();
376 torch::jit::Function& function = class_type->getMethod(n->s(torch::jit::attr::name));
377
378 std::deque<std::string> module_names; // = split(n->input(0)->node()->s(torch::jit::attr::name), '.');
379 {
380 auto np = n->input(0)->node();
381 while (np->hasAttribute(torch::jit::attr::name))
382 {
383 module_names.push_front(np->s(torch::jit::attr::name));
384 np = np->input(0)->node();
385 }
386 }
387
388 std::string wrapped_name;
389 auto sub_mod = mod;
390 for (auto module_name : module_names)
391 {
392 if (wrapped_name.size() > 0)
393 wrapped_name = wrapped_name + "." + module_name;
394 else
395 wrapped_name = module_name;
396 sub_mod = sub_mod.attr(module_name).toModule();
397 }
398
399 op->name = wrapped_name;
400
401#if TORCH_VERSION_MAJOR >= 2 || (TORCH_VERSION_MAJOR >= 1 && TORCH_VERSION_MINOR >= 11)
402 ow->write(op, toGraphFunction(function).graph(), sub_mod);
403#else
404 ow->write(op, function.graph(), sub_mod);
405#endif
406
407 break;
408 }
409 }
410 }
411 // else if (n->kind() == c10::prim::CallFunction)
412 // {
413 // fprintf(stderr, "function %s", n->kind().toDisplayString());
414 //
415 // AT_ASSERT(cur->input(0)->node()->kind() == c10::prim::Constant);
416 // auto function_constant = cur->input(0)->node();
417 // auto fun_type = function_constant->output()->type()->expect<torch::jit::FunctionType>();
418 // if (!fun_type->function()->isGraphFunction())
419 // {
420 // continue;
421 // }
422 // cur->removeInput(0);
423 //
424 // fprintf(stderr, "inline function %s\n", fun_type->function()->name().c_str());
425 //
426 // GRAPH_UPDATE("Inlining function '", fun_type->function()->name(), "' to ", *cur);
427 // GRAPH_UPDATE("Function body: ", *fun_type->function()->optimized_graph());
428 // inlineCallTo(cur, fun_type->function(), false);
429 // break;
430 // }
431 else
432 {
433 char name[32];
434 sprintf(name, "pnnx_%d", pnnx_unknown_index++);
435
436 Operator* op = pg.new_operator(n->kind().toDisplayString(), name);
437
438 for (int i = 0; i < (int)n->inputs().size(); i++)
439 {
440 const auto& in = n->input(i);
441 Operand* r = pg.get_operand(in->debugName());
442 r->consumers.push_back(op);
443 op->inputs.push_back(r);
444 }
445
446 for (int i = 0; i < (int)n->outputs().size(); i++)
447 {
448 const auto& on = n->output(i);
449 Operand* r = pg.new_operand(on);
450 r->producer = op;
451 op->outputs.push_back(r);
452 }
453 }
454 }
455
456 for (int i = 0; i < (int)g->outputs().size(); i++)
457 {
458 const auto& in = g->outputs()[i];
459
460 char name[32];
461 sprintf(name, "pnnx_output_%d", i);
462 Operator* op = pg.new_operator("pnnx.Output", name);
463 Operand* r = pg.get_operand(in->debugName());
464 r->consumers.push_back(op);
465 op->inputs.push_back(r);
466 }
467
468 // post process
469 fuse_moduleop_unpack(pg, module_operators);
470}
471
472} // namespace pnnx