File indexing completed on 2026-01-04 09:48:03
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #include <algorithm>
0011 #include <functional>
0012 #include <iterator>
0013 #include <string>
0014 #include <type_traits>
0015 #include <vector>
0016
0017
0018
0019 #define ORT_CXX_RETURN_ON_API_FAIL(expression) \
0020 { \
0021 auto ort_status = (expression); \
0022 if (ort_status) { \
0023 return Ort::Status(ort_status); \
0024 } \
0025 }
0026
0027 #ifdef __cpp_if_constexpr
0028 #define ORT_CXX_IF_CONSTEXPR if constexpr
0029 #else
0030 #define ORT_CXX_IF_CONSTEXPR if
0031 #endif
0032
0033 namespace Ort {
0034
0035 namespace detail {
0036 inline void ThrowStatus(const Status& st) {
0037 std::string error_message = st.GetErrorMessage();
0038 OrtErrorCode error_code = st.GetErrorCode();
0039 ORT_CXX_API_THROW(std::move(error_message), error_code);
0040 }
0041 }
0042
0043 inline void ThrowOnError(OrtStatus* ort_status) {
0044 if (ort_status) {
0045 Ort::Status st(ort_status);
0046 detail::ThrowStatus(st);
0047 }
0048 }
0049
0050 inline void ThrowOnError(const Status& st) {
0051 if (st) {
0052 detail::ThrowStatus(st);
0053 }
0054 }
0055
0056 inline Status::Status(OrtStatus* status) noexcept : detail::Base<OrtStatus>{status} {
0057 }
0058
0059 inline Status::Status(const std::exception& e) noexcept {
0060 p_ = GetApi().CreateStatus(ORT_FAIL, e.what());
0061 }
0062
0063 inline Status::Status(const Exception& e) noexcept {
0064 p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what());
0065 }
0066
0067 inline Status::Status(const char* message, OrtErrorCode code) noexcept {
0068 p_ = GetApi().CreateStatus(code, message);
0069 }
0070
0071 inline std::string Status::GetErrorMessage() const {
0072 std::string message(GetApi().GetErrorMessage(p_));
0073 return message;
0074 }
0075
0076 inline OrtErrorCode Status::GetErrorCode() const {
0077 return GetApi().GetErrorCode(p_);
0078 }
0079
0080 inline bool Status::IsOK() const noexcept {
0081 return (p_ == nullptr);
0082 }
0083
0084
0085 template <typename T>
0086 struct TypeToTensorType;
0087 template <>
0088 struct TypeToTensorType<float> {
0089 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
0090 };
0091 template <>
0092 struct TypeToTensorType<Float16_t> {
0093 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16;
0094 };
0095 template <>
0096 struct TypeToTensorType<BFloat16_t> {
0097 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16;
0098 };
0099 template <>
0100 struct TypeToTensorType<double> {
0101 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE;
0102 };
0103 template <>
0104 struct TypeToTensorType<int8_t> {
0105 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8;
0106 };
0107 template <>
0108 struct TypeToTensorType<int16_t> {
0109 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16;
0110 };
0111 template <>
0112 struct TypeToTensorType<int32_t> {
0113 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32;
0114 };
0115 template <>
0116 struct TypeToTensorType<int64_t> {
0117 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
0118 };
0119 template <>
0120 struct TypeToTensorType<uint8_t> {
0121 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8;
0122 };
0123 template <>
0124 struct TypeToTensorType<uint16_t> {
0125 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16;
0126 };
0127 template <>
0128 struct TypeToTensorType<uint32_t> {
0129 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32;
0130 };
0131 template <>
0132 struct TypeToTensorType<uint64_t> {
0133 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64;
0134 };
0135 template <>
0136 struct TypeToTensorType<bool> {
0137 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL;
0138 };
0139
0140 template <>
0141 struct TypeToTensorType<Float8E4M3FN_t> {
0142 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN;
0143 };
0144 template <>
0145 struct TypeToTensorType<Float8E4M3FNUZ_t> {
0146 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ;
0147 };
0148 template <>
0149 struct TypeToTensorType<Float8E5M2_t> {
0150 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2;
0151 };
0152 template <>
0153 struct TypeToTensorType<Float8E5M2FNUZ_t> {
0154 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ;
0155 };
0156
0157 inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept {
0158 if (IsNaN() || rhs.IsNaN()) {
0159
0160 return false;
0161 }
0162 return val == rhs.val;
0163 }
0164
0165 inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept {
0166 if (IsNaN() || rhs.IsNaN()) {
0167
0168 return false;
0169 }
0170
0171 const bool left_is_negative = IsNegative();
0172 if (left_is_negative != rhs.IsNegative()) {
0173
0174
0175
0176 return left_is_negative && !AreZero(*this, rhs);
0177 }
0178 return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative);
0179 }
0180
0181 inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size)
0182 : allocator_(allocator), p_(p), size_(size) {
0183 }
0184
0185 inline MemoryAllocation::~MemoryAllocation() {
0186 if (p_ != nullptr) {
0187
0188 auto ret = GetApi().AllocatorFree(allocator_, p_);
0189 static_cast<void>(ret);
0190 }
0191 }
0192
0193 inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) {
0194 *this = std::move(o);
0195 }
0196
0197 inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept {
0198 OrtAllocator* alloc = nullptr;
0199 void* p = nullptr;
0200 size_t sz = 0;
0201
0202
0203 std::swap(alloc, allocator_);
0204 std::swap(p, p_);
0205 std::swap(sz, size_);
0206
0207
0208 std::swap(allocator_, o.allocator_);
0209 std::swap(p_, o.p_);
0210 std::swap(size_, o.size_);
0211
0212
0213 MemoryAllocation this_alloc(alloc, p, sz);
0214 return *this;
0215 }
0216
0217 namespace detail {
0218
0219 template <typename T>
0220 inline void* AllocatorImpl<T>::Alloc(size_t size) {
0221 void* out;
0222 ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
0223 return out;
0224 }
0225
0226 template <typename T>
0227 inline MemoryAllocation AllocatorImpl<T>::GetAllocation(size_t size) {
0228 void* out;
0229 ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
0230 MemoryAllocation result(this->p_, out, size);
0231 return result;
0232 }
0233
0234 template <typename T>
0235 inline void AllocatorImpl<T>::Free(void* p) {
0236 ThrowOnError(GetApi().AllocatorFree(this->p_, p));
0237 }
0238
0239 template <typename T>
0240 inline ConstMemoryInfo AllocatorImpl<T>::GetInfo() const {
0241 const OrtMemoryInfo* out;
0242 ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out));
0243 return ConstMemoryInfo{out};
0244 }
0245
0246 }
0247
0248 inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() {
0249 ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_));
0250 }
0251
0252 inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) {
0253 ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_));
0254 }
0255
0256 namespace detail {
0257
0258 template <typename T>
0259 inline std::string MemoryInfoImpl<T>::GetAllocatorName() const {
0260 const char* name = nullptr;
0261 ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name));
0262 return std::string(name);
0263 }
0264
0265 template <typename T>
0266 inline OrtAllocatorType MemoryInfoImpl<T>::GetAllocatorType() const {
0267 OrtAllocatorType type;
0268 ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type));
0269 return type;
0270 }
0271
0272 template <typename T>
0273 inline int MemoryInfoImpl<T>::GetDeviceId() const {
0274 int id = 0;
0275 ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id));
0276 return id;
0277 }
0278
0279 template <typename T>
0280 inline OrtMemoryInfoDeviceType MemoryInfoImpl<T>::GetDeviceType() const {
0281 OrtMemoryInfoDeviceType type;
0282 GetApi().MemoryInfoGetDeviceType(this->p_, &type);
0283 return type;
0284 }
0285
0286 template <typename T>
0287 inline OrtMemType MemoryInfoImpl<T>::GetMemoryType() const {
0288 OrtMemType type;
0289 ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type));
0290 return type;
0291 }
0292
0293 template <typename T>
0294 template <typename U>
0295 inline bool MemoryInfoImpl<T>::operator==(const MemoryInfoImpl<U>& o) const {
0296 int comp_result = 0;
0297 ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result));
0298 return comp_result == 0;
0299 }
0300
0301 }
0302
0303 inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) {
0304 OrtMemoryInfo* p;
0305 ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p));
0306 return MemoryInfo(p);
0307 }
0308
0309 inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) {
0310 ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_));
0311 }
0312
0313 namespace detail {
0314 template <typename T>
0315 inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames() const {
0316 AllocatorWithDefaultOptions allocator;
0317 return binding_utils::GetOutputNamesHelper(this->p_, allocator);
0318 }
0319
0320 template <typename T>
0321 inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames(OrtAllocator* allocator) const {
0322 return binding_utils::GetOutputNamesHelper(this->p_, allocator);
0323 }
0324
0325 template <typename T>
0326 inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues() const {
0327 AllocatorWithDefaultOptions allocator;
0328 return binding_utils::GetOutputValuesHelper(this->p_, allocator);
0329 }
0330
0331 template <typename T>
0332 inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues(OrtAllocator* allocator) const {
0333 return binding_utils::GetOutputValuesHelper(this->p_, allocator);
0334 }
0335
0336 template <typename T>
0337 inline void IoBindingImpl<T>::BindInput(const char* name, const Value& value) {
0338 ThrowOnError(GetApi().BindInput(this->p_, name, value));
0339 }
0340
0341 template <typename T>
0342 inline void IoBindingImpl<T>::BindOutput(const char* name, const Value& value) {
0343 ThrowOnError(GetApi().BindOutput(this->p_, name, value));
0344 }
0345
0346 template <typename T>
0347 inline void IoBindingImpl<T>::BindOutput(const char* name, const OrtMemoryInfo* mem_info) {
0348 ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info));
0349 }
0350
0351 template <typename T>
0352 inline void IoBindingImpl<T>::ClearBoundInputs() {
0353 GetApi().ClearBoundInputs(this->p_);
0354 }
0355
0356 template <typename T>
0357 inline void IoBindingImpl<T>::ClearBoundOutputs() {
0358 GetApi().ClearBoundOutputs(this->p_);
0359 }
0360
0361 template <typename T>
0362 inline void IoBindingImpl<T>::SynchronizeInputs() {
0363 ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_));
0364 }
0365
0366 template <typename T>
0367 inline void IoBindingImpl<T>::SynchronizeOutputs() {
0368 ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_));
0369 }
0370
0371 namespace binding_utils {
0372 inline std::vector<std::string> GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
0373 std::vector<std::string> result;
0374 auto free_fn = detail::AllocatedFree(allocator);
0375 using Ptr = std::unique_ptr<void, decltype(free_fn)>;
0376
0377 char* buffer = nullptr;
0378 size_t* lengths = nullptr;
0379 size_t count = 0;
0380 ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count));
0381
0382 if (count == 0) {
0383 return result;
0384 }
0385
0386 Ptr buffer_g(buffer, free_fn);
0387 Ptr lengths_g(lengths, free_fn);
0388
0389 result.reserve(count);
0390 for (size_t i = 0; i < count; ++i) {
0391 auto sz = *lengths;
0392 result.emplace_back(buffer, sz);
0393 buffer += sz;
0394 ++lengths;
0395 }
0396 return result;
0397 }
0398
0399 inline std::vector<Value> GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
0400 std::vector<Value> result;
0401 size_t owned = 0;
0402 size_t output_count = 0;
0403
0404
0405 auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) {
0406 if (buffer) {
0407 while (owned < output_count) {
0408 auto* p = buffer + owned++;
0409 GetApi().ReleaseValue(*p);
0410 }
0411 allocator->Free(allocator, buffer);
0412 }
0413 };
0414 using Ptr = std::unique_ptr<OrtValue*, decltype(free_fn)>;
0415
0416 OrtValue** output_buffer = nullptr;
0417 ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count));
0418 if (output_count == 0) {
0419 return result;
0420 }
0421
0422 Ptr buffer_g(output_buffer, free_fn);
0423
0424 result.reserve(output_count);
0425 for (size_t i = 0; i < output_count; ++i) {
0426 result.emplace_back(output_buffer[i]);
0427 ++owned;
0428 }
0429 return result;
0430 }
0431
0432 }
0433 }
0434
0435 inline IoBinding::IoBinding(Session& session) {
0436 ThrowOnError(GetApi().CreateIoBinding(session, &this->p_));
0437 }
0438
0439 inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) {
0440 ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_));
0441 }
0442
0443 inline ThreadingOptions::ThreadingOptions() {
0444 ThrowOnError(GetApi().CreateThreadingOptions(&p_));
0445 }
0446
0447 inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) {
0448 ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads));
0449 return *this;
0450 }
0451
0452 inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) {
0453 ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads));
0454 return *this;
0455 }
0456
0457 inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) {
0458 ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning));
0459 return *this;
0460 }
0461
0462 inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() {
0463 ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_));
0464 return *this;
0465 }
0466
0467 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
0468 ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn));
0469 return *this;
0470 }
0471
0472 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
0473 ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options));
0474 return *this;
0475 }
0476
0477 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
0478 ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn));
0479 return *this;
0480 }
0481
0482 namespace detail {
0483 template <typename T>
0484 inline const char* KeyValuePairsImpl<T>::GetValue(const char* key) const {
0485 return GetApi().GetKeyValue(this->p_, key);
0486 }
0487
0488 template <typename T>
0489 inline std::unordered_map<std::string, std::string> KeyValuePairsImpl<T>::GetKeyValuePairs() const {
0490 std::unordered_map<std::string, std::string> out;
0491
0492 size_t num_pairs = 0;
0493 const char* const* keys = nullptr;
0494 const char* const* values = nullptr;
0495 GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs);
0496 if (num_pairs > 0) {
0497 out.reserve(num_pairs);
0498 for (size_t i = 0; i < num_pairs; ++i) {
0499 out.emplace(keys[i], values[i]);
0500 }
0501 }
0502
0503 return out;
0504 }
0505
0506 template <typename T>
0507 inline void KeyValuePairsImpl<T>::GetKeyValuePairs(std::vector<const char*>& keys,
0508 std::vector<const char*>& values) const {
0509 keys.clear();
0510 values.clear();
0511
0512 size_t num_pairs = 0;
0513 const char* const* keys_ptr = nullptr;
0514 const char* const* values_ptr = nullptr;
0515 GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs);
0516 if (num_pairs > 0) {
0517 keys.resize(num_pairs);
0518 values.resize(num_pairs);
0519 std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin());
0520 std::copy(values_ptr, values_ptr + num_pairs, values.begin());
0521 }
0522 }
0523 }
0524
0525 inline KeyValuePairs::KeyValuePairs() {
0526 GetApi().CreateKeyValuePairs(&p_);
0527 }
0528
0529 inline KeyValuePairs::KeyValuePairs(const std::unordered_map<std::string, std::string>& kv_pairs) {
0530 GetApi().CreateKeyValuePairs(&p_);
0531 for (const auto& kv : kv_pairs) {
0532 GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str());
0533 }
0534 }
0535
0536 inline void KeyValuePairs::Add(const char* key, const char* value) {
0537 GetApi().AddKeyValuePair(this->p_, key, value);
0538 }
0539
0540 inline void KeyValuePairs::Remove(const char* key) {
0541 GetApi().RemoveKeyValuePair(this->p_, key);
0542 }
0543
0544 namespace detail {
0545 template <typename T>
0546 inline OrtHardwareDeviceType HardwareDeviceImpl<T>::Type() const {
0547 return GetApi().HardwareDevice_Type(this->p_);
0548 }
0549
0550 template <typename T>
0551 inline uint32_t HardwareDeviceImpl<T>::VendorId() const {
0552 return GetApi().HardwareDevice_VendorId(this->p_);
0553 }
0554
0555 template <typename T>
0556 inline uint32_t HardwareDeviceImpl<T>::DeviceId() const {
0557 return GetApi().HardwareDevice_DeviceId(this->p_);
0558 }
0559
0560 template <typename T>
0561 inline const char* HardwareDeviceImpl<T>::Vendor() const {
0562 return GetApi().HardwareDevice_Vendor(this->p_);
0563 }
0564
0565 template <typename T>
0566 inline ConstKeyValuePairs HardwareDeviceImpl<T>::Metadata() const {
0567 return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)};
0568 }
0569
0570 template <typename T>
0571 inline const char* EpDeviceImpl<T>::EpName() const {
0572 return GetApi().EpDevice_EpName(this->p_);
0573 }
0574
0575 template <typename T>
0576 inline const char* EpDeviceImpl<T>::EpVendor() const {
0577 return GetApi().EpDevice_EpVendor(this->p_);
0578 }
0579
0580 template <typename T>
0581 inline ConstKeyValuePairs EpDeviceImpl<T>::EpMetadata() const {
0582 return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_));
0583 }
0584
0585 template <typename T>
0586 inline ConstKeyValuePairs EpDeviceImpl<T>::EpOptions() const {
0587 return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_));
0588 }
0589
0590 template <typename T>
0591 inline ConstHardwareDevice EpDeviceImpl<T>::Device() const {
0592 return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_));
0593 }
0594 }
0595
0596 inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device,
0597 ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) {
0598 ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_));
0599 }
0600
0601 inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) {
0602 ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_));
0603 if (strcmp(logid, "onnxruntime-node") == 0) {
0604 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0605 } else {
0606 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0607 }
0608 }
0609
0610 inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) {
0611 ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_));
0612 if (strcmp(logid, "onnxruntime-node") == 0) {
0613 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0614 } else {
0615 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0616 }
0617 }
0618
0619 inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) {
0620 ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_));
0621 if (strcmp(logid, "onnxruntime-node") == 0) {
0622 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0623 } else {
0624 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0625 }
0626 }
0627
0628 inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param,
0629 OrtLoggingLevel logging_level, _In_ const char* logid) {
0630 ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_));
0631 if (strcmp(logid, "onnxruntime-node") == 0) {
0632 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0633 } else {
0634 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0635 }
0636 }
0637
0638 inline Env& Env::EnableTelemetryEvents() {
0639 ThrowOnError(GetApi().EnableTelemetryEvents(p_));
0640 return *this;
0641 }
0642
0643 inline Env& Env::DisableTelemetryEvents() {
0644 ThrowOnError(GetApi().DisableTelemetryEvents(p_));
0645 return *this;
0646 }
0647
0648 inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) {
0649 ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level));
0650 return *this;
0651 }
0652
0653 inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) {
0654 ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg));
0655 return *this;
0656 }
0657
0658 inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map<std::string, std::string>& options, const OrtArenaCfg* arena_cfg) {
0659 std::vector<const char*> keys, values;
0660 auto num_entries = options.size();
0661 if (num_entries > 0) {
0662 keys.reserve(num_entries);
0663 values.reserve(num_entries);
0664 for (const auto& entry : options) {
0665 keys.push_back(entry.first.c_str());
0666 values.push_back(entry.second.c_str());
0667 }
0668 }
0669 ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries));
0670 return *this;
0671 }
0672
0673 inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name,
0674 const std::basic_string<ORTCHAR_T>& path) {
0675 ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str()));
0676 return *this;
0677 }
0678
0679 inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) {
0680 ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name));
0681 return *this;
0682 }
0683
0684 inline std::vector<ConstEpDevice> Env::GetEpDevices() const {
0685 size_t num_devices = 0;
0686 const OrtEpDevice* const* device_ptrs = nullptr;
0687 ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices));
0688
0689 std::vector<ConstEpDevice> devices;
0690 if (num_devices > 0) {
0691 devices.reserve(num_devices);
0692 for (size_t i = 0; i < num_devices; ++i) {
0693 devices.emplace_back(device_ptrs[i]);
0694 }
0695 }
0696
0697 return devices;
0698 }
0699
0700 inline CustomOpDomain::CustomOpDomain(const char* domain) {
0701 ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_));
0702 }
0703
0704 inline void CustomOpDomain::Add(const OrtCustomOp* op) {
0705 ThrowOnError(GetApi().CustomOpDomain_Add(p_, op));
0706 }
0707
0708 inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string<ORTCHAR_T>& adapter_path,
0709 OrtAllocator* allocator) {
0710 OrtLoraAdapter* p;
0711 ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p));
0712 return LoraAdapter{p};
0713 }
0714
0715 inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes,
0716 OrtAllocator* allocator) {
0717 OrtLoraAdapter* p;
0718 ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p));
0719 return LoraAdapter{p};
0720 }
0721
0722 inline RunOptions::RunOptions() {
0723 ThrowOnError(GetApi().CreateRunOptions(&p_));
0724 }
0725
0726 inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) {
0727 ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level));
0728 return *this;
0729 }
0730
0731 inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) {
0732 ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level));
0733 return *this;
0734 }
0735
0736 inline int RunOptions::GetRunLogVerbosityLevel() const {
0737 int out;
0738 ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out));
0739 return out;
0740 }
0741
0742 inline int RunOptions::GetRunLogSeverityLevel() const {
0743 int out;
0744 ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out));
0745 return out;
0746 }
0747
0748 inline RunOptions& RunOptions::SetRunTag(const char* run_tag) {
0749 ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag));
0750 return *this;
0751 }
0752
0753 inline const char* RunOptions::GetRunTag() const {
0754 const char* out;
0755 ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out));
0756 return out;
0757 }
0758
0759 inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) {
0760 ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value));
0761 return *this;
0762 }
0763
0764 inline RunOptions& RunOptions::SetTerminate() {
0765 ThrowOnError(GetApi().RunOptionsSetTerminate(p_));
0766 return *this;
0767 }
0768
0769 inline RunOptions& RunOptions::UnsetTerminate() {
0770 ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_));
0771 return *this;
0772 }
0773
0774 inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) {
0775 ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter));
0776 return *this;
0777 }
0778
0779 inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) {
0780 ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_));
0781 }
0782
0783 inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) {
0784 ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_));
0785 }
0786
0787 inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) {
0788 return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options));
0789 }
0790
0791 inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath(
0792 const ORTCHAR_T* input_model_path) {
0793 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path));
0794 return *this;
0795 }
0796
0797 inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer(
0798 const void* input_model_data, size_t input_model_data_size) {
0799 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data,
0800 input_model_data_size));
0801 return *this;
0802 }
0803
0804 inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath(
0805 const ORTCHAR_T* output_model_path) {
0806 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path));
0807 return *this;
0808 }
0809
0810 inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile(
0811 const ORTCHAR_T* file_path, size_t initializer_size_threshold) {
0812 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile(
0813 this->p_,
0814 file_path,
0815 initializer_size_threshold));
0816 return *this;
0817 }
0818
0819 inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer(
0820 OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) {
0821 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator,
0822 output_model_buffer_ptr,
0823 output_model_buffer_size_ptr));
0824 return *this;
0825 }
0826
0827 inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode(
0828 bool embed_ep_context_in_model) {
0829 Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode(
0830 this->p_,
0831 embed_ep_context_in_model));
0832 return *this;
0833 }
0834
0835 namespace detail {
0836
0837 template <typename T>
0838 inline Ort::SessionOptions ConstSessionOptionsImpl<T>::Clone() const {
0839 OrtSessionOptions* out;
0840 ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out));
0841 return SessionOptions{out};
0842 }
0843
0844 template <typename T>
0845 inline std::string ConstSessionOptionsImpl<T>::GetConfigEntry(const char* config_key) const {
0846 size_t size = 0;
0847
0848 Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size));
0849
0850 std::string out;
0851 out.resize(size);
0852 Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size));
0853 out.resize(size - 1);
0854
0855 return out;
0856 }
0857
0858 template <typename T>
0859 inline bool ConstSessionOptionsImpl<T>::HasConfigEntry(const char* config_key) const {
0860 int out = 0;
0861 Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out));
0862 return static_cast<bool>(out);
0863 }
0864
0865 template <typename T>
0866 inline std::string ConstSessionOptionsImpl<T>::GetConfigEntryOrDefault(const char* config_key,
0867 const std::string& def) const {
0868 if (!this->HasConfigEntry(config_key)) {
0869 return def;
0870 }
0871
0872 return this->GetConfigEntry(config_key);
0873 }
0874
0875 template <typename T>
0876 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetIntraOpNumThreads(int intra_op_num_threads) {
0877 ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads));
0878 return *this;
0879 }
0880
0881 template <typename T>
0882 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetInterOpNumThreads(int inter_op_num_threads) {
0883 ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads));
0884 return *this;
0885 }
0886
0887 template <typename T>
0888 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) {
0889 ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level));
0890 return *this;
0891 }
0892
0893 template <typename T>
0894 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetDeterministicCompute(bool value) {
0895 ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value));
0896 return *this;
0897 }
0898
0899 template <typename T>
0900 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) {
0901 ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath));
0902 return *this;
0903 }
0904
0905 template <typename T>
0906 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableProfiling(const ORTCHAR_T* profile_file_prefix) {
0907 ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix));
0908 return *this;
0909 }
0910
0911 template <typename T>
0912 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableProfiling() {
0913 ThrowOnError(GetApi().DisableProfiling(this->p_));
0914 return *this;
0915 }
0916
0917 template <typename T>
0918 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableOrtCustomOps() {
0919 ThrowOnError(GetApi().EnableOrtCustomOps(this->p_));
0920 return *this;
0921 }
0922
0923 template <typename T>
0924 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableMemPattern() {
0925 ThrowOnError(GetApi().EnableMemPattern(this->p_));
0926 return *this;
0927 }
0928
0929 template <typename T>
0930 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableMemPattern() {
0931 ThrowOnError(GetApi().DisableMemPattern(this->p_));
0932 return *this;
0933 }
0934
0935 template <typename T>
0936 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableCpuMemArena() {
0937 ThrowOnError(GetApi().EnableCpuMemArena(this->p_));
0938 return *this;
0939 }
0940
0941 template <typename T>
0942 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableCpuMemArena() {
0943 ThrowOnError(GetApi().DisableCpuMemArena(this->p_));
0944 return *this;
0945 }
0946
0947 template <typename T>
0948 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetExecutionMode(ExecutionMode execution_mode) {
0949 ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode));
0950 return *this;
0951 }
0952
0953 template <typename T>
0954 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLoadCancellationFlag(bool value) {
0955 ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value));
0956 return *this;
0957 }
0958
0959 template <typename T>
0960 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogId(const char* logid) {
0961 ThrowOnError(GetApi().SetSessionLogId(this->p_, logid));
0962 return *this;
0963 }
0964
0965 template <typename T>
0966 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogSeverityLevel(int level) {
0967 ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level));
0968 return *this;
0969 }
0970
0971 template <typename T>
0972 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::Add(OrtCustomOpDomain* custom_op_domain) {
0973 ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain));
0974 return *this;
0975 }
0976
0977 template <typename T>
0978 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddConfigEntry(const char* config_key, const char* config_value) {
0979 ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value));
0980 return *this;
0981 }
0982
0983 template <typename T>
0984 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddInitializer(const char* name, const OrtValue* ort_val) {
0985 ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val));
0986 return *this;
0987 }
0988
0989 template <typename T>
0990 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisablePerSessionThreads() {
0991 ThrowOnError(GetApi().DisablePerSessionThreads(this->p_));
0992 return *this;
0993 }
0994
0995 template <typename T>
0996 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializers(const std::vector<std::string>& names,
0997 const std::vector<Value>& ort_values) {
0998 const size_t inputs_num = names.size();
0999 if (inputs_num != ort_values.size()) {
1000 ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT);
1001 }
1002 std::vector<const char*> names_ptr;
1003 std::vector<const OrtValue*> ort_values_ptrs;
1004 names_ptr.reserve(inputs_num);
1005 ort_values_ptrs.reserve(inputs_num);
1006 for (size_t i = 0; i < inputs_num; ++i) {
1007 names_ptr.push_back(names[i].c_str());
1008 ort_values_ptrs.push_back(ort_values[i]);
1009 }
1010 ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num));
1011 return *this;
1012 }
1013
1014 template <typename T>
1015 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializersFromFilesInMemory(const std::vector<std::basic_string<ORTCHAR_T>>& file_names,
1016 const std::vector<char*>& buffer_array,
1017 const std::vector<size_t>& file_lengths) {
1018 const size_t inputs_num = file_names.size();
1019 if (inputs_num != buffer_array.size()) {
1020 ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT);
1021 }
1022 if (inputs_num != file_lengths.size()) {
1023 ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT);
1024 }
1025 std::vector<const ORTCHAR_T*> names_ptr;
1026 names_ptr.reserve(inputs_num);
1027 for (size_t i = 0; i < inputs_num; ++i) {
1028 names_ptr.push_back(file_names[i].c_str());
1029 }
1030 ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(),
1031 file_lengths.data(), inputs_num));
1032 return *this;
1033 }
1034
1035 template <typename T>
1036 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) {
1037 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options));
1038 return *this;
1039 }
1040
1041 template <typename T>
1042 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) {
1043 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options));
1044 return *this;
1045 }
1046
1047 template <typename T>
1048 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) {
1049 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options));
1050 return *this;
1051 }
1052
1053 template <typename T>
1054 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) {
1055 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options));
1056 return *this;
1057 }
1058
1059 template <typename T>
1060 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) {
1061 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options));
1062 return *this;
1063 }
1064
1065 template <typename T>
1066 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) {
1067 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options));
1068 return *this;
1069 }
1070
1071 template <typename T>
1072 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) {
1073 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options));
1074 return *this;
1075 }
1076
1077 template <typename T>
1078 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) {
1079 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options));
1080 return *this;
1081 }
1082
1083 template <typename T>
1084 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider(
1085 const std::string& provider_name,
1086 const std::unordered_map<std::string, std::string>& provider_options) {
1087 auto num_entries = provider_options.size();
1088 std::vector<const char*> keys, values;
1089 if (num_entries > 0) {
1090 keys.reserve(num_entries);
1091 values.reserve(num_entries);
1092
1093 for (const auto& entry : provider_options) {
1094 keys.push_back(entry.first.c_str());
1095 values.push_back(entry.second.c_str());
1096 }
1097 }
1098
1099 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(),
1100 keys.data(), values.data(), num_entries));
1101
1102 return *this;
1103 }
1104
1105 namespace {
1106 template <typename T>
1107 void SessionOptionsAppendEP(detail::SessionOptionsImpl<T>& session_options,
1108 Env& env, const std::vector<ConstEpDevice>& ep_devices,
1109 const std::vector<const char*>& ep_options_keys,
1110 const std::vector<const char*>& ep_options_values) {
1111 std::vector<const OrtEpDevice*> ep_devices_ptrs;
1112 ep_devices_ptrs.reserve(ep_devices.size());
1113 for (const auto& ep_device : ep_devices) {
1114 ep_devices_ptrs.push_back(ep_device);
1115 }
1116
1117 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2(
1118 session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(),
1119 ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size()));
1120 }
1121 }
1122
1123 template <typename T>
1124 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_V2(
1125 Env& env, const std::vector<ConstEpDevice>& ep_devices, const KeyValuePairs& ep_options) {
1126 std::vector<const char*> ep_options_keys, ep_options_values;
1127 ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values);
1128
1129 SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values);
1130
1131 return *this;
1132 }
1133
1134 template <typename T>
1135 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_V2(
1136 Env& env, const std::vector<ConstEpDevice>& ep_devices,
1137 const std::unordered_map<std::string, std::string>& ep_options) {
1138 std::vector<const char*> ep_options_keys, ep_options_values;
1139 ep_options_keys.reserve(ep_options.size());
1140 ep_options_values.reserve(ep_options.size());
1141
1142 for (const auto& [key, value] : ep_options) {
1143 ep_options_keys.push_back(key.c_str());
1144 ep_options_values.push_back(value.c_str());
1145 }
1146
1147 SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values);
1148
1149 return *this;
1150 }
1151
1152 template <typename T>
1153 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) {
1154 ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy));
1155 return *this;
1156 }
1157
1158 template <typename T>
1159 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) {
1160 ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state));
1161 return *this;
1162 }
1163
1164 template <typename T>
1165 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
1166 ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn));
1167 return *this;
1168 }
1169
1170 template <typename T>
1171 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
1172 ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options));
1173 return *this;
1174 }
1175
1176 template <typename T>
1177 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
1178 ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn));
1179 return *this;
1180 }
1181
1182 template <typename T>
1183 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) {
1184 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options));
1185 return *this;
1186 }
1187
1188 template <typename T>
1189 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map<std::string, std::string>& provider_options) {
1190 auto num_entries = provider_options.size();
1191 std::vector<const char*> keys, values;
1192 if (num_entries > 0) {
1193 keys.reserve(num_entries);
1194 values.reserve(num_entries);
1195
1196 for (const auto& entry : provider_options) {
1197 keys.push_back(entry.first.c_str());
1198 values.push_back(entry.second.c_str());
1199 }
1200 }
1201
1202 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_,
1203 keys.data(), values.data(), num_entries));
1204
1205 return *this;
1206 }
1207
1208 template <typename T>
1209 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_VitisAI(const std::unordered_map<std::string, std::string>& provider_options) {
1210 auto num_entries = provider_options.size();
1211 std::vector<const char*> keys, values;
1212 if (num_entries > 0) {
1213 keys.reserve(num_entries);
1214 values.reserve(num_entries);
1215
1216 for (const auto& entry : provider_options) {
1217 keys.push_back(entry.first.c_str());
1218 values.push_back(entry.second.c_str());
1219 }
1220 }
1221
1222 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries));
1223
1224 return *this;
1225 }
1226
1227 template <typename T>
1228 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name,
1229 const CustomOpConfigs& custom_op_configs) {
1230
1231
1232 for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) {
1233 AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str());
1234 }
1235
1236 ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name));
1237 return *this;
1238 }
1239
1240 template <typename T>
1241 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsUsingFunction(const char* registration_function_name) {
1242 ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name));
1243 return *this;
1244 }
1245
1246
1247 template <typename T>
1248 inline size_t ConstSessionImpl<T>::GetInputCount() const {
1249 size_t out;
1250 ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out));
1251 return out;
1252 }
1253
1254 template <typename T>
1255 inline size_t ConstSessionImpl<T>::GetOutputCount() const {
1256 size_t out;
1257 ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out));
1258 return out;
1259 }
1260
1261 template <typename T>
1262 inline size_t ConstSessionImpl<T>::GetOverridableInitializerCount() const {
1263 size_t out;
1264 ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out));
1265 return out;
1266 }
1267
1268 template <typename T>
1269 inline std::vector<std::string> ConstSessionImpl<T>::GetInputNames() const {
1270 AllocatorWithDefaultOptions allocator;
1271
1272 auto num_inputs = GetInputCount();
1273 std::vector<std::string> input_names;
1274 input_names.reserve(num_inputs);
1275
1276 for (size_t i = 0; i < num_inputs; ++i) {
1277 char* name = nullptr;
1278 ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name));
1279 input_names.push_back(name);
1280 allocator.Free(name);
1281 }
1282
1283 return input_names;
1284 }
1285
1286 template <typename T>
1287 inline std::vector<std::string> ConstSessionImpl<T>::GetOutputNames() const {
1288 AllocatorWithDefaultOptions allocator;
1289
1290 auto num_inputs = GetOutputCount();
1291 std::vector<std::string> output_names;
1292 output_names.reserve(num_inputs);
1293
1294 for (size_t i = 0; i < num_inputs; ++i) {
1295 char* name = nullptr;
1296 ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name));
1297 output_names.push_back(name);
1298 allocator.Free(name);
1299 }
1300
1301 return output_names;
1302 }
1303
1304 template <typename T>
1305 inline std::vector<std::string> ConstSessionImpl<T>::GetOverridableInitializerNames() const {
1306 AllocatorWithDefaultOptions allocator;
1307
1308 auto num_initializers = GetOverridableInitializerCount();
1309 std::vector<std::string> initializer_names;
1310 initializer_names.reserve(num_initializers);
1311
1312 for (size_t i = 0; i < num_initializers; ++i) {
1313 char* name = nullptr;
1314 ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name));
1315 initializer_names.push_back(name);
1316 }
1317
1318 return initializer_names;
1319 }
1320
1321 template <typename T>
1322 inline AllocatedStringPtr ConstSessionImpl<T>::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const {
1323 char* out;
1324 ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out));
1325 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1326 }
1327
1328 template <typename T>
1329 inline AllocatedStringPtr ConstSessionImpl<T>::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const {
1330 char* out;
1331 ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out));
1332 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1333 }
1334
1335 template <typename T>
1336 inline AllocatedStringPtr ConstSessionImpl<T>::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const {
1337 char* out;
1338 ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out));
1339 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1340 }
1341
1342 template <typename T>
1343 inline uint64_t ConstSessionImpl<T>::GetProfilingStartTimeNs() const {
1344 uint64_t out;
1345 ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out));
1346 return out;
1347 }
1348
1349 template <typename T>
1350 inline ModelMetadata ConstSessionImpl<T>::GetModelMetadata() const {
1351 OrtModelMetadata* out;
1352 ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out));
1353 return ModelMetadata{out};
1354 }
1355
1356 template <typename T>
1357 inline TypeInfo ConstSessionImpl<T>::GetInputTypeInfo(size_t index) const {
1358 OrtTypeInfo* out;
1359 ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out));
1360 return TypeInfo{out};
1361 }
1362
1363 template <typename T>
1364 inline TypeInfo ConstSessionImpl<T>::GetOutputTypeInfo(size_t index) const {
1365 OrtTypeInfo* out;
1366 ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out));
1367 return TypeInfo{out};
1368 }
1369
1370 template <typename T>
1371 inline TypeInfo ConstSessionImpl<T>::GetOverridableInitializerTypeInfo(size_t index) const {
1372 OrtTypeInfo* out;
1373 ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out));
1374 return TypeInfo{out};
1375 }
1376
1377 #if !defined(ORT_MINIMAL_BUILD)
1378 template <typename T>
1379 inline int ConstSessionImpl<T>::GetOpset(const std::string& domain) const {
1380 int opset;
1381 ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset));
1382 return opset;
1383 }
1384 #endif
1385
1386 template <typename T>
1387 std::vector<ValueInfo> ConstSessionImpl<T>::GetInputs() const {
1388 const std::vector<std::string> input_names = GetInputNames();
1389
1390 std::vector<ValueInfo> inputs;
1391 inputs.reserve(input_names.size());
1392
1393 for (size_t i = 0; i < input_names.size(); ++i) {
1394 auto type_info = GetInputTypeInfo(i);
1395 inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()});
1396 }
1397
1398 return inputs;
1399 }
1400
1401 template <typename T>
1402 std::vector<ValueInfo> ConstSessionImpl<T>::GetOutputs() const {
1403 const std::vector<std::string> output_names = GetOutputNames();
1404
1405 std::vector<ValueInfo> outputs;
1406 outputs.reserve(output_names.size());
1407
1408 for (size_t i = 0; i < output_names.size(); ++i) {
1409 auto type_info = GetOutputTypeInfo(i);
1410 outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()});
1411 }
1412
1413 return outputs;
1414 }
1415
1416 template <typename T>
1417 inline std::vector<Value> SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1418 const char* const* output_names, size_t output_count) {
1419 std::vector<Value> output_values;
1420 output_values.reserve(output_count);
1421 for (size_t i = 0; i < output_count; i++)
1422 output_values.emplace_back(nullptr);
1423 Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count);
1424 return output_values;
1425 }
1426
1427 template <typename T>
1428 inline void SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1429 const char* const* output_names, Value* output_values, size_t output_count) {
1430 static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
1431 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
1432 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
1433 ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values));
1434 }
1435
1436 template <typename T>
1437 inline void SessionImpl<T>::Run(const RunOptions& run_options, const IoBinding& io_binding) {
1438 ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding));
1439 }
1440
1441 template <typename T>
1442 inline void SessionImpl<T>::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1443 const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) {
1444 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
1445 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
1446 ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names,
1447 ort_input_values, input_count, output_names, output_count,
1448 ort_output_values, callback, user_data));
1449 }
1450
1451 template <typename T>
1452 inline AllocatedStringPtr SessionImpl<T>::EndProfilingAllocated(OrtAllocator* allocator) {
1453 char* out = nullptr;
1454 ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out));
1455 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1456 }
1457
1458 template <typename T>
1459 inline void SessionImpl<T>::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) {
1460 ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len));
1461 }
1462
1463 #if !defined(ORT_MINIMAL_BUILD)
1464 template <typename T>
1465 inline void SessionImpl<T>::FinalizeModelEditorSession(const Model& model, const SessionOptions& options,
1466 OrtPrepackedWeightsContainer* prepacked_weights_container) {
1467 ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model));
1468 ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container));
1469 }
1470 #endif
1471
1472 }
1473
1474 inline SessionOptions::SessionOptions() {
1475 ThrowOnError(GetApi().CreateSessionOptions(&this->p_));
1476 }
1477
1478
1479 inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) {
1480 std::string config_key = "custom_op.";
1481
1482 config_key += custom_op_name;
1483 config_key += ".";
1484 config_key += config;
1485
1486 return config_key;
1487 }
1488
1489 inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) {
1490 const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key);
1491 flat_configs_[full_flat_key] = config_value;
1492 return *this;
1493 }
1494
1495 inline const std::unordered_map<std::string, std::string>& CustomOpConfigs::GetFlattenedConfigs() const {
1496 return flat_configs_;
1497 }
1498
1499 inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) {
1500 ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_));
1501 }
1502
1503 inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options,
1504 OrtPrepackedWeightsContainer* prepacked_weights_container) {
1505 ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_));
1506 }
1507
1508 inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) {
1509 ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_));
1510 }
1511
1512 inline Session::Session(const Env& env, const void* model_data, size_t model_data_length,
1513 const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) {
1514 ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options,
1515 prepacked_weights_container, &this->p_));
1516 }
1517
1518 #if !defined(ORT_MINIMAL_BUILD)
1519 inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) {
1520 ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model.GetConst(), options, &this->p_));
1521 }
1522
1523
1524 inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path,
1525 const SessionOptions& options) {
1526 OrtSession* session = nullptr;
1527 ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session));
1528 return Session(session);
1529 }
1530
1531
1532 inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length,
1533 const SessionOptions& options) {
1534 OrtSession* session = nullptr;
1535 ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options,
1536 &session));
1537 return Session(session);
1538 }
1539
1540 void FinalizeModelEditorSession(const Model& model, const SessionOptions& options,
1541 OrtPrepackedWeightsContainer* prepacked_weights_container);
1542 #endif
1543
1544 inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const {
1545 char* out;
1546 ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out));
1547 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1548 }
1549
1550 inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const {
1551 char* out;
1552 ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out));
1553 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1554 }
1555
1556 inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const {
1557 char* out;
1558 ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out));
1559 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1560 }
1561
1562 inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const {
1563 char* out;
1564 ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out));
1565 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1566 }
1567
1568 inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const {
1569 char* out;
1570 ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out));
1571 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1572 }
1573
1574 inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const {
1575 char* out;
1576 ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out));
1577 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1578 }
1579
1580 inline std::vector<AllocatedStringPtr> ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const {
1581 auto deletor = detail::AllocatedFree(allocator);
1582 std::vector<AllocatedStringPtr> result;
1583
1584 char** out = nullptr;
1585 int64_t num_keys = 0;
1586 ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys));
1587 if (num_keys <= 0) {
1588 return result;
1589 }
1590
1591
1592 std::unique_ptr<void, decltype(deletor)> array_guard(out, deletor);
1593
1594 auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); };
1595 std::unique_ptr<char*, decltype(strings_deletor)> strings_guard(out, strings_deletor);
1596 result.reserve(static_cast<size_t>(num_keys));
1597 strings_guard.release();
1598 for (int64_t i = 0; i < num_keys; ++i) {
1599 result.push_back(AllocatedStringPtr(out[i], deletor));
1600 }
1601
1602 return result;
1603 }
1604
1605 inline int64_t ModelMetadata::GetVersion() const {
1606 int64_t out;
1607 ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out));
1608 return out;
1609 }
1610
1611 inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type,
1612 const std::vector<int64_t>& dims,
1613 const std::vector<std::string>* symbolic_dims) {
1614 ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_));
1615 ThrowOnError(GetApi().SetTensorElementType(p_, element_type));
1616 ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size()));
1617
1618 if (symbolic_dims) {
1619 std::vector<const char*> symbolic_dims_cstr;
1620 symbolic_dims_cstr.reserve(symbolic_dims->size());
1621 std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr),
1622 [](const std::string& s) { return s.c_str(); });
1623 ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size()));
1624 }
1625 }
1626
1627 #if !defined(ORT_MINIMAL_BUILD)
1628
1629 inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) {
1630 OrtTypeInfo* output = nullptr;
1631 ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output));
1632 return TypeInfo{output};
1633 }
1634
1635
1636 inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) {
1637 OrtTypeInfo* output = nullptr;
1638 ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output));
1639 return TypeInfo{output};
1640 }
1641
1642
1643 inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) {
1644 OrtTypeInfo* output;
1645 ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output));
1646 return TypeInfo{output};
1647 }
1648
1649
1650 inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) {
1651 OrtTypeInfo* output;
1652 ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output));
1653 return TypeInfo{output};
1654 }
1655
1656
1657 inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) {
1658 OrtTypeInfo* output;
1659 ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output));
1660 return TypeInfo{output};
1661 }
1662 #endif
1663
1664 namespace detail {
1665
1666 template <typename T>
1667 inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl<T>::GetElementType() const {
1668 ONNXTensorElementDataType out;
1669 ThrowOnError(GetApi().GetTensorElementType(this->p_, &out));
1670 return out;
1671 }
1672
1673 template <typename T>
1674 inline size_t TensorTypeAndShapeInfoImpl<T>::GetElementCount() const {
1675 size_t out;
1676 ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out));
1677 return static_cast<size_t>(out);
1678 }
1679
1680 template <typename T>
1681 inline size_t TensorTypeAndShapeInfoImpl<T>::GetDimensionsCount() const {
1682 size_t out;
1683 ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out));
1684 return out;
1685 }
1686
1687 template <typename T>
1688 inline void TensorTypeAndShapeInfoImpl<T>::GetDimensions(int64_t* values, size_t values_count) const {
1689 ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count));
1690 }
1691
1692 template <typename T>
1693 inline void TensorTypeAndShapeInfoImpl<T>::GetSymbolicDimensions(const char** values, size_t values_count) const {
1694 ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count));
1695 }
1696
1697 template <typename T>
1698 inline std::vector<const char*> TensorTypeAndShapeInfoImpl<T>::GetSymbolicDimensions() const {
1699 std::vector<const char*> out(GetDimensionsCount(), nullptr);
1700 ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size()));
1701 return out;
1702 }
1703
1704 template <typename T>
1705 inline std::vector<int64_t> TensorTypeAndShapeInfoImpl<T>::GetShape() const {
1706 std::vector<int64_t> out(GetDimensionsCount(), -1);
1707 ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size()));
1708 return out;
1709 }
1710
1711 template <typename T>
1712 inline ConstTensorTypeAndShapeInfo TypeInfoImpl<T>::GetTensorTypeAndShapeInfo() const {
1713 const OrtTensorTypeAndShapeInfo* out;
1714 ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out));
1715 return ConstTensorTypeAndShapeInfo{out};
1716 }
1717
1718 template <typename T>
1719 inline ConstSequenceTypeInfo TypeInfoImpl<T>::GetSequenceTypeInfo() const {
1720 const OrtSequenceTypeInfo* out;
1721 ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out));
1722 return ConstSequenceTypeInfo{out};
1723 }
1724
1725 template <typename T>
1726 inline ConstMapTypeInfo TypeInfoImpl<T>::GetMapTypeInfo() const {
1727 const OrtMapTypeInfo* out;
1728 ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out));
1729 return ConstMapTypeInfo{out};
1730 }
1731
1732 template <typename T>
1733 inline ONNXType TypeInfoImpl<T>::GetONNXType() const {
1734 ONNXType out;
1735 ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out));
1736 return out;
1737 }
1738
1739 template <typename T>
1740 inline TypeInfo SequenceTypeInfoImpl<T>::GetSequenceElementType() const {
1741 OrtTypeInfo* output;
1742 ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output));
1743 return TypeInfo{output};
1744 }
1745
1746 template <typename T>
1747 inline TypeInfo OptionalTypeInfoImpl<T>::GetOptionalElementType() const {
1748 OrtTypeInfo* info;
1749 ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info));
1750 return TypeInfo{info};
1751 }
1752
1753 template <typename T>
1754 inline ONNXTensorElementDataType MapTypeInfoImpl<T>::GetMapKeyType() const {
1755 ONNXTensorElementDataType out;
1756 ThrowOnError(GetApi().GetMapKeyType(this->p_, &out));
1757 return out;
1758 }
1759
1760 template <typename T>
1761 inline TypeInfo MapTypeInfoImpl<T>::GetMapValueType() const {
1762 OrtTypeInfo* output;
1763 ThrowOnError(GetApi().GetMapValueType(this->p_, &output));
1764 return TypeInfo{output};
1765 }
1766
1767 template <typename T>
1768 inline ConstOptionalTypeInfo TypeInfoImpl<T>::GetOptionalTypeInfo() const {
1769 const OrtOptionalTypeInfo* info;
1770 ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info));
1771 return ConstOptionalTypeInfo{info};
1772 }
1773
1774 }
1775
1776 namespace detail {
1777
1778 template <typename T>
1779 template <typename R>
1780 inline void ConstValueImpl<T>::GetOpaqueData(const char* domain, const char* type_name, R& out) const {
1781 ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R)));
1782 }
1783
1784 template <typename T>
1785 inline bool ConstValueImpl<T>::IsTensor() const {
1786 int out;
1787 ThrowOnError(GetApi().IsTensor(this->p_, &out));
1788 return out != 0;
1789 }
1790
1791 template <typename T>
1792 inline bool ConstValueImpl<T>::HasValue() const {
1793 int out;
1794 ThrowOnError(GetApi().HasValue(this->p_, &out));
1795 return out != 0;
1796 }
1797
1798 template <typename T>
1799 inline size_t ConstValueImpl<T>::GetCount() const {
1800 size_t out;
1801 ThrowOnError(GetApi().GetValueCount(this->p_, &out));
1802 return out;
1803 }
1804
1805 template <typename T>
1806 inline Value ConstValueImpl<T>::GetValue(int index, OrtAllocator* allocator) const {
1807 OrtValue* out;
1808 ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out));
1809 return Value{out};
1810 }
1811
1812 template <typename T>
1813 inline size_t ConstValueImpl<T>::GetStringTensorDataLength() const {
1814 size_t out;
1815 ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out));
1816 return out;
1817 }
1818
1819 template <typename T>
1820 inline size_t ConstValueImpl<T>::GetStringTensorElementLength(size_t element_index) const {
1821 size_t out;
1822 ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out));
1823 return out;
1824 }
1825
1826 template <typename T>
1827 template <typename R>
1828 inline const R* ConstValueImpl<T>::GetTensorData() const {
1829 R* out;
1830 ThrowOnError(GetApi().GetTensorMutableData(const_cast<OrtValue*>(this->p_), (void**)&out));
1831 return out;
1832 }
1833
1834 template <typename T>
1835 inline const void* ConstValueImpl<T>::GetTensorRawData() const {
1836 void* out;
1837 ThrowOnError(GetApi().GetTensorMutableData(const_cast<OrtValue*>(this->p_), &out));
1838 return out;
1839 }
1840
1841 template <typename T>
1842 inline TypeInfo ConstValueImpl<T>::GetTypeInfo() const {
1843 OrtTypeInfo* output;
1844 ThrowOnError(GetApi().GetTypeInfo(this->p_, &output));
1845 return TypeInfo{output};
1846 }
1847
1848 template <typename T>
1849 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetTensorTypeAndShapeInfo() const {
1850 OrtTensorTypeAndShapeInfo* output;
1851 ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output));
1852 return TensorTypeAndShapeInfo{output};
1853 }
1854
1855 template <typename T>
1856 inline ConstMemoryInfo ConstValueImpl<T>::GetTensorMemoryInfo() const {
1857 const OrtMemoryInfo* mem_info;
1858 ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info));
1859 return ConstMemoryInfo(mem_info);
1860 }
1861
1862 template <typename T>
1863 inline void ConstValueImpl<T>::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const {
1864 ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer));
1865 }
1866
1867 template <typename T>
1868 inline std::string ConstValueImpl<T>::GetStringTensorElement(size_t element_index) const {
1869 size_t buffer_length;
1870 ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length));
1871
1872 std::string s;
1873 s.resize(buffer_length);
1874 ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0]));
1875 return s;
1876 }
1877
1878 template <typename T>
1879 inline void ConstValueImpl<T>::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const {
1880 ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count));
1881 }
1882
1883 #if !defined(DISABLE_SPARSE_TENSORS)
1884 template <typename T>
1885 inline OrtSparseFormat ConstValueImpl<T>::GetSparseFormat() const {
1886 OrtSparseFormat format;
1887 ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format));
1888 return format;
1889 }
1890
1891 template <typename T>
1892 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorValuesTypeAndShapeInfo() const {
1893 OrtTensorTypeAndShapeInfo* output;
1894 ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output));
1895 return TensorTypeAndShapeInfo{output};
1896 }
1897
1898 template <typename T>
1899 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const {
1900 OrtTensorTypeAndShapeInfo* output;
1901 ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output));
1902 return TensorTypeAndShapeInfo{output};
1903 }
1904
1905 template <typename T>
1906 template <typename R>
1907 inline const R* ConstValueImpl<T>::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const {
1908 const void* out;
1909 ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out));
1910 return reinterpret_cast<const R*>(out);
1911 }
1912
1913 template <typename T>
1914 inline bool ConstValueImpl<T>::IsSparseTensor() const {
1915 int out;
1916 ThrowOnError(GetApi().IsSparseTensor(this->p_, &out));
1917 return out != 0;
1918 }
1919
1920 template <typename T>
1921 template <typename R>
1922 inline const R* ConstValueImpl<T>::GetSparseTensorValues() const {
1923 const void* out;
1924 ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out));
1925 return reinterpret_cast<const R*>(out);
1926 }
1927
1928 #endif
1929
1930 template <typename T>
1931 void ValueImpl<T>::FillStringTensor(const char* const* s, size_t s_len) {
1932 ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len));
1933 }
1934
1935 template <typename T>
1936 void ValueImpl<T>::FillStringTensorElement(const char* s, size_t index) {
1937 ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index));
1938 }
1939
1940 template <typename T>
1941 inline char* ValueImpl<T>::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) {
1942 char* result;
1943 ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result));
1944 return result;
1945 }
1946
1947 template <typename T>
1948 void* ValueImpl<T>::GetTensorMutableRawData() {
1949 void* out;
1950 ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out));
1951 return out;
1952 }
1953
1954 template <typename T>
1955 template <typename R>
1956 R* ValueImpl<T>::GetTensorMutableData() {
1957 R* out;
1958 ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out));
1959 return out;
1960 }
1961
1962 template <typename T>
1963 template <typename R>
1964 R& ValueImpl<T>::At(const std::vector<int64_t>& location) {
1965 static_assert(!std::is_same<T, std::string>::value, "this api does not support std::string");
1966 R* out;
1967 ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out));
1968 return *out;
1969 }
1970
1971 #if !defined(DISABLE_SPARSE_TENSORS)
1972 template <typename T>
1973 void ValueImpl<T>::UseCooIndices(int64_t* indices_data, size_t indices_num) {
1974 ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num));
1975 }
1976
1977 template <typename T>
1978 void ValueImpl<T>::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) {
1979 ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num));
1980 }
1981
1982 template <typename T>
1983 void ValueImpl<T>::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) {
1984 ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data));
1985 }
1986
1987 template <typename T>
1988 void ValueImpl<T>::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param,
1989 const int64_t* indices_data, size_t indices_num) {
1990 ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape,
1991 values_param.values_shape_len, values_param.data.p_data,
1992 indices_data, indices_num));
1993 }
1994
1995 template <typename T>
1996 void ValueImpl<T>::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info,
1997 const OrtSparseValuesParam& values,
1998 const int64_t* inner_indices_data, size_t inner_indices_num,
1999 const int64_t* outer_indices_data, size_t outer_indices_num) {
2000 ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
2001 inner_indices_data, inner_indices_num,
2002 outer_indices_data, outer_indices_num));
2003 }
2004
2005 template <typename T>
2006 void ValueImpl<T>::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info,
2007 const OrtSparseValuesParam& values,
2008 const Shape& indices_shape,
2009 const int32_t* indices_data) {
2010 ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
2011 indices_shape.shape, indices_shape.shape_len,
2012 indices_data));
2013 }
2014
2015 #endif
2016
2017 }
2018
2019 template <typename T>
2020 inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count,
2021 const int64_t* shape, size_t shape_len) {
2022 return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType<T>::type);
2023 }
2024
2025 inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count,
2026 const int64_t* shape, size_t shape_len,
2027 ONNXTensorElementDataType type) {
2028 OrtValue* out;
2029 ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out));
2030 return Value{out};
2031 }
2032
2033 inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count,
2034 const int64_t* shape, size_t shape_len,
2035 ONNXTensorElementDataType type) {
2036 OrtValue* out;
2037 ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count,
2038 shape, shape_len, type, &out));
2039 return Value{out};
2040 }
2041
2042 template <typename T>
2043 inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) {
2044 return CreateTensor(allocator, shape, shape_len, TypeToTensorType<T>::type);
2045 }
2046
2047 inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len,
2048 ONNXTensorElementDataType type) {
2049 OrtValue* out;
2050 ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out));
2051 return Value{out};
2052 }
2053
2054 #if !defined(DISABLE_SPARSE_TENSORS)
2055
2056 template <typename T>
2057 inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape,
2058 const Shape& values_shape) {
2059 return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType<T>::type);
2060 }
2061
2062 inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape,
2063 const Shape& values_shape, ONNXTensorElementDataType type) {
2064 OrtValue* out;
2065 ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len,
2066 values_shape.shape, values_shape.shape_len, type,
2067 &out));
2068 return Value{out};
2069 }
2070
2071 template <typename T>
2072 inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) {
2073 return CreateSparseTensor(allocator, dense_shape, TypeToTensorType<T>::type);
2074 }
2075
2076 inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape,
2077 ONNXTensorElementDataType type) {
2078 OrtValue* out;
2079 ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out));
2080 return Value{out};
2081 }
2082 #endif
2083
2084 inline Value Value::CreateMap(const Value& keys, const Value& values) {
2085 OrtValue* out;
2086 const OrtValue* inputs[2] = {keys, values};
2087 ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out));
2088 return Value{out};
2089 }
2090
2091 inline Value Value::CreateSequence(const std::vector<Value>& values) {
2092 OrtValue* out;
2093 std::vector<const OrtValue*> values_ort{values.data(), values.data() + values.size()};
2094 ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out));
2095 return Value{out};
2096 }
2097
2098 template <typename T>
2099 inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) {
2100 OrtValue* out;
2101 ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out));
2102 return Value{out};
2103 }
2104
2105
2106
2107
2108 inline Logger::Logger(const OrtLogger* logger) : logger_(logger) {
2109 Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_));
2110 }
2111
2112 inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept {
2113 return cached_severity_level_;
2114 }
2115
2116 inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number,
2117 const char* func_name, const char* message) const noexcept {
2118 OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number,
2119 func_name);
2120 return Status{status};
2121 }
2122
2123
2124
2125
2126 #if defined(__GNUC__)
2127 #pragma GCC diagnostic push
2128 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
2129 #pragma GCC diagnostic ignored "-Wformat-security"
2130 #elif defined(__clang__)
2131 #pragma clang diagnostic push
2132 #pragma clang diagnostic ignored "-Wformat-nonliteral"
2133 #pragma clang diagnostic ignored "-Wformat-security"
2134 #endif
2135 template <typename... Args>
2136 inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path,
2137 int line_number, const char* func_name, const char* format,
2138 Args&&... args) const noexcept {
2139 int msg_len = std::snprintf(nullptr, 0U, format, std::forward<Args>(args)...);
2140
2141 if (msg_len < 0) {
2142 return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL);
2143 }
2144
2145 OrtStatus* status = nullptr;
2146 const size_t buffer_size = static_cast<size_t>(msg_len) + 1U;
2147
2148 constexpr size_t kStackBufferSize = 1024;
2149
2150 if (buffer_size < kStackBufferSize) {
2151 char buffer[kStackBufferSize];
2152 snprintf(buffer, kStackBufferSize, format, std::forward<Args>(args)...);
2153 status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name);
2154 } else {
2155
2156 #if (__cplusplus >= 201402L) || (_MSC_VER >= 1900)
2157 auto buffer = std::make_unique<char[]>(buffer_size);
2158 #else
2159 std::unique_ptr<char[]> buffer(new char[buffer_size]);
2160 #endif
2161 std::snprintf(buffer.get(), buffer_size, format, std::forward<Args>(args)...);
2162 status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name);
2163 }
2164
2165 return Status{status};
2166 }
2167
2168 #if defined(__GNUC__)
2169 #pragma GCC diagnostic pop
2170 #elif defined(__clang__)
2171 #pragma clang diagnostic pop
2172 #endif
2173
2174 inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) {
2175 }
2176
2177 inline size_t KernelContext::GetInputCount() const {
2178 size_t out = 0;
2179 Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out));
2180 return out;
2181 }
2182
2183 inline size_t KernelContext::GetOutputCount() const {
2184 size_t out = 0;
2185 Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out));
2186 return out;
2187 }
2188
2189 inline ConstValue KernelContext::GetInput(size_t index) const {
2190 const OrtValue* out = nullptr;
2191 Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out));
2192 return ConstValue{out};
2193 }
2194
2195 inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const {
2196 OrtValue* out = nullptr;
2197 Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out));
2198 return UnownedValue(out);
2199 }
2200
2201 inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector<int64_t>& dims) const {
2202 OrtValue* out = nullptr;
2203 Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out));
2204 return UnownedValue(out);
2205 }
2206
2207 inline void* KernelContext::GetGPUComputeStream() const {
2208 void* out = nullptr;
2209 Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out));
2210 return out;
2211 }
2212
2213 inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const {
2214 OrtAllocator* out = nullptr;
2215 Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out));
2216 return out;
2217 }
2218
2219 inline Logger KernelContext::GetLogger() const {
2220 const OrtLogger* out = nullptr;
2221 ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out));
2222 return Logger{out};
2223 }
2224
2225 inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const {
2226 ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data));
2227 }
2228
2229 inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) {
2230 Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_));
2231 }
2232
2233 namespace detail {
2234 template <typename T>
2235 inline KernelInfo KernelInfoImpl<T>::Copy() const {
2236 OrtKernelInfo* info_copy = nullptr;
2237 Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy));
2238 return KernelInfo{info_copy};
2239 }
2240
2241 template <typename T>
2242 inline size_t KernelInfoImpl<T>::GetInputCount() const {
2243 size_t out = 0;
2244 ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out));
2245 return out;
2246 }
2247
2248 template <typename T>
2249 inline size_t KernelInfoImpl<T>::GetOutputCount() const {
2250 size_t out = 0;
2251 ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out));
2252 return out;
2253 }
2254
2255 template <typename T>
2256 inline std::string KernelInfoImpl<T>::GetInputName(size_t index) const {
2257 size_t size = 0;
2258
2259
2260 Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size));
2261
2262 std::string out;
2263 out.resize(size);
2264 Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size));
2265 out.resize(size - 1);
2266
2267 return out;
2268 }
2269
2270 template <typename T>
2271 inline std::string KernelInfoImpl<T>::GetOutputName(size_t index) const {
2272 size_t size = 0;
2273
2274
2275 Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size));
2276
2277 std::string out;
2278 out.resize(size);
2279 Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size));
2280 out.resize(size - 1);
2281
2282 return out;
2283 }
2284
2285 template <typename T>
2286 inline TypeInfo KernelInfoImpl<T>::GetInputTypeInfo(size_t index) const {
2287 OrtTypeInfo* out = nullptr;
2288 ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out));
2289 return TypeInfo{out};
2290 }
2291
2292 template <typename T>
2293 inline TypeInfo KernelInfoImpl<T>::GetOutputTypeInfo(size_t index) const {
2294 OrtTypeInfo* out = nullptr;
2295 ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out));
2296 return TypeInfo{out};
2297 }
2298
2299 template <typename T>
2300 inline Value KernelInfoImpl<T>::GetTensorAttribute(const char* name, OrtAllocator* allocator) const {
2301 OrtValue* out = nullptr;
2302 ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out));
2303 return Value{out};
2304 }
2305
2306 template <typename T>
2307 inline ConstValue KernelInfoImpl<T>::GetTensorConstantInput(size_t index, int* is_constant) const {
2308 const OrtValue* out = nullptr;
2309 ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out));
2310 return ConstValue{out};
2311 }
2312
2313 template <typename T>
2314 inline std::string KernelInfoImpl<T>::GetNodeName() const {
2315 size_t size = 0;
2316
2317
2318 Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size));
2319
2320 std::string out;
2321 out.resize(size);
2322 Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size));
2323 out.resize(size - 1);
2324
2325 return out;
2326 }
2327
2328 template <typename T>
2329 inline Logger KernelInfoImpl<T>::GetLogger() const {
2330 const OrtLogger* out = nullptr;
2331 ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out));
2332 return Logger{out};
2333 }
2334
2335 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) {
2336 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out));
2337 }
2338
2339 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) {
2340 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out));
2341 }
2342
2343 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) {
2344 size_t size = 0;
2345
2346 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size));
2347
2348 std::string out;
2349 out.resize(size);
2350 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size));
2351 out.resize(size - 1);
2352 out.swap(result);
2353 }
2354
2355 inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<float>& result) {
2356 size_t size = 0;
2357
2358 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size));
2359
2360 std::vector<float> out;
2361 out.resize(size);
2362 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size));
2363 out.swap(result);
2364 }
2365
2366 inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<int64_t>& result) {
2367 size_t size = 0;
2368
2369
2370 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size));
2371
2372 std::vector<int64_t> out;
2373 out.resize(size);
2374 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size));
2375 out.swap(result);
2376 }
2377 }
2378
2379 inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl<OrtKernelInfo>{info} {}
2380
2381 inline Op::Op(OrtOp* p) : detail::Base<OrtOp>(p) {}
2382
2383 inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version,
2384 const char** type_constraint_names,
2385 const ONNXTensorElementDataType* type_constraint_values,
2386 size_t type_constraint_count,
2387 const OpAttr* attr_values, size_t attr_count,
2388 size_t input_count, size_t output_count) {
2389 static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*),
2390 "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely");
2391 auto attr_input_values = reinterpret_cast<const OrtOpAttr* const*>(attr_values);
2392 OrtOp* op;
2393 Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values,
2394 static_cast<int>(type_constraint_count),
2395 attr_input_values,
2396 static_cast<int>(attr_count),
2397 static_cast<int>(input_count),
2398 static_cast<int>(output_count), &op));
2399 return Op{op};
2400 }
2401
2402 inline void Op::Invoke(const OrtKernelContext* context,
2403 const Value* input_values,
2404 size_t input_count,
2405 Value* output_values,
2406 size_t output_count) {
2407 static_assert(sizeof(Value) == sizeof(OrtValue*),
2408 "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
2409 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
2410 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
2411 Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast<int>(input_count),
2412 ort_output_values, static_cast<int>(output_count)));
2413 }
2414
2415 inline void Op::Invoke(const OrtKernelContext* context,
2416 const OrtValue* const* input_values,
2417 size_t input_count,
2418 OrtValue* const* output_values,
2419 size_t output_count) {
2420 Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast<int>(input_count),
2421 output_values, static_cast<int>(output_count)));
2422 }
2423
2424 inline std::string GetVersionString() {
2425 return OrtGetApiBase()->GetVersionString();
2426 }
2427
2428 inline std::string GetBuildInfoString() {
2429 return GetApi().GetBuildInfoString();
2430 }
2431
2432 inline std::vector<std::string> GetAvailableProviders() {
2433 char** providers;
2434 int len;
2435
2436 auto release_fn = [&len](char** providers) {
2437
2438 ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len));
2439 };
2440
2441 ThrowOnError(GetApi().GetAvailableProviders(&providers, &len));
2442 std::unique_ptr<char*, decltype(release_fn)> guard(providers, release_fn);
2443 std::vector<std::string> available_providers;
2444 available_providers.reserve(static_cast<size_t>(len));
2445 for (int i = 0; i < len; ++i) {
2446 available_providers.emplace_back(providers[i]);
2447 }
2448 return available_providers;
2449 }
2450
2451 template <typename TOp, typename TKernel, bool WithStatus>
2452 void CustomOpBase<TOp, TKernel, WithStatus>::GetSessionConfigs(std::unordered_map<std::string, std::string>& out,
2453 ConstSessionOptions options) const {
2454 const TOp* derived = static_cast<const TOp*>(this);
2455 std::vector<std::string> keys = derived->GetSessionConfigKeys();
2456
2457 out.reserve(keys.size());
2458
2459 std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), "");
2460 const size_t prefix_size = config_entry_key.length();
2461
2462 for (const auto& key : keys) {
2463 config_entry_key.resize(prefix_size);
2464 config_entry_key.append(key);
2465 out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), "");
2466 }
2467 }
2468
2469 inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api,
2470 OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) {
2471 size_t input_count = 0;
2472 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count));
2473 for (size_t ith_input = 0; ith_input < input_count; ++ith_input) {
2474 OrtTensorTypeAndShapeInfo* info{};
2475 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info));
2476 TensorTypeAndShapeInfo type_shape_info(info);
2477 auto integer_shape = type_shape_info.GetShape();
2478 std::vector<const char*> symbolic_shape(integer_shape.size(), {});
2479 if (!integer_shape.empty()) {
2480 type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size());
2481 }
2482 Shape shape;
2483 for (size_t ith = 0; ith < integer_shape.size(); ++ith) {
2484 if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) {
2485 shape.emplace_back(symbolic_shape[ith]);
2486 } else {
2487 shape.emplace_back(integer_shape[ith]);
2488 }
2489 }
2490 input_shapes_.push_back(std::move(shape));
2491 type_shape_info.release();
2492 }
2493 }
2494
2495 inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) {
2496 OrtTensorTypeAndShapeInfo* info = {};
2497 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info));
2498 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type));
2499
2500 using InfoPtr = std::unique_ptr<OrtTensorTypeAndShapeInfo, std::function<void(OrtTensorTypeAndShapeInfo*)>>;
2501
2502 InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) {
2503 ort_api_->ReleaseTensorTypeAndShapeInfo(obj);
2504 });
2505
2506 std::vector<int64_t> integer_dims;
2507 std::vector<const char*> symbolic_dims;
2508
2509 for (const auto dim : shape) {
2510 if (dim.IsInt()) {
2511 integer_dims.push_back(dim.AsInt());
2512 symbolic_dims.push_back("");
2513 } else {
2514 if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) {
2515 ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT);
2516 }
2517 integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM);
2518 symbolic_dims.push_back(dim.AsSym());
2519 }
2520 }
2521
2522 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size()));
2523 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size()));
2524 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info));
2525 return Status{nullptr};
2526 }
2527
2528 inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) {
2529 const auto* attr = GetAttrHdl(attr_name);
2530 int64_t i = {};
2531 size_t out = {};
2532 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out));
2533 return i;
2534 }
2535
2536 inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) {
2537 const auto* attr = GetAttrHdl(attr_name);
2538 int64_t i = {};
2539 size_t out = {};
2540
2541
2542
2543
2544 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out);
2545 if (status) {
2546 size_t num_i = out / sizeof(int64_t);
2547 ShapeInferContext::Ints ints(num_i, 0);
2548 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out));
2549 return ints;
2550 } else {
2551 if (out == 0u) {
2552 return {};
2553 }
2554 return {i};
2555 }
2556 }
2557
2558 inline float ShapeInferContext::GetAttrFloat(const char* attr_name) {
2559 const auto* attr = GetAttrHdl(attr_name);
2560 float f = {};
2561 size_t out = {};
2562 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out));
2563 return f;
2564 }
2565
2566 inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) {
2567 const auto* attr = GetAttrHdl(attr_name);
2568 float f = {};
2569 size_t out = {};
2570
2571
2572
2573
2574 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out);
2575 if (status) {
2576 size_t num_f = out / sizeof(float);
2577 ShapeInferContext::Floats floats(num_f, 0);
2578 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out));
2579 return floats;
2580 } else {
2581 if (out == 0u) {
2582 return {};
2583 }
2584 return {f};
2585 }
2586 }
2587
2588 inline std::string ShapeInferContext::GetAttrString(const char* attr_name) {
2589 const auto* attr = GetAttrHdl(attr_name);
2590 char c = {};
2591 size_t out = {};
2592
2593 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out);
2594 if (status) {
2595 std::vector<char> chars(out, '\0');
2596 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out));
2597 return {chars.data()};
2598 } else {
2599 return {c};
2600 }
2601 }
2602
2603 inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) {
2604 const auto* attr = GetAttrHdl(attr_name);
2605 char c = {};
2606 size_t out = {};
2607
2608
2609
2610
2611 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out);
2612 if (status) {
2613 std::vector<char> chars(out, '\0');
2614 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out));
2615 ShapeInferContext::Strings strings;
2616 char* char_st = chars.data();
2617 char* char_ed = char_st + out;
2618 while (char_st < char_ed) {
2619 strings.emplace_back(char_st);
2620 while (*char_st != '\0') {
2621 char_st++;
2622 }
2623 char_st++;
2624 }
2625 return strings;
2626 } else {
2627 if (out == 0u) {
2628 return {};
2629 }
2630 return {std::string{c}};
2631 }
2632 }
2633
2634 inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const {
2635 const OrtOpAttr* attr_hdl = {};
2636 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl));
2637 return attr_hdl;
2638 }
2639
2640 namespace detail {
2641 inline std::vector<const char*> StringsToCharPtrs(const std::vector<std::string>& strings) {
2642 std::vector<const char*> ptrs;
2643 ptrs.reserve(strings.size());
2644 std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs),
2645 [](const std::string& s) { return s.c_str(); });
2646
2647 return ptrs;
2648 }
2649 }
2650
2651 #if !defined(ORT_MINIMAL_BUILD)
2652
2653 inline void Node::Init(const std::string& operator_name, const std::string& operator_domain,
2654 const std::string& node_name,
2655 const std::vector<std::string>& input_names,
2656 const std::vector<std::string>& output_names,
2657 std::vector<OpAttr>& attributes,
2658 OrtNode*& node) {
2659 auto inputs = detail::StringsToCharPtrs(input_names);
2660 auto outputs = detail::StringsToCharPtrs(output_names);
2661
2662 std::vector<OrtOpAttr*> attributes_ptrs;
2663 attributes_ptrs.reserve(attributes.size());
2664 std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs),
2665 [](OpAttr& attr) -> OrtOpAttr* { return attr; });
2666
2667 ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(),
2668 inputs.data(), inputs.size(),
2669 outputs.data(), outputs.size(),
2670 attributes_ptrs.data(), attributes_ptrs.size(),
2671 &node));
2672
2673
2674 std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); });
2675 }
2676
2677 inline Node::Node(const std::string& operator_name, const std::string& operator_domain,
2678 const std::string& node_name,
2679 const std::vector<std::string>& input_names,
2680 const std::vector<std::string>& output_names,
2681 std::vector<OpAttr>& attributes) {
2682 Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_);
2683 }
2684
2685 inline Node::Node(const std::string& operator_name, const std::string& operator_domain,
2686 const std::string& node_name,
2687 const std::vector<std::string>& input_names,
2688 const std::vector<std::string>& output_names) {
2689 std::vector<OpAttr> empty_attributes;
2690 Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_);
2691 }
2692
2693 inline Graph::Graph() {
2694 ThrowOnError(GetModelEditorApi().CreateGraph(&p_));
2695 }
2696
2697 inline Model::Model(const std::vector<DomainOpsetPair>& opsets) {
2698 std::vector<const char*> domains;
2699 std::vector<int> versions;
2700 domains.reserve(opsets.size());
2701 versions.reserve(opsets.size());
2702
2703 for (const auto& pair : opsets) {
2704 domains.push_back(pair.first.c_str());
2705 versions.push_back(pair.second);
2706 }
2707
2708 ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_));
2709 }
2710
2711 inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) {
2712 ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_));
2713 }
2714 #endif
2715
2716 namespace detail {
2717 template <>
2718 inline std::string ValueInfoImpl<OrtValueInfo>::Name() const {
2719 const char* name = nullptr;
2720 ThrowOnError(GetApi().GetValueInfoName(this->p_, &name));
2721 return name;
2722 }
2723
2724 template <>
2725 inline ConstTypeInfo ValueInfoImpl<OrtValueInfo>::TypeInfo() const {
2726 const OrtTypeInfo* type_info = nullptr;
2727 ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info));
2728 return ConstTypeInfo{type_info};
2729 }
2730
2731 #if !defined(ORT_MINIMAL_BUILD)
2732 template <>
2733 inline void GraphImpl<OrtGraph>::SetInputs(std::vector<ValueInfo>& inputs) {
2734 std::vector<OrtValueInfo*> inputs_ptrs;
2735 inputs_ptrs.reserve(inputs.size());
2736 std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs),
2737 [](ValueInfo& vi) -> OrtValueInfo* { return vi; });
2738
2739 ThrowOnError(GetModelEditorApi().SetGraphInputs(p_, inputs_ptrs.data(), inputs_ptrs.size()));
2740
2741
2742 std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); });
2743 }
2744
2745 template <>
2746 inline void GraphImpl<OrtGraph>::SetOutputs(std::vector<ValueInfo>& outputs) {
2747 std::vector<OrtValueInfo*> outputs_ptrs;
2748 outputs_ptrs.reserve(outputs.size());
2749 std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs),
2750 [](ValueInfo& vi) -> OrtValueInfo* { return vi; });
2751
2752 ThrowOnError(GetModelEditorApi().SetGraphOutputs(p_, outputs_ptrs.data(), outputs_ptrs.size()));
2753
2754
2755 std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); });
2756 }
2757
2758 template <>
2759 inline void GraphImpl<OrtGraph>::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) {
2760
2761 ThrowOnError(GetModelEditorApi().AddInitializerToGraph(p_, name.c_str(), initializer.release(), data_is_external));
2762 }
2763
2764 template <>
2765 inline void GraphImpl<OrtGraph>::AddNode(Node& node) {
2766
2767 ThrowOnError(GetModelEditorApi().AddNodeToGraph(p_, node.release()));
2768 }
2769
2770 template <>
2771 inline void ModelImpl<OrtModel>::AddGraph(Graph& graph) {
2772
2773 ThrowOnError(GetModelEditorApi().AddGraphToModel(p_, graph.release()));
2774 }
2775 #endif
2776
2777 }
2778 }