Elffuss BraidHub

kikocis/ncnn public

master · 18.7 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 "load_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 <onnxruntime_c_api.h>
27
28#include "ir.h"
29
30#include "pass_onnx/canonicalize.h"
31#include "pass_onnx/dead_code_elimination.h"
32#include "pass_onnx/eliminate_noop.h"
33#include "pass_onnx/fold_constants.h"
34#include "pass_onnx/inline_containers.h"
35#include "pass_onnx/inline_if_graph.h"
36#include "pass_onnx/model_stat.h"
37#include "pass_onnx/shape_inference.h"
38#include "pass_onnx/fuse_constant_as_attribute.h"
39
40#include "pass_onnx.h"
41
42namespace pnnx {
43
44static size_t type_to_elemsize(int type)
45{
46 if (type == 1) return 4;
47 if (type == 2) return 8;
48 if (type == 3) return 2;
49 if (type == 4) return 4;
50 if (type == 5) return 8;
51 if (type == 6) return 2;
52 if (type == 7) return 1;
53 if (type == 8) return 1;
54 if (type == 9) return 1;
55 if (type == 10) return 8;
56 if (type == 11) return 16;
57 if (type == 12) return 4;
58 return 0; // null
59}
60
61static int get_onnx_tensor_type(int32_t dt)
62{
63 if (dt == onnx::TensorProto::FLOAT) return 1;
64 if (dt == onnx::TensorProto::DOUBLE) return 2;
65 if (dt == onnx::TensorProto::FLOAT16) return 3;
66 if (dt == onnx::TensorProto::INT32) return 4;
67 if (dt == onnx::TensorProto::INT64) return 5;
68 if (dt == onnx::TensorProto::INT16) return 6;
69 if (dt == onnx::TensorProto::INT8) return 7;
70 if (dt == onnx::TensorProto::UINT8) return 8;
71 if (dt == onnx::TensorProto::BOOL) return 9;
72 if (dt == onnx::TensorProto::COMPLEX64) return 10;
73 if (dt == onnx::TensorProto::COMPLEX128) return 11;
74 return 0; // unknown type
75}
76
77Parameter::Parameter(const onnx::AttributeProto& attr)
78{
79 type = 0;
80
81 switch (attr.type())
82 {
83 case onnx::AttributeProto::INT:
84 {
85 type = 2;
86 int64_t i64 = attr.i();
87 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
88 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
89 i = (int)i64;
90 break;
91 }
92 case onnx::AttributeProto::FLOAT:
93 {
94 type = 3;
95 f = attr.f();
96 break;
97 }
98 case onnx::AttributeProto::STRING:
99 {
100 type = 4;
101 s = attr.s();
102 break;
103 }
104 case onnx::AttributeProto::INTS:
105 {
106 type = 5;
107 for (int i = 0; i < attr.ints().size(); i++)
108 {
109 int64_t i64 = attr.ints().at(i);
110 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
111 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
112 ai.push_back(i64);
113 }
114 break;
115 }
116 case onnx::AttributeProto::FLOATS:
117 {
118 type = 6;
119 for (int i = 0; i < attr.floats().size(); i++)
120 {
121 float f = attr.floats().at(i);
122 af.push_back(f);
123 }
124 break;
125 }
126 case onnx::AttributeProto::STRINGS:
127 {
128 type = 7;
129 for (int i = 0; i < attr.strings().size(); i++)
130 {
131 std::string s = attr.strings().at(i);
132 as.push_back(s);
133 }
134 break;
135 }
136 case onnx::AttributeProto::TENSOR:
137 {
138 const onnx::TensorProto& tensor = attr.t();
139
140 int64_t numel = 1;
141 for (int k = 0; k < tensor.dims_size(); k++)
142 {
143 numel *= tensor.dims(k);
144 }
145
146 if (numel == 1)
147 {
148 if (tensor.data_type() == onnx::TensorProto::INT32)
149 {
150 type = 2;
151 if (tensor.has_raw_data())
152 {
153 // assert tensor.raw_data().size() == 4
154 i = ((int*)tensor.raw_data().data())[0];
155 }
156 else
157 {
158 // assert tensor.int32_data().size() == 1
159 i = tensor.int32_data().at(0);
160 }
161 }
162 else if (tensor.data_type() == onnx::TensorProto::INT64)
163 {
164 type = 2;
165 int64_t i64;
166 if (tensor.has_raw_data())
167 {
168 // assert tensor.raw_data().size() == 8
169 i64 = ((int64_t*)tensor.raw_data().data())[0];
170 }
171 else
172 {
173 // assert tensor.int64_data().size() == 1
174 i64 = tensor.int64_data().at(0);
175 }
176 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
177 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
178 i = (int)i64;
179 }
180 else if (tensor.data_type() == onnx::TensorProto::FLOAT)
181 {
182 type = 3;
183 if (tensor.has_raw_data())
184 {
185 // assert tensor.raw_data().size() == 4
186 f = ((float*)tensor.raw_data().data())[0];
187 }
188 else
189 {
190 // assert tensor.float_data().size() == 1
191 f = tensor.float_data().at(0);
192 }
193 }
194 else
195 {
196 fprintf(stderr, "unknown Node attribute tensor data type %d\n", (int)tensor.data_type());
197 }
198 }
199 else
200 {
201 // constant tensor will become pnnx attribute node later
202 type = 8;
203 }
204 break;
205 }
206 default:
207 {
208 fprintf(stderr, "unknown Node attribute type %d\n", (int)attr.type());
209 break;
210 }
211 }
212}
213
214Parameter::Parameter(const onnx2pnnx::OnnxAttributeProxy& attr)
215 : Parameter(attr.attr)
216{
217}
218
219Attribute::Attribute(const onnx::TensorProto& t)
220{
221 type = get_onnx_tensor_type(t.data_type());
222
223 const int ndim = (int)t.dims_size();
224
225 if (ndim == 0)
226 {
227 shape = {1};
228
229 data.resize(type_to_elemsize(type));
230
231 if (t.has_raw_data())
232 {
233 // assert t.raw_data().size() == type_to_elemsize(type)
234 memcpy((void*)data.data(), (const void*)t.raw_data().data(), t.raw_data().size());
235 }
236 else if (t.data_type() == onnx::TensorProto::INT64)
237 {
238 int64_t i = t.int64_data().at(0);
239 memcpy((void*)data.data(), (const void*)&i, data.size());
240 }
241 else if (t.data_type() == onnx::TensorProto::INT32)
242 {
243 int i = t.int32_data().at(0);
244 memcpy((void*)data.data(), (const void*)&i, data.size());
245 }
246 else if (t.data_type() == onnx::TensorProto::DOUBLE)
247 {
248 double f = t.double_data().at(0);
249 memcpy((void*)data.data(), (const void*)&f, data.size());
250 }
251 else if (t.data_type() == onnx::TensorProto::FLOAT)
252 {
253 float f = t.float_data().at(0);
254 memcpy((void*)data.data(), (const void*)&f, data.size());
255 }
256 else
257 {
258 fprintf(stderr, "unknown Attribute tensor scalar type %d\n", type);
259 }
260
261 return;
262 }
263
264 shape.resize(ndim);
265 for (int i = 0; i < ndim; i++)
266 shape[i] = t.dims(i);
267
268 if (shape.size() > 0)
269 {
270 data.resize(elemcount() * type_to_elemsize(type));
271
272 if (t.has_raw_data())
273 {
274 memcpy((void*)data.data(), (const void*)t.raw_data().data(), data.size());
275 }
276 else if (t.data_type() == onnx::TensorProto::INT64)
277 {
278 memcpy((void*)data.data(), (const void*)t.int64_data().data(), data.size());
279 }
280 else if (t.data_type() == onnx::TensorProto::INT32)
281 {
282 memcpy((void*)data.data(), (const void*)t.int32_data().data(), data.size());
283 }
284 else if (t.data_type() == onnx::TensorProto::DOUBLE)
285 {
286 memcpy((void*)data.data(), (const void*)t.double_data().data(), data.size());
287 }
288 else if (t.data_type() == onnx::TensorProto::FLOAT)
289 {
290 memcpy((void*)data.data(), (const void*)t.float_data().data(), data.size());
291 }
292 else
293 {
294 fprintf(stderr, "unknown Attribute tensor scalar type %d\n", type);
295 }
296 }
297}
298
299Operand* Graph::new_operand(const onnx::ValueInfoProto& value)
300{
301 Operand* r = new Operand;
302 r->name = value.name();
303
304 int32_t et = value.type().tensor_type().elem_type();
305 r->type = get_onnx_tensor_type(et);
306
307 const onnx::TensorShapeProto& tensor_shape = value.type().tensor_type().shape();
308 r->shape.resize(tensor_shape.dim_size());
309 for (int z = 0; z < tensor_shape.dim_size(); z++)
310 {
311 if (!tensor_shape.dim(z).has_dim_value())
312 {
313 r->shape[z] = -1;
314 }
315 else
316 {
317 r->shape[z] = tensor_shape.dim(z).dim_value();
318 }
319 }
320
321 operands.push_back(r);
322 return r;
323}
324
325Operand* Graph::new_operand(const onnx::TensorProto& t)
326{
327 Operand* r = new Operand;
328 r->name = t.name();
329
330 r->type = get_onnx_tensor_type(t.data_type());
331
332 const int ndim = (int)t.dims_size();
333 if (ndim == 0)
334 {
335 r->shape = {1};
336 }
337 else
338 {
339 r->shape.resize(ndim);
340 for (int i = 0; i < ndim; i++)
341 r->shape[i] = t.dims(i);
342 }
343
344 operands.push_back(r);
345 return r;
346}
347
348static bool read_proto_from_binary(const char* filepath, onnx::ModelProto* message)
349{
350 std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary);
351 if (!fs.is_open())
352 {
353 fprintf(stderr, "open failed %s\n", filepath);
354 return false;
355 }
356
357 google::protobuf::io::IstreamInputStream input(&fs);
358 google::protobuf::io::CodedInputStream codedstr(&input);
359
360#if GOOGLE_PROTOBUF_VERSION >= 3011000
361 codedstr.SetTotalBytesLimit(INT_MAX);
362#else
363 codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2);
364#endif
365
366 bool success = message->ParseFromCodedStream(&codedstr);
367
368 fs.close();
369
370 return success;
371}
372
373static double get_current_time()
374{
375 auto now = std::chrono::high_resolution_clock::now();
376 auto usec = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
377 return usec.count() / 1000.0;
378}
379
380static const char* get_onnx_tensor_elem_data_type_str(ONNXTensorElementDataType type)
381{
382 switch (type)
383 {
384 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8:
385 return "i8";
386 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8:
387 return "u8";
388 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16:
389 return "i16";
390 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16:
391 return "u16";
392 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32:
393 return "i32";
394 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32:
395 return "u32";
396 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64:
397 return "i64";
398 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64:
399 return "u64";
400 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16:
401 return "f16";
402 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT:
403 return "f32";
404 case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE:
405 return "f64";
406 case ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16:
407 return "bf16";
408 case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64:
409 return "c64";
410 case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128:
411 return "c128";
412 default:
413 break;
414 }
415
416 // unknown
417 fprintf(stderr, "unsupported tensor elem data type %d\n", (int)type);
418 return "";
419}
420
421static bool check_input_shape(onnx::ModelProto& model, const std::vector<std::vector<int64_t> >& input_shapes, const std::vector<std::string>& input_types)
422{
423 const onnx::GraphProto& graph = model.graph();
424
425 if (!input_shapes.empty() && (int)input_shapes.size() != graph.input_size())
426 {
427 fprintf(stderr, "input_shape expect %d tensors but got %d\n", graph.input_size(), (int)input_shapes.size());
428 return false;
429 }
430
431 for (int i = 0; i < graph.input_size(); i++)
432 {
433 const onnx::ValueInfoProto& value = graph.input(i);
434 const onnx::TensorShapeProto& tsp = value.type().tensor_type().shape();
435
436 ONNXTensorElementDataType datatype = (ONNXTensorElementDataType)value.type().tensor_type().elem_type();
437
438 bool matched = true;
439
440 if (input_shapes.empty())
441 {
442 // dynamic dimension size
443 for (int j = 0; j < tsp.dim_size(); j++)
444 {
445 if (!tsp.dim(j).has_dim_value())
446 {
447 matched = false;
448 break;
449 }
450 }
451 }
452 else
453 {
454 if ((int)input_shapes[i].size() != tsp.dim_size())
455 {
456 matched = false;
457 }
458 else
459 {
460 for (int j = 0; j < tsp.dim_size(); j++)
461 {
462 if (!tsp.dim(j).has_dim_value())
463 continue;
464
465 int64_t ds = tsp.dim(j).dim_value();
466 if (ds == -1)
467 continue;
468
469 if (input_shapes[i][j] != ds)
470 matched = false;
471 }
472 }
473
474 if (input_types[i] != get_onnx_tensor_elem_data_type_str(datatype))
475 matched = false;
476 }
477
478 if (!matched)
479 {
480 fprintf(stderr, "input_shapes[%d] expect [", i);
481 for (int j = 0; j < tsp.dim_size(); j++)
482 {
483 if (tsp.dim(j).has_dim_value())
484 {
485 int64_t ds = tsp.dim(j).dim_value();
486 fprintf(stderr, "%ld", ds);
487 }
488 else
489 {
490 fprintf(stderr, "?");
491 }
492 if (j + 1 != tsp.dim_size())
493 fprintf(stderr, ",");
494 }
495 fprintf(stderr, "]%s but got ", get_onnx_tensor_elem_data_type_str(datatype));
496 if (input_shapes.empty())
497 {
498 fprintf(stderr, "nothing\n");
499 }
500 else
501 {
502 fprintf(stderr, "[");
503 for (size_t j = 0; j < input_shapes[i].size(); j++)
504 {
505 fprintf(stderr, "%ld", input_shapes[i][j]);
506 if (j + 1 != input_shapes[i].size())
507 fprintf(stderr, ",");
508 }
509 fprintf(stderr, "]%s\n", input_types[i].c_str());
510 }
511
512 return false;
513 }
514 }
515
516 return true;
517}
518
519int load_onnx(const std::string& onnxpath, Graph& pnnx_graph,
520 const std::vector<std::vector<int64_t> >& input_shapes,
521 const std::vector<std::string>& input_types,
522 const std::vector<std::vector<int64_t> >& input_shapes2,
523 const std::vector<std::string>& input_types2)
524{
525 onnx::ModelProto model;
526
527 bool s1 = read_proto_from_binary(onnxpath.c_str(), &model);
528 if (!s1)
529 {
530 fprintf(stderr, "read_proto_from_binary failed\n");
531 return -1;
532 }
533
534 // input shape sanity check
535 if (!check_input_shape(model, input_shapes, input_types))
536 {
537 return -1;
538 }
539 if (!input_shapes2.empty() && !check_input_shape(model, input_shapes2, input_types2))
540 {
541 return -1;
542 }
543
544 fprintf(stderr, "############# pass_level0 onnx \n");
545
546 onnx2pnnx::ModelStat oldstat = onnx2pnnx::get_model_stat(model);
547
548 double t0 = 0;
549 double t1 = 0;
550
551 int inlined = 0;
552
553 do
554 {
555 fprintf(stderr, "%-34s", "inline_containers ... ");
556
557 t0 = get_current_time();
558
559 onnx2pnnx::inline_containers(model);
560
561 t1 = get_current_time();
562
563 fprintf(stderr, "%8.2fms\n", t1 - t0);
564
565 fprintf(stderr, "%-34s", "eliminate_noop ... ");
566
567 t0 = get_current_time();
568
569 onnx2pnnx::eliminate_noop(model);
570
571 t1 = get_current_time();
572
573 fprintf(stderr, "%8.2fms\n", t1 - t0);
574
575 fprintf(stderr, "%-34s", "fold_constants ... ");
576
577 t0 = get_current_time();
578
579 onnx2pnnx::fold_constants(model, input_shapes, input_types, input_shapes2, input_types2);
580
581 t1 = get_current_time();
582
583 fprintf(stderr, "%8.2fms\n", t1 - t0);
584
585 fprintf(stderr, "%-34s", "canonicalize ... ");
586
587 t0 = get_current_time();
588
589 onnx2pnnx::canonicalize(model);
590
591 t1 = get_current_time();
592
593 fprintf(stderr, "%8.2fms\n", t1 - t0);
594
595 fprintf(stderr, "%-34s", "shape_inference ... ");
596
597 t0 = get_current_time();
598
599 onnx2pnnx::shape_inference(model, input_shapes, input_types, input_shapes2, input_types2);
600
601 t1 = get_current_time();
602
603 fprintf(stderr, "%8.2fms\n", t1 - t0);
604
605 fprintf(stderr, "%-34s", "fold_constants_dynamic_shape ... ");
606
607 t0 = get_current_time();
608
609 onnx2pnnx::fold_constants_dynamic_shape(model, input_shapes, input_types);
610
611 t1 = get_current_time();
612
613 fprintf(stderr, "%8.2fms\n", t1 - t0);
614
615 fprintf(stderr, "%-34s", "inline_if_graph ... ");
616
617 t0 = get_current_time();
618
619 inlined = onnx2pnnx::inline_if_graph(model);
620
621 t1 = get_current_time();
622
623 fprintf(stderr, "%8.2fms\n", t1 - t0);
624
625 } while (inlined);
626
627 fprintf(stderr, "%-34s", "fuse_constant_as_attribute ... ");
628
629 t0 = get_current_time();
630
631 onnx2pnnx::fuse_constant_as_attribute(model);
632
633 t1 = get_current_time();
634
635 fprintf(stderr, "%8.2fms\n", t1 - t0);
636
637 fprintf(stderr, "%-34s", "eliminate_noop_with_shape ... ");
638
639 t0 = get_current_time();
640
641 onnx2pnnx::eliminate_noop_with_shape(model);
642
643 t1 = get_current_time();
644
645 fprintf(stderr, "%8.2fms\n", t1 - t0);
646
647 // save
648 {
649 std::string simonnx_path;
650 if (onnxpath.size() > 5 && onnxpath.substr(onnxpath.size() - 5) == ".onnx")
651 {
652 simonnx_path = onnxpath.substr(0, onnxpath.size() - 5) + ".pnnxsim.onnx";
653 }
654 else
655 {
656 simonnx_path = onnxpath + ".pnnxsim.onnx";
657 }
658 std::fstream output(simonnx_path, std::ios::out | std::ios::trunc | std::ios::binary);
659 if (!model.SerializeToOstream(&output))
660 {
661 fprintf(stderr, "write pnnxsim onnx failed\n");
662 return -1;
663 }
664 }
665
666 onnx2pnnx::ModelStat newstat = onnx2pnnx::get_model_stat(model);
667
668 onnx2pnnx::print_model_stat(oldstat, newstat);
669
670 fprintf(stderr, "############# pass_level1 onnx\n");
671
672 pass_onnx(model, pnnx_graph);
673
674 return 0;
675}
676
677} // namespace pnnx