Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#ifdef _WIN32
#pragma warning(disable : 4267)
#endif
 
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
 
#include <gsl/gsl>
#include "core/common/safeint.h"
#include "core/common/string_helper.h"
#include "core/common/logging/logging.h"
#include "core/framework/data_types.h"
#include "core/framework/error_code_helper.h"
#include "core/framework/onnxruntime_typeinfo.h"
#include "core/framework/op_kernel_context_internal.h"
#include "core/framework/op_kernel_info.h"
#include "core/framework/tensor_type_and_shape.h"
#include "core/framework/tensorprotoutils.h"
#include "core/graph/onnx_protobuf.h"
#include "core/session/allocator_adapters.h"
#include "core/session/utils.h"
#include "core/session/custom_ops.h"
#include "core/session/inference_session.h"
#include "core/session/onnxruntime_type_conversion.h"
#include "core/session/ort_apis.h"
#include "core/platform/threadpool.h"
 
// NOTE: OrtKernelContext/OrtKernelInfo are used by both custom ops and kernels for both plugin and provider-bridge EPs.
// In a minimal build, ORT_EXTENDED_MINIMAL_BUILD is used to enable EPs like CoreML/NNAPI which use compiled kernels.
// ORT_MINIMAL_BUILD_CUSTOM_OPS is used to allow external custom op libraries to be used.
// Plugin EPs (with registered and compiled kernels) are enabled in non-minimal builds.
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
#define ENABLE_ORT_KERNEL_API 1
#endif
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_MINIMAL_BUILD_CUSTOM_OPS)
#define ENABLE_CUSTOM_OP_API 1
#endif
 
#if !defined(ORT_MINIMAL_BUILD)
static constexpr uint32_t min_ort_version_with_optional_io_support = 8;
static constexpr uint32_t min_ort_version_with_variadic_io_support = 14;
static constexpr uint32_t min_ort_version_with_custom_version = 17;
#endif
 
#if ENABLE_CUSTOM_OP_API
static constexpr uint32_t min_ort_version_with_compute_v2_support = 16;
static constexpr uint32_t min_ort_version_with_shape_inference = 17;
#endif
 
#if !defined(DISABLE_FLOAT8_TYPES) && !defined(DISABLE_FLOAT4_TYPES)
#define SUPPORTED_TENSOR_TYPES DataTypeImpl::AllTensorTypesIRv11()
#elif !defined(DISABLE_FLOAT8_TYPES)
#define SUPPORTED_TENSOR_TYPES DataTypeImpl::AllTensorTypesIRv10()
#else
#define SUPPORTED_TENSOR_TYPES DataTypeImpl::AllTensorTypesIRv4()
#endif
 
#if defined(ORT_MINIMAL_BUILD)
struct OrtShapeInferContext {
  size_t GetInputCount() const { return 0; }
  OrtTensorTypeAndShapeInfo* GetInputTypeShape(size_t) const { return {}; }
  onnxruntime::Status SetOutputTypeShape(size_t, const OrtTensorTypeAndShapeInfo*) const {
    return ORT_MAKE_STATUS(ONNXRUNTIME, NOT_IMPLEMENTED,
                           "OrtShapeInferContext::SetOutputTypeShape not implemented for minimal build");
  }
  const ONNX_NAMESPACE::AttributeProto* GetAttr(const char*) const { return {}; }
};
#else
struct OrtShapeInferContext {
  OrtShapeInferContext(ONNX_NAMESPACE::InferenceContext& ctx) : ctx_(ctx) {
    auto num_inputs = ctx_.getNumInputs();
    for (size_t ith_input = 0; ith_input < num_inputs; ++ith_input) {
      const auto* input_type = ctx_.getInputType(ith_input);
      if (input_type != nullptr) {
        const auto& value_case = input_type->value_case();
        ORT_ENFORCE(value_case == ONNX_NAMESPACE::TypeProto::kTensorType,
                    "shape inference not yet supported for non-tensor types");
        const auto& shape_proto = input_type->tensor_type().shape();
        const auto& type_proto = input_type->tensor_type();
        auto elem_type = ::onnxruntime::utils::CApiElementTypeFromProtoType(type_proto.elem_type());
        auto tensor_shape = ::onnxruntime::utils::GetTensorShapeFromTensorShapeProto(shape_proto);
        auto symbolic_dims = GetSymbolicDims(shape_proto);
        input_type_shapes_.emplace_back(
            OrtTensorTypeAndShapeInfo::GetTensorShapeAndTypeHelper(elem_type, &tensor_shape, &symbolic_dims));
      } else {
        input_type_shapes_.emplace_back(
            OrtTensorTypeAndShapeInfo::GetTensorShapeAndTypeHelper(
                ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, nullptr, nullptr));
      }
    }
  }
 
  ~OrtShapeInferContext() = default;
  size_t GetInputCount() const { return input_type_shapes_.size(); }
 
  OrtTensorTypeAndShapeInfo* GetInputTypeShape(size_t idx) const {
    return input_type_shapes_.at(idx).get();
  }
 
  onnxruntime::Status SetOutputTypeShape(size_t index, const OrtTensorTypeAndShapeInfo* info) const {
    ORT_RETURN_IF_NOT(info, "Invalid shape info");
    ONNX_NAMESPACE::TensorShapeProto shape_proto;
    if (info->HasShape()) {
      const auto& symbolic_dims = *info->GetDimParams();
      const auto integer_dims = info->GetShape()->GetDims();
      ORT_RETURN_IF_NOT(symbolic_dims.size() == integer_dims.size(), "symbolic and integer dims mismatch!");
      for (size_t ith = 0, end = symbolic_dims.size(); ith < end; ith++) {
        auto* dim_proto = shape_proto.add_dim();
        if (symbolic_dims[ith].size() > 0) {
          dim_proto->set_dim_param(symbolic_dims[ith]);
        } else {
          dim_proto->set_dim_value(integer_dims[ith]);
        }
      }
    }
    ONNX_NAMESPACE::updateOutputShape(ctx_, index, shape_proto);
    ONNX_NAMESPACE::updateOutputElemType(
        ctx_, index, onnxruntime::utils::ToTensorProtoElementType(info->GetElementType()));
    return onnxruntime::Status::OK();
  }
 
  const ONNX_NAMESPACE::AttributeProto* GetAttr(const char* attr_name) const {
    return ctx_.getAttribute(attr_name);
  }
 
 private:
  static std::vector<std::string> GetSymbolicDims(const ONNX_NAMESPACE::TensorShapeProto& shape_proto) {
    std::vector<std::string> symblic_dims;
    for (int ith = 0; ith < shape_proto.dim_size(); ith++) {
      const auto& dim = shape_proto.dim(ith);
      if (::onnxruntime::utils::HasDimValue(dim)) {
        symblic_dims.emplace_back();
      } else {
        symblic_dims.emplace_back(dim.dim_param());
      }
    }
    return symblic_dims;
  }
  ONNX_NAMESPACE::InferenceContext& ctx_;
  using TypeShapePtr = std::unique_ptr<OrtTensorTypeAndShapeInfo>;
  onnxruntime::InlinedVector<TypeShapePtr> input_type_shapes_;
};
#endif
 
#if ENABLE_ORT_KERNEL_API
template <typename T>
static OrtStatusPtr ExecuteIfKernelApiEnabled(const T& fn) {
  API_IMPL_BEGIN
  return fn();
  API_IMPL_END
}
#else
template <typename T>
static OrtStatusPtr ExecuteIfKernelApiEnabled(const T&) {
  return OrtApis::CreateStatus(ORT_NOT_IMPLEMENTED,
                               "APIs for OrtKernelContext and OrtKernelInfo are not enabled in this build");
}
#endif
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    *out = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context)->InputCount();
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    *out = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context)->OutputCount();
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index,
                    _Out_ const OrtValue** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* ctx = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context);
    *out = reinterpret_cast<const OrtValue*>(ctx->GetInputMLValue(onnxruntime::narrow<int>(index)));
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index,
                    _In_ const int64_t* dim_values, size_t dim_count, _Out_ OrtValue** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    onnxruntime::TensorShape shape(dim_values, dim_count);
    auto* ctx = reinterpret_cast<onnxruntime::OpKernelContextInternal*>(context);
    *out = reinterpret_cast<OrtValue*>(ctx->OutputMLValue(onnxruntime::narrow<int>(index), shape));
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetPreallocatedOutput, _In_ const OrtKernelContext* context,
                    _In_ size_t output_index, _Outptr_result_maybenull_ OrtValue** output) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    if (context == nullptr || output == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "context and output must not be null");
    }
 
    const auto* ctx = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context);
    if (output_index >= static_cast<size_t>(ctx->OutputCount())) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "output_index is out of range");
    }
 
    *output = reinterpret_cast<OrtValue*>(ctx->GetPreallocatedOutputMLValue(onnxruntime::narrow<int>(output_index)));
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context,
                    _Outptr_ void** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    auto* stream = reinterpret_cast<const onnxruntime::OpKernelContext*>(context)->GetComputeStream();
    if (stream)
      *out = stream->GetHandle();
    else
      *out = nullptr;
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetSyncStream, _In_ const OrtKernelContext* context,
                    _Outptr_result_maybenull_ OrtSyncStream** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    auto* stream = reinterpret_cast<const onnxruntime::OpKernelContext*>(context)->GetComputeStream();
    *out = reinterpret_cast<OrtSyncStream*>(stream);
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetAllocator, _In_ const OrtKernelContext* context,
                    _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* ctx = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context);
    onnxruntime::AllocatorPtr allocator = ctx->GetAllocator(mem_info->device);
    if (!allocator) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "No requested allocator available");
    }
 
    auto p = std::make_unique<onnxruntime::OrtAllocatorImplWrappingIAllocator>(std::move(allocator));
    *out = p.release();
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetResource, _In_ const OrtKernelContext* context,
                    _In_ int resource_version, _In_ int resource_id, _Outptr_ void** resource) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    *resource = {};
    const auto* ctx = reinterpret_cast<const onnxruntime::OpKernelContext*>(context);
    auto* stream = reinterpret_cast<onnxruntime::Stream*>(ctx->GetComputeStream());
    if (!stream) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "Failed to fetch a stream hosting the requested resource");
    }
    *resource = stream->GetResource(resource_version, resource_id);
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_ParallelFor, _In_ const OrtKernelContext* context,
                    _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    if (!context) {
      return OrtApis::CreateStatus(ORT_RUNTIME_EXCEPTION, "Invalid context");
    }
    if (fn && total) {
      const auto* ctx = reinterpret_cast<const onnxruntime::OpKernelContext*>(context);
      auto* tp = ctx->GetOperatorThreadPool();
      if (num_batch) {
        onnxruntime::concurrency::ThreadPool::TryBatchParallelFor(
            tp,
            static_cast<std::ptrdiff_t>(total),
            [fn, usr_data](std::ptrdiff_t ith) { fn(usr_data, static_cast<size_t>(ith)); },
            static_cast<std::ptrdiff_t>(num_batch));
      } else {
        onnxruntime::concurrency::ThreadPool::TrySimpleParallelFor(
            tp,
            static_cast<std::ptrdiff_t>(total),
            [fn, usr_data](std::ptrdiff_t ith) { fn(usr_data, static_cast<size_t>(ith)); });
      }
    }
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetLogger, _In_ const OrtKernelContext* context,
                    _Outptr_ const OrtLogger** logger) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto& kernel_ctx_logger = reinterpret_cast<const onnxruntime::OpKernelContextInternal*>(context)->Logger();
 
    *logger = kernel_ctx_logger.ToExternal();
    return nullptr;
  });
}
 
// Enabled via ExecuteIfKernelApiEnabled due to KernelContext_GetLogger
ORT_API_STATUS_IMPL(OrtApis::Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level,
                    _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number,
                    _In_z_ const char* func_name) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto& actual_logger = *reinterpret_cast<const onnxruntime::logging::Logger*>(logger);
    const auto severity = static_cast<onnxruntime::logging::Severity>(log_severity_level);
    const auto log_data_type = onnxruntime::logging::DataType::SYSTEM;
 
    if (actual_logger.OutputIsEnabled(severity, log_data_type)) {
#ifdef _WIN32
      const std::string file_path_str = onnxruntime::ToUTF8String(file_path);
      onnxruntime::CodeLocation location(file_path_str.c_str(), line_number, func_name);
#else
      onnxruntime::CodeLocation location(file_path, line_number, func_name);
#endif
 
      onnxruntime::logging::Capture(
          actual_logger,
          severity,
          onnxruntime::logging::Category::onnxruntime,
          log_data_type,
          location)
              .Stream()
          << message;
    }
 
    return nullptr;
  });
}
 
// Enabled via ExecuteIfKernelApiEnabled due to KernelContext_GetLogger
ORT_API_STATUS_IMPL(OrtApis::Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger,
                    _Out_ OrtLoggingLevel* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto& actual_logger = *reinterpret_cast<const onnxruntime::logging::Logger*>(logger);
    *out = static_cast<OrtLoggingLevel>(actual_logger.GetSeverity());
    return nullptr;
  });
}
 
#if ENABLE_CUSTOM_OP_API
template <typename T>
static OrtStatusPtr ExecuteIfCustomOpsApiEnabled(const T& fn) {
  API_IMPL_BEGIN
  return fn();
  API_IMPL_END
}
#else
template <typename T>
static OrtStatusPtr ExecuteIfCustomOpsApiEnabled(const T&) {
  return OrtApis::CreateStatus(ORT_NOT_IMPLEMENTED, "Custom operator API is not enabled in this build");
}
#endif
 
ORT_API_STATUS_IMPL(OrtApis::ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context,
                    _Out_ size_t* out) {
  return ExecuteIfCustomOpsApiEnabled([&]() -> OrtStatusPtr {
    *out = context->GetInputCount();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context,
                    _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info) {
  return ExecuteIfCustomOpsApiEnabled([&]() -> OrtStatusPtr {
    *info = context->GetInputTypeShape(index);
    if (*info) {
      return nullptr;
    } else {
      return OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                   "Failed to fetch type shape info for the index.");
    }
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context,
                    _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr) {
  return ExecuteIfCustomOpsApiEnabled([&]() -> OrtStatusPtr {
    *attr = reinterpret_cast<const OrtOpAttr*>(context->GetAttr(attr_name));
    if (*attr) {
      return nullptr;
    } else {
      return OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT, "Attribute does not exist.");
    }
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context,
                    _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info) {
  return ExecuteIfCustomOpsApiEnabled([&]() -> OrtStatusPtr {
    auto status = context->SetOutputTypeShape(index, info);
    if (status.IsOK()) {
      return nullptr;
    } else {
      return OrtApis::CreateStatus(static_cast<OrtErrorCode>(status.Code()), status.ErrorMessage().c_str());
    }
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data,
                    _In_ size_t len, _Out_ size_t* out) {
  return ExecuteIfCustomOpsApiEnabled([&]() -> OrtStatusPtr {
    if (!op_attr) {
      return OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT, "Invalid attribute.");
    }
 
    auto attr = reinterpret_cast<const ONNX_NAMESPACE::AttributeProto*>(op_attr);
    OrtStatusPtr ret = nullptr;
    *out = 0;
 
    switch (type) {
      case OrtOpAttrType::ORT_OP_ATTR_FLOAT: {
        if (len < sizeof(float)) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold a float.");
        } else {
          if (attr->has_f()) {
            auto output_f = reinterpret_cast<float*>(data);
            *output_f = attr->f();
          } else {
            ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT, "Attribute has no float value.");
          }
        }
        *out = sizeof(float);
 
        break;
      }
      case OrtOpAttrType::ORT_OP_ATTR_FLOATS: {
        const auto& floats = attr->floats();
        auto num_floats = floats.size();
 
        if (len < sizeof(float) * num_floats) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold the array of floats.");
        } else {
          auto output_f = reinterpret_cast<float*>(data);
          for (auto f : floats) {
            *output_f = f;
            output_f++;
          }
        }
        *out = num_floats * sizeof(float);
        break;
      }
      case OrtOpAttrType::ORT_OP_ATTR_INT: {
        if (len < sizeof(int)) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold an int64.");
        } else {
          if (attr->has_i()) {
            auto output_i = reinterpret_cast<int64_t*>(data);
            *output_i = attr->i();
          } else {
            ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT, "Attribute has no int64 value.");
          }
        }
        *out = sizeof(int64_t);
        break;
      }
      case OrtOpAttrType::ORT_OP_ATTR_INTS: {
        const auto& ints = attr->ints();
        auto num_ints = ints.size();
 
        if (len < sizeof(int64_t) * num_ints) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold the array of int64.");
        } else {
          auto output_i = reinterpret_cast<int64_t*>(data);
          for (auto i : ints) {
            *output_i = i;
            output_i++;
          }
        }
        *out = num_ints * sizeof(int64_t);
        break;
      }
      case OrtOpAttrType::ORT_OP_ATTR_STRING: {
        const auto& s = attr->s();
        if (len < s.size()) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold the string.");
        } else {
          char* output_c = reinterpret_cast<char*>(data);
          memcpy(output_c, s.data(), s.size());
        }
        *out = s.size();
        break;
      }
      case OrtOpAttrType::ORT_OP_ATTR_STRINGS: {
        const auto& ss = attr->strings();
        size_t num_bytes = 0;
        for_each(ss.begin(), ss.end(), [&num_bytes](const std::string& s) { num_bytes += s.size() + 1; });
 
        if (len < num_bytes) {
          ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT,
                                      "Size of data not large enough to hold the array of strings.");
        } else {
          char* output_c = reinterpret_cast<char*>(data);
          for (const auto& s : ss) {
            for (char c : s) {
              *output_c++ = c;
            }
            *output_c++ = '\0';
          }
        }
        *out = num_bytes;
        break;
      }
      default:
        ret = OrtApis::CreateStatus(OrtErrorCode::ORT_INVALID_ARGUMENT, "Unexpected attribute type. ");
    }
 
    return ret;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Out_ float* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttr<float>(name, out);
    if (status.IsOK())
      return nullptr;
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Out_ int64_t* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttr<int64_t>(name, out);
    if (status.IsOK())
      return nullptr;
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Out_ char* out, _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    std::string value;
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttr<std::string>(name, &value);
    if (status.IsOK()) {
      if (out == nullptr) {  // User is querying the true size of the attribute
        *size = value.size() + 1;
        return nullptr;
      } else if (*size >= value.size() + 1) {
        std::memcpy(out, value.data(), value.size());
        out[value.size()] = '\0';
        *size = value.size() + 1;
        return nullptr;
      } else {  // User has provided a buffer that is not large enough
        *size = value.size() + 1;
        return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "Result buffer is not large enough");
      }
    }
    return onnxruntime::ToOrtStatus(status);
  });
}
 
template <typename T, typename std::enable_if<std::is_fundamental<T>::value, int>::type = 0>
static Status CopyDataFromVectorToMemory(const std::vector<T>& values, T* out, size_t* size) {
  if (out == nullptr) {  // User is querying the true size of the attribute
    *size = values.size();
    return Status::OK();
  } else if (*size >= values.size()) {
    std::memcpy(out, values.data(), values.size() * sizeof(T));
    *size = values.size();
  } else {  // User has provided a buffer that is not large enough
    *size = values.size();
    return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Result buffer is not large enough");
  }
 
  return Status::OK();
}
 
static char* DuplicateStringToAllocatorMemory(const std::string& value, OrtAllocator* allocator) {
  SafeInt<size_t> allocation_size(value.size());
  allocation_size += 1;
 
  char* duplicated_value = static_cast<char*>(allocator->Alloc(allocator, allocation_size));
  if (duplicated_value == nullptr) {
    return nullptr;
  }
 
  std::memcpy(duplicated_value, value.data(), value.size());
  duplicated_value[value.size()] = '\0';
  return duplicated_value;
}
 
static Status CopyStringDataFromVectorToMemory(const std::vector<std::string>& values, OrtAllocator* allocator, char*** out, size_t* size) {
  *size = values.size();
 
  if (out == nullptr) {
    return Status::OK();
  }
 
  ORT_RETURN_IF_NOT(allocator != nullptr, "allocator must not be null when out is provided");
  *out = nullptr;
 
  if (values.empty()) {
    return Status::OK();
  }
 
  auto free_with_allocator = [allocator](void* value) {
    allocator->Free(allocator, value);
  };
  SafeInt<size_t> alloc_count(values.size());
  char** array = reinterpret_cast<char**>(allocator->Alloc(allocator, alloc_count * sizeof(char*)));
  ORT_RETURN_IF_NOT(array != nullptr, "Failed to allocate string attribute pointer array");
  std::unique_ptr<void, decltype(free_with_allocator)> array_guard(array, free_with_allocator);
 
  size_t allocated_string_count = 0;
  for (size_t i = 0; i < values.size(); ++i) {
    char* duplicated_value = DuplicateStringToAllocatorMemory(values[i], allocator);
    if (duplicated_value == nullptr) {
      for (size_t j = 0; j < allocated_string_count; ++j) {
        if (array[j] != nullptr) {
          allocator->Free(allocator, array[j]);
        }
      }
 
      return Status(onnxruntime::common::ONNXRUNTIME, onnxruntime::common::FAIL,
                    "Failed to allocate string attribute array");
    }
 
    array[i] = duplicated_value;
    ++allocated_string_count;
  }
 
  *out = array;
  array_guard.release();
  return Status::OK();
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Out_ float* out, _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    std::vector<float> values;
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttrs<float>(name, values);
    if (status.IsOK()) {
      status = CopyDataFromVectorToMemory<float>(values, out, size);
    }
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Out_ int64_t* out, _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    std::vector<int64_t> values;
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttrs<int64_t>(name, values);
    if (status.IsOK()) {
      status = CopyDataFromVectorToMemory<int64_t>(values, out, size);
    }
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttributeArray_string, _In_ const OrtKernelInfo* info, _In_ const char* name,
                    _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*size) char*** out, _Out_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    std::vector<std::string> values;
    auto status = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAttrs<std::string>(name, values);
    if (status.IsOK()) {
      status = CopyStringDataFromVectorToMemory(values, allocator, out, size);
    }
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name,
                    _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_kinfo = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
 
    // Get TensorProto attribute
    onnx::TensorProto tensor_proto;
    auto status = op_kinfo->GetAttr<onnx::TensorProto>(name, &tensor_proto);
    if (!status.IsOK()) {
      return onnxruntime::ToOrtStatus(status);
    }
 
    // Determine the tensor's size in bytes.
    size_t req_size = 0;
    status = onnxruntime::utils::GetSizeInBytesFromTensorProto<0>(tensor_proto, &req_size);
    if (!status.IsOK()) {
      return onnxruntime::ToOrtStatus(status);
    }
 
    // Create Tensor that owns buffer memory that will be allocated with the provided OrtAllocator.
    onnxruntime::TensorShape tensor_shape = onnxruntime::utils::GetTensorShapeFromTensorProto(tensor_proto);
    const auto* type = onnxruntime::DataTypeImpl::TensorTypeFromONNXEnum(tensor_proto.data_type())->GetElementType();
    onnxruntime::AllocatorPtr alloc_ptr = std::make_shared<onnxruntime::IAllocatorImplWrappingOrtAllocator>(allocator);
    auto tensor = onnxruntime::Tensor{type, tensor_shape, std::move(alloc_ptr)};
 
    // Deserialize TensorProto into pre-allocated, empty Tensor.
    // TODO: here the TensorProto loses model path information, so it cannot be an external tensor.
    status = onnxruntime::utils::TensorProtoToTensor(onnxruntime::Env::Default(), std::filesystem::path(),
                                                     tensor_proto, tensor);
    if (!status.IsOK()) {
      return onnxruntime::ToOrtStatus(status);
    }
 
    // Initialize OrtValue from Tensor.
    auto value = std::make_unique<OrtValue>();
    onnxruntime::Tensor::InitOrtValue(std::move(tensor), *value);
    *out = value.release();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    *out = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetInputCount();
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    *out = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetOutputCount();
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index,
                    _Out_opt_ char* out, _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    const auto input_defs = op_info->node().InputDefs();
 
    if (index >= input_defs.size()) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "::OrtKernelInfo input index is out of bounds");
    }
 
    auto status = CopyStringToOutputArg(input_defs[index]->Name(),
                                        "Output buffer is not large enough for ::OrtKernelInfo input name", out, size);
 
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index,
                    _Out_opt_ char* out, _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    const auto output_defs = op_info->node().OutputDefs();
 
    if (index >= output_defs.size()) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "::OrtKernelInfo output index is out of bounds");
    }
 
    auto status = CopyStringToOutputArg(output_defs[index]->Name(),
                                        "Output buffer is not large enough for ::OrtKernelInfo output name",
                                        out, size);
 
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index,
                    _Outptr_ OrtTypeInfo** type_info) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    const auto input_defs = op_info->node().InputDefs();
 
    if (index >= input_defs.size()) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "::OrtKernelInfo input index is out of bounds");
    }
 
    const onnxruntime::NodeArg* node_arg = input_defs[index];
    const ONNX_NAMESPACE::TypeProto* type_proto = node_arg->TypeAsProto();
 
    if (type_proto == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_GRAPH, "::OrtKernelInfo input does not have a type");
    }
 
    auto type_info_ret = OrtTypeInfo::FromTypeProto(*type_proto);
    *type_info = type_info_ret.release();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index,
                    _Outptr_ OrtTypeInfo** type_info) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    const auto output_defs = op_info->node().OutputDefs();
 
    if (index >= output_defs.size()) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "::OrtKernelInfo output index is out of bounds");
    }
 
    const onnxruntime::NodeArg* node_arg = output_defs[index];
    const ONNX_NAMESPACE::TypeProto* type_proto = node_arg->TypeAsProto();
 
    if (type_proto == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_GRAPH, "::OrtKernelInfo output does not have a type");
    }
 
    auto type_info_ret = OrtTypeInfo::FromTypeProto(*type_proto);
    *type_info = type_info_ret.release();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, _In_ size_t index,
                    _Out_ int* is_constant, _Outptr_ const OrtValue** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    *is_constant = static_cast<int>(op_info->TryGetConstantInput(gsl::narrow_cast<int>(index), out));
    return nullptr;
  });
};
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_opt_ char* out,
                    _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
 
    auto status = CopyStringToOutputArg(op_info->node().Name(),
                                        "Output buffer is not large enough for ::OrtKernelInfo node name", out, size);
 
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOperatorDomain, _In_ const OrtKernelInfo* info, _Out_opt_ char* out,
                    _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
 
    auto status = CopyStringToOutputArg(op_info->node().Domain(),
                                        "Output buffer is not large enough for ::OrtKernelInfo's operator domain",
                                        out, size);
 
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOperatorType, _In_ const OrtKernelInfo* info, _Out_opt_ char* out,
                    _Inout_ size_t* size) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
 
    auto status = CopyStringToOutputArg(op_info->node().OpType(),
                                        "Output buffer is not large enough for ::OrtKernelInfo's operator type",
                                        out, size);
 
    return onnxruntime::ToOrtStatus(status);
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetOperatorSinceVersion, _In_ const OrtKernelInfo* info,
                    _Out_ int* since_version) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
 
    if (since_version == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT,
                                   "Output parameter for ::OrtKernelInfo's since version is NULL");
    }
 
    *since_version = op_info->node().SinceVersion();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* ep = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetExecutionProvider();
 
    if (ep == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_GRAPH, "::OrtKernelInfo does not have an execution provider");
    }
 
    const auto* ep_logger = ep->GetLogger();
 
    if (ep_logger == nullptr) {
      return OrtApis::CreateStatus(ORT_INVALID_GRAPH,
                                   "::OrtKernelInfo cannot get a valid logger from "
                                   "its execution provider");
    }
 
    *logger = ep_logger->ToExternal();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    onnxruntime::AllocatorPtr allocator = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info)->GetAllocator(mem_type);
    if (!allocator) {
      return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "No requested allocator available");
    }
    auto p = std::make_unique<onnxruntime::OrtAllocatorImplWrappingIAllocator>(std::move(allocator));
    *out = p.release();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelInfo_GetConfigEntries, _In_ const OrtKernelInfo* info, _Outptr_ OrtKeyValuePairs** out) {
  return ExecuteIfKernelApiEnabled([&]() -> OrtStatusPtr {
    const auto* op_info = reinterpret_cast<const onnxruntime::OpKernelInfo*>(info);
    const auto& config_options_map = op_info->GetConfigOptions().GetConfigOptionsMap();
 
    auto kvps = std::make_unique<OrtKeyValuePairs>();
    for (const auto& kv : config_options_map) {
      kvps->Add(kv.first.c_str(), kv.second.c_str());
    }
 
    *out = kvps.release();
    return nullptr;
  });
}
 
ORT_API_STATUS_IMPL(OrtApis::KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out) {
  if (count_or_bytes == 0) {
    *out = nullptr;
    return nullptr;
  }
  onnxruntime::AllocatorPtr allocator = reinterpret_cast<const onnxruntime::OpKernelContext*>(context)->GetAllocator(mem_info->device);
  if (!allocator) {
    return OrtApis::CreateStatus(ORT_INVALID_ARGUMENT, "No requested allocator available");
  }
  onnxruntime::Stream* stream = reinterpret_cast<const onnxruntime::OpKernelContext*>(context)->GetComputeStream();
  *out = AllocateBufferWithOptions(*allocator, count_or_bytes, false, stream);
  return nullptr;
};
 
#if ENABLE_CUSTOM_OP_API
#include "core/framework/customregistry.h"
namespace onnxruntime {
struct CustomOpKernel : OpKernel {
  CustomOpKernel(const OpKernelInfo& info, const OrtCustomOp& op) : OpKernel(info), op_(op) {
    // Cap the version to the current ORT API version. This allows custom ops compiled against a newer ORT
    // to work on an older ORT runtime, provided they don't call API functions unavailable at the runtime version.
    // Individual newer functions in OrtCustomOp are gated by per-function version checks throughout this file.
    const uint32_t api_version = std::min(op_.version, static_cast<uint32_t>(ORT_API_VERSION));
    const OrtApi* ort_api = OrtGetApiBase()->GetApi(api_version);
    ORT_ENFORCE(ort_api != nullptr, "Failed to get ORT API for version ",
                api_version, " in custom op '", op_.GetName(&op_), "'");
 
    if (op_.version >= min_ort_version_with_compute_v2_support &&
        op_.CreateKernelV2) {
      op_kernel_ = nullptr;
      Ort::ThrowOnError(
          op_.CreateKernelV2(
              &op_,
              ort_api,
              reinterpret_cast<const OrtKernelInfo*>(&info),
              &op_kernel_));
    } else {
      op_kernel_ = op_.CreateKernel(&op_, ort_api,
                                    reinterpret_cast<const OrtKernelInfo*>(&info));
    }
  }
 
  ~CustomOpKernel() override {
    op_.KernelDestroy(op_kernel_);
  }
 
  Status Compute(OpKernelContext* ctx) const override {
    if (op_.version >= min_ort_version_with_compute_v2_support &&
        op_.KernelComputeV2) {
      return ToStatusAndRelease(op_.KernelComputeV2(op_kernel_, reinterpret_cast<OrtKernelContext*>(ctx)));
    } else {
      op_.KernelCompute(op_kernel_, reinterpret_cast<OrtKernelContext*>(ctx));
      return Status::OK();
    }
  }
 
 private:
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(CustomOpKernel);
 
  const OrtCustomOp& op_;
  void* op_kernel_;
};
 
#if !defined(ORT_MINIMAL_BUILD)
KernelCreateInfo CreateKernelCreateInfo(const std::string& domain, const OrtCustomOp* op) {
  const size_t input_count = op->GetInputTypeCount(op);
  const size_t output_count = op->GetOutputTypeCount(op);
 
  KernelDefBuilder def_builder;
  def_builder.SetName(op->GetName(op))
      .SetDomain(domain);
 
  if (op->version >= min_ort_version_with_custom_version) {
    if (op->GetStartVersion && op->GetEndVersion) {
      def_builder.SinceVersion(op->GetStartVersion(op), op->GetEndVersion(op));
    } else if (op->GetStartVersion) {
      def_builder.SinceVersion(op->GetStartVersion(op));
    } else {
      def_builder.SinceVersion(1);
    }
  } else {
    def_builder.SinceVersion(1);
  }
 
  // GetInputMemoryType was introduced in ver 13. This check allows custom ops compiled using older versions
  // to work with newer versions (> 12) of the ORT binary.
  if (op->version > 12) {
    for (size_t i = 0; i < input_count; i++) {
      def_builder.InputMemoryType(op->GetInputMemoryType(op, i), gsl::narrow_cast<int>(i));
    }
  }
 
  for (size_t i = 0; i < input_count; i++) {
    const auto input_type = op->GetInputType(op, i);
    const auto input_name = "Input" + std::to_string(i);
    if (input_type == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED) {
      def_builder.TypeConstraint(input_name, SUPPORTED_TENSOR_TYPES);
    } else {
      const auto* tensor_type = DataTypeImpl::TensorTypeFromONNXEnum(utils::ToTensorProtoElementType(input_type));
      def_builder.TypeConstraint(input_name, tensor_type->AsTensorType());
    }
  }
 
  for (size_t i = 0; i < output_count; i++) {
    const auto output_type = op->GetOutputType(op, i);
    const auto output_name = "Output" + std::to_string(i);
    if (output_type == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED) {
      def_builder.TypeConstraint(output_name, SUPPORTED_TENSOR_TYPES);
    } else {
      const auto* tensor_type = DataTypeImpl::TensorTypeFromONNXEnum(utils::ToTensorProtoElementType(output_type));
      def_builder.TypeConstraint(output_name, tensor_type->AsTensorType());
    }
  }
 
  if (const char* provider_type = op->GetExecutionProviderType(op)) {
    def_builder.Provider(provider_type);
  } else {
    def_builder.Provider(onnxruntime::kCpuExecutionProvider);
  }
 
  if (op->version >= 18 && op->GetMayInplace != nullptr) {
    int* input_index = nullptr;
    int* output_index = nullptr;
    size_t len = op->GetMayInplace(&input_index, &output_index);
    if (len > 0) {
      for (size_t i = 0; i < len; i++) def_builder.MayInplace(input_index[i], output_index[i]);
      op->ReleaseMayInplace(input_index, output_index);
    }
  }
 
  if (op->version >= 18 && op->GetAliasMap != nullptr) {
    int* input_index = nullptr;
    int* output_index = nullptr;
    size_t len = op->GetAliasMap(&input_index, &output_index);
    if (len > 0) {
      for (size_t i = 0; i < len; i++) def_builder.Alias(input_index[i], output_index[i]);
      op->ReleaseAliasMap(input_index, output_index);
    }
  }
 
  KernelCreateFn kernel_create_fn = [op](FuncManager&, const OpKernelInfo& info,
                                         std::unique_ptr<OpKernel>& out) -> Status {
    out = std::make_unique<CustomOpKernel>(info, *op);
    return Status::OK();
  };
 
  return KernelCreateInfo(def_builder.Build(), kernel_create_fn);
}
 
ONNX_NAMESPACE::OpSchema CreateSchema(const std::string& domain, const std::vector<const OrtCustomOp*>& ops) {
  // The function registers the first schema assuming all the other one are the same except the types constraints.
  ORT_ENFORCE(ops.size() > 0, "No kernels to registers.");
  int num_inputs_with_dynamic_type = 0;
 
  // Creation of the schema for the first kernel in ops.
  const OrtCustomOp* op = *ops.begin();
  ONNX_NAMESPACE::OpSchema schema(op->GetName(op), "custom op registered at runtime", 0);
 
  auto create_type_constraint = [&ops, &schema, &num_inputs_with_dynamic_type](
                                    const OrtCustomOp* op, int count, int i, bool is_input) {
    onnx::OpSchema::FormalParameterOption option = onnx::OpSchema::FormalParameterOption::Single;
    bool is_homogeneous = true;
    int min_arity = 1;
 
    // The OrtCustomOp interface did not support the methods to query input/output characteristics before
    // ORT API version 8. So, query the relevant methods ONLY from API version 8 onwards.
    if (op->version >= min_ort_version_with_optional_io_support) {
      const auto characteristic = is_input ? op->GetInputCharacteristic(op, i) : op->GetOutputCharacteristic(op, i);
 
      // Support for optional and variadic inputs/output was added in versions 8 and 14, respectively.
      if (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_OPTIONAL) {
        option = onnx::OpSchema::FormalParameterOption::Optional;
      } else if ((op->version >= min_ort_version_with_variadic_io_support) &&
                 (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_VARIADIC)) {
        ORT_ENFORCE(i == count - 1, "Only the last ", (is_input ? "input" : "output"),
                    " to a custom op may be marked variadic.");
        option = onnx::OpSchema::FormalParameterOption::Variadic;
        min_arity = is_input ? op->GetVariadicInputMinArity(op) : op->GetVariadicOutputMinArity(op);
        is_homogeneous = static_cast<bool>(is_input
                                               ? op->GetVariadicInputHomogeneity(op)
                                               : op->GetVariadicOutputHomogeneity(op));
      }
    }
 
    // The loop goes through all operators sharing the same schema to build
    // the minimal type constraints for all of them. All kernels must have
    // the same number of inputs / outputs among themselves to be able to build
    // the type constraints. Any kind of incompatibility between a schema and
    // a kernel is checked by method IsCompatible once the schema is created
    // by this method.
    std::unordered_set<ONNXTensorElementDataType> all_types;
    for (auto o : ops) {
      ORT_ENFORCE(static_cast<size_t>(i) != (is_input ? o->GetInputTypeCount(o) : o->GetOutputTypeCount(o)),
                  "Another version of operator '", schema.Name(),
                  "'has a different number of ", (is_input ? "inputs" : "outputs"),
                  ". onnxruntime allows the overloading of an operator "
                  "if all versions have the same number of declared ",
                  (is_input ? "inputs" : "outputs"), ".");
      const auto type = is_input ? o->GetInputType(o, i) : o->GetOutputType(o, i);
      if (type == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED) {
        // If 'type' is undefined, all types are allowed regardless of what other versions of the same operator
        // define. In that case, all_types is cleared, that's the convention used by the code following this loop
        // to declare all types as possible types.
        all_types.clear();
        break;
      }
      all_types.insert(type);
    }
 
    std::string prefix = is_input ? "Input" : "Output";
    std::string name = prefix + std::to_string(i);
    if (is_input) {
      schema.Input(gsl::narrow_cast<int>(i), name, "", name, option, is_homogeneous, min_arity);
    } else {
      schema.Output(gsl::narrow_cast<int>(i), name, "", name, option, is_homogeneous, min_arity);
    }
 
    if (!all_types.empty()) {
      // all_types is not empty then only the types in this container are allowed of this input.
      std::vector<std::string> types;
      for (auto type : all_types) {
        const ONNX_NAMESPACE::TypeProto* type_proto =
            DataTypeImpl::TensorTypeFromONNXEnum(utils::ToTensorProtoElementType(type))->GetTypeProto();
        types.push_back(*ONNX_NAMESPACE::Utils::DataTypeUtils::ToType(*type_proto));
      }
      schema.TypeConstraint(name, types, "defined list of types");
    } else {
      // all_types is empty. As mentioned in the previous loop, all types are allowed.
      schema.TypeConstraint(name, DataTypeImpl::ToString(SUPPORTED_TENSOR_TYPES), "all types");
      if (is_input) {
        ++num_inputs_with_dynamic_type;
      }
    }
  };
 
  const size_t input_count = op->GetInputTypeCount(op);
  for (size_t i = 0; i < input_count; i++) {
    create_type_constraint(op, static_cast<int>(input_count), static_cast<int>(i), true);
  }
 
  const bool have_shape_infer_fn = op->version >= min_ort_version_with_shape_inference && op->InferOutputShapeFn;
 
  const size_t output_count = op->GetOutputTypeCount(op);
  for (size_t i = 0; i < output_count; i++) {
    const auto type = op->GetOutputType(op, i);
    if (ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED == type) {
      if (op->GetOutputCharacteristic(op, i) == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED) {
        // if there's a dynamically typed input and output we infer they both have the same type from the input.
        // if that isn't the case the user must provide an output shape inference fn which must set the output type.
        ORT_ENFORCE(num_inputs_with_dynamic_type == 1 || have_shape_infer_fn,
                    "The type of a dynamically typed output can be inferred from a single dynamically typed input, "
                    "or by a user provided OrtCustomOp->InferOutputShapeFn that sets the output type.");
      }
    }
 
    create_type_constraint(op, static_cast<int>(output_count), static_cast<int>(i), false);
  }
 
  schema.SetDomain(domain);
  if (op->version >= min_ort_version_with_custom_version && op->GetStartVersion) {
    schema.SinceVersion(op->GetStartVersion(op));
  } else {
    schema.SinceVersion(1);
  }
  schema.AllowUncheckedAttributes();
 
  if (op->version >= min_ort_version_with_shape_inference && op->InferOutputShapeFn) {
    schema.TypeAndShapeInferenceFunction([op](ONNX_NAMESPACE::InferenceContext& infer_ctx) {
      OrtShapeInferContext ctx(infer_ctx);
      op->InferOutputShapeFn(op, &ctx);
    });
  }
  return schema;
}
 
Status IsCompatible(const ONNX_NAMESPACE::OpSchema& schema, const OrtCustomOp* op) {
  const size_t input_count = op->GetInputTypeCount(op);
  const size_t output_count = op->GetOutputTypeCount(op);
 
  // check inputs
  const auto& input_parameters = schema.inputs();
  ORT_RETURN_IF_NOT(input_parameters.size() == input_count, "input count does not match");
  for (size_t i = 0; i < input_parameters.size(); ++i) {
    const auto characteristic = op->GetInputCharacteristic(op, i);
    const auto& formal_parameter = input_parameters[i];
    if (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_OPTIONAL) {
      ORT_RETURN_IF_NOT(op->version < min_ort_version_with_optional_io_support ||
                            formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Optional,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " input to be of optional type");
    } else if (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_VARIADIC) {
      ORT_RETURN_IF_NOT(formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Variadic,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " input to be of variadic type");
      ORT_RETURN_IF_NOT(op->version < min_ort_version_with_variadic_io_support ||
                            formal_parameter.GetIsHomogeneous() == (op->GetVariadicInputHomogeneity(op) != 0),
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " input to keep same homogeneity");
      ORT_RETURN_IF_NOT(formal_parameter.GetMinArity() == op->GetVariadicInputMinArity(op),
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " input to keep same arity");
    } else {
      ORT_RETURN_IF_NOT(formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Single,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " input to be of single type");
    }
  }
  // check outputs
  const auto& output_parameters = schema.outputs();
  ORT_RETURN_IF_NOT(output_parameters.size() == output_count, "output count does not match");
  for (size_t i = 0; i < output_parameters.size(); ++i) {
    const auto characteristic = op->GetOutputCharacteristic(op, i);
    const auto& formal_parameter = output_parameters[i];
    if (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_OPTIONAL) {
      ORT_RETURN_IF_NOT(formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Optional,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " output to be of optional type");
    } else if (characteristic == OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_VARIADIC) {
      ORT_RETURN_IF_NOT(formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Variadic,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " output to be of variadic type");
      ORT_RETURN_IF_NOT(formal_parameter.GetIsHomogeneous() == (op->GetVariadicOutputHomogeneity(op) != 0),
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " output to keep same homogeneity");
      ORT_RETURN_IF_NOT(formal_parameter.GetMinArity() == op->GetVariadicOutputMinArity(op),
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " output to keep same arity");
    } else {
      ORT_RETURN_IF_NOT(formal_parameter.GetOption() == onnx::OpSchema::FormalParameterOption::Single,
                        "custom op schemas mismatch, expecting ", i + 1,
                        i == 0 ? "st" : (i == 1 ? "nd" : "th"),
                        " output to be of single type");
    }
  }
  return Status::OK();
}
 
// This function attempts to do its best for older custom ops (most of them) who do not have
// they own type and shape inference function. However, it falls short in some cases, and we leave
// those for the user to handle in their own inference function.
static void InferOutputTypes(const ONNX_NAMESPACE::OpSchema& schema, gsl::span<const KernelDef* const> kernel_defs,
                             ONNX_NAMESPACE::InferenceContext& infer_ctx) {
  const auto& inputs = schema.inputs();
  const auto node_input_num = infer_ctx.getNumInputs();
 
  const KernelDef* def_selected = nullptr;
  bool is_variadic_input = false;
  bool is_homogeneous_input = false;
  int32_t output_propagate{0};
 
  for (size_t kernel_index = 0;
       kernel_index < kernel_defs.size() && def_selected == nullptr;
       ++kernel_index) {
    const auto* kernel_def = kernel_defs[kernel_index];
    const auto& type_constraints = kernel_def->TypeConstraints();
    def_selected = kernel_def;
 
    for (size_t i = 0; i < node_input_num; ++i) {
      const auto input_type = infer_ctx.getInputType(i);
 
      // Guard against variadic parameter index
      const size_t schema_input_index = (i < inputs.size()) ? i : inputs.size() - 1;
      const auto& param = inputs[schema_input_index];
      const auto& input_name = param.GetName();
      if (input_type == nullptr) {
        if (param.GetOption() == ONNX_NAMESPACE::OpSchema::FormalParameterOption::Optional)
          continue;
 
        ORT_THROW("[CustomOP type inferencing error]: kernel Input: ", input_name,
                  " is absent, but not optional. Op : ", schema.Name());
      }
 
      is_variadic_input = (param.GetOption() == ONNX_NAMESPACE::OpSchema::FormalParameterOption::Variadic);
      is_homogeneous_input = param.GetIsHomogeneous();
 
      if (!is_variadic_input || is_homogeneous_input) {
        auto hit = type_constraints.find(input_name);
        if (hit != type_constraints.end()) {
          const auto& types = hit->second;
          // For custom ops kernel constraints are never empty
          assert(!types.empty());
          if (!std::any_of(types.cbegin(), types.cend(),
                           [input_type](const DataTypeImpl* type) {
                             return type->IsCompatible(*input_type);
                           })) {
            def_selected = nullptr;
            output_propagate = 0;
            break;
          }
 
          // If we have multiple types possible from the constraints,
          // record the last type and use it to guess the output type if
          // output may have different types. Works well for symmetric single input/outputs
          // otherwise give up and let the user supply their own function
          if (types.size() > 1) {
            output_propagate = input_type->tensor_type().elem_type();
          }
        } else {
          ORT_THROW("[CustomOP type inferencing error]: no type constraint found for input: ",
                    input_name, " Op: ", schema.Name());
        }
      }
    }
  }
 
  if (def_selected == nullptr) {
    ORT_THROW("[CustomOP type inferencing error]: no kernel def matches node inputs for Op: ", schema.Name());
  }
 
  const auto& outputs = schema.outputs();
  const auto node_output_num = infer_ctx.getNumOutputs();
  const auto& selected_type_constraints = def_selected->TypeConstraints();
 
  for (size_t i = 0; i < node_output_num; ++i) {
    auto output_type = infer_ctx.getOutputType(i);
    // Account for variadic outputs
    const size_t schema_output_index = (i < outputs.size()) ? i : outputs.size() - 1;
    const auto& param = outputs[schema_output_index];
    const auto& output_name = param.GetName();
 
    const bool is_variadic_output = (param.GetOption() == ONNX_NAMESPACE::OpSchema::FormalParameterOption::Variadic);
    const bool is_homogeneous = param.GetIsHomogeneous();
 
    // We give up on variadic non-homogeneous outputs
    // Let the user handle it in their inference function
    if (is_variadic_output && !is_homogeneous) {
      break;
    }
 
    auto hit = selected_type_constraints.find(output_name);
    if (hit != selected_type_constraints.end()) {
      const auto& types = hit->second;
      assert(!types.empty());
 
      if (types.size() == 1) {
        // Use the constraint type
        output_type->mutable_tensor_type()->set_elem_type(
            types[0]->GetTypeProto()->tensor_type().elem_type());
      } else if (!is_variadic_input || is_homogeneous_input) {
        // If not variadic or homogeneous, and there are multiple types possible, guess from the last input type
        // as this works for symmetric varied single input/outputs
        // otherwise give up and let the user supply their own function
        output_type->mutable_tensor_type()->set_elem_type(output_propagate);
      }
    } else {
      ORT_THROW("[CustomOP type inferencing error]: no type constraint found for output: ",
                output_name, " Op: ", schema.Name());
    }
  }
}
 
#endif
 
common::Status CreateCustomRegistry(gsl::span<OrtCustomOpDomain* const> op_domains,
                                    std::shared_ptr<CustomRegistry>& output) {
  output = std::make_shared<CustomRegistry>();
 
  for (const auto& domain : op_domains) {
#if !defined(ORT_MINIMAL_BUILD)
    std::unordered_map<std::string, ONNX_NAMESPACE::OpSchema> schema_map;
    std::unordered_map<std::string, InlinedVector<const KernelDef*>> kernel_def_map;
 
    // Domain is not empty - add it to the DomainToVersion ONNX map
    // If domain is empty, it is assumed to be part of the ONNX domain
    if (!domain->domain_.empty()) {
      // Add it to the DomainToVersion ONNX map if it doesn't already exist
      // For example, two sessions using the same session_options should not add the same custom op domain
      // to the version map twice
      auto& domain_to_version_range_instance = ONNX_NAMESPACE::OpSchemaRegistry::DomainToVersionRange::Instance();
      const auto& domain_to_version_map = domain_to_version_range_instance.Map();
 
      if (domain_to_version_map.find(domain->domain_) == domain_to_version_map.end()) {
        domain_to_version_range_instance.AddDomainToVersion(domain->domain_, 1, 1000);
      }
    }
 
    // domain_kernels aggregate all custom operator per names.
    std::unordered_map<std::string, std::vector<const OrtCustomOp*>> domain_kernels;
    for (const auto* op : domain->custom_ops_) {
      // define kernel
      const auto* name = op->GetName(op);
      domain_kernels[name].push_back(op);
    }
 
    // Creation of the schemas, one per unique name.
    for (auto& [name, ops] : domain_kernels) {
      auto schema = CreateSchema(domain->domain_, ops);
      // schema.Name() is equal to ops[0]->GetName(ops[0]) and op->GetName(op) is the value
      // used as a key for dictionary domain_kernels, therefore name == schema.Name().
      schema_map.emplace(schema.Name(), schema);
 
      // This loops checks that all custom operators sharing the same name are compatible with the defined schema.
      for (const auto* op : ops) {
        // define kernel
        auto kernel_create_info = CreateKernelCreateInfo(domain->domain_, op);
        const auto* op_name = op->GetName(op);
        kernel_def_map[op_name].push_back(kernel_create_info.kernel_def.get());
        ORT_RETURN_IF_ERROR(output->RegisterCustomKernel(kernel_create_info));
        // If IsCompatible returns false, then all custom operators named
        // 'op->GetName(op)' are not compatible among themselves.
        // They should have the same number of inputs and outputs, the same characteristics,
        // (optional, ...). Only the type can change.
        ORT_RETURN_IF_ERROR(IsCompatible(schema, op));
      }
    }
 
    std::vector<ONNX_NAMESPACE::OpSchema> schemas;
    for (auto& [name, schema] : schema_map) {
      schemas.push_back(schema);
      auto infer_fn = schemas.back().GetTypeAndShapeInferenceFunction();
      ONNX_NAMESPACE::InferenceFunction extended_infer_fn =
          [sch = schema, infer_fn = std::move(infer_fn),
           kernel_defs = std::move(kernel_def_map[name])](ONNX_NAMESPACE::InferenceContext& infer_ctx) {
            InferOutputTypes(sch, kernel_defs, infer_ctx);
            if (infer_fn) {
              infer_fn(infer_ctx);
            }
          };
      schemas.back().TypeAndShapeInferenceFunction(extended_infer_fn);
    }
 
    ORT_RETURN_IF_ERROR(output->RegisterOpSet(schemas,
                                              domain->domain_,
                                              1 /* baseline opset version */,
                                              1000 /* opset version */));
#else
    // For a minimal build, we may not need any of the ONNX schema stuff but we still need to track
    // the type template parameters to be used during the kernel def building step below
    for (const auto* op : domain->custom_ops_) {
      size_t undefined = 0;
      size_t input_count = op->GetInputTypeCount(op);
      for (size_t i = 0; i < input_count; i++) {
        auto type = op->GetInputType(op, i);
        if (ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED == type) {
          undefined++;
        }
      }
 
      KernelDefBuilder def_builder;
      def_builder.SetName(op->GetName(op))
          .SetDomain(domain->domain_)
          .SinceVersion(1);
 
      // GetInputMemoryType was introduced in ver 13. This check allows custom ops compiled using older versions
      // to work with newer versions (> 12) of the ORT binary.
      if (op->version > 12) {
        for (size_t i = 0; i < input_count; i++) {
          def_builder.InputMemoryType(op->GetInputMemoryType(op, i), i);
        }
      }
 
      for (size_t i = 0; i < undefined; i++) {
        def_builder.TypeConstraint("T" + std::to_string(i), SUPPORTED_TENSOR_TYPES);
      }
 
      if (const char* provider_type = op->GetExecutionProviderType(op)) {
        def_builder.Provider(provider_type);
      } else {
        def_builder.Provider(onnxruntime::kCpuExecutionProvider);
      }
 
      KernelCreateFn kernel_create_fn = [op](FuncManager&, const OpKernelInfo& info, std::unique_ptr<OpKernel>& out) -> Status {
        out = std::make_unique<CustomOpKernel>(info, *op);
        return Status::OK();
      };
 
      KernelCreateInfo create_info(def_builder.Build(), kernel_create_fn);
      ORT_RETURN_IF_ERROR(output->RegisterCustomKernel(create_info));
    }
#endif
  }  // for each domain
 
  return Status::OK();
}
 
}  // namespace onnxruntime
#endif  // ENABLE_CUSTOM_OP_API