Elffuss BraidHub

kikocis/ncnn public

master · 36.5 KiBRawPermalink
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_onnx.h"
16
17#include "onnx-ml.pb.h"
18
19#include <google/protobuf/io/coded_stream.h>
20#include <google/protobuf/io/zero_copy_stream_impl.h>
21#include <google/protobuf/message.h>
22#include <google/protobuf/text_format.h>
23
24#include <fstream>
25
26#include "ir.h"
27
28namespace pnnx {
29
30namespace onnx2pnnx {
31
32static float get_tensor_f(const onnx::TensorProto& tensor)
33{
34 int64_t numel = 1;
35 for (int k = 0; k < tensor.dims_size(); k++)
36 {
37 numel *= tensor.dims(k);
38 }
39
40 if (numel != 1)
41 {
42 fprintf(stderr, "get_tensor_f numel %ld\n", numel);
43 }
44
45 if (tensor.data_type() == onnx::TensorProto::FLOAT)
46 {
47 if (tensor.has_raw_data())
48 {
49 // assert tensor.raw_data().size() == 4
50 return ((float*)tensor.raw_data().data())[0];
51 }
52
53 // assert tensor.float_data().size() == 1
54 return tensor.float_data().at(0);
55 }
56
57 // fatal error
58 fprintf(stderr, "get_tensor_f failed\n");
59 return 0.f;
60}
61
62static std::vector<float> get_tensor_af(const onnx::TensorProto& tensor)
63{
64 if (tensor.dims_size() != 1)
65 {
66 fprintf(stderr, "get_tensor_af dims_size %d\n", (int)tensor.dims_size());
67 }
68
69 const int64_t numel = tensor.dims(0);
70
71 if (tensor.data_type() == onnx::TensorProto::FLOAT)
72 {
73 const float* p = tensor.has_raw_data() ? (float*)tensor.raw_data().data() : tensor.float_data().data();
74 std::vector<float> af(numel);
75 memcpy(af.data(), p, sizeof(float) * numel);
76 return af;
77 }
78
79 // fatal error
80 fprintf(stderr, "get_tensor_af failed\n");
81 return std::vector<float>();
82}
83
84static int64_t get_tensor_i(const onnx::TensorProto& tensor)
85{
86 int64_t numel = 1;
87 for (int k = 0; k < tensor.dims_size(); k++)
88 {
89 numel *= tensor.dims(k);
90 }
91
92 if (numel != 1)
93 {
94 fprintf(stderr, "get_tensor_i numel %ld\n", numel);
95 }
96
97 if (tensor.data_type() == onnx::TensorProto::INT32)
98 {
99 if (tensor.has_raw_data())
100 {
101 // assert tensor.raw_data().size() == 4
102 return ((int*)tensor.raw_data().data())[0];
103 }
104
105 // assert tensor.int32_data().size() == 1
106 return tensor.int32_data().at(0);
107 }
108
109 if (tensor.data_type() == onnx::TensorProto::INT64)
110 {
111 if (tensor.has_raw_data())
112 {
113 // assert tensor.raw_data().size() == 8
114 return ((int64_t*)tensor.raw_data().data())[0];
115 }
116
117 // assert tensor.int64_data().size() == 1
118 return tensor.int64_data().at(0);
119 }
120
121 // fatal error
122 fprintf(stderr, "get_tensor_i failed\n");
123 return 0;
124}
125
126static std::vector<int64_t> get_tensor_ai(const onnx::TensorProto& tensor)
127{
128 if (tensor.dims_size() != 1)
129 {
130 fprintf(stderr, "get_tensor_af dims_size %d\n", (int)tensor.dims_size());
131 }
132
133 const int64_t numel = tensor.dims(0);
134
135 if (tensor.data_type() == onnx::TensorProto::INT32)
136 {
137 const int* p = tensor.has_raw_data() ? (int*)tensor.raw_data().data() : tensor.int32_data().data();
138 std::vector<int64_t> ai(numel);
139 for (int i = 0; i < numel; i++)
140 ai[i] = p[i];
141 return ai;
142 }
143
144 if (tensor.data_type() == onnx::TensorProto::INT64)
145 {
146 const int64_t* p = tensor.has_raw_data() ? (int64_t*)tensor.raw_data().data() : tensor.int64_data().data();
147 std::vector<int64_t> ai(numel);
148 memcpy(ai.data(), p, sizeof(int64_t) * numel);
149 return ai;
150 }
151
152 // fatal error
153 fprintf(stderr, "get_tensor_ai failed\n");
154 return std::vector<int64_t>();
155}
156
157float OnnxAttributeProxy::value_f() const
158{
159 if (attr.type() == onnx::AttributeProto::FLOAT)
160 {
161 return attr.f();
162 }
163
164 if (attr.type() == onnx::AttributeProto::TENSOR)
165 {
166 return get_tensor_f(attr.t());
167 }
168
169 fprintf(stderr, "OnnxAttributeProxy value_f failed\n");
170 return 0.f;
171}
172
173int64_t OnnxAttributeProxy::value_i() const
174{
175 if (attr.type() == onnx::AttributeProto::INT)
176 {
177 return attr.i();
178 }
179
180 if (attr.type() == onnx::AttributeProto::TENSOR)
181 {
182 return get_tensor_i(attr.t());
183 }
184
185 fprintf(stderr, "OnnxAttributeProxy value_i failed\n");
186 return 0;
187}
188
189std::string OnnxAttributeProxy::value_s() const
190{
191 if (attr.type() != onnx::AttributeProto::STRING)
192 fprintf(stderr, "OnnxAttributeProxy value_s failed\n");
193
194 return attr.s();
195}
196
197std::vector<float> OnnxAttributeProxy::value_fs() const
198{
199 if (attr.type() == onnx::AttributeProto::FLOATS)
200 {
201 const int size = attr.floats().size();
202 std::vector<float> fs(size);
203 for (int i = 0; i < size; i++)
204 {
205 fs[i] = attr.floats().at(i);
206 }
207 return fs;
208 }
209
210 if (attr.type() == onnx::AttributeProto::TENSOR)
211 {
212 return get_tensor_af(attr.t());
213 }
214
215 fprintf(stderr, "OnnxAttributeProxy value_fs failed\n");
216 return std::vector<float>();
217}
218
219std::vector<int64_t> OnnxAttributeProxy::value_is() const
220{
221 if (attr.type() == onnx::AttributeProto::INTS)
222 {
223 const int size = attr.ints().size();
224 std::vector<int64_t> is(size);
225 for (int i = 0; i < size; i++)
226 {
227 is[i] = attr.ints().at(i);
228 }
229 return is;
230 }
231
232 if (attr.type() == onnx::AttributeProto::TENSOR)
233 {
234 return get_tensor_ai(attr.t());
235 }
236
237 fprintf(stderr, "OnnxAttributeProxy value_is failed\n");
238 return std::vector<int64_t>();
239}
240
241std::vector<std::string> OnnxAttributeProxy::value_ss() const
242{
243 if (attr.type() != onnx::AttributeProto::STRINGS)
244 fprintf(stderr, "OnnxAttributeProxy value_ss failed\n");
245
246 const int size = attr.strings().size();
247 std::vector<std::string> ss(size);
248 for (int i = 0; i < size; i++)
249 {
250 ss[i] = attr.strings().at(i);
251 }
252 return ss;
253}
254
255OnnxNodeProxy::OnnxNodeProxy(const onnx::NodeProto& _node)
256 : node(_node)
257{
258 // extract attribute info
259 for (int i = 0; i < node.attribute_size(); i++)
260 {
261 const std::string& name = node.attribute(i).name();
262 attributes.insert(std::make_pair(name, i));
263 }
264}
265
266bool OnnxNodeProxy::has_attribute(const std::string& name) const
267{
268 return attributes.count(name);
269}
270
271const OnnxAttributeProxy OnnxNodeProxy::attribute(const std::string& name) const
272{
273 int attribute_index = attributes.at(name);
274 return node.attribute(attribute_index);
275}
276
277OnnxFunctionProxy::OnnxFunctionProxy(const onnx::ModelProto& _model, const onnx::NodeProto& _caller, const onnx::FunctionProto& _function)
278 : model(_model), caller(_caller), function(_function)
279{
280 for (int i = 0; i < function.node_size(); i++)
281 {
282 const std::string& name = function.node(i).name();
283 named_nodes.insert(std::make_pair(name, i));
284
285 const std::string& type = function.node(i).op_type();
286 typed_nodes.insert(std::make_pair(type, i));
287 }
288
289 for (int i = 0; i < caller.input_size(); i++)
290 {
291 const std::string& function_argument = caller.input(i);
292
293 int initializer_index = -1;
294 for (int j = 0; j < model.graph().initializer_size(); j++)
295 {
296 if (model.graph().initializer(j).name() == function_argument)
297 {
298 initializer_index = j;
299 break;
300 }
301 }
302
303 const std::string& function_parameter = function.input(i);
304 initializers.insert(std::make_pair(function_parameter, initializer_index));
305 }
306}
307
308bool OnnxFunctionProxy::has_typed_node(const std::string& type) const
309{
310 return typed_nodes.count(type);
311}
312
313bool OnnxFunctionProxy::has_named_node(const std::string& name) const
314{
315 return named_nodes.count(name);
316}
317
318const OnnxNodeProxy OnnxFunctionProxy::typed_node(const std::string& type) const
319{
320 int node_index = typed_nodes.at(type);
321 return function.node(node_index);
322}
323
324const OnnxNodeProxy OnnxFunctionProxy::named_node(const std::string& name) const
325{
326 int node_index = named_nodes.at(name);
327 return function.node(node_index);
328}
329
330const OnnxNodeProxy OnnxFunctionProxy::find_producer(const std::string& name) const
331{
332 // find Constant node which produces name
333 for (int i = 0; i < function.node_size(); i++)
334 {
335 const onnx::NodeProto& node = function.node(i);
336 for (int j = 0; j < node.output_size(); j++)
337 {
338 if (node.output(j) == name)
339 {
340 return node;
341 }
342 }
343 }
344
345 // should never reach here
346 return function.node(0);
347}
348
349bool OnnxFunctionProxy::has_initializer(const std::string& name) const
350{
351 return initializers.count(name);
352}
353
354const onnx::TensorProto& OnnxFunctionProxy::initializer(const std::string& name) const
355{
356 int initializer_index = initializers.at(name);
357 return model.graph().initializer(initializer_index);
358}
359
360OnnxModelProxy::OnnxModelProxy(const onnx::ModelProto& _model)
361 : model(_model)
362{
363 for (int i = 0; i < model.graph().node_size(); i++)
364 {
365 const std::string& name = model.graph().node(i).name();
366 nodes.insert(std::make_pair(name, i));
367
368 for (int j = 0; j < model.functions_size(); j++)
369 {
370 const std::string& function_name = model.functions(j).name();
371 if (function_name == model.graph().node(i).op_type())
372 {
373 functions.insert(std::make_pair(function_name + name, j));
374 }
375 }
376 }
377
378 for (int i = 0; i < model.graph().input_size(); i++)
379 {
380 const std::string& name = model.graph().input(i).name();
381 valueinfos.insert(std::make_pair(name, -1));
382 }
383 for (int i = 0; i < model.graph().output_size(); i++)
384 {
385 const std::string& name = model.graph().output(i).name();
386 valueinfos.insert(std::make_pair(name, -2));
387 }
388
389 for (int i = 0; i < model.graph().value_info_size(); i++)
390 {
391 const std::string& name = model.graph().value_info(i).name();
392 valueinfos.insert(std::make_pair(name, i));
393 }
394
395 for (int i = 0; i < model.graph().initializer_size(); i++)
396 {
397 const std::string& name = model.graph().initializer(i).name();
398 initializers.insert(std::make_pair(name, i));
399 }
400}
401
402bool OnnxModelProxy::has_node(const std::string& name) const
403{
404 return nodes.count(name);
405}
406
407const OnnxNodeProxy OnnxModelProxy::node(const std::string& name) const
408{
409 int node_index = nodes.at(name);
410 return model.graph().node(node_index);
411}
412
413bool OnnxModelProxy::has_function(const std::string& name, const std::string& caller) const
414{
415 return functions.count(name + caller);
416}
417
418const OnnxFunctionProxy OnnxModelProxy::function(const std::string& name, const std::string& caller) const
419{
420 int function_index = functions.at(name + caller);
421 return OnnxFunctionProxy(model, node(caller).node, model.functions(function_index));
422}
423
424bool OnnxModelProxy::has_valueinfo(const std::string& name) const
425{
426 return valueinfos.count(name);
427}
428
429const onnx::ValueInfoProto& OnnxModelProxy::valueinfo(const std::string& name) const
430{
431 int valueinfo_index = valueinfos.at(name);
432 if (valueinfo_index == -1)
433 {
434 for (int i = 0; i < model.graph().input_size(); i++)
435 {
436 if (model.graph().input(i).name() == name)
437 return model.graph().input(i);
438 }
439 }
440 if (valueinfo_index == -2)
441 {
442 for (int i = 0; i < model.graph().output_size(); i++)
443 {
444 if (model.graph().output(i).name() == name)
445 return model.graph().output(i);
446 }
447 }
448
449 return model.graph().value_info(valueinfo_index);
450}
451
452bool OnnxModelProxy::has_initializer(const std::string& name) const
453{
454 return initializers.count(name);
455}
456
457const onnx::TensorProto& OnnxModelProxy::initializer(const std::string& name) const
458{
459 int initializer_index = initializers.at(name);
460 return model.graph().initializer(initializer_index);
461}
462
463FuseFunctionPass::~FuseFunctionPass()
464{
465}
466
467void FuseFunctionPass::write(Operator* /*op*/, const OnnxFunctionProxy& /*function*/) const
468{
469}
470
471static std::vector<const FuseFunctionPass*> g_global_pnnx_fuse_function_passes;
472
473const std::vector<const FuseFunctionPass*>& get_global_pnnx_fuse_function_passes()
474{
475 return g_global_pnnx_fuse_function_passes;
476}
477
478FuseFunctionPassRegister::FuseFunctionPassRegister(const FuseFunctionPass* _pass)
479 : pass(_pass)
480{
481 g_global_pnnx_fuse_function_passes.push_back(pass);
482}
483
484FuseFunctionPassRegister::~FuseFunctionPassRegister()
485{
486 delete pass;
487}
488
489} // namespace onnx2pnnx
490
491static bool string_starts_with(const std::string& s, const std::string& s2)
492{
493 return strncmp(s.c_str(), s2.c_str(), s2.size()) == 0;
494}
495
496static void fuse_list_unpack(Graph& graph)
497{
498 // prim::Constant + aten::getitem ... -> prim::ListUnpack
499
500 while (1)
501 {
502 bool matched = false;
503
504 for (size_t i = 0; i < graph.ops.size(); i++)
505 {
506 Operator* op = graph.ops[i];
507
508 if (op->type != "aten::getitem")
509 continue;
510
511 Operand* op_in = op->inputs[0];
512
513 const int item_count = (int)op_in->consumers.size();
514
515 std::vector<Operator*> getitem_ops(item_count);
516
517 Operator* cur = op;
518
519 bool full_getitem = true;
520 for (Operator* op2 : op_in->consumers)
521 {
522 if (op2->type != "aten::getitem")
523 {
524 fprintf(stderr, "unbalanced getitem\n");
525 full_getitem = false;
526 break;
527 }
528
529 int gi = op2->inputs[1]->producer->params.at("value").i;
530 getitem_ops[gi] = op2;
531
532 if (std::find(graph.ops.begin(), graph.ops.end(), op2) < std::find(graph.ops.begin(), graph.ops.end(), cur))
533 cur = op2;
534 }
535
536 if (!full_getitem)
537 continue;
538
539 matched = true;
540
541 // delete all getitem ops and replace with ListUnpack
542 Operator* op_list_unpack = graph.new_operator_before("prim::ListUnpack", op->name, cur);
543
544 op_list_unpack->inputs.push_back(op_in);
545 for (auto op2 : getitem_ops)
546 {
547 op_in->remove_consumer(op2);
548 }
549 op_in->consumers.push_back(op_list_unpack);
550
551 op_list_unpack->outputs.resize(getitem_ops.size());
552 for (size_t j = 0; j < getitem_ops.size(); j++)
553 {
554 op_list_unpack->outputs[j] = getitem_ops[j]->outputs[0];
555 getitem_ops[j]->outputs[0]->producer = op_list_unpack;
556 }
557
558 for (auto op2 : getitem_ops)
559 {
560 op2->inputs[1]->remove_consumer(op2);
561
562 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op2));
563 delete op2;
564 }
565
566 break;
567 }
568
569 if (!matched)
570 break;
571 }
572}
573
574static void constant_unpooling(Graph& graph)
575{
576 while (1)
577 {
578 bool matched = false;
579
580 for (size_t i = 0; i < graph.ops.size(); i++)
581 {
582 Operator* op = graph.ops[i];
583
584 if (op->type != "prim::Constant" && op->type != "pnnx.Expression" && op->type != "pnnx.Attribute")
585 continue;
586
587 Operand* op_out = op->outputs[0];
588 if (op_out->consumers.size() == 1)
589 continue;
590
591 matched = true;
592
593 // create shadow node for all consumers
594 for (size_t j = 1; j < op_out->consumers.size(); j++)
595 {
596 Operator* op1 = op_out->consumers[j];
597
598 Operator* op0 = graph.new_operator_before(op->type, op->name + "_pnnxshadow" + std::to_string(j), op1);
599 op0->inputnames = op->inputnames;
600 op0->params = op->params;
601 op0->attrs = op->attrs;
602
603 Operand* op0_out = graph.new_operand(op_out->name + "_pnnxshadow" + std::to_string(j));
604 op0_out->type = op_out->type;
605 op0_out->shape = op_out->shape;
606 op0_out->params = op_out->params;
607
608 op0_out->producer = op0;
609 op0->outputs.push_back(op0_out);
610
611 for (size_t k = 0; k < op1->inputs.size(); k++)
612 {
613 if (op1->inputs[k] == op_out)
614 {
615 op1->inputs[k] = op0_out;
616 break;
617 }
618 }
619
620 op0_out->consumers.push_back(op1);
621 }
622
623 op_out->consumers.resize(1);
624
625 break;
626 }
627
628 if (!matched)
629 break;
630 }
631}
632
633void pass_onnx(const onnx::ModelProto& model, Graph& pnnx_graph)
634{
635 onnx2pnnx::OnnxModelProxy modelproxy(model);
636
637 const onnx::GraphProto& graph = model.graph();
638
639 for (int i = 0; i < graph.input_size(); i++)
640 {
641 const std::string& input = graph.input(i).name();
642
643 Operator* op = pnnx_graph.new_operator("pnnx.Input", input);
644
645 const onnx::ValueInfoProto& value = modelproxy.valueinfo(input);
646
647 Operand* op_out = pnnx_graph.new_operand(value);
648
649 op_out->producer = op;
650 op->outputs.push_back(op_out);
651 }
652
653 for (int i = 0; i < graph.node_size(); i++)
654 {
655 const onnx::NodeProto& node = graph.node(i);
656
657 std::string op_type = node.op_type();
658
659 // drop |folded_N suffix
660 if (op_type.size() > 8)
661 {
662 size_t folded_N_index = op_type.rfind("|folded_");
663 if (folded_N_index != std::string::npos)
664 {
665 op_type = op_type.substr(0, folded_N_index);
666 }
667 }
668
669 std::string sim_op_type;
670
671 if (node.domain().empty())
672 {
673 // native onnx op
674 sim_op_type = op_type;
675
676 if (op_type == "SequenceConstruct")
677 {
678 sim_op_type = "prim::ListConstruct";
679 }
680
681 if (op_type == "Concat")
682 {
683 sim_op_type = "aten::cat";
684 }
685
686 if (op_type == "Split")
687 {
688 sim_op_type = "aten::split";
689 }
690
691 if (op_type == "Shape")
692 {
693 sim_op_type = "aten::size";
694 }
695
696 // unaryop
697 if (op_type == "Abs") sim_op_type = "aten::abs";
698 if (op_type == "Acos") sim_op_type = "aten::acos";
699 if (op_type == "Acosh") sim_op_type = "aten::acosh";
700 if (op_type == "Asin") sim_op_type = "aten::asin";
701 if (op_type == "Asinh") sim_op_type = "aten::asinh";
702 if (op_type == "Atan") sim_op_type = "aten::atan";
703 if (op_type == "Atanh") sim_op_type = "aten::atanh";
704 if (op_type == "Ceil") sim_op_type = "aten::ceil";
705 if (op_type == "Cos") sim_op_type = "aten::cos";
706 if (op_type == "Cosh") sim_op_type = "aten::cosh";
707 if (op_type == "Erf") sim_op_type = "aten::erf";
708 if (op_type == "Exp") sim_op_type = "aten::exp";
709 if (op_type == "Floor") sim_op_type = "aten::floor";
710 if (op_type == "Log") sim_op_type = "aten::log";
711 if (op_type == "Neg") sim_op_type = "aten::neg";
712 if (op_type == "Reciprocal") sim_op_type = "aten::reciprocal";
713 if (op_type == "Round") sim_op_type = "aten::round";
714 if (op_type == "Sigmoid") sim_op_type = "aten::sigmoid";
715 if (op_type == "Sign") sim_op_type = "aten::sign";
716 if (op_type == "Sin") sim_op_type = "aten::sin";
717 if (op_type == "Sinh") sim_op_type = "aten::sinh";
718 if (op_type == "Sqrt") sim_op_type = "aten::sqrt";
719 if (op_type == "Tan") sim_op_type = "aten::tan";
720 if (op_type == "Tanh") sim_op_type = "aten::tanh";
721
722 // binaryop
723 if (op_type == "Add") sim_op_type = "aten::add";
724 if (op_type == "Sub") sim_op_type = "aten::sub";
725 if (op_type == "Mul") sim_op_type = "aten::mul";
726 if (op_type == "Div") sim_op_type = "aten::div";
727 if (op_type == "Max") sim_op_type = "aten::max";
728 if (op_type == "Min") sim_op_type = "aten::min";
729 if (op_type == "Pow") sim_op_type = "aten::pow";
730 if (op_type == "Equal") sim_op_type = "aten::eq";
731 if (op_type == "Less") sim_op_type = "aten::lt";
732 if (op_type == "LessOrEqual") sim_op_type = "aten::le";
733 if (op_type == "Greater") sim_op_type = "aten::gt";
734 if (op_type == "GreaterOrEqual") sim_op_type = "aten::ge";
735 if (op_type == "BitwiseAnd") sim_op_type = "aten::bitwise_and";
736 if (op_type == "BitwiseNot") sim_op_type = "aten::bitwise_not";
737 if (op_type == "BitwiseOr") sim_op_type = "aten::bitwise_or";
738 if (op_type == "BitwiseXor") sim_op_type = "aten::bitwise_xor";
739 if (op_type == "And") sim_op_type = "aten::__and__";
740 if (op_type == "Or") sim_op_type = "aten::__or__";
741 if (op_type == "Xor") sim_op_type = "aten::__xor__";
742
743 // trinaryop
744 if (op_type == "Clip") sim_op_type = "aten::clamp";
745 if (op_type == "Where") sim_op_type = "aten::where";
746 }
747 else if (string_starts_with(op_type, "aten_"))
748 {
749 // aten_view
750 sim_op_type = std::string("aten::") + op_type.substr(5);
751 }
752 else if (string_starts_with(op_type, "_aten_"))
753 {
754 // _aten_roll_shift_and_dim_onnx
755 sim_op_type = std::string("aten::") + op_type.substr(6);
756 }
757 else if (string_starts_with(op_type, "prims_"))
758 {
759 // prims_convert_element_type
760 sim_op_type = std::string("prim::") + op_type.substr(6);
761 }
762 else if (string_starts_with(op_type, "nn_"))
763 {
764 // torch_nn_modules_conv_Conv2d _conv1_1
765 sim_op_type = op_type;
766 // nn_Conv2d_i -> nn.Conv2d
767 sim_op_type[2] = '.';
768 if (sim_op_type.find_first_of('_') != std::string::npos)
769 sim_op_type = sim_op_type.substr(0, sim_op_type.find_first_of('_'));
770 }
771 else
772 {
773 // custom function
774 sim_op_type = std::string("custom_op.") + op_type;
775 }
776
777 // fprintf(stderr, "%-24s %-8s", sim_op_type.c_str(), node.name().c_str());
778
779 Operator* op = pnnx_graph.new_operator(sim_op_type, node.name());
780
781 // bool is_function = modelproxy.has_function(node.op_type(), node.name());
782
783 bool is_function_op = string_starts_with(sim_op_type, "nn.") || string_starts_with(sim_op_type, "custom_op.");
784
785 bool is_aten_op = string_starts_with(sim_op_type, "aten::");
786
787 bool is_prim_op = string_starts_with(sim_op_type, "prim::");
788
789 for (int j = 0; j < node.input_size(); j++)
790 {
791 const std::string& input = node.input(j);
792
793 if (input.empty())
794 continue;
795
796 Operand* op_in = pnnx_graph.get_operand(input);
797
798 if (!op_in && modelproxy.has_initializer(input))
799 {
800 // skip function weight
801 if (is_function_op)
802 continue;
803
804 const onnx::TensorProto& tensor = modelproxy.initializer(input);
805
806 bool is_attr_list = false;
807 if (tensor.dims_size() == 1 && (tensor.data_type() == onnx::TensorProto::INT32 || tensor.data_type() == onnx::TensorProto::INT64))
808 {
809 if (is_aten_op)
810 is_attr_list = true;
811 }
812
813 bool is_attr_weight = false;
814 {
815 if (sim_op_type == "BatchNormalization" && (j == 1 || j == 2 || j == 3 || j == 4))
816 is_attr_weight = true;
817 if (sim_op_type == "Conv" && (j == 1 || j == 2))
818 is_attr_weight = true;
819 if (sim_op_type == "ConvTranspose" && (j == 1 || j == 2))
820 is_attr_weight = true;
821 if (sim_op_type == "Gather" && j == 0)
822 is_attr_weight = true;
823 if (sim_op_type == "Gemm" && (j == 1 || j == 2))
824 is_attr_weight = true;
825 if (sim_op_type == "GroupNormalization" && (j == 1 || j == 2))
826 is_attr_weight = true;
827 if (sim_op_type == "GRU" && (j == 1 || j == 2 || j == 3 || j == 5))
828 is_attr_weight = true;
829 if (sim_op_type == "InstanceNormalization" && (j == 1 || j == 2))
830 is_attr_weight = true;
831 if (sim_op_type == "LayerNormalization" && (j == 1 || j == 2))
832 is_attr_weight = true;
833 if (sim_op_type == "LSTM" && (j == 1 || j == 2 || j == 3 || j == 5 || j == 6))
834 is_attr_weight = true;
835 if (sim_op_type == "PRelu" && j == 1)
836 is_attr_weight = true;
837 if (sim_op_type == "RNN" && (j == 1 || j == 2 || j == 3 || j == 5))
838 is_attr_weight = true;
839 }
840
841 int64_t numel = 1;
842 for (int k = 0; k < tensor.dims_size(); k++)
843 {
844 numel *= tensor.dims(k);
845 }
846
847 if (numel == 1 && !is_attr_weight)
848 {
849 Operator* op_const = pnnx_graph.new_operator_before("prim::Constant", input, op);
850
851 Operand* op_const_out = pnnx_graph.new_operand(input);
852
853 op_const_out->producer = op_const;
854 op_const->outputs.push_back(op_const_out);
855
856 if (tensor.data_type() == onnx::TensorProto::INT32)
857 {
858 if (tensor.has_raw_data())
859 {
860 // assert tensor.raw_data().size() == 4
861 op_const->params["value"] = ((int*)tensor.raw_data().data())[0];
862 }
863 else
864 {
865 // assert tensor.int32_data().size() == 1
866 op_const->params["value"] = tensor.int32_data().at(0);
867 }
868 }
869 else if (tensor.data_type() == onnx::TensorProto::INT64)
870 {
871 int64_t i64;
872 if (tensor.has_raw_data())
873 {
874 // assert tensor.raw_data().size() == 8
875 i64 = ((int64_t*)tensor.raw_data().data())[0];
876 }
877 else
878 {
879 // assert tensor.int64_data().size() == 1
880 i64 = tensor.int64_data().at(0);
881 }
882 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
883 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
884 op_const->params["value"] = (int)i64;
885 }
886 else if (tensor.data_type() == onnx::TensorProto::FLOAT)
887 {
888 if (tensor.has_raw_data())
889 {
890 // assert tensor.raw_data().size() == 4
891 op_const->params["value"] = ((float*)tensor.raw_data().data())[0];
892 }
893 else
894 {
895 // assert tensor.float_data().size() == 1
896 op_const->params["value"] = tensor.float_data().at(0);
897 }
898 }
899 else if (tensor.data_type() == onnx::TensorProto::BOOL)
900 {
901 if (tensor.has_raw_data())
902 {
903 // assert tensor.raw_data().size() == 2
904 op_const->params["value"] = ((uint16_t*)tensor.raw_data().data())[0] ? true : false;
905 }
906 else
907 {
908 // assert tensor.int32_data().size() == 1
909 op_const->params["value"] = tensor.int32_data().at(0) ? true : false;
910 }
911 }
912 else
913 {
914 fprintf(stderr, "unknown constant scalar type %d\n", (int)tensor.data_type());
915 }
916 }
917 else if (is_attr_list && !is_attr_weight)
918 {
919 // create list expression
920 Operator* op_const = pnnx_graph.new_operator_before("pnnx.Expression", input, op);
921
922 Operand* op_const_out = pnnx_graph.new_operand(input);
923
924 op_const_out->producer = op_const;
925 op_const->outputs.push_back(op_const_out);
926
927 const int list_size = tensor.dims(0);
928 if (tensor.data_type() == onnx::TensorProto::INT32)
929 {
930 std::vector<int> ai(list_size);
931 if (tensor.has_raw_data())
932 {
933 // assert tensor.raw_data().size() == 4 * list_size
934 memcpy((void*)ai.data(), (int*)tensor.raw_data().data(), sizeof(int) * list_size);
935 }
936 else
937 {
938 // assert tensor.int32_data().size() == list_size
939 memcpy((void*)ai.data(), tensor.int32_data().data(), sizeof(int) * list_size);
940 }
941 std::string expr = "[";
942 for (int k = 0; k < (int)ai.size(); k++)
943 {
944 expr += std::to_string(ai[k]);
945 if (k != (int)ai.size() - 1)
946 expr += ",";
947 }
948 expr += "]";
949 op_const->params["expr"] = expr;
950 }
951 else if (tensor.data_type() == onnx::TensorProto::INT64)
952 {
953 std::vector<int64_t> ai(list_size);
954 if (tensor.has_raw_data())
955 {
956 // assert tensor.raw_data().size() == 8 * list_size
957 memcpy((void*)ai.data(), (int64_t*)tensor.raw_data().data(), sizeof(int64_t) * list_size);
958 }
959 else
960 {
961 // assert tensor.int64_data().size() == list_size
962 memcpy((void*)ai.data(), tensor.int64_data().data(), sizeof(int64_t) * list_size);
963 }
964 std::string expr = "[";
965 for (int k = 0; k < (int)ai.size(); k++)
966 {
967 int64_t i64 = ai[k];
968 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
969 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
970 expr += std::to_string(i64);
971 if (k != (int)ai.size() - 1)
972 expr += ",";
973 }
974 expr += "]";
975 op_const->params["expr"] = expr;
976 }
977 }
978 else
979 {
980 // create constant for functions
981 Operator* op_const = pnnx_graph.new_operator_before("pnnx.Attribute", input, op);
982
983 // sanitize 123 to c123
984 {
985 char hc = op_const->name[0];
986 if (hc >= '0' && hc <= '9')
987 op_const->name = std::string("pnnx_") + op_const->name;
988 }
989
990 Operand* op_const_out = pnnx_graph.new_operand(tensor);
991
992 op_const_out->producer = op_const;
993 op_const->outputs.push_back(op_const_out);
994
995 op_const->attrs["data"] = tensor;
996 }
997
998 op_in = pnnx_graph.get_operand(input);
999 }
1000
1001 op_in->consumers.push_back(op);
1002 op->inputs.push_back(op_in);
1003 }
1004
1005 for (int j = 0; j < node.output_size(); j++)
1006 {
1007 const std::string& output = node.output(j);
1008
1009 if (output.empty())
1010 continue;
1011
1012 Operand* op_out = 0;
1013
1014 if (modelproxy.has_valueinfo(output))
1015 {
1016 const onnx::ValueInfoProto& value = modelproxy.valueinfo(output);
1017 op_out = pnnx_graph.new_operand(value);
1018 }
1019 else
1020 {
1021 op_out = pnnx_graph.new_operand(output);
1022 }
1023
1024 op_out->producer = op;
1025 op->outputs.push_back(op_out);
1026 }
1027
1028 if (is_function_op)
1029 {
1030 const onnx2pnnx::OnnxFunctionProxy function = modelproxy.function(node.op_type(), node.name());
1031
1032 for (const auto& ow : onnx2pnnx::get_global_pnnx_fuse_function_passes())
1033 {
1034 if (sim_op_type != ow->match_type_str())
1035 continue;
1036
1037 op->type = ow->type_str();
1038 ow->write(op, function);
1039
1040 break;
1041 }
1042 }
1043 else if (is_aten_op)
1044 {
1045 // extract attributes
1046 for (int j = 0; j < node.attribute_size(); j++)
1047 {
1048 const onnx::AttributeProto& attr = node.attribute(j);
1049
1050 op->params[attr.name()] = attr;
1051 }
1052
1053 if (op_type == "Concat")
1054 {
1055 op->params["dim"] = op->params["axis"];
1056 op->params.erase("axis");
1057
1058 // insert for cat prim::ListConstruct
1059 Operator* opm1 = pnnx_graph.new_operator_before("prim::ListConstruct", op->name + "_listconstruct", op);
1060 Operand* opm1_out = pnnx_graph.new_operand(op->name + "_in");
1061 opm1_out->producer = opm1;
1062 opm1->outputs.push_back(opm1_out);
1063 for (auto& x : op->inputs)
1064 {
1065 opm1->inputs.push_back(x);
1066 x->remove_consumer(op);
1067 x->consumers.push_back(opm1);
1068 }
1069 opm1_out->consumers.push_back(op);
1070 op->inputs.clear();
1071 op->inputs.push_back(opm1_out);
1072 }
1073
1074 if (op_type == "Split")
1075 {
1076 op->params["dim"] = op->params["axis"];
1077 op->params.erase("axis");
1078 op->params["indices"] = op->params["split"];
1079 op->params.erase("split");
1080
1081 // insert for tensor_split prim::ListUnpack
1082 Operator* op1 = pnnx_graph.new_operator_after("prim::ListUnpack", op->name + "_listunpack", op);
1083 Operand* op1_in = pnnx_graph.new_operand(op->name + "_out");
1084 op1_in->producer = op;
1085 op1_in->consumers.push_back(op1);
1086 op1->inputs.push_back(op1_in);
1087 for (auto& x : op->outputs)
1088 {
1089 x->producer = op1;
1090 op1->outputs.push_back(x);
1091 }
1092 op->outputs.clear();
1093 op->outputs.push_back(op1_in);
1094 }
1095 }
1096 else if (is_prim_op)
1097 {
1098 // do nothing :)
1099 }
1100 else
1101 {
1102 // onnx native op, extract attributes
1103 for (int j = 0; j < node.attribute_size(); j++)
1104 {
1105 const onnx::AttributeProto& attr = node.attribute(j);
1106
1107 op->params[attr.name()] = attr;
1108 }
1109 }
1110 }
1111
1112 for (int i = 0; i < graph.output_size(); i++)
1113 {
1114 const std::string& input = graph.output(i).name();
1115
1116 Operator* op = pnnx_graph.new_operator("pnnx.Output", input);
1117
1118 Operand* op_in = pnnx_graph.get_operand(input);
1119
1120 op_in->consumers.push_back(op);
1121 op->inputs.push_back(op_in);
1122 }
1123
1124 // post process
1125 fuse_list_unpack(pnnx_graph);
1126
1127 constant_unpooling(pnnx_graph);
1128}
1129
1130} // namespace pnnx