// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/session/environment.h" #include #include #include #include "core/common/basic_types.h" #include "core/common/safeint.h" #include "core/framework/allocator.h" #include "core/framework/allocator_utils.h" #include "core/framework/error_code_helper.h" #include "core/framework/plugin_data_transfer.h" #include "core/graph/constants.h" #include "core/graph/op.h" #include "core/platform/device_discovery.h" #include "core/session/abi_session_options_impl.h" #include "core/session/allocator_adapters.h" #include "core/session/inference_session.h" #include "core/session/onnxruntime_env_config_keys.h" #include "core/session/onnxruntime_ep_device_ep_metadata_keys.h" #include "core/session/plugin_ep/ep_allocator_utils.h" #include "core/session/plugin_ep/ep_factory_internal.h" #include "core/session/plugin_ep/ep_library_internal.h" #include "core/session/plugin_ep/ep_library_plugin.h" #include "core/session/plugin_ep/ep_library_provider_bridge.h" #include "core/session/plugin_ep/ep_static_plugins.h" #include "core/session/ort_apis.h" #include "core/session/utils.h" #if !defined(ORT_MINIMAL_BUILD) #include "onnx/defs/operator_sets.h" #include "onnx/defs/operator_sets_ml.h" #include "core/graph/contrib_ops/internal_nhwc_onnx_schemas.h" #include "core/graph/contrib_ops/ms_opset.h" #include "core/graph/contrib_ops/onnx_deprecated_opset.h" #if defined(ENABLE_TRAINING_OPS) #include "onnx/defs/operator_sets_training.h" #endif #endif #ifndef DISABLE_CONTRIB_OPS #include "core/graph/contrib_ops/contrib_defs.h" #endif #ifdef USE_DML #include "core/graph/dml_ops/dml_defs.h" #endif #include "core/platform/env.h" #include "core/util/thread_utils.h" #ifdef ONNXRUNTIME_ENABLE_INSTRUMENT #include "core/platform/tracing.h" #endif #if defined(ENABLE_TRAINING_OPS) #include "orttraining/core/graph/training_op_defs.h" #endif #ifdef ENABLE_TRAINING #include "orttraining/core/graph/gradient_builder_registry.h" #include "orttraining/core/graph/optimizer_builder.h" #include "orttraining/core/graph/optimizer_graph_builder_registry.h" #include "orttraining/core/graph/loss_function_registry.h" #include "orttraining/core/optimizer/graph_transformer_registry.h" #endif #if !defined(NDEBUG) && defined(__linux__) && !defined(__ANDROID__) #include "absl/debugging/symbolize.h" #endif #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) #include "core/providers/cuda/cuda_provider_factory.h" #include "core/providers/cuda/cuda_execution_provider_info.h" #endif namespace onnxruntime { using namespace ::onnxruntime::common; using namespace ONNX_NAMESPACE; std::once_flag schemaRegistrationOnceFlag; std::once_flag symbolizerInitOnceFlag; #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) ProviderInfo_CUDA& GetProviderInfo_CUDA(); #endif // defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) namespace { // Ignore whether there is an arena wrapping the allocator by excluding OrtMemoryInfo.alloc_type from the comparison. static bool AreOrtMemoryInfosEquivalent( const OrtMemoryInfo& left, const OrtMemoryInfo& right, bool match_name = true, bool ignore_alignment = false) { return left.mem_type == right.mem_type && (ignore_alignment ? left.device.EqualIgnoringAlignment(right.device) : left.device == right.device) && (!match_name || left.name == right.name); } std::vector::const_iterator FindExistingAllocator(const std::vector& allocators, const OrtMemoryInfo& mem_info, bool match_name = true, bool ignore_alignment = false) { auto ite = std::find_if(std::begin(allocators), std::end(allocators), [&mem_info, match_name, ignore_alignment](const AllocatorPtr& alloc_ptr) { // We want to do the equality checking of 2 OrtMemoryInfos sans the OrtAllocatorType field. // This is because we want to avoid registering two allocators for the same device that just // differ on OrtAllocatorType. // To be more specific, we want to avoid the scenario where the user calls CreateAndRegiserAllocator() // and registers the ORT-internal arena allocator and then tries to register their own custom // allocator using RegisterAllocator() for the same device that has an OrtAllocatorType as // OrtDeviceAllocator (which is the only accepted value while registering a custom allocator). // If we allowed this, it could potentially cause a lot of confusion as to which shared allocator // to use for that device and we want to avoid having any ugly logic around this. return AreOrtMemoryInfosEquivalent(alloc_ptr->Info(), mem_info, match_name, ignore_alignment); }); return ite; } std::unordered_set::const_iterator FindExistingAllocator(const std::unordered_set& allocators, const OrtMemoryInfo& mem_info, bool match_name = true) { return std::find_if(std::begin(allocators), std::end(allocators), [&mem_info, match_name](const OrtAllocator* alloc_ptr) { const auto* alloc_mem_info = alloc_ptr->Info(alloc_ptr); return AreOrtMemoryInfosEquivalent(*alloc_mem_info, mem_info, match_name); }); } } // namespace Status Environment::Create(std::unique_ptr logging_manager, std::unique_ptr& environment, const OrtThreadingOptions* tp_options, bool create_global_thread_pools, const OrtKeyValuePairs* config_entries) { environment = std::make_unique(); auto status = environment->Initialize(std::move(logging_manager), tp_options, create_global_thread_pools, config_entries); return status; } Status Environment::RegisterAllocator(OrtAllocator* allocator) { std::lock_guard lock{mutex_}; auto allocator_ptr = std::make_shared(allocator); // for the public API we always want to replace any existing allocator for the device. auto status = RegisterAllocatorImpl(allocator_ptr); // update shared_ort_allocators_ if (status.IsOK()) { if (auto it = FindExistingAllocator(shared_ort_allocators_, *allocator->Info(allocator), /*match_name*/ true); it != shared_ort_allocators_.end()) { shared_ort_allocators_.erase(it); } shared_ort_allocators_.insert(allocator); } return status; } Status Environment::RegisterAllocatorImpl(AllocatorPtr allocator) { const auto& mem_info = allocator->Info(); const bool match_name = false; if (FindExistingAllocator(shared_allocators_, mem_info, match_name) != shared_allocators_.end()) { ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(mem_info, match_name)); } shared_allocators_.push_back(std::move(allocator)); return Status::OK(); } Status Environment::UnregisterAllocator(const OrtMemoryInfo& mem_info) { std::lock_guard lock{mutex_}; return UnregisterAllocatorImpl(mem_info); } Status Environment::UnregisterAllocatorImpl(const OrtMemoryInfo& mem_info, bool error_if_not_found) { auto it = FindExistingAllocator(shared_allocators_, mem_info); const bool found_shared_allocator = it != shared_allocators_.end(); if (!found_shared_allocator && error_if_not_found) { return Status(ONNXRUNTIME, INVALID_ARGUMENT, "No allocator for this device has been registered for sharing."); } // we need to remove from shared_ort_allocators_ first in case the entry in shared_allocators_ owns the pointer in // shared_ort_allocators_ // e.g. a plug-in EP allocator is an IAllocatorImplWrappingOrtAllocator that owns the OrtAllocator* created by the EP // so when we remove that from shared_allocators_ we release the OrtAllocator instance. // shared_ort_allocators_ are internal only so never an error if there's no match if (auto it2 = FindExistingAllocator(shared_ort_allocators_, mem_info); it2 != shared_ort_allocators_.end()) { shared_ort_allocators_.erase(it2); } if (found_shared_allocator) { shared_allocators_.erase(it); } return Status::OK(); } Status Environment::CreateAndRegisterAllocator(const OrtMemoryInfo& mem_info, const OrtArenaCfg* arena_cfg) { // TODO should we allow sharing of non-CPU allocators? if (mem_info.device.Type() != OrtDevice::CPU) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Only CPU devices are supported. Please call CreateAndRegisterAllocatorV2() for other device."); } // determine if arena should be used const bool create_arena = DoesCpuAllocatorSupportArenaUsage() ? (mem_info.alloc_type == OrtArenaAllocator) : false; AllocatorPtr allocator_ptr; // create appropriate DeviceAllocatorRegistrationInfo and allocator based on create_arena if (create_arena) { // defaults in case arena_cfg is nullptr (not supplied by the user) size_t max_mem = 0; int arena_extend_strategy = -1; int initial_chunk_size_bytes = -1; int max_dead_bytes_per_chunk = -1; int initial_growth_chunk_size_bytes = -1; int64_t max_power_of_two_extend_bytes = -1L; // override with values from the user supplied arena_cfg object if (arena_cfg) { max_mem = arena_cfg->max_mem; arena_extend_strategy = arena_cfg->arena_extend_strategy; initial_chunk_size_bytes = arena_cfg->initial_chunk_size_bytes; max_dead_bytes_per_chunk = arena_cfg->max_dead_bytes_per_chunk; initial_growth_chunk_size_bytes = arena_cfg->initial_growth_chunk_size_bytes; max_power_of_two_extend_bytes = arena_cfg->max_power_of_two_extend_bytes; } OrtArenaCfg l_arena_cfg{max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, initial_growth_chunk_size_bytes, max_power_of_two_extend_bytes}; AllocatorCreationInfo alloc_creation_info{ [mem_info](int) { return std::make_unique(mem_info); }, 0, create_arena, l_arena_cfg}; allocator_ptr = CreateAllocator(alloc_creation_info); } else { AllocatorCreationInfo alloc_creation_info{[mem_info](int) { return std::make_unique(mem_info); }, 0, create_arena}; allocator_ptr = CreateAllocator(alloc_creation_info); } std::lock_guard lock{mutex_}; return RegisterAllocatorImpl(allocator_ptr); } Status Environment::Initialize(std::unique_ptr logging_manager, const OrtThreadingOptions* tp_options, bool create_global_thread_pools, const OrtKeyValuePairs* config_entries) { auto status = Status::OK(); logging_manager_ = std::move(logging_manager); if (config_entries != nullptr) { config_entries_ = *config_entries; const auto& config_map = config_entries_.Entries(); if (auto iter = config_map.find(kOrtEnvAllowVirtualDevices); iter != config_map.end() && iter->second == "1") { num_allow_virtual_device_uses_ = 1; } } // create thread pools if (create_global_thread_pools) { ORT_RETURN_IF_ERROR(SetGlobalThreadingOptions(*tp_options)); } // Initialize abseil symbolizer for readable stack traces in debug builds. // Restricted to Linux: InitializeSymbolizer(nullptr) relies on /proc/self/exe // to locate the executable, which is Linux-specific. Other platforms either // use a different mechanism (Windows: C++23 ) or would need a real // argv[0] path plumbed through, which is out of scope for this debug helper. #if !defined(NDEBUG) && defined(__linux__) && !defined(__ANDROID__) std::call_once(symbolizerInitOnceFlag, []() { absl::InitializeSymbolizer(nullptr); }); #endif ORT_TRY { #if !defined(ORT_MINIMAL_BUILD) // Register Microsoft domain with min/max op_set version as 1/1. std::call_once(schemaRegistrationOnceFlag, []() { auto& domainToVersionRangeInstance = ONNX_NAMESPACE::OpSchemaRegistry::DomainToVersionRange::Instance(); if (domainToVersionRangeInstance.Map().find(onnxruntime::kMSDomain) == domainToVersionRangeInstance.Map().end()) { // External shared providers may have already added kMSDomain domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSDomain, 1, 1); } domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSExperimentalDomain, 1, 1); domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSNchwcDomain, 1, 1); // we have static registrations for NHWC versions of ONNX operators so this domain needs to extend to the // latest ONNX version auto onnx_version = domainToVersionRangeInstance.LastReleaseVersionMap() .find(ONNX_NAMESPACE::ONNX_DOMAIN) ->second; domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSInternalNHWCDomain, 1, onnx_version); domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kPytorchAtenDomain, 1, 1); #ifdef USE_DML domainToVersionRangeInstance.AddDomainToVersion(onnxruntime::kMSDmlDomain, 1, 1); #endif // Register contributed schemas. // The corresponding kernels are registered inside the appropriate execution provider. #ifndef DISABLE_CONTRIB_OPS RegisterOpSetSchema(); RegisterOpSetSchema(); // internal opset that has NHWC versions of ONNX operators RegisterOpSetSchema(); contrib::RegisterContribSchemas(); #endif #ifdef USE_DML dml::RegisterDmlSchemas(); #endif // ONNX registers these schemas automatically unless static registration was disabled at build time. if (ONNX_NAMESPACE::IsOnnxStaticRegistrationDisabled()) { RegisterOnnxOperatorSetSchema(); #ifndef DISABLE_ML_OPS RegisterOnnxMLOperatorSetSchema(); #endif #if defined(ENABLE_TRAINING_OPS) RegisterOnnxTrainingOperatorSetSchema(); #endif } #if defined(ENABLE_TRAINING_OPS) // preserve this order until : this depends on operatorsetschema registration. training::RegisterTrainingOpSchemas(); #endif #ifdef ENABLE_TRAINING training::GradientBuilderRegistry::GetInstance().RegisterGradientBuilders(); training::LossFunctionRegistry::GetInstance().RegisterNonOperatorLossFunctions(); training::OptimizerBuilderRegistry::GetInstance().RegisterBuilders(); training::OptimizerGraphBuilderRegistry::GetInstance().RegisterGraphBuilders(); // // This was added for a partner team and is most probably no longer in use. // Can be removed once we have the confirmation. training::GraphTransformerRegistry::GetInstance().RegisterExternalGraphTransformers(); #endif }); // Register MemCpy schema; // These ops are internal-only, so register outside of onnx std::vector all_fixed_size_types; std::vector all_tensor_types = OpSchema::all_tensor_types_ir9(); std::vector all_sequence_types = OpSchema::all_tensor_sequence_types(); all_fixed_size_types.insert(all_fixed_size_types.end(), all_tensor_types.begin(), all_tensor_types.end()); all_fixed_size_types.insert(all_fixed_size_types.end(), all_sequence_types.begin(), all_sequence_types.end()); all_fixed_size_types.emplace_back("seq(tensor(bfloat16))"); all_fixed_size_types.erase(std::remove_if(all_fixed_size_types.begin(), all_fixed_size_types.end(), [](const std::string& s) { return s.find("string") != std::string::npos; }), all_fixed_size_types.end()); ORT_ATTRIBUTE_UNUSED ONNX_OPERATOR_SCHEMA(MemcpyFromHost) .Input(0, "X", "input", "T") .Output(0, "Y", "output", "T") .TypeConstraint( "T", all_fixed_size_types, "Constrain to all fixed size tensor and sequence types. If the dtype attribute is not provided this must be a valid output type.") .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput) .SetDoc(R"DOC( Internal copy node )DOC"); ORT_ATTRIBUTE_UNUSED ONNX_OPERATOR_SCHEMA(MemcpyToHost) .Input(0, "X", "input", "T") .Output(0, "Y", "output", "T") .TypeConstraint( "T", all_fixed_size_types, "Constrain to all fixed size tensor and sequence types. If the dtype attribute is not provided this must be a valid output type.") .TypeAndShapeInferenceFunction(propagateShapeAndTypeFromFirstInput) .SetDoc(R"DOC( Internal copy node )DOC"); #endif // !defined(ORT_MINIMAL_BUILD) // fire off startup telemetry (this call is idempotent) const Env& env = Env::Default(); env.GetTelemetryProvider().LogProcessInfo(); #if !defined(ORT_MINIMAL_BUILD) // register internal EPs for autoep selection ORT_RETURN_IF_ERROR(CreateAndRegisterInternalEps()); #endif } ORT_CATCH(const std::exception& ex) { ORT_HANDLE_EXCEPTION([&]() { status = Status(ONNXRUNTIME, common::RUNTIME_EXCEPTION, std::string{"Exception caught: "} + ex.what()); }); } ORT_CATCH(...) { status = Status{ONNXRUNTIME, common::RUNTIME_EXCEPTION}; } return status; } Status Environment::SetGlobalThreadingOptions(const OrtThreadingOptions& tp_options) { if (create_global_thread_pools_) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Global thread pools have already been created, cannot replace them"); } create_global_thread_pools_ = true; OrtThreadPoolParams to = tp_options.intra_op_thread_pool_params; if (to.name == nullptr) { to.name = ORT_TSTR("intra-op"); } intra_op_thread_pool_ = concurrency::CreateThreadPool(&Env::Default(), to, concurrency::ThreadPoolType::INTRA_OP); to = tp_options.inter_op_thread_pool_params; if (to.name == nullptr) { to.name = ORT_TSTR("inter-op"); } inter_op_thread_pool_ = concurrency::CreateThreadPool(&Env::Default(), to, concurrency::ThreadPoolType::INTER_OP); return Status::OK(); } Status Environment::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo& mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { if (provider_type == onnxruntime::kCpuExecutionProvider) { ORT_UNUSED_PARAMETER(options); return CreateAndRegisterAllocator(mem_info, arena_cfg); } #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) if (provider_type == onnxruntime::kCudaExecutionProvider) { if (mem_info.device.MemType() == OrtDevice::MemType::HOST_ACCESSIBLE) { AllocatorPtr allocator_ptr = GetProviderInfo_CUDA().CreateCudaPinnedAllocator( static_cast(mem_info.device.Id()), arena_cfg->max_mem, static_cast(arena_cfg->arena_extend_strategy), arena_cfg); return RegisterAllocatorImpl(allocator_ptr); } else { CUDAExecutionProviderInfo cuda_ep_info; GetProviderInfo_CUDA().CUDAExecutionProviderInfo__FromProviderOptions(options, cuda_ep_info); CUDAExecutionProviderExternalAllocatorInfo external_info = cuda_ep_info.external_allocator_info; AllocatorPtr allocator_ptr = GetProviderInfo_CUDA().CreateCudaAllocator( static_cast(mem_info.device.Id()), arena_cfg->max_mem, static_cast(arena_cfg->arena_extend_strategy), external_info, arena_cfg); return RegisterAllocatorImpl(allocator_ptr); } } #endif return Status{ONNXRUNTIME, common::INVALID_ARGUMENT, provider_type + " is not implemented in CreateAndRegisterAllocatorV2()"}; } #ifdef ORT_ENABLE_SESSION_THREADPOOL_CALLBACKS Status Environment::SetPerSessionWorkCallbacks(const OrtThreadPoolCallbacksConfig& config) { per_session_work_callbacks_ = config; return Status::OK(); } #endif Environment::~Environment() { // need to make sure all the OrtAllocator instances are released prior to any plugin EPs being freed. // this is because any entry in shared_allocators_ wrapping an OrtAllocator from a plugin EP owns the OrtAllocator // instance and will call Release on it. If the plugin EP has been freed the Release will fail. shared_allocators_.clear(); // and as any OrtAllocator instances in shared_ort_allocators_ were owned by values in shared_allocators_ and have // now been released we need to clear that too before calling UnregisterExecutionProviderLibrary(). shared_ort_allocators_.clear(); #if !defined(ORT_MINIMAL_BUILD) // unregister any remaining EP libraries so they're cleaned up in a determistic way. while (!ep_libraries_.empty()) { auto it = ep_libraries_.begin(); ORT_IGNORE_RETURN_VALUE(UnregisterExecutionProviderLibrary(it->first)); } #endif } AllocatorPtr Environment::GetRegisteredSharedAllocator(const OrtMemoryInfo& mem_info) const { std::lock_guard lock{mutex_}; auto it = FindExistingAllocator(shared_allocators_, mem_info, /*match_name*/ false, /*ignore_alignment*/ true); return it != shared_allocators_.end() ? *it : nullptr; } Status Environment::GetSharedAllocator(const OrtMemoryInfo& mem_info, OrtAllocator*& allocator) { std::lock_guard lock{mutex_}; // doesn't matter whether we match a custom allocator or an EP allocator so match_name is false auto it = FindExistingAllocator(shared_ort_allocators_, mem_info, /*match_name*/ false); allocator = it != shared_ort_allocators_.end() ? *it : nullptr; // use the default CPU allocator if there's no custom or EP provided CPU allocator if (!allocator && (mem_info.device.Type() == OrtDevice::CPU && mem_info.device.MemType() == OrtDevice::MemType::DEFAULT)) { if (!default_cpu_ort_allocator_) { auto cpu_ort_allocator = std::make_unique(CPUAllocator::DefaultInstance()); default_cpu_ort_allocator_ = std::move(cpu_ort_allocator); } allocator = default_cpu_ort_allocator_.get(); } return Status::OK(); } OrtKeyValuePairs Environment::GetConfigEntries() const { std::shared_lock lock{config_entries_mutex_}; return config_entries_; // copy } void Environment::InsertOrAssignConfigEntry(std::string key, std::string value) { std::lock_guard lock{config_entries_mutex_}; config_entries_.Add(std::move(key), std::move(value)); } void Environment::RemoveConfigEntry(const std::string& key) { std::lock_guard lock{config_entries_mutex_}; config_entries_.Remove(key.c_str()); } #if !defined(ORT_MINIMAL_BUILD) // // Plugin EP support // namespace { Status CreateDataTransferForFactory(OrtEpFactory& ep_factory, std::unique_ptr& data_transfer) { OrtDataTransferImpl* data_transfer_impl = nullptr; OrtStatus* ort_status = ep_factory.CreateDataTransfer(&ep_factory, &data_transfer_impl); plugin_ep::OrtDataTransferImplUniquePtr owned_impl{data_transfer_impl}; if (ort_status != nullptr) { return ORT_MAKE_STATUS(ONNXRUNTIME, EP_FAIL, "Error creating data transfer: ", ToStatusAndRelease(ort_status).ToString()); } if (owned_impl != nullptr) { data_transfer = std::make_unique(std::move(owned_impl)); } return Status::OK(); } bool AreVirtualDevicesAllowed(std::string_view lib_registration_name) { constexpr std::string_view suffix{".virtual"}; return lib_registration_name.size() >= suffix.size() && lib_registration_name.compare(lib_registration_name.size() - suffix.size(), suffix.size(), suffix) == 0; } } // namespace Status Environment::RegisterExecutionProviderLibrary(const std::string& registration_name, std::unique_ptr ep_library, const std::vector& internal_factories) { #if defined(_WIN32) || defined(ORT_USE_TELEMETRY) const Env& env = Env::Default(); #if defined(ORT_USE_TELEMETRY) const TimePoint tp = std::chrono::high_resolution_clock::now(); #endif // Windows ETW needs these calls even without ORT_USE_TELEMETRY. env.GetTelemetryProvider().LogRegisterEpLibraryStart(registration_name); #endif // defined(_WIN32) || defined(ORT_USE_TELEMETRY) auto status = Status::OK(); ORT_TRY { status = [&]() -> Status { bool registration_succeeded = false; if (ep_libraries_.contains(registration_name)) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "EP library is already registered under ", registration_name); } std::unique_ptr ep_info; ORT_RETURN_IF_ERROR(EpInfo::Create(std::move(ep_library), ep_info, internal_factories)); // Register shared allocators const size_t max_allocator_count = SafeInt(ep_info->execution_devices.size()) * 2; std::vector registered_allocator_memory_infos; registered_allocator_memory_infos.reserve(max_allocator_count); auto rollback_shared_allocator_registrations = gsl::finally([&]() { if (registration_succeeded) { return; } for (auto it = registered_allocator_memory_infos.rbegin(); it != registered_allocator_memory_infos.rend(); ++it) { ORT_IGNORE_RETURN_VALUE(UnregisterAllocatorImpl(**it, /*error_if_not_found*/ false)); } }); for (const auto& ed : ep_info->execution_devices) { // Add shared allocators so they're available without an inference session being required. Do not replace an // existing allocator: we only need one for the OrtMemoryInfo and must preserve user-provided allocators. for (const OrtMemoryInfo* memory_info : {ed->device_memory_info, ed->host_accessible_memory_info}) { if (memory_info == nullptr) { continue; } OrtAllocator* registered_allocator = nullptr; ORT_RETURN_IF_ERROR(CreateSharedAllocatorImpl(*ed, *memory_info, OrtDeviceAllocator, nullptr, ®istered_allocator, /*replace_existing*/ false)); if (registered_allocator != nullptr) { registered_allocator_memory_infos.push_back(memory_info); } } } // Register data transfers std::vector registered_data_transfers; registered_data_transfers.reserve(ep_info->factories.size()); ep_info->data_transfers.reserve(ep_info->factories.size()); auto rollback_data_transfer_registrations = gsl::finally([&]() { if (registration_succeeded) { return; } for (auto it = registered_data_transfers.rbegin(); it != registered_data_transfers.rend(); ++it) { ORT_IGNORE_RETURN_VALUE(data_transfer_mgr_.UnregisterDataTransfer(*it)); } }); for (auto* factory : ep_info->factories) { std::unique_ptr data_transfer; ORT_RETURN_IF_ERROR(CreateDataTransferForFactory(*factory, data_transfer)); if (data_transfer) { auto* data_transfer_ptr = data_transfer.get(); ORT_RETURN_IF_ERROR(data_transfer_mgr_.RegisterDataTransfer(std::move(data_transfer))); registered_data_transfers.push_back(data_transfer_ptr); ep_info->data_transfers.push_back(data_transfer_ptr); } } // Register internal factories std::vector registered_internal_factories; registered_internal_factories.reserve(internal_factories.size()); auto rollback_internal_factory_registration = gsl::finally([&]() { if (registration_succeeded) { return; } for (auto it = registered_internal_factories.rbegin(); it != registered_internal_factories.rend(); ++it) { internal_ep_factories_.erase(*it); } }); for (auto* internal_factory : internal_factories) { if (internal_ep_factories_.insert(internal_factory).second) { registered_internal_factories.push_back(internal_factory); } } // Register EP devices auto rollback_execution_devices_registration = gsl::finally( [&, original_size = execution_devices_.size()]() { if (registration_succeeded) { return; } execution_devices_.erase(execution_devices_.begin() + original_size, execution_devices_.end()); }); execution_devices_.reserve(SafeInt(execution_devices_.size()) + ep_info->execution_devices.size()); std::transform(ep_info->execution_devices.begin(), ep_info->execution_devices.end(), std::back_inserter(execution_devices_), [](const std::unique_ptr& ep_device) { return ep_device.get(); }); // Finally, register the EP library // Notes: // `ep_info`'s target must stay alive for any rollback logic that may need to run. // Directly moving into `ep_libraries_.emplace()` could cause it to be prematurely destroyed if emplace throws // after ownership has transferred from `ep_info`. This is why we first emplace an empty unique_ptr and then // swap into it. // // We ignore `emplace_result.second` since we already checked for an existing entry in `ep_libraries_` above. const auto emplace_result = ep_libraries_.emplace(registration_name, nullptr); emplace_result.first->second.swap(ep_info); registration_succeeded = true; return Status::OK(); }(); } ORT_CATCH(const std::exception& ex) { ORT_HANDLE_EXCEPTION([&]() { status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Failed to register EP library under '", registration_name, "' with error: ", ex.what()); }); } ORT_CATCH(...) { ORT_HANDLE_EXCEPTION([&]() { status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Failed to register EP library under '", registration_name, "' with unknown exception."); }); } #if defined(ORT_USE_TELEMETRY) env.GetTelemetryProvider().LogRegisterEpLibraryEnd(registration_name, status, TimeDiffMicroSeconds(tp)); #elif defined(_WIN32) env.GetTelemetryProvider().LogRegisterEpLibraryEnd(registration_name, status, 0); #endif return status; } Status Environment::CreateAndRegisterInternalEps() { // Capture allow_virtual_devices here (lock-free) and pass it to the internal EP factories at // construction. The internal WebGPU EP factory needs it in GetSupportedDevices but cannot query the // OrtEnv singleton there: internal EPs are registered from Environment::Create, before OrtEnv // publishes p_instance_, so there is no instance to find. const bool allow_virtual_devices = num_allow_virtual_device_uses_ > 0; auto internal_ep_libraries = EpLibraryInternal::CreateInternalEps(allow_virtual_devices); for (auto& ep_library : internal_ep_libraries) { // we do a std::move in the function call so need a valid pointer for the args after the move auto* internal_library_ptr = ep_library.get(); ORT_RETURN_IF_ERROR(RegisterExecutionProviderLibrary(internal_library_ptr->RegistrationName(), std::move(ep_library), {&internal_library_ptr->GetInternalFactory()})); } return Status::OK(); } Status Environment::CreateAndRegisterStaticPluginEps(StaticPluginEpRegistrationToken) { // Intentionally does not take mutex_ and calls the private, non-locking RegisterExecutionProviderLibrary overload. // This is safe because the caller holds the OrtEnv creation mutex, so no other thread can obtain a reference to this // Environment yet. Taking mutex_ here would deadlock if a plugin EP called a locking Environment API from // OrtEpFactory::GetSupportedDevices. auto static_plugin_ep_libraries = CreateStaticPluginEpLibraries(); for (auto& ep_library : static_plugin_ep_libraries) { const std::string registration_name = ep_library->RegistrationName(); ORT_RETURN_IF_ERROR(RegisterExecutionProviderLibrary(registration_name, std::move(ep_library))); } return Status::OK(); } Status Environment::RegisterExecutionProviderLibrary(const std::string& registration_name, const ORTCHAR_T* lib_path) { std::lock_guard lock{mutex_}; #if defined(_WIN32) || defined(ORT_USE_TELEMETRY) std::string lib_file_name = PathToUTF8String(std::filesystem::path(lib_path).filename().native()); Env::Default().GetTelemetryProvider().LogRegisterEpLibraryWithLibPath(registration_name, lib_file_name); #endif std::vector internal_factories; std::unique_ptr ep_library; // An application can allow EP libraries to create virtual devices by using an EP library registration name that // ends in the suffix ".virtual". If so, ORT automatically sets the config key "allow_virtual_devices" to "1" // in the environment. We track the number of libraries that use virtual devices to be able to remove // "allow_virtual_devices" from the config entries when the last library is unregistered. In practice, // we expect only one such library to be registered for cross-compilation. if (AreVirtualDevicesAllowed(registration_name)) { if (num_allow_virtual_device_uses_ == 0) { InsertOrAssignConfigEntry(kOrtEnvAllowVirtualDevices, "1"); } num_allow_virtual_device_uses_ += 1; } // This will create an EpLibraryPlugin or an EpLibraryProviderBridge depending on what the library supports. ORT_RETURN_IF_ERROR(LoadPluginOrProviderBridge(registration_name, lib_path, ep_library, internal_factories)); return RegisterExecutionProviderLibrary(registration_name, std::move(ep_library), internal_factories); } Status Environment::UnregisterExecutionProviderLibrary(const std::string& registration_name) { std::lock_guard lock{mutex_}; if (ep_libraries_.count(registration_name) == 0) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Execution provider library: ", registration_name, " was not registered."); } auto status = Status::OK(); ORT_TRY { auto ep_info = std::move(ep_libraries_[registration_name]); // Clean up environment config entry that may have been added to enable virtual devices. if (AreVirtualDevicesAllowed(registration_name)) { num_allow_virtual_device_uses_ -= 1; if (num_allow_virtual_device_uses_ == 0) { RemoveConfigEntry(kOrtEnvAllowVirtualDevices); } } // remove from map and global list of OrtEpDevice* before unloading so we don't get a leftover entry if // something goes wrong in any of the following steps.. ep_libraries_.erase(registration_name); for (auto* data_transfer : ep_info->data_transfers) { ORT_RETURN_IF_ERROR(data_transfer_mgr_.UnregisterDataTransfer(data_transfer)); } for (auto* internal_factory : ep_info->internal_factories) { internal_ep_factories_.erase(internal_factory); } for (const auto& ed : ep_info->execution_devices) { // remove from global list of OrtEpDevices if (auto it = std::find(execution_devices_.begin(), execution_devices_.end(), ed.get()); it != execution_devices_.end()) { execution_devices_.erase(it); } // unregister any shared allocators. // match only the OrtEpDevice allocator in case the user registered a custom allocator with matching info. const bool error_if_not_found = false; if (ed->device_memory_info != nullptr) { ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(*ed->device_memory_info, error_if_not_found)); } if (ed->host_accessible_memory_info != nullptr) { ORT_RETURN_IF_ERROR(UnregisterAllocatorImpl(*ed->host_accessible_memory_info, error_if_not_found)); } } ep_info.reset(); } ORT_CATCH(const std::exception& ex) { ORT_HANDLE_EXCEPTION([&]() { status = ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Failed to unregister EP library: ", registration_name, " with error: ", ex.what()); }); } return status; } Status Environment::GetHardwareDeviceEpIncompatibilityDetails( const std::string& ep_name, const OrtHardwareDevice* hw, std::unique_ptr& details) const { std::lock_guard lock{mutex_}; OrtEpFactory* matched_factory = nullptr; // Search for a factory whose GetName() matches ep_name exactly. for (const auto& [registration_name, ep_info] : ep_libraries_) { for (OrtEpFactory* factory : ep_info->factories) { if (factory != nullptr && factory->GetName != nullptr) { const char* factory_name = factory->GetName(factory); if (factory_name != nullptr && ep_name == factory_name) { matched_factory = factory; break; } } } if (matched_factory != nullptr) { break; } } if (matched_factory == nullptr) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "No valid factory found for execution provider '", ep_name, "'."); } // ORT creates the details object with default values (compatible) details = std::make_unique(); // If the factory implements GetHardwareDeviceIncompatibilityDetails, let it initialize the details if (matched_factory->GetHardwareDeviceIncompatibilityDetails != nullptr) { OrtStatusPtr status = matched_factory->GetHardwareDeviceIncompatibilityDetails(matched_factory, hw, details.get()); if (status != nullptr) { return ToStatusAndRelease(status); } } // Factory doesn't implement the hook - details remain with default values (compatible) return Status::OK(); } namespace { std::vector SortDevicesByType() { auto& devices = DeviceDiscovery::GetDevices(); std::vector sorted_devices; sorted_devices.reserve(devices.size()); const auto select_by_type = [&](OrtHardwareDeviceType type) { for (const auto& device : devices) { if (device.type == type) { sorted_devices.push_back(&device); } } }; select_by_type(OrtHardwareDeviceType_NPU); select_by_type(OrtHardwareDeviceType_GPU); select_by_type(OrtHardwareDeviceType_CPU); return sorted_devices; } // Returns a static reference to sorted hardware devices. // Hardware devices are discovered once at startup and don't change. const std::vector& GetSortedHardwareDevices() { static const auto sorted_devices = SortDevicesByType(); return sorted_devices; } } // namespace const std::vector& Environment::GetSortedOrtHardwareDevices() const { return GetSortedHardwareDevices(); } Status Environment::CreateSharedAllocator(const OrtEpDevice& ep_device, OrtDeviceMemoryType mem_type, OrtAllocatorType allocator_type, const OrtKeyValuePairs* allocator_options, OrtAllocator** allocator_out) { auto* memory_info = mem_type == OrtDeviceMemoryType_DEFAULT ? ep_device.device_memory_info : ep_device.host_accessible_memory_info; if (memory_info == nullptr) { return Status(ONNXRUNTIME, ORT_INVALID_ARGUMENT, "Invalid memory type for OrtEpDevice."); } std::lock_guard lock{mutex_}; return CreateSharedAllocatorImpl(ep_device, *memory_info, allocator_type, allocator_options, allocator_out, /*replace_existing*/ true); } Status Environment::CreateSharedAllocatorImpl(const OrtEpDevice& ep_device, const OrtMemoryInfo& memory_info, OrtAllocatorType allocator_type, const OrtKeyValuePairs* allocator_options, OrtAllocator** allocator_out, bool replace_existing) { // NOTE: memory_info is guaranteed to come from the OrtEpDevice when this is called if (allocator_type == OrtAllocatorType::OrtArenaAllocator) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "OrtAllocatorType::OrtArenaAllocator is reserved for ONNX Runtime internal usage only. " "The EP implements arena support internally so please use OrtDeviceAllocator and provide " "any arena options via the allocator options."); } // we only want one shared allocator for an OrtDevice in the shared_allocators_ so that it's deterministic which // one will be used for an inference session. ignore the name so that is the case. auto existing_ort_allocator = FindExistingAllocator(shared_ort_allocators_, memory_info, /*match_name*/ true); auto existing_shared_allocator = FindExistingAllocator(shared_allocators_, memory_info, /*match_name*/ false); if (!replace_existing && (existing_ort_allocator != shared_ort_allocators_.end() || existing_shared_allocator != shared_allocators_.end())) { if (allocator_out != nullptr) { *allocator_out = nullptr; } LOGS_DEFAULT(INFO) << "A shared allocator is already registered for " << memory_info << ". Skipping EP allocator creation."; return Status::OK(); } // we need to remove from shared_ort_allocators_ first in case the entry in shared_allocators_ owns the pointer in // shared_ort_allocators_. if (existing_ort_allocator != shared_ort_allocators_.end()) { shared_ort_allocators_.erase(existing_ort_allocator); } if (existing_shared_allocator != shared_allocators_.end()) { shared_allocators_.erase(existing_shared_allocator); } // Create a new allocator. auto* ep_factory = ep_device.ep_factory; OrtAllocator* raw_ort_allocator = nullptr; AllocatorPtr shared_allocator; ORT_RETURN_IF_ERROR(ep_allocator_utils::CreateAndWrapEpAllocator(*ep_factory, memory_info, allocator_options, shared_allocator, &raw_ort_allocator)); ORT_RETURN_IF_NOT(raw_ort_allocator != nullptr, "OrtEpFactory returned a null allocator."); shared_allocators_.reserve(SafeInt(shared_allocators_.size()) + 1); const auto [_, inserted] = shared_ort_allocators_.insert(raw_ort_allocator); ORT_RETURN_IF_NOT(inserted, "OrtEpFactory returned an allocator that is already registered."); shared_allocators_.push_back(std::move(shared_allocator)); if (allocator_out != nullptr) { *allocator_out = raw_ort_allocator; } return Status::OK(); } Status Environment::ReleaseSharedAllocator(const OrtEpDevice& ep_device, OrtDeviceMemoryType mem_type) { auto* memory_info = mem_type == OrtDeviceMemoryType_DEFAULT ? ep_device.device_memory_info : ep_device.host_accessible_memory_info; if (memory_info == nullptr) { return Status(ONNXRUNTIME, ORT_INVALID_ARGUMENT, "Invalid memory type for OrtEpDevice."); } auto status = UnregisterAllocator(*memory_info); return status; } Status Environment::EpInfo::Create(std::unique_ptr library_in, std::unique_ptr& out, const std::vector& internal_factories) { if (!library_in) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "EpLibrary was null"); } auto instance_unique_ptr = std::unique_ptr(new EpInfo()); // can't use make_unique with private ctor EpInfo& instance = *instance_unique_ptr; instance.library = std::move(library_in); instance.internal_factories = internal_factories; ORT_RETURN_IF_ERROR(instance.library->Load()); { auto factories = instance.library->GetFactories(); instance.factories.assign(factories.begin(), factories.end()); } // OrtHardwareDevice instances to pass to GetSupportedDevices. const auto& sorted_devices = GetSortedHardwareDevices(); for (auto* factory_ptr : instance.factories) { ORT_ENFORCE(factory_ptr != nullptr, "Factory pointer was null. EpLibrary should prevent this. Library:", instance.library->RegistrationName()); auto& factory = *factory_ptr; std::array ep_devices{nullptr}; size_t num_ep_devices = 0; ORT_RETURN_IF_ERROR(ToStatusAndRelease( factory.GetSupportedDevices(&factory, sorted_devices.data(), sorted_devices.size(), ep_devices.data(), ep_devices.size(), &num_ep_devices))); const auto* library_path = instance.library->LibraryPath(); for (size_t i = 0; i < num_ep_devices; ++i) { if (ep_devices[i] != nullptr) { // should never happen but just in case... if (library_path != nullptr) { // Add library path to EP metadata if available. // This is used by GenAI for custom library loading so we want to consistently set it. ep_devices[i]->ep_metadata.Add(kOrtEpDevice_EpMetadataKey_LibraryPath, library_path->string()); } instance.execution_devices.emplace_back(ep_devices[i]); // take ownership } } } out = std::move(instance_unique_ptr); return Status::OK(); } Environment::EpInfo::~EpInfo() { execution_devices.clear(); auto status = library->Unload(); if (!status.IsOK()) { LOGS_DEFAULT(WARNING) << "Failed to unload EP library registered under '" << library->RegistrationName() << "' with error: " << status.ErrorMessage(); } } #endif // !defined(ORT_MINIMAL_BUILD) } // namespace onnxruntime