File indexing completed on 2025-01-18 10:02:52
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #include <algorithm>
0011 #include <functional>
0012 #include <iterator>
0013 #include <type_traits>
0014
0015
0016
0017 #define ORT_CXX_RETURN_ON_API_FAIL(expression) \
0018 { \
0019 auto ort_status = (expression); \
0020 if (ort_status) { \
0021 return Ort::Status(ort_status); \
0022 } \
0023 }
0024
0025 #ifdef __cpp_if_constexpr
0026 #define ORT_CXX_IF_CONSTEXPR if constexpr
0027 #else
0028 #define ORT_CXX_IF_CONSTEXPR if
0029 #endif
0030
0031 namespace Ort {
0032
0033 namespace detail {
0034 inline void ThrowStatus(const Status& st) {
0035 std::string error_message = st.GetErrorMessage();
0036 OrtErrorCode error_code = st.GetErrorCode();
0037 ORT_CXX_API_THROW(std::move(error_message), error_code);
0038 }
0039 }
0040
0041 inline void ThrowOnError(OrtStatus* ort_status) {
0042 if (ort_status) {
0043 Ort::Status st(ort_status);
0044 detail::ThrowStatus(st);
0045 }
0046 }
0047
0048 inline void ThrowOnError(const Status& st) {
0049 if (st) {
0050 detail::ThrowStatus(st);
0051 }
0052 }
0053
0054 inline Status::Status(OrtStatus* status) noexcept : Base<OrtStatus>{status} {
0055 }
0056
0057 inline Status::Status(const std::exception& e) noexcept {
0058 p_ = GetApi().CreateStatus(ORT_FAIL, e.what());
0059 }
0060
0061 inline Status::Status(const Exception& e) noexcept {
0062 p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what());
0063 }
0064
0065 inline Status::Status(const char* message, OrtErrorCode code) noexcept {
0066 p_ = GetApi().CreateStatus(code, message);
0067 }
0068
0069 inline std::string Status::GetErrorMessage() const {
0070 std::string message(GetApi().GetErrorMessage(p_));
0071 return message;
0072 }
0073
0074 inline OrtErrorCode Status::GetErrorCode() const {
0075 return GetApi().GetErrorCode(p_);
0076 }
0077
0078 inline bool Status::IsOK() const noexcept {
0079 return (p_ == nullptr);
0080 }
0081
0082
0083 template <typename T>
0084 struct TypeToTensorType;
0085 template <>
0086 struct TypeToTensorType<float> {
0087 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
0088 };
0089 template <>
0090 struct TypeToTensorType<Float16_t> {
0091 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16;
0092 };
0093 template <>
0094 struct TypeToTensorType<BFloat16_t> {
0095 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16;
0096 };
0097 template <>
0098 struct TypeToTensorType<double> {
0099 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE;
0100 };
0101 template <>
0102 struct TypeToTensorType<int8_t> {
0103 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8;
0104 };
0105 template <>
0106 struct TypeToTensorType<int16_t> {
0107 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16;
0108 };
0109 template <>
0110 struct TypeToTensorType<int32_t> {
0111 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32;
0112 };
0113 template <>
0114 struct TypeToTensorType<int64_t> {
0115 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
0116 };
0117 template <>
0118 struct TypeToTensorType<uint8_t> {
0119 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8;
0120 };
0121 template <>
0122 struct TypeToTensorType<uint16_t> {
0123 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16;
0124 };
0125 template <>
0126 struct TypeToTensorType<uint32_t> {
0127 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32;
0128 };
0129 template <>
0130 struct TypeToTensorType<uint64_t> {
0131 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64;
0132 };
0133 template <>
0134 struct TypeToTensorType<bool> {
0135 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL;
0136 };
0137
0138 template <>
0139 struct TypeToTensorType<Float8E4M3FN_t> {
0140 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN;
0141 };
0142 template <>
0143 struct TypeToTensorType<Float8E4M3FNUZ_t> {
0144 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ;
0145 };
0146 template <>
0147 struct TypeToTensorType<Float8E5M2_t> {
0148 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2;
0149 };
0150 template <>
0151 struct TypeToTensorType<Float8E5M2FNUZ_t> {
0152 static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ;
0153 };
0154
0155 inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept {
0156 if (IsNaN() || rhs.IsNaN()) {
0157
0158 return false;
0159 }
0160 return val == rhs.val;
0161 }
0162
0163 inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept {
0164 if (IsNaN() || rhs.IsNaN()) {
0165
0166 return false;
0167 }
0168
0169 const bool left_is_negative = IsNegative();
0170 if (left_is_negative != rhs.IsNegative()) {
0171
0172
0173
0174 return left_is_negative && !AreZero(*this, rhs);
0175 }
0176 return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative);
0177 }
0178
0179 inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size)
0180 : allocator_(allocator), p_(p), size_(size) {
0181 }
0182
0183 inline MemoryAllocation::~MemoryAllocation() {
0184 if (p_ != nullptr) {
0185
0186 auto ret = GetApi().AllocatorFree(allocator_, p_);
0187 static_cast<void>(ret);
0188 }
0189 }
0190
0191 inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) {
0192 *this = std::move(o);
0193 }
0194
0195 inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept {
0196 OrtAllocator* alloc = nullptr;
0197 void* p = nullptr;
0198 size_t sz = 0;
0199
0200
0201 std::swap(alloc, allocator_);
0202 std::swap(p, p_);
0203 std::swap(sz, size_);
0204
0205
0206 std::swap(allocator_, o.allocator_);
0207 std::swap(p_, o.p_);
0208 std::swap(size_, o.size_);
0209
0210
0211 MemoryAllocation this_alloc(alloc, p, sz);
0212 return *this;
0213 }
0214
0215 namespace detail {
0216
0217 template <typename T>
0218 inline void* AllocatorImpl<T>::Alloc(size_t size) {
0219 void* out;
0220 ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
0221 return out;
0222 }
0223
0224 template <typename T>
0225 inline MemoryAllocation AllocatorImpl<T>::GetAllocation(size_t size) {
0226 void* out;
0227 ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
0228 MemoryAllocation result(this->p_, out, size);
0229 return result;
0230 }
0231
0232 template <typename T>
0233 inline void AllocatorImpl<T>::Free(void* p) {
0234 ThrowOnError(GetApi().AllocatorFree(this->p_, p));
0235 }
0236
0237 template <typename T>
0238 inline ConstMemoryInfo AllocatorImpl<T>::GetInfo() const {
0239 const OrtMemoryInfo* out;
0240 ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out));
0241 return ConstMemoryInfo{out};
0242 }
0243
0244 }
0245
0246 inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() {
0247 ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_));
0248 }
0249
0250 inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) {
0251 ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_));
0252 }
0253
0254 namespace detail {
0255
0256 template <typename T>
0257 inline std::string MemoryInfoImpl<T>::GetAllocatorName() const {
0258 const char* name = nullptr;
0259 ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name));
0260 return std::string(name);
0261 }
0262
0263 template <typename T>
0264 inline OrtAllocatorType MemoryInfoImpl<T>::GetAllocatorType() const {
0265 OrtAllocatorType type;
0266 ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type));
0267 return type;
0268 }
0269
0270 template <typename T>
0271 inline int MemoryInfoImpl<T>::GetDeviceId() const {
0272 int id = 0;
0273 ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id));
0274 return id;
0275 }
0276
0277 template <typename T>
0278 inline OrtMemoryInfoDeviceType MemoryInfoImpl<T>::GetDeviceType() const {
0279 OrtMemoryInfoDeviceType type;
0280 GetApi().MemoryInfoGetDeviceType(this->p_, &type);
0281 return type;
0282 }
0283
0284 template <typename T>
0285 inline OrtMemType MemoryInfoImpl<T>::GetMemoryType() const {
0286 OrtMemType type;
0287 ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type));
0288 return type;
0289 }
0290
0291 template <typename T>
0292 template <typename U>
0293 inline bool MemoryInfoImpl<T>::operator==(const MemoryInfoImpl<U>& o) const {
0294 int comp_result = 0;
0295 ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result));
0296 return comp_result == 0;
0297 }
0298
0299 }
0300
0301 inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) {
0302 OrtMemoryInfo* p;
0303 ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p));
0304 return MemoryInfo(p);
0305 }
0306
0307 inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) {
0308 ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_));
0309 }
0310
0311 namespace detail {
0312 template <typename T>
0313 inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames() const {
0314 AllocatorWithDefaultOptions allocator;
0315 return binding_utils::GetOutputNamesHelper(this->p_, allocator);
0316 }
0317
0318 template <typename T>
0319 inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames(OrtAllocator* allocator) const {
0320 return binding_utils::GetOutputNamesHelper(this->p_, allocator);
0321 }
0322
0323 template <typename T>
0324 inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues() const {
0325 AllocatorWithDefaultOptions allocator;
0326 return binding_utils::GetOutputValuesHelper(this->p_, allocator);
0327 }
0328
0329 template <typename T>
0330 inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues(OrtAllocator* allocator) const {
0331 return binding_utils::GetOutputValuesHelper(this->p_, allocator);
0332 }
0333
0334 template <typename T>
0335 inline void IoBindingImpl<T>::BindInput(const char* name, const Value& value) {
0336 ThrowOnError(GetApi().BindInput(this->p_, name, value));
0337 }
0338
0339 template <typename T>
0340 inline void IoBindingImpl<T>::BindOutput(const char* name, const Value& value) {
0341 ThrowOnError(GetApi().BindOutput(this->p_, name, value));
0342 }
0343
0344 template <typename T>
0345 inline void IoBindingImpl<T>::BindOutput(const char* name, const OrtMemoryInfo* mem_info) {
0346 ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info));
0347 }
0348
0349 template <typename T>
0350 inline void IoBindingImpl<T>::ClearBoundInputs() {
0351 GetApi().ClearBoundInputs(this->p_);
0352 }
0353
0354 template <typename T>
0355 inline void IoBindingImpl<T>::ClearBoundOutputs() {
0356 GetApi().ClearBoundOutputs(this->p_);
0357 }
0358
0359 template <typename T>
0360 inline void IoBindingImpl<T>::SynchronizeInputs() {
0361 ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_));
0362 }
0363
0364 template <typename T>
0365 inline void IoBindingImpl<T>::SynchronizeOutputs() {
0366 ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_));
0367 }
0368
0369 namespace binding_utils {
0370 inline std::vector<std::string> GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
0371 std::vector<std::string> result;
0372 auto free_fn = detail::AllocatedFree(allocator);
0373 using Ptr = std::unique_ptr<void, decltype(free_fn)>;
0374
0375 char* buffer = nullptr;
0376 size_t* lengths = nullptr;
0377 size_t count = 0;
0378 ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count));
0379
0380 if (count == 0) {
0381 return result;
0382 }
0383
0384 Ptr buffer_g(buffer, free_fn);
0385 Ptr lengths_g(lengths, free_fn);
0386
0387 result.reserve(count);
0388 for (size_t i = 0; i < count; ++i) {
0389 auto sz = *lengths;
0390 result.emplace_back(buffer, sz);
0391 buffer += sz;
0392 ++lengths;
0393 }
0394 return result;
0395 }
0396
0397 inline std::vector<Value> GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
0398 std::vector<Value> result;
0399 size_t owned = 0;
0400 size_t output_count = 0;
0401
0402
0403 auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) {
0404 if (buffer) {
0405 while (owned < output_count) {
0406 auto* p = buffer + owned++;
0407 GetApi().ReleaseValue(*p);
0408 }
0409 allocator->Free(allocator, buffer);
0410 }
0411 };
0412 using Ptr = std::unique_ptr<OrtValue*, decltype(free_fn)>;
0413
0414 OrtValue** output_buffer = nullptr;
0415 ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count));
0416 if (output_count == 0) {
0417 return result;
0418 }
0419
0420 Ptr buffer_g(output_buffer, free_fn);
0421
0422 result.reserve(output_count);
0423 for (size_t i = 0; i < output_count; ++i) {
0424 result.emplace_back(output_buffer[i]);
0425 ++owned;
0426 }
0427 return result;
0428 }
0429
0430 }
0431 }
0432
0433 inline IoBinding::IoBinding(Session& session) {
0434 ThrowOnError(GetApi().CreateIoBinding(session, &this->p_));
0435 }
0436
0437 inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) {
0438 ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_));
0439 }
0440
0441 inline ThreadingOptions::ThreadingOptions() {
0442 ThrowOnError(GetApi().CreateThreadingOptions(&p_));
0443 }
0444
0445 inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) {
0446 ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads));
0447 return *this;
0448 }
0449
0450 inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) {
0451 ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads));
0452 return *this;
0453 }
0454
0455 inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) {
0456 ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning));
0457 return *this;
0458 }
0459
0460 inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() {
0461 ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_));
0462 return *this;
0463 }
0464
0465 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
0466 ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn));
0467 return *this;
0468 }
0469
0470 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
0471 ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options));
0472 return *this;
0473 }
0474
0475 inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
0476 ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn));
0477 return *this;
0478 }
0479
0480 inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) {
0481 ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_));
0482 if (strcmp(logid, "onnxruntime-node") == 0) {
0483 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0484 } else {
0485 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0486 }
0487 }
0488
0489 inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) {
0490 ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_));
0491 if (strcmp(logid, "onnxruntime-node") == 0) {
0492 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0493 } else {
0494 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0495 }
0496 }
0497
0498 inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) {
0499 ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_));
0500 if (strcmp(logid, "onnxruntime-node") == 0) {
0501 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0502 } else {
0503 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0504 }
0505 }
0506
0507 inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param,
0508 OrtLoggingLevel logging_level, _In_ const char* logid) {
0509 ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_));
0510 if (strcmp(logid, "onnxruntime-node") == 0) {
0511 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
0512 } else {
0513 ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
0514 }
0515 }
0516
0517 inline Env& Env::EnableTelemetryEvents() {
0518 ThrowOnError(GetApi().EnableTelemetryEvents(p_));
0519 return *this;
0520 }
0521
0522 inline Env& Env::DisableTelemetryEvents() {
0523 ThrowOnError(GetApi().DisableTelemetryEvents(p_));
0524 return *this;
0525 }
0526
0527 inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) {
0528 ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level));
0529 return *this;
0530 }
0531
0532 inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) {
0533 ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg));
0534 return *this;
0535 }
0536
0537 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) {
0538 std::vector<const char*> keys, values;
0539 auto num_entries = options.size();
0540 if (num_entries > 0) {
0541 keys.reserve(num_entries);
0542 values.reserve(num_entries);
0543 for (const auto& entry : options) {
0544 keys.push_back(entry.first.c_str());
0545 values.push_back(entry.second.c_str());
0546 }
0547 }
0548 ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries));
0549 return *this;
0550 }
0551
0552 inline CustomOpDomain::CustomOpDomain(const char* domain) {
0553 ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_));
0554 }
0555
0556 inline void CustomOpDomain::Add(const OrtCustomOp* op) {
0557 ThrowOnError(GetApi().CustomOpDomain_Add(p_, op));
0558 }
0559
0560 inline RunOptions::RunOptions() {
0561 ThrowOnError(GetApi().CreateRunOptions(&p_));
0562 }
0563
0564 inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) {
0565 ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level));
0566 return *this;
0567 }
0568
0569 inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) {
0570 ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level));
0571 return *this;
0572 }
0573
0574 inline int RunOptions::GetRunLogVerbosityLevel() const {
0575 int out;
0576 ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out));
0577 return out;
0578 }
0579
0580 inline int RunOptions::GetRunLogSeverityLevel() const {
0581 int out;
0582 ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out));
0583 return out;
0584 }
0585
0586 inline RunOptions& RunOptions::SetRunTag(const char* run_tag) {
0587 ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag));
0588 return *this;
0589 }
0590
0591 inline const char* RunOptions::GetRunTag() const {
0592 const char* out;
0593 ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out));
0594 return out;
0595 }
0596
0597 inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) {
0598 ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value));
0599 return *this;
0600 }
0601
0602 inline RunOptions& RunOptions::SetTerminate() {
0603 ThrowOnError(GetApi().RunOptionsSetTerminate(p_));
0604 return *this;
0605 }
0606
0607 inline RunOptions& RunOptions::UnsetTerminate() {
0608 ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_));
0609 return *this;
0610 }
0611
0612 namespace detail {
0613
0614 template <typename T>
0615 inline Ort::SessionOptions ConstSessionOptionsImpl<T>::Clone() const {
0616 OrtSessionOptions* out;
0617 ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out));
0618 return SessionOptions{out};
0619 }
0620
0621 template <typename T>
0622 inline std::string ConstSessionOptionsImpl<T>::GetConfigEntry(const char* config_key) const {
0623 size_t size = 0;
0624
0625 Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size));
0626
0627 std::string out;
0628 out.resize(size);
0629 Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size));
0630 out.resize(size - 1);
0631
0632 return out;
0633 }
0634
0635 template <typename T>
0636 inline bool ConstSessionOptionsImpl<T>::HasConfigEntry(const char* config_key) const {
0637 int out = 0;
0638 Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out));
0639 return static_cast<bool>(out);
0640 }
0641
0642 template <typename T>
0643 inline std::string ConstSessionOptionsImpl<T>::GetConfigEntryOrDefault(const char* config_key, const std::string& def) {
0644 if (!this->HasConfigEntry(config_key)) {
0645 return def;
0646 }
0647
0648 return this->GetConfigEntry(config_key);
0649 }
0650
0651 template <typename T>
0652 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetIntraOpNumThreads(int intra_op_num_threads) {
0653 ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads));
0654 return *this;
0655 }
0656
0657 template <typename T>
0658 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetInterOpNumThreads(int inter_op_num_threads) {
0659 ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads));
0660 return *this;
0661 }
0662
0663 template <typename T>
0664 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) {
0665 ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level));
0666 return *this;
0667 }
0668
0669 template <typename T>
0670 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetDeterministicCompute(bool value) {
0671 ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value));
0672 return *this;
0673 }
0674
0675 template <typename T>
0676 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) {
0677 ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath));
0678 return *this;
0679 }
0680
0681 template <typename T>
0682 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableProfiling(const ORTCHAR_T* profile_file_prefix) {
0683 ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix));
0684 return *this;
0685 }
0686
0687 template <typename T>
0688 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableProfiling() {
0689 ThrowOnError(GetApi().DisableProfiling(this->p_));
0690 return *this;
0691 }
0692
0693 template <typename T>
0694 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableOrtCustomOps() {
0695 ThrowOnError(GetApi().EnableOrtCustomOps(this->p_));
0696 return *this;
0697 }
0698
0699 template <typename T>
0700 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableMemPattern() {
0701 ThrowOnError(GetApi().EnableMemPattern(this->p_));
0702 return *this;
0703 }
0704
0705 template <typename T>
0706 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableMemPattern() {
0707 ThrowOnError(GetApi().DisableMemPattern(this->p_));
0708 return *this;
0709 }
0710
0711 template <typename T>
0712 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableCpuMemArena() {
0713 ThrowOnError(GetApi().EnableCpuMemArena(this->p_));
0714 return *this;
0715 }
0716
0717 template <typename T>
0718 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableCpuMemArena() {
0719 ThrowOnError(GetApi().DisableCpuMemArena(this->p_));
0720 return *this;
0721 }
0722
0723 template <typename T>
0724 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetExecutionMode(ExecutionMode execution_mode) {
0725 ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode));
0726 return *this;
0727 }
0728
0729 template <typename T>
0730 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogId(const char* logid) {
0731 ThrowOnError(GetApi().SetSessionLogId(this->p_, logid));
0732 return *this;
0733 }
0734
0735 template <typename T>
0736 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogSeverityLevel(int level) {
0737 ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level));
0738 return *this;
0739 }
0740
0741 template <typename T>
0742 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::Add(OrtCustomOpDomain* custom_op_domain) {
0743 ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain));
0744 return *this;
0745 }
0746
0747 template <typename T>
0748 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddConfigEntry(const char* config_key, const char* config_value) {
0749 ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value));
0750 return *this;
0751 }
0752
0753 template <typename T>
0754 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddInitializer(const char* name, const OrtValue* ort_val) {
0755 ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val));
0756 return *this;
0757 }
0758
0759 template <typename T>
0760 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisablePerSessionThreads() {
0761 ThrowOnError(GetApi().DisablePerSessionThreads(this->p_));
0762 return *this;
0763 }
0764
0765 template <typename T>
0766 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializers(const std::vector<std::string>& names,
0767 const std::vector<Value>& ort_values) {
0768 const size_t inputs_num = names.size();
0769 if (inputs_num != ort_values.size()) {
0770 ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT);
0771 }
0772 std::vector<const char*> names_ptr;
0773 std::vector<const OrtValue*> ort_values_ptrs;
0774 names_ptr.reserve(inputs_num);
0775 ort_values_ptrs.reserve(inputs_num);
0776 for (size_t i = 0; i < inputs_num; ++i) {
0777 names_ptr.push_back(names[i].c_str());
0778 ort_values_ptrs.push_back(ort_values[i]);
0779 }
0780 ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num));
0781 return *this;
0782 }
0783
0784 template <typename T>
0785 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializersFromFilesInMemory(const std::vector<std::basic_string<ORTCHAR_T>>& file_names,
0786 const std::vector<char*>& buffer_array,
0787 const std::vector<size_t>& file_lengths) {
0788 const size_t inputs_num = file_names.size();
0789 if (inputs_num != buffer_array.size()) {
0790 ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT);
0791 }
0792 if (inputs_num != file_lengths.size()) {
0793 ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT);
0794 }
0795 std::vector<const ORTCHAR_T*> names_ptr;
0796 names_ptr.reserve(inputs_num);
0797 for (size_t i = 0; i < inputs_num; ++i) {
0798 names_ptr.push_back(file_names[i].c_str());
0799 }
0800 ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(),
0801 file_lengths.data(), inputs_num));
0802 return *this;
0803 }
0804
0805 template <typename T>
0806 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) {
0807 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options));
0808 return *this;
0809 }
0810
0811 template <typename T>
0812 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) {
0813 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options));
0814 return *this;
0815 }
0816
0817 template <typename T>
0818 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) {
0819 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options));
0820 return *this;
0821 }
0822
0823 template <typename T>
0824 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) {
0825 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options));
0826 return *this;
0827 }
0828
0829 template <typename T>
0830 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) {
0831 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options));
0832 return *this;
0833 }
0834
0835 template <typename T>
0836 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) {
0837 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options));
0838 return *this;
0839 }
0840
0841 template <typename T>
0842 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) {
0843 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options));
0844 return *this;
0845 }
0846
0847 template <typename T>
0848 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) {
0849 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options));
0850 return *this;
0851 }
0852
0853 template <typename T>
0854 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider(
0855 const std::string& provider_name,
0856 const std::unordered_map<std::string, std::string>& provider_options) {
0857 auto num_entries = provider_options.size();
0858 std::vector<const char*> keys, values;
0859 if (num_entries > 0) {
0860 keys.reserve(num_entries);
0861 values.reserve(num_entries);
0862
0863 for (const auto& entry : provider_options) {
0864 keys.push_back(entry.first.c_str());
0865 values.push_back(entry.second.c_str());
0866 }
0867 }
0868
0869 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(),
0870 keys.data(), values.data(), num_entries));
0871
0872 return *this;
0873 }
0874
0875 template <typename T>
0876 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
0877 ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn));
0878 return *this;
0879 }
0880
0881 template <typename T>
0882 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
0883 ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options));
0884 return *this;
0885 }
0886
0887 template <typename T>
0888 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
0889 ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn));
0890 return *this;
0891 }
0892
0893 template <typename T>
0894 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) {
0895 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options));
0896 return *this;
0897 }
0898
0899 template <typename T>
0900 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map<std::string, std::string>& provider_options) {
0901 auto num_entries = provider_options.size();
0902 std::vector<const char*> keys, values;
0903 if (num_entries > 0) {
0904 keys.reserve(num_entries);
0905 values.reserve(num_entries);
0906
0907 for (const auto& entry : provider_options) {
0908 keys.push_back(entry.first.c_str());
0909 values.push_back(entry.second.c_str());
0910 }
0911 }
0912
0913 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_,
0914 keys.data(), values.data(), num_entries));
0915
0916 return *this;
0917 }
0918
0919 template <typename T>
0920 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_VitisAI(const std::unordered_map<std::string, std::string>& provider_options) {
0921 auto num_entries = provider_options.size();
0922 std::vector<const char*> keys, values;
0923 if (num_entries > 0) {
0924 keys.reserve(num_entries);
0925 values.reserve(num_entries);
0926
0927 for (const auto& entry : provider_options) {
0928 keys.push_back(entry.first.c_str());
0929 values.push_back(entry.second.c_str());
0930 }
0931 }
0932
0933 ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries));
0934
0935 return *this;
0936 }
0937
0938 template <typename T>
0939 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name,
0940 const CustomOpConfigs& custom_op_configs) {
0941
0942
0943 for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) {
0944 AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str());
0945 }
0946
0947 ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name));
0948 return *this;
0949 }
0950
0951 template <typename T>
0952 inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsUsingFunction(const char* registration_function_name) {
0953 ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name));
0954 return *this;
0955 }
0956
0957
0958 template <typename T>
0959 inline size_t ConstSessionImpl<T>::GetInputCount() const {
0960 size_t out;
0961 ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out));
0962 return out;
0963 }
0964
0965 template <typename T>
0966 inline size_t ConstSessionImpl<T>::GetOutputCount() const {
0967 size_t out;
0968 ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out));
0969 return out;
0970 }
0971
0972 template <typename T>
0973 inline size_t ConstSessionImpl<T>::GetOverridableInitializerCount() const {
0974 size_t out;
0975 ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out));
0976 return out;
0977 }
0978
0979 template <typename T>
0980 inline AllocatedStringPtr ConstSessionImpl<T>::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const {
0981 char* out;
0982 ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out));
0983 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
0984 }
0985
0986 template <typename T>
0987 inline AllocatedStringPtr ConstSessionImpl<T>::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const {
0988 char* out;
0989 ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out));
0990 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
0991 }
0992
0993 template <typename T>
0994 inline AllocatedStringPtr ConstSessionImpl<T>::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const {
0995 char* out;
0996 ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out));
0997 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
0998 }
0999
1000 template <typename T>
1001 inline uint64_t ConstSessionImpl<T>::GetProfilingStartTimeNs() const {
1002 uint64_t out;
1003 ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out));
1004 return out;
1005 }
1006
1007 template <typename T>
1008 inline ModelMetadata ConstSessionImpl<T>::GetModelMetadata() const {
1009 OrtModelMetadata* out;
1010 ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out));
1011 return ModelMetadata{out};
1012 }
1013
1014 template <typename T>
1015 inline TypeInfo ConstSessionImpl<T>::GetInputTypeInfo(size_t index) const {
1016 OrtTypeInfo* out;
1017 ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out));
1018 return TypeInfo{out};
1019 }
1020
1021 template <typename T>
1022 inline TypeInfo ConstSessionImpl<T>::GetOutputTypeInfo(size_t index) const {
1023 OrtTypeInfo* out;
1024 ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out));
1025 return TypeInfo{out};
1026 }
1027
1028 template <typename T>
1029 inline TypeInfo ConstSessionImpl<T>::GetOverridableInitializerTypeInfo(size_t index) const {
1030 OrtTypeInfo* out;
1031 ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out));
1032 return TypeInfo{out};
1033 }
1034
1035 template <typename T>
1036 inline std::vector<Value> SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1037 const char* const* output_names, size_t output_count) {
1038 std::vector<Value> output_values;
1039 output_values.reserve(output_count);
1040 for (size_t i = 0; i < output_count; i++)
1041 output_values.emplace_back(nullptr);
1042 Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count);
1043 return output_values;
1044 }
1045
1046 template <typename T>
1047 inline void SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1048 const char* const* output_names, Value* output_values, size_t output_count) {
1049 static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
1050 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
1051 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
1052 ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values));
1053 }
1054
1055 template <typename T>
1056 inline void SessionImpl<T>::Run(const RunOptions& run_options, const IoBinding& io_binding) {
1057 ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding));
1058 }
1059
1060 template <typename T>
1061 inline void SessionImpl<T>::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
1062 const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) {
1063 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
1064 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
1065 ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names,
1066 ort_input_values, input_count, output_names, output_count,
1067 ort_output_values, callback, user_data));
1068 }
1069
1070 template <typename T>
1071 inline AllocatedStringPtr SessionImpl<T>::EndProfilingAllocated(OrtAllocator* allocator) {
1072 char* out = nullptr;
1073 ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out));
1074 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1075 }
1076
1077 }
1078
1079 inline SessionOptions::SessionOptions() {
1080 ThrowOnError(GetApi().CreateSessionOptions(&this->p_));
1081 }
1082
1083
1084 inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) {
1085 std::string config_key = "custom_op.";
1086
1087 config_key += custom_op_name;
1088 config_key += ".";
1089 config_key += config;
1090
1091 return config_key;
1092 }
1093
1094 inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) {
1095 const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key);
1096 flat_configs_[full_flat_key] = config_value;
1097 return *this;
1098 }
1099
1100 inline const std::unordered_map<std::string, std::string>& CustomOpConfigs::GetFlattenedConfigs() const {
1101 return flat_configs_;
1102 }
1103
1104 inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) {
1105 ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_));
1106 }
1107
1108 inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options,
1109 OrtPrepackedWeightsContainer* prepacked_weights_container) {
1110 ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_));
1111 }
1112
1113 inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) {
1114 ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_));
1115 }
1116
1117 inline Session::Session(const Env& env, const void* model_data, size_t model_data_length,
1118 const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) {
1119 ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options,
1120 prepacked_weights_container, &this->p_));
1121 }
1122
1123 inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const {
1124 char* out;
1125 ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out));
1126 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1127 }
1128
1129 inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const {
1130 char* out;
1131 ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out));
1132 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1133 }
1134
1135 inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const {
1136 char* out;
1137 ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out));
1138 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1139 }
1140
1141 inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const {
1142 char* out;
1143 ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out));
1144 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1145 }
1146
1147 inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const {
1148 char* out;
1149 ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out));
1150 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1151 }
1152
1153 inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const {
1154 char* out;
1155 ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out));
1156 return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
1157 }
1158
1159 inline std::vector<AllocatedStringPtr> ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const {
1160 auto deletor = detail::AllocatedFree(allocator);
1161 std::vector<AllocatedStringPtr> result;
1162
1163 char** out = nullptr;
1164 int64_t num_keys = 0;
1165 ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys));
1166 if (num_keys <= 0) {
1167 return result;
1168 }
1169
1170
1171 std::unique_ptr<void, decltype(deletor)> array_guard(out, deletor);
1172
1173 auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); };
1174 std::unique_ptr<char*, decltype(strings_deletor)> strings_guard(out, strings_deletor);
1175 result.reserve(static_cast<size_t>(num_keys));
1176 strings_guard.release();
1177 for (int64_t i = 0; i < num_keys; ++i) {
1178 result.push_back(AllocatedStringPtr(out[i], deletor));
1179 }
1180
1181 return result;
1182 }
1183
1184 inline int64_t ModelMetadata::GetVersion() const {
1185 int64_t out;
1186 ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out));
1187 return out;
1188 }
1189
1190 namespace detail {
1191
1192 template <typename T>
1193 inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl<T>::GetElementType() const {
1194 ONNXTensorElementDataType out;
1195 ThrowOnError(GetApi().GetTensorElementType(this->p_, &out));
1196 return out;
1197 }
1198
1199 template <typename T>
1200 inline size_t TensorTypeAndShapeInfoImpl<T>::GetElementCount() const {
1201 size_t out;
1202 ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out));
1203 return static_cast<size_t>(out);
1204 }
1205
1206 template <typename T>
1207 inline size_t TensorTypeAndShapeInfoImpl<T>::GetDimensionsCount() const {
1208 size_t out;
1209 ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out));
1210 return out;
1211 }
1212
1213 template <typename T>
1214 inline void TensorTypeAndShapeInfoImpl<T>::GetDimensions(int64_t* values, size_t values_count) const {
1215 ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count));
1216 }
1217
1218 template <typename T>
1219 inline void TensorTypeAndShapeInfoImpl<T>::GetSymbolicDimensions(const char** values, size_t values_count) const {
1220 ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count));
1221 }
1222
1223 template <typename T>
1224 inline std::vector<int64_t> TensorTypeAndShapeInfoImpl<T>::GetShape() const {
1225 std::vector<int64_t> out(GetDimensionsCount(), 0);
1226 ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size()));
1227 return out;
1228 }
1229
1230 template <typename T>
1231 inline ConstTensorTypeAndShapeInfo TypeInfoImpl<T>::GetTensorTypeAndShapeInfo() const {
1232 const OrtTensorTypeAndShapeInfo* out;
1233 ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out));
1234 return ConstTensorTypeAndShapeInfo{out};
1235 }
1236
1237 template <typename T>
1238 inline ConstSequenceTypeInfo TypeInfoImpl<T>::GetSequenceTypeInfo() const {
1239 const OrtSequenceTypeInfo* out;
1240 ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out));
1241 return ConstSequenceTypeInfo{out};
1242 }
1243
1244 template <typename T>
1245 inline ConstMapTypeInfo TypeInfoImpl<T>::GetMapTypeInfo() const {
1246 const OrtMapTypeInfo* out;
1247 ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out));
1248 return ConstMapTypeInfo{out};
1249 }
1250
1251 template <typename T>
1252 inline ONNXType TypeInfoImpl<T>::GetONNXType() const {
1253 ONNXType out;
1254 ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out));
1255 return out;
1256 }
1257
1258 template <typename T>
1259 inline TypeInfo SequenceTypeInfoImpl<T>::GetSequenceElementType() const {
1260 OrtTypeInfo* output;
1261 ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output));
1262 return TypeInfo{output};
1263 }
1264
1265 template <typename T>
1266 inline TypeInfo OptionalTypeInfoImpl<T>::GetOptionalElementType() const {
1267 OrtTypeInfo* info;
1268 ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info));
1269 return TypeInfo{info};
1270 }
1271
1272 template <typename T>
1273 inline ONNXTensorElementDataType MapTypeInfoImpl<T>::GetMapKeyType() const {
1274 ONNXTensorElementDataType out;
1275 ThrowOnError(GetApi().GetMapKeyType(this->p_, &out));
1276 return out;
1277 }
1278
1279 template <typename T>
1280 inline TypeInfo MapTypeInfoImpl<T>::GetMapValueType() const {
1281 OrtTypeInfo* output;
1282 ThrowOnError(GetApi().GetMapValueType(this->p_, &output));
1283 return TypeInfo{output};
1284 }
1285
1286 template <typename T>
1287 inline ConstOptionalTypeInfo TypeInfoImpl<T>::GetOptionalTypeInfo() const {
1288 const OrtOptionalTypeInfo* info;
1289 ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info));
1290 return ConstOptionalTypeInfo{info};
1291 }
1292
1293 }
1294
1295 namespace detail {
1296
1297 template <typename T>
1298 template <typename R>
1299 inline void ConstValueImpl<T>::GetOpaqueData(const char* domain, const char* type_name, R& out) const {
1300 ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R)));
1301 }
1302
1303 template <typename T>
1304 inline bool ConstValueImpl<T>::IsTensor() const {
1305 int out;
1306 ThrowOnError(GetApi().IsTensor(this->p_, &out));
1307 return out != 0;
1308 }
1309
1310 template <typename T>
1311 inline bool ConstValueImpl<T>::HasValue() const {
1312 int out;
1313 ThrowOnError(GetApi().HasValue(this->p_, &out));
1314 return out != 0;
1315 }
1316
1317 template <typename T>
1318 inline size_t ConstValueImpl<T>::GetCount() const {
1319 size_t out;
1320 ThrowOnError(GetApi().GetValueCount(this->p_, &out));
1321 return out;
1322 }
1323
1324 template <typename T>
1325 inline Value ConstValueImpl<T>::GetValue(int index, OrtAllocator* allocator) const {
1326 OrtValue* out;
1327 ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out));
1328 return Value{out};
1329 }
1330
1331 template <typename T>
1332 inline size_t ConstValueImpl<T>::GetStringTensorDataLength() const {
1333 size_t out;
1334 ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out));
1335 return out;
1336 }
1337
1338 template <typename T>
1339 inline size_t ConstValueImpl<T>::GetStringTensorElementLength(size_t element_index) const {
1340 size_t out;
1341 ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out));
1342 return out;
1343 }
1344
1345 template <typename T>
1346 template <typename R>
1347 inline const R* ConstValueImpl<T>::GetTensorData() const {
1348 R* out;
1349 ThrowOnError(GetApi().GetTensorMutableData(const_cast<OrtValue*>(this->p_), (void**)&out));
1350 return out;
1351 }
1352
1353 template <typename T>
1354 inline const void* ConstValueImpl<T>::GetTensorRawData() const {
1355 void* out;
1356 ThrowOnError(GetApi().GetTensorMutableData(const_cast<OrtValue*>(this->p_), &out));
1357 return out;
1358 }
1359
1360 template <typename T>
1361 inline TypeInfo ConstValueImpl<T>::GetTypeInfo() const {
1362 OrtTypeInfo* output;
1363 ThrowOnError(GetApi().GetTypeInfo(this->p_, &output));
1364 return TypeInfo{output};
1365 }
1366
1367 template <typename T>
1368 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetTensorTypeAndShapeInfo() const {
1369 OrtTensorTypeAndShapeInfo* output;
1370 ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output));
1371 return TensorTypeAndShapeInfo{output};
1372 }
1373
1374 template <typename T>
1375 inline ConstMemoryInfo ConstValueImpl<T>::GetTensorMemoryInfo() const {
1376 const OrtMemoryInfo* mem_info;
1377 ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info));
1378 return ConstMemoryInfo(mem_info);
1379 }
1380
1381 template <typename T>
1382 inline void ConstValueImpl<T>::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const {
1383 ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer));
1384 }
1385
1386 template <typename T>
1387 inline std::string ConstValueImpl<T>::GetStringTensorElement(size_t element_index) const {
1388 size_t buffer_length;
1389 ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length));
1390
1391 std::string s;
1392 s.resize(buffer_length);
1393 ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0]));
1394 return s;
1395 }
1396
1397 template <typename T>
1398 inline void ConstValueImpl<T>::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const {
1399 ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count));
1400 }
1401
1402 #if !defined(DISABLE_SPARSE_TENSORS)
1403 template <typename T>
1404 inline OrtSparseFormat ConstValueImpl<T>::GetSparseFormat() const {
1405 OrtSparseFormat format;
1406 ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format));
1407 return format;
1408 }
1409
1410 template <typename T>
1411 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorValuesTypeAndShapeInfo() const {
1412 OrtTensorTypeAndShapeInfo* output;
1413 ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output));
1414 return TensorTypeAndShapeInfo{output};
1415 }
1416
1417 template <typename T>
1418 inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const {
1419 OrtTensorTypeAndShapeInfo* output;
1420 ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output));
1421 return TensorTypeAndShapeInfo{output};
1422 }
1423
1424 template <typename T>
1425 template <typename R>
1426 inline const R* ConstValueImpl<T>::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const {
1427 const void* out;
1428 ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out));
1429 return reinterpret_cast<const R*>(out);
1430 }
1431
1432 template <typename T>
1433 inline bool ConstValueImpl<T>::IsSparseTensor() const {
1434 int out;
1435 ThrowOnError(GetApi().IsSparseTensor(this->p_, &out));
1436 return out != 0;
1437 }
1438
1439 template <typename T>
1440 template <typename R>
1441 inline const R* ConstValueImpl<T>::GetSparseTensorValues() const {
1442 const void* out;
1443 ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out));
1444 return reinterpret_cast<const R*>(out);
1445 }
1446
1447 #endif
1448
1449 template <typename T>
1450 void ValueImpl<T>::FillStringTensor(const char* const* s, size_t s_len) {
1451 ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len));
1452 }
1453
1454 template <typename T>
1455 void ValueImpl<T>::FillStringTensorElement(const char* s, size_t index) {
1456 ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index));
1457 }
1458
1459 template <typename T>
1460 inline char* ValueImpl<T>::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) {
1461 char* result;
1462 ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result));
1463 return result;
1464 }
1465
1466 template <typename T>
1467 void* ValueImpl<T>::GetTensorMutableRawData() {
1468 void* out;
1469 ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out));
1470 return out;
1471 }
1472
1473 template <typename T>
1474 template <typename R>
1475 R* ValueImpl<T>::GetTensorMutableData() {
1476 R* out;
1477 ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out));
1478 return out;
1479 }
1480
1481 template <typename T>
1482 template <typename R>
1483 R& ValueImpl<T>::At(const std::vector<int64_t>& location) {
1484 static_assert(!std::is_same<T, std::string>::value, "this api does not support std::string");
1485 R* out;
1486 ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out));
1487 return *out;
1488 }
1489
1490 #if !defined(DISABLE_SPARSE_TENSORS)
1491 template <typename T>
1492 void ValueImpl<T>::UseCooIndices(int64_t* indices_data, size_t indices_num) {
1493 ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num));
1494 }
1495
1496 template <typename T>
1497 void ValueImpl<T>::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) {
1498 ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num));
1499 }
1500
1501 template <typename T>
1502 void ValueImpl<T>::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) {
1503 ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data));
1504 }
1505
1506 template <typename T>
1507 void ValueImpl<T>::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param,
1508 const int64_t* indices_data, size_t indices_num) {
1509 ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape,
1510 values_param.values_shape_len, values_param.data.p_data,
1511 indices_data, indices_num));
1512 }
1513
1514 template <typename T>
1515 void ValueImpl<T>::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info,
1516 const OrtSparseValuesParam& values,
1517 const int64_t* inner_indices_data, size_t inner_indices_num,
1518 const int64_t* outer_indices_data, size_t outer_indices_num) {
1519 ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
1520 inner_indices_data, inner_indices_num,
1521 outer_indices_data, outer_indices_num));
1522 }
1523
1524 template <typename T>
1525 void ValueImpl<T>::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info,
1526 const OrtSparseValuesParam& values,
1527 const Shape& indices_shape,
1528 const int32_t* indices_data) {
1529 ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
1530 indices_shape.shape, indices_shape.shape_len,
1531 indices_data));
1532 }
1533
1534 #endif
1535
1536 }
1537
1538 template <typename T>
1539 inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len) {
1540 return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType<T>::type);
1541 }
1542
1543 inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, const int64_t* shape, size_t shape_len,
1544 ONNXTensorElementDataType type) {
1545 OrtValue* out;
1546 ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out));
1547 return Value{out};
1548 }
1549
1550 template <typename T>
1551 inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) {
1552 return CreateTensor(allocator, shape, shape_len, TypeToTensorType<T>::type);
1553 }
1554
1555 inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type) {
1556 OrtValue* out;
1557 ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out));
1558 return Value{out};
1559 }
1560
1561 #if !defined(DISABLE_SPARSE_TENSORS)
1562
1563 template <typename T>
1564 inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape,
1565 const Shape& values_shape) {
1566 return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType<T>::type);
1567 }
1568
1569 inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape,
1570 const Shape& values_shape, ONNXTensorElementDataType type) {
1571 OrtValue* out;
1572 ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len,
1573 values_shape.shape, values_shape.shape_len, type, &out));
1574 return Value{out};
1575 }
1576
1577 template <typename T>
1578 inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) {
1579 return CreateSparseTensor(allocator, dense_shape, TypeToTensorType<T>::type);
1580 }
1581
1582 inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape,
1583 ONNXTensorElementDataType type) {
1584 OrtValue* out;
1585 ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out));
1586 return Value{out};
1587 }
1588 #endif
1589
1590 inline Value Value::CreateMap(const Value& keys, const Value& values) {
1591 OrtValue* out;
1592 const OrtValue* inputs[2] = {keys, values};
1593 ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out));
1594 return Value{out};
1595 }
1596
1597 inline Value Value::CreateSequence(const std::vector<Value>& values) {
1598 OrtValue* out;
1599 std::vector<const OrtValue*> values_ort{values.data(), values.data() + values.size()};
1600 ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out));
1601 return Value{out};
1602 }
1603
1604 template <typename T>
1605 inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) {
1606 OrtValue* out;
1607 ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out));
1608 return Value{out};
1609 }
1610
1611
1612
1613
1614 inline Logger::Logger(const OrtLogger* logger) : logger_(logger) {
1615 Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_));
1616 }
1617
1618 inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept {
1619 return cached_severity_level_;
1620 }
1621
1622 inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number,
1623 const char* func_name, const char* message) const noexcept {
1624 OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number,
1625 func_name);
1626 return Status{status};
1627 }
1628
1629
1630
1631
1632 #if defined(__GNUC__)
1633 #pragma GCC diagnostic push
1634 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1635 #pragma GCC diagnostic ignored "-Wformat-security"
1636 #elif defined(__clang__)
1637 #pragma clang diagnostic push
1638 #pragma clang diagnostic ignored "-Wformat-nonliteral"
1639 #pragma clang diagnostic ignored "-Wformat-security"
1640 #endif
1641 template <typename... Args>
1642 inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path,
1643 int line_number, const char* func_name, const char* format,
1644 Args&&... args) const noexcept {
1645 int msg_len = std::snprintf(nullptr, 0U, format, std::forward<Args>(args)...);
1646
1647 if (msg_len < 0) {
1648 return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL);
1649 }
1650
1651 OrtStatus* status = nullptr;
1652 const size_t buffer_size = static_cast<size_t>(msg_len) + 1U;
1653
1654 constexpr size_t kStackBufferSize = 1024;
1655
1656 if (buffer_size < kStackBufferSize) {
1657 char buffer[kStackBufferSize];
1658 snprintf(buffer, kStackBufferSize, format, std::forward<Args>(args)...);
1659 status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name);
1660 } else {
1661
1662 #if (__cplusplus >= 201402L) || (_MSC_VER >= 1900)
1663 auto buffer = std::make_unique<char[]>(buffer_size);
1664 #else
1665 std::unique_ptr<char[]> buffer(new char[buffer_size]);
1666 #endif
1667 std::snprintf(buffer.get(), buffer_size, format, std::forward<Args>(args)...);
1668 status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name);
1669 }
1670
1671 return Status{status};
1672 }
1673
1674 #if defined(__GNUC__)
1675 #pragma GCC diagnostic pop
1676 #elif defined(__clang__)
1677 #pragma clang diagnostic pop
1678 #endif
1679
1680 inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) {
1681 }
1682
1683 inline size_t KernelContext::GetInputCount() const {
1684 size_t out = 0;
1685 Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out));
1686 return out;
1687 }
1688
1689 inline size_t KernelContext::GetOutputCount() const {
1690 size_t out = 0;
1691 Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out));
1692 return out;
1693 }
1694
1695 inline ConstValue KernelContext::GetInput(size_t index) const {
1696 const OrtValue* out = nullptr;
1697 Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out));
1698 return ConstValue{out};
1699 }
1700
1701 inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const {
1702 OrtValue* out = nullptr;
1703 Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out));
1704 return UnownedValue(out);
1705 }
1706
1707 inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector<int64_t>& dims) const {
1708 OrtValue* out = nullptr;
1709 Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out));
1710 return UnownedValue(out);
1711 }
1712
1713 inline void* KernelContext::GetGPUComputeStream() const {
1714 void* out = nullptr;
1715 Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out));
1716 return out;
1717 }
1718
1719 inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const {
1720 OrtAllocator* out = nullptr;
1721 Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out));
1722 return out;
1723 }
1724
1725 inline Logger KernelContext::GetLogger() const {
1726 const OrtLogger* out = nullptr;
1727 ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out));
1728 return Logger{out};
1729 }
1730
1731 inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const {
1732 ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data));
1733 }
1734
1735 inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) {
1736 Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_));
1737 }
1738
1739 namespace detail {
1740 template <typename T>
1741 inline KernelInfo KernelInfoImpl<T>::Copy() const {
1742 OrtKernelInfo* info_copy = nullptr;
1743 Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy));
1744 return KernelInfo{info_copy};
1745 }
1746
1747 template <typename T>
1748 inline size_t KernelInfoImpl<T>::GetInputCount() const {
1749 size_t out = 0;
1750 ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out));
1751 return out;
1752 }
1753
1754 template <typename T>
1755 inline size_t KernelInfoImpl<T>::GetOutputCount() const {
1756 size_t out = 0;
1757 ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out));
1758 return out;
1759 }
1760
1761 template <typename T>
1762 inline std::string KernelInfoImpl<T>::GetInputName(size_t index) const {
1763 size_t size = 0;
1764
1765
1766 Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size));
1767
1768 std::string out;
1769 out.resize(size);
1770 Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size));
1771 out.resize(size - 1);
1772
1773 return out;
1774 }
1775
1776 template <typename T>
1777 inline std::string KernelInfoImpl<T>::GetOutputName(size_t index) const {
1778 size_t size = 0;
1779
1780
1781 Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size));
1782
1783 std::string out;
1784 out.resize(size);
1785 Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size));
1786 out.resize(size - 1);
1787
1788 return out;
1789 }
1790
1791 template <typename T>
1792 inline TypeInfo KernelInfoImpl<T>::GetInputTypeInfo(size_t index) const {
1793 OrtTypeInfo* out = nullptr;
1794 ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out));
1795 return TypeInfo{out};
1796 }
1797
1798 template <typename T>
1799 inline TypeInfo KernelInfoImpl<T>::GetOutputTypeInfo(size_t index) const {
1800 OrtTypeInfo* out = nullptr;
1801 ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out));
1802 return TypeInfo{out};
1803 }
1804
1805 template <typename T>
1806 inline Value KernelInfoImpl<T>::GetTensorAttribute(const char* name, OrtAllocator* allocator) const {
1807 OrtValue* out = nullptr;
1808 ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out));
1809 return Value{out};
1810 }
1811
1812 template <typename T>
1813 inline ConstValue KernelInfoImpl<T>::GetTensorConstantInput(size_t index, int* is_constant) const {
1814 const OrtValue* out = nullptr;
1815 ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out));
1816 return ConstValue{out};
1817 }
1818
1819 template <typename T>
1820 inline std::string KernelInfoImpl<T>::GetNodeName() const {
1821 size_t size = 0;
1822
1823
1824 Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size));
1825
1826 std::string out;
1827 out.resize(size);
1828 Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size));
1829 out.resize(size - 1);
1830
1831 return out;
1832 }
1833
1834 template <typename T>
1835 inline Logger KernelInfoImpl<T>::GetLogger() const {
1836 const OrtLogger* out = nullptr;
1837 ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out));
1838 return Logger{out};
1839 }
1840
1841 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) {
1842 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out));
1843 }
1844
1845 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) {
1846 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out));
1847 }
1848
1849 inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) {
1850 size_t size = 0;
1851
1852 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size));
1853
1854 std::string out;
1855 out.resize(size);
1856 Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size));
1857 out.resize(size - 1);
1858 out.swap(result);
1859 }
1860
1861 inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<float>& result) {
1862 size_t size = 0;
1863
1864 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size));
1865
1866 std::vector<float> out;
1867 out.resize(size);
1868 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size));
1869 out.swap(result);
1870 }
1871
1872 inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<int64_t>& result) {
1873 size_t size = 0;
1874
1875
1876 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size));
1877
1878 std::vector<int64_t> out;
1879 out.resize(size);
1880 Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size));
1881 out.swap(result);
1882 }
1883 }
1884
1885 inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl<OrtKernelInfo>{info} {}
1886
1887 inline Op::Op(OrtOp* p) : Base<OrtOp>(p) {}
1888
1889 inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version,
1890 const char** type_constraint_names,
1891 const ONNXTensorElementDataType* type_constraint_values,
1892 size_t type_constraint_count,
1893 const OpAttr* attr_values, size_t attr_count,
1894 size_t input_count, size_t output_count) {
1895 static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*),
1896 "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely");
1897 auto attr_input_values = reinterpret_cast<const OrtOpAttr* const*>(attr_values);
1898 OrtOp* op;
1899 Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values,
1900 static_cast<int>(type_constraint_count),
1901 attr_input_values,
1902 static_cast<int>(attr_count),
1903 static_cast<int>(input_count),
1904 static_cast<int>(output_count), &op));
1905 return Op{op};
1906 }
1907
1908 inline void Op::Invoke(const OrtKernelContext* context,
1909 const Value* input_values,
1910 size_t input_count,
1911 Value* output_values,
1912 size_t output_count) {
1913 static_assert(sizeof(Value) == sizeof(OrtValue*),
1914 "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
1915 auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
1916 auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
1917 Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast<int>(input_count),
1918 ort_output_values, static_cast<int>(output_count)));
1919 }
1920
1921 inline void Op::Invoke(const OrtKernelContext* context,
1922 const OrtValue* const* input_values,
1923 size_t input_count,
1924 OrtValue* const* output_values,
1925 size_t output_count) {
1926 Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast<int>(input_count),
1927 output_values, static_cast<int>(output_count)));
1928 }
1929
1930 inline std::string GetVersionString() {
1931 return OrtGetApiBase()->GetVersionString();
1932 }
1933
1934 inline std::string GetBuildInfoString() {
1935 return GetApi().GetBuildInfoString();
1936 }
1937
1938 inline std::vector<std::string> GetAvailableProviders() {
1939 char** providers;
1940 int len;
1941
1942 auto release_fn = [&len](char** providers) {
1943
1944 ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len));
1945 };
1946
1947 ThrowOnError(GetApi().GetAvailableProviders(&providers, &len));
1948 std::unique_ptr<char*, decltype(release_fn)> guard(providers, release_fn);
1949 std::vector<std::string> available_providers;
1950 available_providers.reserve(static_cast<size_t>(len));
1951 for (int i = 0; i < len; ++i) {
1952 available_providers.emplace_back(providers[i]);
1953 }
1954 return available_providers;
1955 }
1956
1957 template <typename TOp, typename TKernel, bool WithStatus>
1958 void CustomOpBase<TOp, TKernel, WithStatus>::GetSessionConfigs(std::unordered_map<std::string, std::string>& out,
1959 ConstSessionOptions options) const {
1960 const TOp* derived = static_cast<const TOp*>(this);
1961 std::vector<std::string> keys = derived->GetSessionConfigKeys();
1962
1963 out.reserve(keys.size());
1964
1965 std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), "");
1966 const size_t prefix_size = config_entry_key.length();
1967
1968 for (const auto& key : keys) {
1969 config_entry_key.resize(prefix_size);
1970 config_entry_key.append(key);
1971 out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), "");
1972 }
1973 }
1974
1975 inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api,
1976 OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) {
1977 size_t input_count = 0;
1978 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count));
1979 for (size_t ith_input = 0; ith_input < input_count; ++ith_input) {
1980 OrtTensorTypeAndShapeInfo* info{};
1981 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info));
1982 TensorTypeAndShapeInfo type_shape_info(info);
1983 auto integer_shape = type_shape_info.GetShape();
1984 std::vector<const char*> symbolic_shape(integer_shape.size(), {});
1985 type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size());
1986 Shape shape;
1987 for (size_t ith = 0; ith < integer_shape.size(); ++ith) {
1988 if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) {
1989 shape.emplace_back(symbolic_shape[ith]);
1990 } else {
1991 shape.emplace_back(integer_shape[ith]);
1992 }
1993 }
1994 input_shapes_.push_back(std::move(shape));
1995 type_shape_info.release();
1996 }
1997 }
1998
1999 inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape) {
2000 OrtTensorTypeAndShapeInfo* info = {};
2001 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info));
2002
2003 using InfoPtr = std::unique_ptr<OrtTensorTypeAndShapeInfo, std::function<void(OrtTensorTypeAndShapeInfo*)>>;
2004
2005 InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) {
2006 ort_api_->ReleaseTensorTypeAndShapeInfo(obj);
2007 });
2008
2009 std::vector<int64_t> integer_dims;
2010 std::vector<const char*> symbolic_dims;
2011
2012 for (const auto dim : shape) {
2013 if (dim.IsInt()) {
2014 integer_dims.push_back(dim.IsInt());
2015 symbolic_dims.push_back("");
2016 } else {
2017 if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) {
2018 ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT);
2019 }
2020 integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM);
2021 symbolic_dims.push_back(dim.AsSym());
2022 }
2023 }
2024
2025 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size()));
2026 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size()));
2027 ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info));
2028 return Status{nullptr};
2029 }
2030
2031 inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) {
2032 const auto* attr = GetAttrHdl(attr_name);
2033 int64_t i = {};
2034 size_t out = {};
2035 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out));
2036 return i;
2037 }
2038
2039 inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) {
2040 const auto* attr = GetAttrHdl(attr_name);
2041 int64_t i = {};
2042 size_t out = {};
2043
2044 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out);
2045 if (status) {
2046 size_t num_i = out / sizeof(int64_t);
2047 ShapeInferContext::Ints ints(num_i, 0);
2048 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out));
2049 return ints;
2050 } else {
2051 return {i};
2052 }
2053 }
2054
2055 inline float ShapeInferContext::GetAttrFloat(const char* attr_name) {
2056 const auto* attr = GetAttrHdl(attr_name);
2057 float f = {};
2058 size_t out = {};
2059 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out));
2060 return f;
2061 }
2062
2063 inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) {
2064 const auto* attr = GetAttrHdl(attr_name);
2065 float f = {};
2066 size_t out = {};
2067
2068 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out);
2069 if (status) {
2070 size_t num_f = out / sizeof(float);
2071 ShapeInferContext::Floats floats(num_f, 0);
2072 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out));
2073 return floats;
2074 } else {
2075 return {f};
2076 }
2077 }
2078
2079 inline std::string ShapeInferContext::GetAttrString(const char* attr_name) {
2080 const auto* attr = GetAttrHdl(attr_name);
2081 char c = {};
2082 size_t out = {};
2083
2084 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out);
2085 if (status) {
2086 std::vector<char> chars(out, '\0');
2087 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out));
2088 return {chars.data()};
2089 } else {
2090 return {c};
2091 }
2092 }
2093
2094 inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) {
2095 const auto* attr = GetAttrHdl(attr_name);
2096 char c = {};
2097 size_t out = {};
2098
2099 auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out);
2100 if (status) {
2101 std::vector<char> chars(out, '\0');
2102 Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out));
2103 ShapeInferContext::Strings strings;
2104 char* char_st = chars.data();
2105 char* char_ed = char_st + out;
2106 while (char_st < char_ed) {
2107 strings.emplace_back(char_st);
2108 while (*char_st != '\0') {
2109 char_st++;
2110 }
2111 char_st++;
2112 }
2113 return strings;
2114 } else {
2115 return {std::string{c}};
2116 }
2117 }
2118
2119 inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const {
2120 const OrtOpAttr* attr_hdl = {};
2121 Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl));
2122 return attr_hdl;
2123 }
2124
2125 }