Elffuss BraidHub

kikocis/ncnn public

master · 40.2 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 "fold_constants.h"
16
17#include <sstream>
18#include <string>
19#include <unordered_map>
20#include <unordered_set>
21
22#include <onnxruntime_c_api.h>
23
24#include "dead_code_elimination.h"
25
26namespace pnnx {
27
28namespace onnx2pnnx {
29
30static size_t sizeof_onnx_datatype(ONNXTensorElementDataType type)
31{
32 switch (type)
33 {
34 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED:
35 case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING:
36 return 0;
37 case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL:
38 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8:
39 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8:
40 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN:
41 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ:
42 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2:
43 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ:
44 return 1;
45 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16:
46 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16:
47 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16:
48 case ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16:
49 return 2;
50 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32:
51 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32:
52 case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT:
53 return 4;
54 case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64:
55 case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64:
56 case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE:
57 case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64:
58 return 8;
59 case ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128:
60 return 16;
61 default:
62 break;
63 }
64
65 return 0;
66}
67
68static ONNXTensorElementDataType get_onnx_tensor_elem_data_type(const std::string& type)
69{
70 if (type == "i8") return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8;
71 if (type == "u8") return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8;
72 if (type == "i16") return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16;
73 if (type == "u16") return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16;
74 if (type == "i32") return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32;
75 if (type == "u32") return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32;
76 if (type == "i64") return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
77 if (type == "u64") return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64;
78 if (type == "f16") return ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16;
79 if (type == "f32") return ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
80 if (type == "f64") return ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE;
81 if (type == "bf16") return ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16;
82 if (type == "c64") return ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64;
83 if (type == "c128") return ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128;
84
85 // unknown
86 fprintf(stderr, "unsupported tensor elem data type %s\n", type.c_str());
87 return ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
88}
89
90static void onnx_tensor_fill_random(void* ort_val_data, const std::vector<int64_t>& shape, ONNXTensorElementDataType datatype)
91{
92 if (shape.empty())
93 return;
94
95 int64_t n = 1;
96 for (size_t i = 0; i < shape.size(); i++)
97 {
98 n *= shape[i];
99 }
100
101 if (datatype == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)
102 {
103 float* p = (float*)ort_val_data;
104 for (int64_t i = 0; i < n; i++)
105 {
106 p[i] = 0.1f;
107 }
108 }
109
110 if (datatype == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64)
111 {
112 int64_t* p = (int64_t*)ort_val_data;
113 for (int64_t i = 0; i < n; i++)
114 {
115 p[i] = 7;
116 }
117 }
118}
119
120static bool check_outputs_foldable(const onnx::NodeProto& node, const std::unordered_set<std::string>& non_foldable_outputs)
121{
122 for (int i = 0; i < node.input_size(); i++)
123 {
124 if (non_foldable_outputs.find(node.input(i)) != non_foldable_outputs.end())
125 return false;
126 }
127
128 // recurse subgraph
129 for (int i = 0; i < node.attribute_size(); i++)
130 {
131 const onnx::AttributeProto& attr = node.attribute(i);
132
133 if (attr.type() == onnx::AttributeProto::GRAPH)
134 {
135 const onnx::GraphProto& sg = attr.g();
136
137 for (int j = 0; j < sg.node_size(); j++)
138 {
139 if (!check_outputs_foldable(sg.node(j), non_foldable_outputs))
140 return false;
141 }
142 }
143 if (attr.type() == onnx::AttributeProto::GRAPHS)
144 {
145 for (int k = 0; k < attr.graphs().size(); k++)
146 {
147 const onnx::GraphProto& sg = attr.graphs().at(k);
148
149 for (int j = 0; j < sg.node_size(); j++)
150 {
151 if (!check_outputs_foldable(sg.node(j), non_foldable_outputs))
152 return false;
153 }
154 }
155 }
156 }
157
158 return true;
159}
160
161void fold_constants(onnx::ModelProto& model,
162 const std::vector<std::vector<int64_t> >& input_shapes,
163 const std::vector<std::string>& input_types,
164 const std::vector<std::vector<int64_t> >& input_shapes2,
165 const std::vector<std::string>& input_types2)
166{
167 bool ignore_aten_size = input_shapes2.empty();
168
169 // collect initializers
170 std::unordered_set<std::string> initializers;
171 {
172 const onnx::GraphProto& graph = model.graph();
173 for (int i = 0; i < graph.initializer_size(); i++)
174 {
175 initializers.insert(graph.initializer(i).name());
176 }
177 }
178
179 // collect all outputs that have no links with graph inputs
180 std::vector<std::string> foldable_constants;
181 {
182 const onnx::GraphProto& graph = model.graph();
183
184 std::unordered_set<std::string> foldable_outputs;
185 std::unordered_set<std::string> non_foldable_outputs;
186 for (int i = 0; i < graph.input_size(); i++)
187 {
188 non_foldable_outputs.insert(graph.input(i).name());
189 }
190
191 for (int i = 0; i < graph.node_size(); i++)
192 {
193 const onnx::NodeProto& node = graph.node(i);
194
195 bool is_outputs_foldable = check_outputs_foldable(node, non_foldable_outputs);
196
197 const std::string& op_type = node.op_type();
198
199 // TODO whitelist for static shape
200 // aten::size
201 // aten::_shape_as_tensor
202 if (op_type == "aten_new_empty"
203 || op_type == "aten_new_full"
204 || op_type == "aten_new_ones"
205 || op_type == "aten_new_zeros"
206 || op_type == "aten_empty_like"
207 || op_type == "aten_full_like"
208 || op_type == "aten_ones_like"
209 || op_type == "aten_zeros_like")
210 {
211 is_outputs_foldable = ignore_aten_size;
212 }
213
214 // TODO whitelist for static shape
215 if (op_type == "Shape")
216 {
217 is_outputs_foldable = ignore_aten_size;
218 }
219
220 // TODO whitelist for static type
221 if (op_type == "CastLike")
222 {
223 is_outputs_foldable = non_foldable_outputs.find(node.input(0)) == non_foldable_outputs.end();
224 }
225
226 if (!is_outputs_foldable)
227 {
228 for (int j = 0; j < node.input_size(); j++)
229 {
230 if (non_foldable_outputs.find(node.input(j)) == non_foldable_outputs.end())
231 {
232 // some input/output may have empty name, it causes trouble, skip it
233 if (node.input(j).empty())
234 continue;
235
236 foldable_outputs.insert(node.input(j));
237 // fprintf(stderr, "foldable_outputs %s\n", node.input(j).c_str());
238 }
239 }
240
241 for (int j = 0; j < node.output_size(); j++)
242 {
243 non_foldable_outputs.insert(node.output(j));
244 }
245 }
246 }
247
248 // skip initializers
249 for (const std::string& x : foldable_outputs)
250 {
251 if (initializers.find(x) == initializers.end())
252 {
253 foldable_constants.push_back(x);
254 }
255 }
256 }
257
258 if (foldable_constants.empty())
259 return;
260
261 onnx::GraphProto* graph = model.mutable_graph();
262
263 // save original outputs
264 std::vector<std::string> orig_outputs;
265 {
266 for (int i = 0; i < graph->output_size(); i++)
267 {
268 orig_outputs.push_back(graph->output(i).name());
269 }
270 }
271
272 // add foldable outputs to onnx output
273 {
274 graph->clear_output();
275
276 for (size_t i = 0; i < foldable_constants.size(); i++)
277 {
278 graph->add_output()->set_name(foldable_constants[i]);
279 }
280 }
281
282 // generate temp onnx graph
283 std::string tmp_onnx_data;
284 {
285 std::stringstream tmp_onnx_data_ss;
286 if (!model.SerializeToOstream(&tmp_onnx_data_ss))
287 {
288 fprintf(stderr, "write onnx failed\n");
289 return;
290 }
291
292 tmp_onnx_data = tmp_onnx_data_ss.str();
293 }
294
295 // onnxrt inference
296 {
297 const OrtApi* ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
298
299 OrtStatus* ort_status = 0;
300
301 OrtEnv* ort_env = 0;
302 ort_status = ort_api->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "pnnx", &ort_env);
303 if (ort_status)
304 {
305 fprintf(stderr, "ort CreateEnv failed %s\n", ort_api->GetErrorMessage(ort_status));
306 }
307
308 OrtSessionOptions* ort_session_opt = 0;
309 ort_status = ort_api->CreateSessionOptions(&ort_session_opt);
310 if (ort_status)
311 {
312 fprintf(stderr, "ort CreateSessionOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
313 }
314
315 ort_status = ort_api->SetSessionGraphOptimizationLevel(ort_session_opt, ORT_DISABLE_ALL);
316 if (ort_status)
317 {
318 fprintf(stderr, "ort SetSessionGraphOptimizationLevel failed %s\n", ort_api->GetErrorMessage(ort_status));
319 }
320
321 // ort_status = ort_api->SetIntraOpNumThreads(ort_session_opt, 4);
322 // if (ort_status)
323 // {
324 // fprintf(stderr, "ort SetIntraOpNumThreads failed %s\n", ort_api->GetErrorMessage(ort_status));
325 // }
326 //
327 // ort_status = ort_api->SetInterOpNumThreads(ort_session_opt, 4);
328 // if (ort_status)
329 // {
330 // fprintf(stderr, "ort SetInterOpNumThreads failed %s\n", ort_api->GetErrorMessage(ort_status));
331 // }
332
333 OrtSession* ort_session = 0;
334 ort_status = ort_api->CreateSessionFromArray(ort_env, (const void*)tmp_onnx_data.data(), tmp_onnx_data.size(), ort_session_opt, &ort_session);
335 if (ort_status)
336 {
337 fprintf(stderr, "ort CreateSession failed %s\n", ort_api->GetErrorMessage(ort_status));
338 }
339
340 OrtRunOptions* ort_run_opt = 0;
341 ort_status = ort_api->CreateRunOptions(&ort_run_opt);
342 if (ort_status)
343 {
344 fprintf(stderr, "ort CreateRunOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
345 }
346
347 OrtAllocator* ort_allocator = 0;
348 ort_status = ort_api->GetAllocatorWithDefaultOptions(&ort_allocator);
349 if (ort_status)
350 {
351 fprintf(stderr, "ort GetAllocatorWithDefaultOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
352 }
353
354 std::vector<const char*> input_names;
355 std::vector<OrtValue*> inputs;
356 for (int i = 0; i < graph->input_size(); i++)
357 {
358 const onnx::ValueInfoProto& value = graph->input(i);
359
360 std::vector<int64_t> shape;
361 ONNXTensorElementDataType datatype;
362 if (!input_shapes.empty())
363 {
364 shape = input_shapes[i];
365 datatype = get_onnx_tensor_elem_data_type(input_types[i]);
366 }
367 else
368 {
369 const onnx::TensorShapeProto& tsp = value.type().tensor_type().shape();
370 for (int k = 0; k < tsp.dim_size(); k++)
371 {
372 shape.push_back(tsp.dim(k).dim_value());
373 }
374
375 datatype = (ONNXTensorElementDataType)value.type().tensor_type().elem_type();
376 }
377
378 OrtValue* ort_val = 0;
379 ort_status = ort_api->CreateTensorAsOrtValue(ort_allocator, (const int64_t*)shape.data(), shape.size(), datatype, &ort_val);
380 if (ort_status)
381 {
382 fprintf(stderr, "ort CreateTensorAsOrtValue failed %s\n", ort_api->GetErrorMessage(ort_status));
383 }
384
385 void* ort_val_data = 0;
386 ort_status = ort_api->GetTensorMutableData(ort_val, &ort_val_data);
387 if (ort_status)
388 {
389 fprintf(stderr, "ort GetTensorMutableData failed %s\n", ort_api->GetErrorMessage(ort_status));
390 }
391 onnx_tensor_fill_random(ort_val_data, shape, datatype);
392
393 input_names.push_back(value.name().c_str());
394 inputs.push_back(ort_val);
395 }
396
397 std::vector<const char*> output_names;
398 std::vector<OrtValue*> outputs;
399 for (size_t i = 0; i < foldable_constants.size(); i++)
400 {
401 output_names.push_back(foldable_constants[i].c_str());
402 outputs.push_back(0);
403 }
404
405 ort_status = ort_api->Run(ort_session, ort_run_opt,
406 input_names.data(), inputs.data(), input_names.size(),
407 output_names.data(), output_names.size(), outputs.data());
408 if (ort_status)
409 {
410 fprintf(stderr, "ort Run failed %s\n", ort_api->GetErrorMessage(ort_status));
411 }
412
413 // TODO get output data
414
415 // graph->clear_output();
416
417 for (size_t i = 0; i < output_names.size(); i++)
418 {
419 OrtTensorTypeAndShapeInfo* info = 0;
420 ort_status = ort_api->GetTensorTypeAndShape(outputs[i], &info);
421 if (ort_status)
422 {
423 fprintf(stderr, "ort GetTensorTypeAndShape failed %s\n", ort_api->GetErrorMessage(ort_status));
424 }
425
426 ONNXTensorElementDataType datatype = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
427 ort_status = ort_api->GetTensorElementType(info, &datatype);
428 if (ort_status)
429 {
430 fprintf(stderr, "ort GetTensorElementType failed %s\n", ort_api->GetErrorMessage(ort_status));
431 }
432
433 size_t out_dims = 0;
434 ort_status = ort_api->GetDimensionsCount(info, &out_dims);
435 if (ort_status)
436 {
437 fprintf(stderr, "ort GetDimensionsCount failed %s\n", ort_api->GetErrorMessage(ort_status));
438 }
439
440 // fprintf(stderr, " out_dims = %lu\n", out_dims);
441
442 std::vector<int64_t> out_shape;
443 out_shape.resize(out_dims);
444 ort_status = ort_api->GetDimensions(info, out_shape.data(), out_dims);
445 if (ort_status)
446 {
447 fprintf(stderr, "ort GetDimensions failed %s\n", ort_api->GetErrorMessage(ort_status));
448 }
449
450 void* tensor_data = 0;
451 ort_status = ort_api->GetTensorMutableData(outputs[i], &tensor_data);
452 if (ort_status)
453 {
454 fprintf(stderr, "ort GetTensorMutableData failed %s\n", ort_api->GetErrorMessage(ort_status));
455 }
456
457 size_t elemcount = 0;
458 ort_status = ort_api->GetTensorShapeElementCount(info, &elemcount);
459 if (ort_status)
460 {
461 fprintf(stderr, "ort GetTensorShapeElementCount failed %s\n", ort_api->GetErrorMessage(ort_status));
462 }
463
464 // fprintf(stderr, "%16s = ", output_names[i]);
465 // for (size_t j = 0; j < out_dims; j++)
466 // {
467 // fprintf(stderr, "%lu ", out_shape[j]);
468 // }
469 // fprintf(stderr, "\n");
470
471 // unlink any node that has this output
472 {
473 for (int j = 0; j < graph->node_size(); j++)
474 {
475 const onnx::NodeProto& node = graph->node(j);
476
477 bool is_producer = false;
478 int producer_node_output_index = -1;
479 for (int k = 0; k < node.output_size(); k++)
480 {
481 if (node.output(k) == output_names[i])
482 {
483 is_producer = true;
484 producer_node_output_index = k;
485 break;
486 }
487 }
488
489 if (is_producer)
490 {
491 graph->mutable_node(j)->set_output(producer_node_output_index, std::string("pnnx_unlink_") + output_names[i]);
492 break;
493 }
494 }
495 }
496
497 // create initializer
498 {
499 onnx::TensorProto* tp = graph->add_initializer();
500 tp->set_name(output_names[i]);
501
502 for (size_t j = 0; j < out_dims; j++)
503 {
504 tp->add_dims(out_shape[j]);
505 }
506
507 tp->set_data_type((int32_t)datatype);
508
509 std::string* data = tp->mutable_raw_data();
510 data->resize(sizeof_onnx_datatype(datatype) * elemcount);
511 memcpy((void*)data->data(), tensor_data, sizeof_onnx_datatype(datatype) * elemcount);
512 }
513
514 ort_api->ReleaseTensorTypeAndShapeInfo(info);
515 }
516
517 for (size_t i = 0; i < input_names.size(); i++)
518 {
519 ort_api->ReleaseValue(inputs[i]);
520 }
521
522 for (size_t i = 0; i < output_names.size(); i++)
523 {
524 ort_api->ReleaseValue(outputs[i]);
525 }
526
527 ort_api->ReleaseRunOptions(ort_run_opt);
528 ort_api->ReleaseSession(ort_session);
529 ort_api->ReleaseSessionOptions(ort_session_opt);
530 ort_api->ReleaseEnv(ort_env);
531 }
532
533 // restore original outputs
534 {
535 graph->clear_output();
536
537 for (size_t i = 0; i < orig_outputs.size(); i++)
538 {
539 graph->add_output()->set_name(orig_outputs[i]);
540 }
541 }
542
543 onnx2pnnx::dead_code_elimination(model);
544}
545
546void fold_constants_dynamic_shape(onnx::ModelProto& model,
547 const std::vector<std::vector<int64_t> >& input_shapes,
548 const std::vector<std::string>& input_types)
549{
550 // collect initializers
551 std::unordered_map<std::string, int> initializers;
552 {
553 const onnx::GraphProto& graph = model.graph();
554 for (int i = 0; i < graph.initializer_size(); i++)
555 {
556 initializers.insert(std::make_pair(graph.initializer(i).name(), i));
557 }
558 }
559
560 // collect all outputs that have no links with graph inputs
561 std::vector<std::string> foldable_constants;
562 {
563 const onnx::GraphProto& graph = model.graph();
564
565 std::unordered_set<std::string> foldable_outputs;
566 std::unordered_set<std::string> non_foldable_outputs;
567 for (int i = 0; i < graph.input_size(); i++)
568 {
569 non_foldable_outputs.insert(graph.input(i).name());
570 }
571
572 for (int i = 0; i < graph.node_size(); i++)
573 {
574 const onnx::NodeProto& node = graph.node(i);
575
576 bool is_outputs_foldable = check_outputs_foldable(node, non_foldable_outputs);
577
578 const std::string& op_type = node.op_type();
579
580 if (op_type == "Slice")
581 {
582 // match Shape + Slice pattern for partial static shape
583 const std::string& input = node.input(0);
584 bool is_producer_shape = false;
585 int producer_node_output_index = -1;
586 if (!input.empty() && initializers.find(input) == initializers.end())
587 {
588 for (int j = 0; j < i; j++)
589 {
590 const onnx::NodeProto& node0 = graph.node(j);
591
592 for (int k = 0; k < node0.output_size(); k++)
593 {
594 if (node0.output(k) == input)
595 {
596 producer_node_output_index = j;
597 break;
598 }
599 }
600
601 if (producer_node_output_index != -1)
602 {
603 const onnx::NodeProto& node0 = graph.node(producer_node_output_index);
604 is_producer_shape = node0.op_type() == "Shape";
605 break;
606 }
607 }
608 }
609
610 if (is_producer_shape)
611 {
612 // get shape info
613 const onnx::NodeProto& node0 = graph.node(producer_node_output_index);
614
615 int value_info_index = -1;
616 bool value_is_graph_input = false;
617 for (int j = 0; j < graph.input_size(); j++)
618 {
619 if (graph.input(j).name() == node0.input(0))
620 {
621 value_info_index = j;
622 value_is_graph_input = true;
623 break;
624 }
625 }
626 if (value_info_index == -1)
627 {
628 for (int j = 0; j < graph.value_info_size(); j++)
629 {
630 if (graph.value_info(j).name() == node0.input(0))
631 {
632 value_info_index = j;
633 break;
634 }
635 }
636 }
637
638 std::vector<int> shape;
639 if (value_info_index != -1)
640 {
641 const onnx::ValueInfoProto& value = value_is_graph_input ? graph.input(value_info_index) : graph.value_info(value_info_index);
642 const onnx::TensorShapeProto& tsp = value.type().tensor_type().shape();
643 shape.resize(tsp.dim_size());
644 for (int j = 0; j < tsp.dim_size(); j++)
645 {
646 if (tsp.dim(j).has_dim_value())
647 {
648 shape[j] = tsp.dim(j).dim_value();
649 }
650 else
651 {
652 shape[j] = -1;
653 }
654 }
655 }
656
657 if (!shape.empty())
658 {
659 std::vector<int> slice_args;
660 for (int j = 1; j < node.input_size(); j++)
661 {
662 if (initializers.find(node.input(j)) != initializers.end())
663 {
664 const onnx::TensorProto& tensor = graph.initializer(initializers.at(node.input(j)));
665 int64_t i64;
666 if (tensor.has_raw_data())
667 {
668 // assert tensor.raw_data().size() == 8
669 i64 = ((int64_t*)tensor.raw_data().data())[0];
670 }
671 else
672 {
673 // assert tensor.int64_data().size() == 1
674 i64 = tensor.int64_data().at(0);
675 }
676 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
677 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
678 slice_args.push_back((int)i64);
679 }
680 }
681
682 // check slice dim=0 step=1
683 if (slice_args.size() == 2 || (slice_args.size() == 3 && slice_args[2] == 0) || (slice_args.size() == 4 && slice_args[2] == 0 && slice_args[3] == 1))
684 {
685 int start = slice_args[0];
686 int end = slice_args[1];
687
688 is_outputs_foldable = true;
689 for (int j = start; j < end; j++)
690 {
691 if (shape[j] == -1)
692 {
693 is_outputs_foldable = false;
694 break;
695 }
696 }
697 }
698 }
699 }
700 }
701
702 if (op_type == "Gather")
703 {
704 // match Shape + Gather pattern for partial static shape
705 const std::string& input = node.input(0);
706 bool is_producer_shape = false;
707 int producer_node_output_index = -1;
708 if (!input.empty() && initializers.find(input) == initializers.end())
709 {
710 for (int j = 0; j < i; j++)
711 {
712 const onnx::NodeProto& node0 = graph.node(j);
713
714 for (int k = 0; k < node0.output_size(); k++)
715 {
716 if (node0.output(k) == input)
717 {
718 producer_node_output_index = j;
719 break;
720 }
721 }
722
723 if (producer_node_output_index != -1)
724 {
725 const onnx::NodeProto& node0 = graph.node(producer_node_output_index);
726 is_producer_shape = node0.op_type() == "Shape";
727 break;
728 }
729 }
730 }
731
732 if (is_producer_shape)
733 {
734 // get shape info
735 const onnx::NodeProto& node0 = graph.node(producer_node_output_index);
736
737 int value_info_index = -1;
738 bool value_is_graph_input = false;
739 for (int j = 0; j < graph.input_size(); j++)
740 {
741 if (graph.input(j).name() == node0.input(0))
742 {
743 value_info_index = j;
744 value_is_graph_input = true;
745 break;
746 }
747 }
748 if (value_info_index == -1)
749 {
750 for (int j = 0; j < graph.value_info_size(); j++)
751 {
752 if (graph.value_info(j).name() == node0.input(0))
753 {
754 value_info_index = j;
755 break;
756 }
757 }
758 }
759
760 std::vector<int> shape;
761 if (value_info_index != -1)
762 {
763 const onnx::ValueInfoProto& value = value_is_graph_input ? graph.input(value_info_index) : graph.value_info(value_info_index);
764 const onnx::TensorShapeProto& tsp = value.type().tensor_type().shape();
765 shape.resize(tsp.dim_size());
766 for (int j = 0; j < tsp.dim_size(); j++)
767 {
768 if (tsp.dim(j).has_dim_value())
769 {
770 shape[j] = tsp.dim(j).dim_value();
771 }
772 else
773 {
774 shape[j] = -1;
775 }
776 }
777 }
778
779 if (!shape.empty())
780 {
781 if (initializers.find(node.input(1)) != initializers.end())
782 {
783 const onnx::TensorProto& tensor = graph.initializer(initializers.at(node.input(1)));
784 int64_t i64;
785 if (tensor.has_raw_data())
786 {
787 // assert tensor.raw_data().size() == 8
788 i64 = ((int64_t*)tensor.raw_data().data())[0];
789 }
790 else
791 {
792 // assert tensor.int64_data().size() == 1
793 i64 = tensor.int64_data().at(0);
794 }
795 if (i64 == std::numeric_limits<int64_t>::max()) i64 = INT_MAX;
796 if (i64 == std::numeric_limits<int64_t>::min()) i64 = INT_MIN;
797 int gather_indices = (int)i64;
798
799 is_outputs_foldable = true;
800
801 if (shape[gather_indices] == -1)
802 {
803 is_outputs_foldable = false;
804 }
805 }
806 }
807 }
808 }
809
810 if (!is_outputs_foldable)
811 {
812 for (int j = 0; j < node.input_size(); j++)
813 {
814 if (non_foldable_outputs.find(node.input(j)) == non_foldable_outputs.end())
815 {
816 // some input/output may have empty name, it causes trouble, skip it
817 if (node.input(j).empty())
818 continue;
819
820 foldable_outputs.insert(node.input(j));
821 }
822 }
823
824 for (int j = 0; j < node.output_size(); j++)
825 {
826 non_foldable_outputs.insert(node.output(j));
827 }
828 }
829 }
830
831 // skip initializers
832 for (const std::string& x : foldable_outputs)
833 {
834 if (initializers.find(x) == initializers.end())
835 {
836 foldable_constants.push_back(x);
837 }
838 }
839 }
840
841 if (foldable_constants.empty())
842 return;
843
844 onnx::GraphProto* graph = model.mutable_graph();
845
846 // save original outputs
847 std::vector<std::string> orig_outputs;
848 {
849 for (int i = 0; i < graph->output_size(); i++)
850 {
851 orig_outputs.push_back(graph->output(i).name());
852 }
853 }
854
855 // add foldable outputs to onnx output
856 {
857 graph->clear_output();
858
859 for (size_t i = 0; i < foldable_constants.size(); i++)
860 {
861 graph->add_output()->set_name(foldable_constants[i]);
862 }
863 }
864
865 // generate temp onnx graph
866 std::string tmp_onnx_data;
867 {
868 std::stringstream tmp_onnx_data_ss;
869 if (!model.SerializeToOstream(&tmp_onnx_data_ss))
870 {
871 fprintf(stderr, "write onnx failed\n");
872 return;
873 }
874
875 tmp_onnx_data = tmp_onnx_data_ss.str();
876 }
877
878 // onnxrt inference
879 {
880 const OrtApi* ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION);
881
882 OrtStatus* ort_status = 0;
883
884 OrtEnv* ort_env = 0;
885 ort_status = ort_api->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "pnnx", &ort_env);
886 if (ort_status)
887 {
888 fprintf(stderr, "ort CreateEnv failed %s\n", ort_api->GetErrorMessage(ort_status));
889 }
890
891 OrtSessionOptions* ort_session_opt = 0;
892 ort_status = ort_api->CreateSessionOptions(&ort_session_opt);
893 if (ort_status)
894 {
895 fprintf(stderr, "ort CreateSessionOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
896 }
897
898 ort_status = ort_api->SetSessionGraphOptimizationLevel(ort_session_opt, ORT_DISABLE_ALL);
899 if (ort_status)
900 {
901 fprintf(stderr, "ort SetSessionGraphOptimizationLevel failed %s\n", ort_api->GetErrorMessage(ort_status));
902 }
903
904 // ort_status = ort_api->SetIntraOpNumThreads(ort_session_opt, 4);
905 // if (ort_status)
906 // {
907 // fprintf(stderr, "ort SetIntraOpNumThreads failed %s\n", ort_api->GetErrorMessage(ort_status));
908 // }
909 //
910 // ort_status = ort_api->SetInterOpNumThreads(ort_session_opt, 4);
911 // if (ort_status)
912 // {
913 // fprintf(stderr, "ort SetInterOpNumThreads failed %s\n", ort_api->GetErrorMessage(ort_status));
914 // }
915
916 OrtSession* ort_session = 0;
917 ort_status = ort_api->CreateSessionFromArray(ort_env, (const void*)tmp_onnx_data.data(), tmp_onnx_data.size(), ort_session_opt, &ort_session);
918 if (ort_status)
919 {
920 fprintf(stderr, "ort CreateSession failed %s\n", ort_api->GetErrorMessage(ort_status));
921 }
922
923 OrtRunOptions* ort_run_opt = 0;
924 ort_status = ort_api->CreateRunOptions(&ort_run_opt);
925 if (ort_status)
926 {
927 fprintf(stderr, "ort CreateRunOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
928 }
929
930 OrtAllocator* ort_allocator = 0;
931 ort_status = ort_api->GetAllocatorWithDefaultOptions(&ort_allocator);
932 if (ort_status)
933 {
934 fprintf(stderr, "ort GetAllocatorWithDefaultOptions failed %s\n", ort_api->GetErrorMessage(ort_status));
935 }
936
937 std::vector<const char*> input_names;
938 std::vector<OrtValue*> inputs;
939 for (int i = 0; i < graph->input_size(); i++)
940 {
941 const onnx::ValueInfoProto& value = graph->input(i);
942
943 std::vector<int64_t> shape;
944 ONNXTensorElementDataType datatype;
945 if (!input_shapes.empty())
946 {
947 shape = input_shapes[i];
948 datatype = get_onnx_tensor_elem_data_type(input_types[i]);
949 }
950 else
951 {
952 const onnx::TensorShapeProto& tsp = value.type().tensor_type().shape();
953 for (int k = 0; k < tsp.dim_size(); k++)
954 {
955 shape.push_back(tsp.dim(k).dim_value());
956 }
957
958 datatype = (ONNXTensorElementDataType)value.type().tensor_type().elem_type();
959 }
960
961 OrtValue* ort_val = 0;
962 ort_status = ort_api->CreateTensorAsOrtValue(ort_allocator, (const int64_t*)shape.data(), shape.size(), datatype, &ort_val);
963 if (ort_status)
964 {
965 fprintf(stderr, "ort CreateTensorAsOrtValue failed %s\n", ort_api->GetErrorMessage(ort_status));
966 }
967
968 void* ort_val_data = 0;
969 ort_status = ort_api->GetTensorMutableData(ort_val, &ort_val_data);
970 if (ort_status)
971 {
972 fprintf(stderr, "ort GetTensorMutableData failed %s\n", ort_api->GetErrorMessage(ort_status));
973 }
974 onnx_tensor_fill_random(ort_val_data, shape, datatype);
975
976 input_names.push_back(value.name().c_str());
977 inputs.push_back(ort_val);
978 }
979
980 std::vector<const char*> output_names;
981 std::vector<OrtValue*> outputs;
982 for (size_t i = 0; i < foldable_constants.size(); i++)
983 {
984 output_names.push_back(foldable_constants[i].c_str());
985 outputs.push_back(0);
986 }
987
988 ort_status = ort_api->Run(ort_session, ort_run_opt,
989 input_names.data(), inputs.data(), input_names.size(),
990 output_names.data(), output_names.size(), outputs.data());
991 if (ort_status)
992 {
993 fprintf(stderr, "ort Run failed %s\n", ort_api->GetErrorMessage(ort_status));
994 }
995
996 // TODO get output data
997
998 // graph->clear_output();
999
1000 for (size_t i = 0; i < output_names.size(); i++)
1001 {
1002 OrtTensorTypeAndShapeInfo* info = 0;
1003 ort_status = ort_api->GetTensorTypeAndShape(outputs[i], &info);
1004 if (ort_status)
1005 {
1006 fprintf(stderr, "ort GetTensorTypeAndShape failed %s\n", ort_api->GetErrorMessage(ort_status));
1007 }
1008
1009 ONNXTensorElementDataType datatype = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
1010 ort_status = ort_api->GetTensorElementType(info, &datatype);
1011 if (ort_status)
1012 {
1013 fprintf(stderr, "ort GetTensorElementType failed %s\n", ort_api->GetErrorMessage(ort_status));
1014 }
1015
1016 size_t out_dims = 0;
1017 ort_status = ort_api->GetDimensionsCount(info, &out_dims);
1018 if (ort_status)
1019 {
1020 fprintf(stderr, "ort GetDimensionsCount failed %s\n", ort_api->GetErrorMessage(ort_status));
1021 }
1022
1023 // fprintf(stderr, " out_dims = %lu\n", out_dims);
1024
1025 std::vector<int64_t> out_shape;
1026 out_shape.resize(out_dims);
1027 ort_status = ort_api->GetDimensions(info, out_shape.data(), out_dims);
1028 if (ort_status)
1029 {
1030 fprintf(stderr, "ort GetDimensions failed %s\n", ort_api->GetErrorMessage(ort_status));
1031 }
1032
1033 void* tensor_data = 0;
1034 ort_status = ort_api->GetTensorMutableData(outputs[i], &tensor_data);
1035 if (ort_status)
1036 {
1037 fprintf(stderr, "ort GetTensorMutableData failed %s\n", ort_api->GetErrorMessage(ort_status));
1038 }
1039
1040 size_t elemcount = 0;
1041 ort_status = ort_api->GetTensorShapeElementCount(info, &elemcount);
1042 if (ort_status)
1043 {
1044 fprintf(stderr, "ort GetTensorShapeElementCount failed %s\n", ort_api->GetErrorMessage(ort_status));
1045 }
1046
1047 // fprintf(stderr, "%16s = ", output_names[i]);
1048 // for (size_t j = 0; j < out_dims; j++)
1049 // {
1050 // fprintf(stderr, "%lu ", out_shape[j]);
1051 // }
1052 // fprintf(stderr, "\n");
1053
1054 // unlink any node that has this output
1055 {
1056 for (int j = 0; j < graph->node_size(); j++)
1057 {
1058 const onnx::NodeProto& node = graph->node(j);
1059
1060 bool is_producer = false;
1061 int producer_node_output_index = -1;
1062 for (int k = 0; k < node.output_size(); k++)
1063 {
1064 if (node.output(k) == output_names[i])
1065 {
1066 is_producer = true;
1067 producer_node_output_index = k;
1068 break;
1069 }
1070 }
1071
1072 if (is_producer)
1073 {
1074 graph->mutable_node(j)->set_output(producer_node_output_index, std::string("pnnx_unlink_") + output_names[i]);
1075 break;
1076 }
1077 }
1078 }
1079
1080 // create initializer
1081 {
1082 onnx::TensorProto* tp = graph->add_initializer();
1083 tp->set_name(output_names[i]);
1084
1085 for (size_t j = 0; j < out_dims; j++)
1086 {
1087 tp->add_dims(out_shape[j]);
1088 }
1089
1090 tp->set_data_type((int32_t)datatype);
1091
1092 std::string* data = tp->mutable_raw_data();
1093 data->resize(sizeof_onnx_datatype(datatype) * elemcount);
1094 memcpy((void*)data->data(), tensor_data, sizeof_onnx_datatype(datatype) * elemcount);
1095 }
1096
1097 ort_api->ReleaseTensorTypeAndShapeInfo(info);
1098 }
1099
1100 for (size_t i = 0; i < input_names.size(); i++)
1101 {
1102 ort_api->ReleaseValue(inputs[i]);
1103 }
1104
1105 for (size_t i = 0; i < output_names.size(); i++)
1106 {
1107 ort_api->ReleaseValue(outputs[i]);
1108 }
1109
1110 ort_api->ReleaseRunOptions(ort_run_opt);
1111 ort_api->ReleaseSession(ort_session);
1112 ort_api->ReleaseSessionOptions(ort_session_opt);
1113 ort_api->ReleaseEnv(ort_env);
1114 }
1115
1116 // restore original outputs
1117 {
1118 graph->clear_output();
1119
1120 for (size_t i = 0; i < orig_outputs.size(); i++)
1121 {
1122 graph->add_output()->set_name(orig_outputs[i]);
1123 }
1124 }
1125
1126 onnx2pnnx::dead_code_elimination(model);
1127}
1128
1129} // namespace onnx2pnnx
1130
1131} // namespace pnnx