-
Notifications
You must be signed in to change notification settings - Fork 3k
/
graph.cc
5575 lines (4802 loc) · 225 KB
/
graph.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/graph.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include <numeric>
#include <stack>
#include <queue>
#include "core/common/common.h"
#include <gsl/gsl>
#include "core/common/inlined_containers.h"
#include "core/common/logging/logging.h"
#include "core/common/narrow.h"
#include "core/flatbuffers/flatbuffers_utils.h"
#include "core/flatbuffers/schema/ort.fbs.h"
#include "core/framework/tensor_shape.h"
#include "core/framework/tensorprotoutils.h"
#include "core/framework/utils.h"
#include "core/graph/graph_flatbuffers_utils.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/indexed_sub_graph.h"
#include "core/graph/model.h"
#include "core/graph/model_load_utils.h"
#include "core/graph/node_attr_utils.h"
#include "core/graph/op.h"
#include "core/graph/runtime_optimization_record_container.h"
#include "core/graph/function_utils.h"
#if !defined(ORT_MINIMAL_BUILD)
#include "core/graph/function.h"
#include "core/graph/function_impl.h"
#include "core/graph/schema_registry.h"
#include "onnx/checker.h"
using namespace ONNX_NAMESPACE::checker;
#endif
using namespace ONNX_NAMESPACE;
using namespace ONNX_NAMESPACE::Utils;
using namespace ::onnxruntime::common;
namespace onnxruntime {
#if !defined(ORT_MINIMAL_BUILD)
#define NO_CHANGE_ON_SYNC_FLAG(...) \
do { \
const bool sync_needed = GraphProtoSyncNeeded(); \
{ __VA_ARGS__; } \
GraphProtoSyncNeeded(sync_needed); \
} while (0)
static Status MergeShapeInfo(const std::string& output_name,
const TypeProto& source, TypeProto& target,
bool strict, const logging::Logger& logger) {
if (!(utils::HasTensorType(source) && utils::HasTensorType(target))
#if !defined(DISABLE_OPTIONAL_TYPE)
&& !(utils::HasOptionalTensorType(source) && utils::HasOptionalTensorType(target))
#endif
#if !defined(DISABLE_SPARSE_TENSORS)
&& !(utils::HasSparseTensorType(source) && utils::HasSparseTensorType(target))
#endif
) {
std::ostringstream ss;
ss << "Source and target must both be tensors";
#if !defined(DISABLE_OPTIONAL_TYPE)
ss << " , or optional typed entities";
#endif
#if !defined(DISABLE_SPARSE_TENSORS)
ss << " , or sparse tensors";
#endif
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, ss.str());
}
auto status = Status::OK();
ORT_TRY {
if (utils::HasTensorType(source)) {
ONNX_NAMESPACE::mergeInShapeInfo(source.tensor_type(), *target.mutable_tensor_type());
}
#if !defined(DISABLE_OPTIONAL_TYPE)
else if (utils::HasOptionalTensorType(source)) {
ONNX_NAMESPACE::mergeInShapeInfo(utils::GetOptionalTypeProto(source).tensor_type(),
*utils::GetMutableOptionalTypeProto(target)->mutable_tensor_type());
}
#endif
#if !defined(DISABLE_SPARSE_TENSORS)
else {
ONNX_NAMESPACE::mergeInShapeInfo(source.sparse_tensor_type(), *target.mutable_sparse_tensor_type());
}
#endif
}
ORT_CATCH(const ONNX_NAMESPACE::InferenceError& ex) {
// if this model was not created with the latest onnx version, allow the shape inferencing failure
// (strict == false).
// we do this to have strict testing of the latest inferencing to detect bugs, but lenient shape inferencing for
// older models in case later changes to the ONNX shape inferencing or ORT break them.
if (!strict) {
// mergeInShapeInfo does nothing unless source.shape() is not null, and there would be no conflict if
// target.shape() was empty. 'assert' just in case that ever changes.
assert(utils::HasShape(source) && utils::HasShape(target));
LOGS(logger, WARNING) << "Error merging shape info for output. '" << output_name
<< "' source:" << utils::GetTensorShapeFromTensorShapeProto(utils::GetShape(source))
<< " target:" << utils::GetTensorShapeFromTensorShapeProto(utils::GetShape(target))
<< ". Falling back to lenient merge.";
if (utils::HasTensorType(source)) {
ONNX_NAMESPACE::UnionShapeInfo(utils::GetShape(source), *target.mutable_tensor_type());
}
#if !defined(DISABLE_OPTIONAL_TYPE)
else if (utils::HasOptionalTensorType(source)) {
ONNX_NAMESPACE::UnionShapeInfo(utils::GetShape(source),
*utils::GetMutableOptionalTypeProto(target)->mutable_tensor_type());
}
#endif
#if !defined(DISABLE_SPARSE_TENSORS)
else {
ONNX_NAMESPACE::UnionShapeInfo(utils::GetShape(source), *target.mutable_sparse_tensor_type());
}
#endif
} else {
ORT_UNUSED_PARAMETER(logger);
ORT_UNUSED_PARAMETER(strict);
ORT_UNUSED_PARAMETER(output_name);
ORT_HANDLE_EXCEPTION([&]() {
status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Output:", output_name, " ", ex.what());
});
}
}
return status;
}
static bool GraphLoadedFromModelFile(const GraphProto* graph_proto) {
return graph_proto && (graph_proto->node_size() != 0 ||
graph_proto->output_size() != 0);
}
// there are some known invalid usages of dim_param and dim_value. remove them from the TypeProto so that
// they don't affect shape inferencing or the allocation planner
static void RemoveInvalidValues(ONNX_NAMESPACE::TypeProto& type) {
if (utils::HasTensorType(type) && utils::HasShape(type.tensor_type())) {
auto* shape = type.mutable_tensor_type()->mutable_shape();
for (int i = 0, end = shape->dim_size(); i < end; ++i) {
auto& dim = *shape->mutable_dim(i);
if (utils::HasDimParam(dim)) {
if (dim.dim_param().empty()) {
dim.clear_dim_param();
}
} else if (utils::HasDimValue(dim)) {
if (dim.dim_value() < 0) {
dim.clear_dim_value();
}
}
}
}
}
static TypeProto TypeProtoFromTensorProto(const TensorProto& tensor) {
TypeProto t;
t.mutable_tensor_type()->set_elem_type(tensor.data_type());
auto shape = t.mutable_tensor_type()->mutable_shape();
for (auto dim : tensor.dims())
shape->add_dim()->set_dim_value(dim);
return t;
}
static std::string GenerateSchemaKey(const IndexedSubGraph& subgraph_ptr) {
return MakeString(subgraph_ptr.GetMetaDef()->domain, "_",
subgraph_ptr.GetMetaDef()->name, "_",
subgraph_ptr.GetMetaDef()->since_version);
}
#endif // !defined(ORT_MINIMAL_BUILD)
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
NodeArg::NodeArg(const std::string& name, const TypeProto* p_node_arg_type) {
node_arg_info_.set_name(name);
// If the name is empty, it means the arg does not exist.
exists_ = !(name.empty());
if (nullptr != p_node_arg_type) {
(*node_arg_info_.mutable_type()) = *p_node_arg_type;
#if !defined(ORT_MINIMAL_BUILD)
// should not be possible to have invalid values in the ORT format model, so we don't need this
// in a minimal build
RemoveInvalidValues(*node_arg_info_.mutable_type());
#endif
type_ = DataTypeUtils::ToType(node_arg_info_.type());
} else {
type_ = nullptr;
}
}
#endif // #if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
NodeArg::NodeArg(NodeArgInfo&& node_arg_info) {
node_arg_info_ = std::move(node_arg_info);
exists_ = !node_arg_info_.name().empty();
if (node_arg_info_.has_type())
type_ = DataTypeUtils::ToType(node_arg_info_.type());
else {
type_ = nullptr;
}
}
const std::string& NodeArg::Name() const noexcept {
return node_arg_info_.name();
}
DataType NodeArg::Type() const noexcept {
return type_;
}
const TypeProto* NodeArg::TypeAsProto() const noexcept {
if (utils::HasType(node_arg_info_))
return &node_arg_info_.type();
return nullptr;
}
const TensorShapeProto* NodeArg::Shape() const {
const TypeProto* type = TypeAsProto();
if (type == nullptr) return nullptr;
const auto typeCase = type->value_case();
switch (typeCase) {
case TypeProto::kTensorType: {
if (utils::HasShape(type->tensor_type())) {
return &(type->tensor_type().shape());
}
return nullptr;
}
#if !defined(DISABLE_SPARSE_TENSORS)
case TypeProto::kSparseTensorType: {
if (utils::HasShape(type->sparse_tensor_type())) {
return &(type->sparse_tensor_type().shape());
}
return nullptr;
}
#endif
#if !defined(DISABLE_OPTIONAL_TYPE)
case TypeProto::kOptionalType: {
// Shape is applicable only for optional tensor type
if (utils::HasOptionalTensorType(*type) &&
utils::HasShape(utils::GetOptionalTypeProto(*type).tensor_type())) {
return &(utils::GetOptionalTypeProto(*type).tensor_type().shape());
}
return nullptr;
}
#endif
case TypeProto::kSequenceType:
case TypeProto::kMapType:
case TypeProto::kOpaqueType:
case TypeProto::VALUE_NOT_SET:
default:
return nullptr;
}
}
bool NodeArg::HasTensorOrScalarShape() const {
const TypeProto* type = TypeAsProto();
if (!type) return false;
const auto type_case = type->value_case();
switch (type_case) {
case TypeProto::kTensorType:
#if !defined(DISABLE_SPARSE_TENSORS)
case TypeProto::kSparseTensorType:
#endif
// Standard tensor has a valid shape field while
// scalar's shape is empty. Thus, we don't need to
// check shape here.
return true;
case TypeProto::kSequenceType:
case TypeProto::kOptionalType:
case TypeProto::kMapType:
case TypeProto::kOpaqueType:
case TypeProto::VALUE_NOT_SET:
default:
return false;
}
}
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
void NodeArg::SetShape(const TensorShapeProto& shape) {
const auto type_case = node_arg_info_.type().value_case();
switch (type_case) {
case TypeProto::kTensorType:
*(node_arg_info_.mutable_type()->mutable_tensor_type()->mutable_shape()) = shape;
break;
#if !defined(DISABLE_SPARSE_TENSORS)
case TypeProto::kSparseTensorType:
*(node_arg_info_.mutable_type()->mutable_sparse_tensor_type()->mutable_shape()) = shape;
break;
#endif
#if !defined(DISABLE_OPTIONAL_TYPE)
case TypeProto::kOptionalType:
// Set shape only for optional tensors
if (utils::HasOptionalTensorType(node_arg_info_.type())) {
*(utils::GetMutableOptionalTypeProto(*(node_arg_info_.mutable_type()))
->mutable_tensor_type()
->mutable_shape()) = shape;
}
break;
#endif
case TypeProto::kSequenceType:
case TypeProto::kMapType:
case TypeProto::kOpaqueType:
case TypeProto::VALUE_NOT_SET:
default:
return;
}
}
void NodeArg::ClearShape() {
const auto type_case = node_arg_info_.type().value_case();
switch (type_case) {
case TypeProto::kTensorType:
node_arg_info_.mutable_type()->mutable_tensor_type()->clear_shape();
break;
#if !defined(DISABLE_SPARSE_TENSORS)
case TypeProto::kSparseTensorType:
node_arg_info_.mutable_type()->mutable_sparse_tensor_type()->clear_shape();
break;
#endif
#if !defined(DISABLE_OPTIONAL_TYPE)
case TypeProto::kOptionalType:
// Clear shape only for optional tensors
if (utils::HasOptionalTensorType(node_arg_info_.type())) {
utils::GetMutableOptionalTypeProto(*(node_arg_info_.mutable_type()))
->mutable_tensor_type()
->clear_shape();
}
break;
#endif
case TypeProto::kSequenceType:
case TypeProto::kMapType:
case TypeProto::kOpaqueType:
case TypeProto::VALUE_NOT_SET:
default:
return;
}
}
#endif // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
#if !defined(ORT_MINIMAL_BUILD)
common::Status NodeArg::OverrideTypesHelper(const ONNX_NAMESPACE::TypeProto& input_type,
int32_t input_tensor_elem_type,
int32_t current_tensor_elem_type,
bool override_types) {
if (input_tensor_elem_type != current_tensor_elem_type) {
if (override_types) {
DataType inferred_type = DataTypeUtils::ToType(input_type);
// The "SetType" call will override the shape information to empty.
// If the original tensor has shape information, need to set it back.
if (Shape()) {
auto old_shape = *Shape();
SetType(inferred_type);
SetShape(old_shape);
} else {
SetType(inferred_type);
}
} else {
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Tensor element type mismatch. ",
static_cast<TensorProto_DataType>(input_tensor_elem_type), " != ",
static_cast<TensorProto_DataType>(current_tensor_elem_type));
}
}
return Status::OK();
}
common::Status NodeArg::UpdateTypeAndShape(const ONNX_NAMESPACE::TypeProto& input_type, bool strict,
bool override_types, const logging::Logger& logger) {
if (!utils::HasType(node_arg_info_)) {
SetType(input_type);
return Status::OK();
}
auto& current_type = *node_arg_info_.mutable_type();
const auto current_type_case = current_type.value_case();
const auto input_type_case = input_type.value_case();
if (current_type_case != input_type_case)
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Type mismatch. Current=",
current_type_case, " Input=", input_type_case);
switch (input_type_case) {
case TypeProto::kTensorType: {
const auto& input_tensor_type = input_type.tensor_type();
const auto& input_tensor_elem_type = input_tensor_type.elem_type();
const auto& current_tensor_elem_type = current_type.tensor_type().elem_type();
ORT_RETURN_IF_ERROR(OverrideTypesHelper(input_type, input_tensor_elem_type, current_tensor_elem_type,
override_types));
if (utils::HasShape(input_tensor_type)) {
if (utils::HasShape(current_type)) {
ORT_RETURN_IF_ERROR(MergeShapeInfo(Name(), input_type, current_type, strict, logger));
} else {
*current_type.mutable_tensor_type() = input_tensor_type;
}
}
break;
}
#if !defined(DISABLE_SPARSE_TENSORS)
case TypeProto::kSparseTensorType: {
const auto& input_tensor_type = input_type.sparse_tensor_type();
const auto input_tensor_elem_type = input_tensor_type.elem_type();
const auto current_tensor_elem_type = current_type.sparse_tensor_type().elem_type();
ORT_RETURN_IF_ERROR(OverrideTypesHelper(input_type, input_tensor_elem_type, current_tensor_elem_type,
override_types));
if (utils::HasShape(input_tensor_type)) {
if (utils::HasShape(current_type)) {
ORT_RETURN_IF_ERROR(MergeShapeInfo(Name(), input_type, current_type, strict, logger));
} else {
*current_type.mutable_sparse_tensor_type() = input_tensor_type;
}
}
break;
}
#endif
#if !defined(DISABLE_OPTIONAL_TYPE)
case TypeProto::kOptionalType: {
bool is_input_type_optional_tensor_type = utils::HasOptionalTensorType(input_type);
bool is_current_type_optional_tensor_type = utils::HasOptionalTensorType(current_type);
// Check for homogeneity within optional type
if (is_input_type_optional_tensor_type != is_current_type_optional_tensor_type) {
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Optional Type mismatch. Expected: ",
ONNX_NAMESPACE::Utils::DataTypeUtils::ToType(current_type),
" . Got: ", ONNX_NAMESPACE::Utils::DataTypeUtils::ToType(input_type));
}
// Updating element type and shape is only applicable for optional tensors
if (is_input_type_optional_tensor_type) {
const auto& optional_input_type = utils::GetOptionalTypeProto(input_type);
auto& optional_current_type = *utils::GetMutableOptionalTypeProto(current_type);
const auto& input_tensor_type = optional_input_type.tensor_type();
const auto& input_tensor_elem_type = input_tensor_type.elem_type();
const auto& current_tensor_elem_type = optional_current_type.tensor_type().elem_type();
ORT_RETURN_IF_ERROR(OverrideTypesHelper(input_type, input_tensor_elem_type, current_tensor_elem_type,
override_types));
if (utils::HasShape(optional_input_type.tensor_type())) {
if (utils::HasShape(optional_current_type.tensor_type())) {
ORT_RETURN_IF_ERROR(MergeShapeInfo(Name(), optional_input_type, optional_current_type, strict, logger));
} else {
*optional_current_type.mutable_tensor_type() = input_tensor_type;
}
}
} else {
// TODO: What is the plan for optional sequence tensors ?
// Currently, we don't do anything for the generic sequence type
// as seen below. This section needs an update if we choose to
// change that in the future.
}
break;
}
#endif
case TypeProto::kSequenceType:
case TypeProto::kMapType:
case TypeProto::kOpaqueType:
case TypeProto::VALUE_NOT_SET:
default:
break;
}
return Status::OK();
}
common::Status NodeArg::UpdateTypeAndShape(const NodeArg& node_arg, bool strict, bool override_types,
const logging::Logger& logger) {
auto status = Status::OK();
if (utils::HasType(node_arg.node_arg_info_))
status = UpdateTypeAndShape(node_arg.node_arg_info_.type(), strict, override_types, logger);
return status;
}
void NodeArg::SetType(DataType p_type) {
if (nullptr == p_type) {
return;
}
type_ = p_type;
*(node_arg_info_.mutable_type()) = DataTypeUtils::ToTypeProto(p_type);
}
#endif // !defined(ORT_MINIMAL_BUILD)
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
void NodeArg::SetType(const TypeProto& type_proto) {
type_ = DataTypeUtils::ToType(type_proto);
*(node_arg_info_.mutable_type()) = type_proto;
}
#endif // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
bool NodeArg::Exists() const noexcept {
return exists_;
}
Node::EdgeEnd::EdgeEnd(const Node& node, int src_arg_index, int dst_arg_index) noexcept
: node_(&node),
src_arg_index_(src_arg_index),
dst_arg_index_(dst_arg_index) {
}
Node::EdgeEnd::EdgeEnd(const Node& node) noexcept
: EdgeEnd(node, INT_MAX, INT_MAX) {
}
Node::NodeConstIterator::NodeConstIterator(EdgeConstIterator p_iter) {
m_iter = p_iter;
}
bool Node::NodeConstIterator::operator==(const NodeConstIterator& p_other) const {
return m_iter == p_other.m_iter;
}
bool Node::NodeConstIterator::operator!=(const NodeConstIterator& p_other) const {
return m_iter != p_other.m_iter;
}
void Node::NodeConstIterator::operator++() {
++m_iter;
}
void Node::NodeConstIterator::operator--() {
--m_iter;
}
const Node& Node::NodeConstIterator::operator*() const {
return (*m_iter).GetNode();
}
const Node* Node::NodeConstIterator::operator->() const {
return &(operator*());
}
void Node::SetPriority(int priority) noexcept {
priority_ = priority;
}
const std::filesystem::path& Node::ModelPath() const noexcept {
return graph_->ModelPath();
}
#if !defined(ORT_MINIMAL_BUILD)
bool Node::CanBeInlined() const {
if (func_body_ || func_template_)
return true;
if (!op_) return false;
ONNX_NAMESPACE::FunctionProto function_proto;
return TryGetFunctionProto(function_proto);
// Note: We end up doing some redundant work, which can be eliminated if we cache
// the constructed FunctionProto. Keeping the changes localized for now. A better
// implementation would require some more invasive refactoring.
}
bool Node::TryGetFunctionProto(ONNX_NAMESPACE::FunctionProto& onnx_function_proto) const {
if (func_template_) {
onnx_function_proto = *func_template_->onnx_func_proto_;
return true;
} else if (op_) {
auto get_opset_version = [op = op_](Graph* graph) -> std::optional<int> {
if (op->domain() == kOnnxDomain) {
const auto& domain_to_version = graph->DomainToVersionMap();
const auto iter = domain_to_version.find(kOnnxDomain);
if (iter != domain_to_version.cend()) {
return iter->second;
}
}
return {};
};
// Check if this node has a schema defined function proto.
if (op_->HasContextDependentFunction()) {
NodeProto node_proto;
ToProto(node_proto, true);
std::vector<TypeProto> input_types;
for (size_t i = 0, n = InputDefs().size(); i < n; i++) {
auto p_node_arg = InputDefs().at(i);
if ((nullptr != p_node_arg) && p_node_arg->Exists()) {
auto& type = *(p_node_arg->TypeAsProto());
input_types.emplace_back(type);
} else
input_types.emplace_back();
}
auto requested_opset_version = get_opset_version(graph_);
if (!requested_opset_version.has_value()) {
requested_opset_version = SinceVersion();
}
ONNX_NAMESPACE::FunctionBodyBuildContextImpl function_body_ctx(node_proto, input_types);
return op_->BuildContextDependentFunction(function_body_ctx, onnx_function_proto, *requested_opset_version);
} else if (op_->HasFunction()) {
const FunctionProto* function_ptr = nullptr;
// We need to get a function-body suitable for the ONNX opset used by the model.
// The first-parameter to GetFunction needs to be the ONNX opset used by the model.
// Unfortunately, ONNX's function-registration code uses the function's since-version
// as the default-version, which is incorrect in the case of functions belonging to
// non-onnx domains, like MSDOMAIN.
auto requested_opset_version = get_opset_version(graph_);
if (requested_opset_version.has_value()) {
function_ptr = op_->GetFunction(*requested_opset_version, true);
} else {
function_ptr = op_->GetFunction(SinceVersion(), false);
}
if (function_ptr != nullptr) {
onnx_function_proto = *function_ptr;
return true;
}
}
}
return false;
}
void Node::SetFunctionTemplate(const FunctionTemplate& func_template) {
op_ = func_template.op_schema_.get();
since_version_ = op_->since_version();
func_template_ = &func_template;
}
void Node::ToProto(NodeProto& proto, bool update_subgraphs) const {
proto.set_name(name_);
proto.set_op_type(op_type_);
if (!domain_.empty())
proto.set_domain(domain_);
if (!description_.empty())
proto.set_doc_string(description_);
// Checks an attribute was not removed.
if (!can_be_saved_) {
ORT_THROW("Removable attributes were removed before the conversion is started.");
}
// Set attributes.
proto.clear_attribute();
for (const auto& attribute : attributes_) {
const gsl::not_null<AttributeProto*> attr{proto.add_attribute()};
*attr = attribute.second; // copy
if (update_subgraphs && attr->has_g()) {
attr->clear_g();
*attr->mutable_g() = attr_to_subgraph_map_.find(attribute.first)->second->ToGraphProto();
}
}
// Set inputs' definitions.
proto.clear_input();
for (auto& input_def : definitions_.input_defs) {
proto.add_input(input_def->Name());
}
// Set outputs' definitions.
proto.clear_output();
for (auto& output_def : definitions_.output_defs) {
proto.add_output(output_def->Name());
}
}
Status Node::SaveToOrtFormat(flatbuffers::FlatBufferBuilder& builder,
flatbuffers::Offset<fbs::Node>& fbs_node) const {
// if type is Primitive it's an ONNX function and currently we have kernel implementations for all those
if (func_body_ != nullptr && node_type_ != Type::Primitive) {
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Serialization of fused function body is not currently supported, ",
"Node [", name_, "] op_type [", op_type_, "]");
}
auto GetNodeArgsOrtFormat = [&builder](const std::vector<NodeArg*>& src) {
std::vector<flatbuffers::Offset<flatbuffers::String>> node_args(src.size());
std::transform(src.cbegin(), src.cend(), node_args.begin(),
[&builder](const NodeArg* nodearg) {
// NodeArg's name will be used by multiple places, create shared string
return builder.CreateSharedString(nodearg->Name());
});
return builder.CreateVector(node_args);
};
auto name = builder.CreateString(name_);
auto doc_string = builder.CreateString(description_);
auto domain = builder.CreateSharedString(domain_);
auto op_type = builder.CreateSharedString(op_type_);
auto ep = builder.CreateSharedString(execution_provider_type_);
auto inputs = GetNodeArgsOrtFormat(definitions_.input_defs);
auto outputs = GetNodeArgsOrtFormat(definitions_.output_defs);
auto input_arg_counts = builder.CreateVector(definitions_.input_arg_count);
auto implicit_inputs = GetNodeArgsOrtFormat(definitions_.implicit_input_defs);
// Checks an attribute was not removed.
if (!can_be_saved_) {
return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Removable attributes were removed before the node is saved.");
}
// Node attributes
std::vector<flatbuffers::Offset<fbs::Attribute>> attributes_vec;
attributes_vec.reserve(attributes_.size());
for (const auto& entry : attributes_) {
const auto& attr_name = entry.first;
const auto& attr_proto = entry.second;
flatbuffers::Offset<fbs::Attribute> fbs_attr;
Graph* subgraph = nullptr;
if (attr_proto.has_g()) {
const auto it = attr_to_subgraph_map_.find(attr_name);
ORT_RETURN_IF_NOT(it != attr_to_subgraph_map_.cend(),
"Node [", name_, "] op_type [", op_type_, "] ", "does not have the graph for key ", attr_name);
subgraph = it->second;
}
ORT_RETURN_IF_ERROR(
fbs::utils::SaveAttributeOrtFormat(builder, attr_proto, fbs_attr, ModelPath(), subgraph));
attributes_vec.push_back(fbs_attr);
}
auto attributes = builder.CreateVector(attributes_vec);
fbs::NodeBuilder nb(builder);
nb.add_name(name);
nb.add_doc_string(doc_string);
nb.add_domain(domain);
nb.add_since_version(since_version_);
nb.add_index(narrow<uint32_t>(index_));
nb.add_op_type(op_type);
nb.add_type(static_cast<fbs::NodeType>(node_type_));
nb.add_execution_provider_type(ep);
nb.add_inputs(inputs);
nb.add_outputs(outputs);
nb.add_attributes(attributes);
nb.add_input_arg_counts(input_arg_counts);
nb.add_implicit_inputs(implicit_inputs);
fbs_node = nb.Finish();
return Status::OK();
}
flatbuffers::Offset<fbs::NodeEdge> Node::SaveEdgesToOrtFormat(flatbuffers::FlatBufferBuilder& builder) const {
auto get_edges = [](const EdgeSet& edge_set) {
std::vector<fbs::EdgeEnd> edges;
edges.reserve(edge_set.size());
for (const auto& edge : edge_set)
edges.push_back(fbs::EdgeEnd(narrow<uint32_t>(edge.GetNode().Index()),
edge.GetSrcArgIndex(), edge.GetDstArgIndex()));
return edges;
};
const auto input_edges = get_edges(relationships_.input_edges);
const auto output_edges = get_edges(relationships_.output_edges);
return fbs::CreateNodeEdgeDirect(builder, narrow<uint32_t>(index_), &input_edges, &output_edges);
}
#endif // !defined(ORT_MINIMAL_BUILD)
Status Node::LoadFromOrtFormat(const onnxruntime::fbs::Node& fbs_node, Graph& graph,
const OrtFormatLoadOptions& load_options,
const logging::Logger& logger, std::unique_ptr<Node>& node) {
node = std::make_unique<Node>(fbs_node.index(), graph);
return node->LoadFromOrtFormat(fbs_node, load_options, logger);
}
Status Node::LoadFromOrtFormat(const onnxruntime::fbs::Node& fbs_node,
const OrtFormatLoadOptions& load_options,
const logging::Logger& logger) {
auto LoadNodeArgsFromOrtFormat =
[&](const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>* fbs_node_arg_names,
std::vector<NodeArg*>& node_args,
bool check_parent_graph = false) -> Status {
ORT_RETURN_IF(nullptr == fbs_node_arg_names, "fbs_node_arg_names cannot be null");
node_args.reserve(fbs_node_arg_names->size());
for (const auto* node_arg_name : *fbs_node_arg_names) {
ORT_RETURN_IF(nullptr == node_arg_name, "node_arg_name cannot be null");
auto* node_arg = check_parent_graph ? graph_->GetNodeArgIncludingParentGraphs(node_arg_name->str())
: graph_->GetNodeArg(node_arg_name->str());
ORT_RETURN_IF(nullptr == node_arg, "LoadNodeArgsFromOrtFormat: Node [", name_, "] op_type [", op_type_,
"], could not find NodeArg ", node_arg_name->str());
node_args.push_back(node_arg);
}
return Status::OK();
};
// index_ was set in the ctor of this Node instance
fbs::utils::LoadStringFromOrtFormat(name_, fbs_node.name());
fbs::utils::LoadStringFromOrtFormat(description_, fbs_node.doc_string());
fbs::utils::LoadStringFromOrtFormat(domain_, fbs_node.domain());
since_version_ = fbs_node.since_version();
fbs::utils::LoadStringFromOrtFormat(op_type_, fbs_node.op_type());
node_type_ = static_cast<Node::Type>(fbs_node.type());
// we skip populating the saved EP here
// the node will be assigned to an EP by the ORT format model-specific graph partitioning
// fbs::utils::LoadStringFromOrtFormat(execution_provider_type_, fbs_node.execution_provider_type());
ORT_RETURN_IF_ERROR(LoadNodeArgsFromOrtFormat(fbs_node.inputs(), definitions_.input_defs));
// attributes
auto fbs_attributes = fbs_node.attributes();
if (fbs_attributes) {
for (const auto* fbs_attr : *fbs_attributes) {
ORT_RETURN_IF(nullptr == fbs_attr, "fbs_attr cannot be null");
AttributeProto attr_proto;
std::unique_ptr<Graph> subgraph;
ORT_RETURN_IF_ERROR(
fbs::utils::LoadAttributeOrtFormat(*fbs_attr, attr_proto, subgraph, *graph_, *this, load_options, logger));
// If we have a sub graph in this attributes, it will be loaded into subgraph ptr
// while the attribute proto contains the sub graph will have the empty g() field
if (attr_proto.type() == AttributeProto_AttributeType_GRAPH) {
ORT_RETURN_IF_NOT(subgraph, "Serialization error. Graph attribute was serialized without Graph instance");
attr_to_subgraph_map_.emplace(attr_proto.name(), gsl::not_null<Graph*>(subgraph.get()));
subgraphs_.push_back(std::move(subgraph));
}
AddAttributeProto(std::move(attr_proto));
}
}
ORT_RETURN_IF_ERROR(LoadNodeArgsFromOrtFormat(fbs_node.implicit_inputs(), definitions_.implicit_input_defs,
/* check parent graphs */ true));
{ // input_arg_counts
auto fbs_input_arg_counts = fbs_node.input_arg_counts();
ORT_RETURN_IF(nullptr == fbs_input_arg_counts, "Node::LoadFromOrtFormat, input_arg_counts is missing");
auto& input_arg_count = definitions_.input_arg_count;
input_arg_count.reserve(fbs_input_arg_counts->size());
input_arg_count.insert(input_arg_count.begin(), fbs_input_arg_counts->cbegin(), fbs_input_arg_counts->cend());
}
ORT_RETURN_IF_ERROR(LoadNodeArgsFromOrtFormat(fbs_node.outputs(), definitions_.output_defs));
return Status::OK();
}
Status Node::LoadEdgesFromOrtFormat(const onnxruntime::fbs::NodeEdge& fbs_node_edges,
const Graph& graph) {
ORT_RETURN_IF(fbs_node_edges.node_index() != index_,
"input index: ", fbs_node_edges.node_index(), " is not the same as this node's index:", index_);
auto add_edges = [&graph](const flatbuffers::Vector<const onnxruntime::fbs::EdgeEnd*>* fbs_edges,
EdgeSet& edge_set, const std::string& dst_name) -> Status {
if (fbs_edges) {
for (const auto* fbs_edge : *fbs_edges) {
ORT_RETURN_IF(nullptr == fbs_edge, "Node::LoadEdgesFromOrtFormat, edge is missing for ", dst_name);
edge_set.emplace(*graph.GetNode(fbs_edge->node_index()), fbs_edge->src_arg_index(), fbs_edge->dst_arg_index());
}
}
return Status::OK();
};
ORT_RETURN_IF_ERROR(add_edges(fbs_node_edges.input_edges(), relationships_.input_edges, "input edges"));
ORT_RETURN_IF_ERROR(add_edges(fbs_node_edges.output_edges(), relationships_.output_edges, "output edges"));
return Status::OK();
}
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
void Node::Init(std::string_view name,
std::string_view op_type,
std::string_view description,
gsl::span<NodeArg* const> input_args,
gsl::span<NodeArg* const> output_args,
const NodeAttributes* attributes,
std::string_view domain) {
name_ = name;
op_type_ = op_type;
description_ = description;
definitions_.input_defs.assign(input_args.begin(), input_args.end());
definitions_.output_defs.assign(output_args.begin(), output_args.end());
domain_ = domain;
can_be_saved_ = true;
priority_ = 0;
if (kOnnxDomainAlias == domain_) {
domain_ = kOnnxDomain;
}
// Set each arg count as 1 by default.
// It could be adjusted when resolving the node with its operator
// information.
definitions_.input_arg_count.assign(input_args.size(), 1);
if (attributes) {
attributes_ = *attributes;
for (auto& name_to_attr : attributes_) {
if (utils::HasGraph(name_to_attr.second)) {
#if !defined(ORT_MINIMAL_BUILD)
CreateSubgraph(name_to_attr.first);
#else
ORT_THROW("Creating node with a subgraph via AddNode is not supported in this build.");
#endif
}
}
}
}
void Node::Init(std::string_view name,
std::string_view op_type,
std::string_view description,
gsl::span<NodeArg* const> input_args,
gsl::span<NodeArg* const> output_args,
NodeAttributes&& attributes,
std::string_view domain) {
name_ = name;
op_type_ = op_type;
description_ = description;
definitions_.input_defs.assign(input_args.begin(), input_args.end());
definitions_.output_defs.assign(output_args.begin(), output_args.end());
domain_ = domain;
can_be_saved_ = true;
priority_ = 0;
if (kOnnxDomainAlias == domain_) {
domain_ = kOnnxDomain;
}
// Set each arg count as 1 by default.
// It could be adjusted when resolving the node with its operator
// information.
definitions_.input_arg_count.assign(input_args.size(), 1);
attributes_ = std::move(attributes);
for (auto& name_to_attr : attributes_) {
if (utils::HasGraph(name_to_attr.second)) {
#if !defined(ORT_MINIMAL_BUILD)
CreateSubgraph(name_to_attr.first);
#else
ORT_THROW("Creating node with a subgraph via AddNode is not supported in this build.");
#endif
}
}
}
#endif // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
Node::Definitions& Node::MutableDefinitions() noexcept {
// someone fetching these is going to change something
graph_->SetGraphResolveNeeded();
graph_->SetGraphProtoSyncNeeded();
return definitions_;
}
Node::Relationships& Node::MutableRelationships() noexcept {
// someone fetching these is going to change something
graph_->SetGraphResolveNeeded();
graph_->SetGraphProtoSyncNeeded();
return relationships_;
}
#endif // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
#if !defined(ORT_MINIMAL_BUILD)
void Node::CreateSubgraph(const std::string& attr_name) {
auto attr = attributes_.find(attr_name);
if (attr != attributes_.cend() && utils::HasGraph(attr->second)) {
GraphProto& mutable_graph = *attr->second.mutable_g();
std::unique_ptr<Graph> subgraph = std::make_unique<Graph>(*graph_, *this, mutable_graph);
attr_to_subgraph_map_.insert({std::string(attr_name), gsl::not_null<Graph*>{subgraph.get()}});
subgraphs_.emplace_back(std::move(subgraph));
}
}
#endif // !defined(ORT_MINIMAL_BUILD)
void Node::AddAttributeProto(AttributeProto value) {
utils::SetNodeAttribute(std::move(value), attributes_);
if (graph_) {
graph_->SetGraphResolveNeeded();
graph_->SetGraphProtoSyncNeeded();
}
}
#define ADD_ATTR_SINGLE_IMPL(Type) \
void Node::AddAttribute(std::string attr_name, Type value) { \
AttributeProto a = utils::MakeAttribute(std::move(attr_name), std::move(value)); \
AddAttributeProto(std::move(a)); \
}
#define ADD_ATTR_LIST_IMPL(Type) \