Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[AUTO] Implement device selection before each inference (#39440)

guozhong wang9079d13308fc
diff --git a/src/inference/include/openvino/runtime/auto/properties.hpp b/src/inference/include/openvino/runtime/auto/properties.hpp
index 30d42d50471..1be8d97a929 100644
--- a/src/inference/include/openvino/runtime/auto/properties.hpp
+++ b/src/inference/include/openvino/runtime/auto/properties.hpp
@@ -78,6 +78,14 @@ static constexpr Property<SchedulePolicy> schedule_policy{"SCHEDULE_POLICY"};
/**
* @brief Device utilization thresholds (in percent) used by AUTO for device selection.
+ * A nonempty value enables per-inference device selection for stateless, in-memory AUTO models with an alternative
+ * device, unless the performance mode is THROUGHPUT or CUMULATIVE_THROUGHPUT, or device_bind_buffer is enabled.
+ * In this mode the target device is selected for every inference and inference is serialized per compiled model.
+ * Startup and runtime fallback are not supported: explicitly enabling ENABLE_STARTUP_FALLBACK or
+ * ENABLE_RUNTIME_FALLBACK makes compilation fail. More than one stream is not supported, and MODEL_PRIORITY
+ * is ignored. These restrictions apply only when per-inference selection is active.
+ * The thresholds are ignored, and AUTO behaves as without this property, when the telemetry backend (IPF)
+ * is not available.
* @ingroup ov_runtime_cpp_prop_api
*/
static constexpr Property<std::map<std::string, unsigned>> devices_utilization_threshold{
@@ -95,6 +103,8 @@ using PerfCurveTable = std::map<std::string, std::map<unsigned, float>>;
* AUTO for device selection when set. A lower interpolated score indicates a more preferred device: AUTO ranks
* candidates in ascending order of score and selects the one with the lowest score for the current utilization.
* Device key must be one of "CPU", "iGPU", "dGPU", "NPU".
+ * Setting it enables the per inference device selection, which does not support startup or runtime fallback (see
+ * devices_utilization_threshold).
* @ingroup ov_runtime_cpp_prop_api
*/
static constexpr Property<PerfCurveTable> perf_curve_table{"PERF_CURVE_TABLE"};
@@ -105,8 +115,10 @@ static constexpr Property<PerfCurveTable> perf_curve_table{"PERF_CURVE_TABLE"};
* devices_utilization_threshold when the platform is in low power mode. The value is matched
* against a candidate DeviceInformation::device_name first (e.g. "GPU.0"), then against its base
* device name (e.g. "NPU" also matches a candidate named "NPU.5010").
- * On builds without OV_AUTO_ENABLE_IPF, the telemetry backend always returns unknown, so this
- * property has no effect.
+ * On builds without OV_AUTO_ENABLE_IPF, or when the IPF backend cannot be initialized, the platform is never
+ * considered to be in low power mode, so this property has no effect.
+ * Otherwise setting it enables the per inference device selection, which does not support startup or runtime
+ * fallback (see devices_utilization_threshold).
* @ingroup ov_runtime_cpp_prop_api
*/
static constexpr Property<std::string> low_power_device{"LOW_POWER_DEVICE"};
diff --git a/src/inference/include/openvino/runtime/properties.hpp b/src/inference/include/openvino/runtime/properties.hpp
index 5727fbd6252..25c6c6ccec2 100644
--- a/src/inference/include/openvino/runtime/properties.hpp
+++ b/src/inference/include/openvino/runtime/properties.hpp
@@ -325,6 +325,8 @@ inline std::istream& operator>>(std::istream& is, Priority& priority) {
/**
* @brief High-level OpenVINO model priority hint
* Defines what model should be provided with more performant bounded resource first
+ * AUTO ignores this hint when it selects the target device for every inference (see
+ * ov::intel_auto::devices_utilization_threshold), since no device stays reserved for the model.
* @ingroup ov_runtime_cpp_prop_api
*/
static constexpr Property<Priority> model_priority{"MODEL_PRIORITY"};
diff --git a/src/plugins/auto/src/auto_compiled_model.cpp b/src/plugins/auto/src/auto_compiled_model.cpp
index 128e02547f9..12a24a1661f 100644
--- a/src/plugins/auto/src/auto_compiled_model.cpp
+++ b/src/plugins/auto/src/auto_compiled_model.cpp
@@ -90,6 +90,10 @@ ov::Any AutoCompiledModel::get_property(const std::string& name) const {
auto value = m_context->m_model_priority;
return value ? ((value > 1) ? ov::hint::Priority::LOW : ov::hint::Priority::MEDIUM) : ov::hint::Priority::HIGH;
} else if (name == ov::optimal_number_of_infer_requests) {
+ if (m_context->m_dynamic_device_selection) {
+ // inference is serialized in dynamic mode, so more than one request cannot run at a time
+ return decltype(ov::optimal_number_of_infer_requests)::value_type{1u};
+ }
const unsigned int default_num_for_tput = 4u;
const unsigned int default_num_for_latency = 1u;
unsigned int real = 0;
@@ -204,6 +208,12 @@ ov::Any AutoCompiledModel::get_property(const std::string& name) const {
}
return decltype(ov::optimal_number_of_infer_requests)::value_type {real};
} else if (name == ov::execution_devices) {
+ if (m_context->m_dynamic_device_selection) {
+ const auto active_device = m_scheduler->get_dynamic_active_device();
+ if (!active_device.empty()) {
+ return decltype(ov::execution_devices)::value_type{active_device};
+ }
+ }
ov::Any execution_devices;
auto get_execution_devices = [&execution_devices](std::string exe_devices_string) {
std::vector<std::string> exe_devices = {};
diff --git a/src/plugins/auto/src/auto_schedule.cpp b/src/plugins/auto/src/auto_schedule.cpp
index f4d466a808e..693f71ae84b 100644
--- a/src/plugins/auto/src/auto_schedule.cpp
+++ b/src/plugins/auto/src/auto_schedule.cpp
@@ -5,6 +5,8 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "auto_schedule.hpp"
+#include <stdexcept>
+
#include "async_infer_request.hpp"
#include "openvino/runtime/compilation_context.hpp"
#include "openvino/util/file_util.hpp"
@@ -31,8 +33,9 @@ bool AutoSchedule::select_other_device(const std::string& cur_dev_name) {
} else {
real_device_name = device_name;
}
+ const bool low_power_first_failure = check_and_disable_if_low_power_device_failed(real_device_name);
const auto current_device_iter = deviceChecker().check_and_return_if_device_in_list<DeviceInformation>
- (real_device_name, m_context->m_device_priorities);
+ (real_device_name, m_context->m_device_priorities, true);
if (current_device_iter != m_context->m_device_priorities.end()) {
if (m_context->m_device_priorities.size() == 1) {
LOG_INFO_TAG("No other devices in m_device_priorities");
@@ -42,7 +45,9 @@ bool AutoSchedule::select_other_device(const std::string& cur_dev_name) {
if (is_cpuhelp) {
return true;
}
- } else {
+ } else if (!low_power_first_failure) {
+ // an out-of-list low power target is absent from m_device_priorities, but its first failure
+ // still needs a fallback
LOG_DEBUG_TAG("Already selected the fallback device");
return m_compile_context[FALLBACKDEVICE].m_is_reload_success ? true : false;
}
@@ -50,12 +55,19 @@ bool AutoSchedule::select_other_device(const std::string& cur_dev_name) {
m_compile_context[FALLBACKDEVICE].m_is_load_success = false;
m_compile_context[FALLBACKDEVICE].m_worker_name = "";
m_compile_context[FALLBACKDEVICE].m_is_reload_success = false;
+ // a previous fallback device is being replaced, drop its reservation
+ if (!m_compile_context[FALLBACKDEVICE].m_priority_released &&
+ !m_compile_context[FALLBACKDEVICE].m_device_info.unique_name.empty()) {
+ m_plugin->unregister_priority(m_context->m_model_priority,
+ m_compile_context[FALLBACKDEVICE].m_device_info.unique_name);
+ }
+ m_compile_context[FALLBACKDEVICE].m_priority_released = false;
m_compile_context[FALLBACKDEVICE].m_device_info =
m_plugin->select_device(m_context->m_device_priorities,
m_compile_context[FALLBACKDEVICE].m_model_precision,
m_context->m_model_priority,
m_context->m_selection_policy,
- m_context->m_low_power_device);
+ (m_context->m_low_power_device_unavailable ? std::nullopt : m_context->m_low_power_device));
try {
m_compile_context[FALLBACKDEVICE].m_task();
// FALLBACKDEVICE need to be load again if infer failed, so reset promise here
@@ -80,10 +92,32 @@ bool AutoSchedule::select_other_device(const std::string& cur_dev_name) {
}
}
+bool AutoSchedule::check_and_disable_if_low_power_device_failed(const std::string& failed_device_name) const {
+ if (m_context->m_low_power_device && m_context->m_low_power_device->device_name == failed_device_name &&
+ !m_context->m_low_power_device_unavailable.exchange(true)) {
+ LOG_WARNING_TAG("low_power_device:%s failed, excluding it from future selection",
+ failed_device_name.c_str());
+ return true;
+ }
+ return false;
+}
+
+DeviceName AutoSchedule::get_dynamic_active_device() const {
+ std::lock_guard<std::mutex> lock(m_gate_mutex);
+ return m_gate_current_device;
+}
+
void AutoSchedule::init() {
if (m_context->m_bind_buffer) {
LOG_INFO_TAG("bind buffer supported only under cumulative mode, ignoring");
}
+ if (m_context->m_dynamic_device_selection) {
+ // snapshot of the graph for on-demand compilation
+ m_dynamic_model = m_context->m_model->clone();
+ m_dynamic_executor = m_plugin->get_executor_manager()->get_idle_cpu_streams_executor(
+ ov::threading::IStreamsExecutor::Config{"AutoDynamicSchedule", 1, 0});
+ LOG_INFO_TAG("[dynamic] device is re-selected for every inference, inference is serialized per compiled model");
+ }
// initialize cpuHelpReleasetime
m_cpuhelp_release_time = std::chrono::steady_clock::now();
std::string profilingTask = "AutoSchedule::AutoSchedule:AutoMode";
@@ -100,7 +134,11 @@ void AutoSchedule::init() {
m_compile_context[ACTUALDEVICE].m_model_precision,
m_context->m_model_priority,
m_context->m_selection_policy,
- m_context->m_low_power_device);
+ (m_context->m_low_power_device_unavailable ? std::nullopt : m_context->m_low_power_device));
+ if (m_context->m_dynamic_device_selection) {
+ // nothing was reserved by select_device() in this mode
+ m_compile_context[ACTUALDEVICE].m_priority_released = true;
+ }
auto load_device_task = [&](AutoCompileContext* context_ptr, const std::shared_ptr<ov::Model>& model) {
try_to_compile_model(*context_ptr, model);
@@ -198,6 +236,13 @@ void AutoSchedule::init() {
m_worker_requests[device.device_name];
m_infer_pipeline_tasks_device_specific[device.device_name] = nullptr;
}
+ // an out-of-list low power device is not covered above but can be compiled concurrently with CPU_HELP
+ if (m_context->m_low_power_device) {
+ const auto& low_power_name = m_context->m_low_power_device->device_name;
+ m_idle_worker_requests[low_power_name];
+ m_worker_requests[low_power_name];
+ m_infer_pipeline_tasks_device_specific[low_power_name] = nullptr;
+ }
m_idle_worker_requests["CPU_HELP"];
m_worker_requests["CPU_HELP"];
m_infer_pipeline_tasks_device_specific["CPU_HELP"] = nullptr;
@@ -253,7 +298,7 @@ void AutoSchedule::init() {
: cpuhelp_all_end_times.back() - cpuhelp_all_start_times.front();
m_cpuhelp_fps = cpuhelp_all_start_times.size() * 1000 / duration.count();
LOG_INFO_TAG("CPU_HELP: first inference time:%lf ms", first_infer_time.count());
- LOG_INFO_TAG("CPU_HELP:infer:%ld", m_cpuhelp_infer_count);
+ LOG_INFO_TAG("CPU_HELP:infer:%zu", m_cpuhelp_infer_count);
LOG_INFO_TAG("CPU_HELP:fps:%lf", m_cpuhelp_fps);
}
});
@@ -268,8 +313,14 @@ void AutoSchedule::init() {
}
};
m_executor->run(std::move(recycleTask));
- } else if (m_context->m_device_priorities.size() != 1 && m_context->m_str_devices_initial.size() != 1 &&
- m_context->m_runtime_fallback) {
+ } else if (m_context->m_dynamic_device_selection ||
+ (m_context->m_runtime_fallback &&
+ ((m_context->m_device_priorities.size() != 1 && m_context->m_str_devices_initial.size() != 1) ||
+ // an out-of-list low power device can still fall back onto the candidates at runtime
+ !deviceChecker().check_if_device_in_list<DeviceInformation>(
+ m_compile_context[ACTUALDEVICE].m_device_info.device_name,
+ m_context->m_device_priorities,
+ true)))) {
// The performance will has some drop then m_passthrough_compiled_model when enable ENABLE_RUNTIME_FALLBACK
for (auto&& device : m_context->m_device_priorities) {
// initialize containers before run async task
@@ -278,6 +329,14 @@ void AutoSchedule::init() {
m_infer_pipeline_tasks_device_specific[device.device_name] = nullptr;
}
m_compile_context[ACTUALDEVICE].m_task();
+ if (m_context->m_dynamic_device_selection && m_compile_context[ACTUALDEVICE].m_is_already) {
+ // devices that failed to compile at startup were pruned from this copy only
+ m_context->m_device_priorities = m_compile_context[ACTUALDEVICE].m_meta_devices;
+ const auto& initial_device = m_compile_context[ACTUALDEVICE].m_device_info.device_name;
+ m_dynamic_compiled_models[initial_device] = m_compile_context[ACTUALDEVICE].m_compiled_model;
+ m_gate_current_device = initial_device;
+ LOG_INFO_TAG("[dynamic] initial target device:%s", initial_device.c_str());
+ }
} else {
// Only one device, or multiple devices of the same type (e.g., all GPU devices, including iGPU and dGPU), can
// use passthrough model; no need to compile asynchronously
@@ -348,7 +407,12 @@ void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::
LOG_WARNING_TAG("Device: [%s]: Compile model failure: %s", device.c_str(), e.what());
context.m_is_load_success = false;
}
- if (context.m_is_load_success || cur_dev_is_cpu) {
+ const bool low_power_first_failure =
+ !context.m_is_load_success && check_and_disable_if_low_power_device_failed(device);
+ // a failed low power CPU picked at startup must still cascade to the candidates
+ const bool retry_actual_low_power_device =
+ low_power_first_failure && &context == &m_compile_context[ACTUALDEVICE];
+ if (context.m_is_load_success || (cur_dev_is_cpu && !retry_actual_low_power_device)) {
return;
}
// need to recompile model, unregister it's priority
@@ -357,7 +421,10 @@ void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::
// configure 0 dGPU, 1 NPU, if dGPU compile failed,
// the result will be not sure, maybe two models are compiled into NPU,
// maybe 0 is compiled to NPU, 1 is compiled to iGPU
- m_plugin->unregister_priority(m_context->m_model_priority, context.m_device_info.unique_name);
+ if (!context.m_priority_released) {
+ m_plugin->unregister_priority(m_context->m_model_priority, context.m_device_info.unique_name);
+ context.m_priority_released = true;
+ }
// remove the current device from device_list
auto erase_device = deviceChecker().check_and_return_if_device_in_list(device, device_list, true);
if (erase_device != device_list.end())
@@ -372,10 +439,21 @@ void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::
context.m_model_precision,
m_context->m_model_priority,
m_context->m_selection_policy,
- m_context->m_low_power_device);
+ (m_context->m_low_power_device_unavailable ? std::nullopt : m_context->m_low_power_device));
} catch (const ov::Exception&) {
return;
}
+ // select_device() registered the reselected device, so a failure on it has to unregister it again, unless
+ // the dynamic selection reserved nothing
+ context.m_priority_released = m_context->m_dynamic_device_selection;
+ if (m_context->m_dynamic_device_selection) {
+ const auto cached = m_dynamic_compiled_models.find(context.m_device_info.device_name);
+ if (cached != m_dynamic_compiled_models.end()) {
+ context.m_compiled_model = cached->second;
+ context.m_is_load_success = true;
+ return;
+ }
+ }
// if the select device is CPU, need to check the config of m_compile_context[CPU]
// if they are same, do not need to compile again
cur_dev_is_cpu = (context.m_device_info.device_name.find("CPU") != std::string::npos);
@@ -451,6 +529,9 @@ void AutoSchedule::wait_actual_compiled_model_ready() const {
}
bool AutoSchedule::schedule_to_worker_infer_request(ov::threading::Task pipeline_task, DeviceName preferred_device) {
+ if (m_context->m_dynamic_device_selection) {
+ return schedule_dynamic_task(std::move(pipeline_task), preferred_device);
+ }
std::vector<DeviceInformation> devices;
// AUTO work mode
// Devices that fail infer will be removed from the priority list in the callback, need lock here
@@ -497,7 +578,297 @@ bool AutoSchedule::schedule_to_worker_infer_request(ov::threading::Task pipeline
return false;
}
+bool AutoSchedule::schedule_dynamic_task(ov::threading::Task pipeline_task, const DeviceName& preferred_device) {
+ std::shared_ptr<ov::threading::IStreamsExecutor> executor;
+ {
+ std::lock_guard<std::mutex> lock(m_gate_mutex);
+ if (m_dynamic_shutdown) {
+ // AutoSchedule is being torn down, do not touch m_dynamic_executor anymore
+ return false;
+ }
+ if (m_gate_busy) {
+ m_gate_pending_tasks.emplace_back(std::move(pipeline_task), preferred_device);
+ LOG_DEBUG_TAG("[dynamic] an inference is still running, request queued, queue size:%zu",
+ m_gate_pending_tasks.size());
+ return false;
+ }
+ m_gate_busy = true;
+ executor = m_dynamic_executor;
+ ++m_active_dispatch;
+ }
+ // dispatching is offloaded so that neither start_async() nor the completion callback of a device is blocked
+ // by the device re-selection and by the compilation of the model on a newly selected device
+ submit_dynamic_dispatch(executor, std::move(pipeline_task), preferred_device);
+ return true;
+}
+
+void AutoSchedule::submit_dynamic_dispatch(const std::shared_ptr<ov::threading::IStreamsExecutor>& executor,
+ ov::threading::Task pipeline_task,
+ const DeviceName& preferred_device) {
+ executor->run([this, task = std::move(pipeline_task), preferred_device]() mutable {
+ // runs last in this body, so ~AutoSchedule() waiting on it never frees this under a live dispatch;
+ // the task stays owned by the closure so dropping its last reference cannot run ~AutoSchedule() here
+ struct DispatchDone {
+ AutoSchedule* self;
+ ~DispatchDone() {
+ self->end_dynamic_dispatch();
+ }
+ } done{this};
+ dispatch_dynamic_task(task, preferred_device);
+ });
+}
+
+void AutoSchedule::end_dynamic_dispatch() {
+ std::lock_guard<std::mutex> lock(m_gate_mutex);
+ if (--m_active_dispatch == 0) {
+ m_dispatch_done.notify_all();
+ }
+}
+
+void AutoSchedule::dispatch_dynamic_task(ov::threading::Task& pipeline_task, const DeviceName& preferred_device) {
+ try {
+ DeviceInformation device;
+ if (!preferred_device.empty()) {
+ std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
+ const auto iter = deviceChecker().check_and_return_if_device_in_list<DeviceInformation>(
+ preferred_device, m_context->m_device_priorities, true);
+ if (iter != m_context->m_device_priorities.end()) {
+ device = *iter;
+ } else {
+ // a remote tensor of the low power device pins it even though it is not a candidate
+ const auto& low_power = m_context->m_low_power_device;
+ OPENVINO_ASSERT(low_power && !m_context->m_low_power_device_unavailable &&
+ low_power->device_name == preferred_device,
+ "The preferred device should be one of the candidate devices or the low power device");
+ device = *low_power;
+ }
+ LOG_DEBUG_TAG("[dynamic] request is pinned to device:%s by a remote tensor, skip device re-selection",
+ device.device_name.c_str());
+ } else {
+ device = select_dynamic_device();
+ }
+ const bool is_pinned = !preferred_device.empty();
+ const auto pinned_device_name = device.device_name;
+ OPENVINO_ASSERT(ensure_device_ready(device),
+ get_log_tag(),
+ ": failed to compile the model on the selected device ",
+ device.device_name);
+ // reject if a pinned request ended up compiled on a different device
+ OPENVINO_ASSERT(!is_pinned || device.device_name == pinned_device_name,
+ get_log_tag(),
+ ": failed to compile the model on the device pinned by the remote tensor ",
+ pinned_device_name);
+ const auto& device_name = device.device_name;
+ {
+ std::lock_guard<std::mutex> lock(m_gate_mutex);
+ if (m_gate_current_device == device_name) {
+ LOG_DEBUG_TAG("[dynamic] target device:%s is unchanged, reuse its idle worker", device_name.c_str());
+ } else {
+ LOG_INFO_TAG("[dynamic] target device switched from %s to %s",
+ m_gate_current_device.empty() ? "none" : m_gate_current_device.c_str(),
+ device_name.c_str());
+ m_gate_current_device = device_name;
+ m_dynamic_switch_count++;
+ }
+ }
+ m_dynamic_infer_count++;
+ const bool dispatched = run_pipeline_task(pipeline_task, m_idle_worker_requests[device_name], device_name);
+ OPENVINO_ASSERT(dispatched, get_log_tag(), ": no idle infer request available on device ", device_name);
+ // a failure to start the request is swallowed by the pipeline and no callback returns the worker, so give
+ // it back here and open the gate
+ if (m_this_worker_infer_request && m_this_worker_infer_request->m_dispatch_failed) {
+ auto* worker = m_this_worker_infer_request;
+ worker->m_dispatch_failed = false;
+ // the start was recorded but the final stage never runs to record its end
+ INFO_RUN([worker]() {
+ if (worker->m_start_times.size() > worker->m_end_times.size()) {
+ worker->m_start_times.pop_back();
+ }
+ });
+ m_idle_worker_requests[device_name].try_push(std::make_pair(worker->m_index, worker));
+ release_execution_slot();
+ }
+ } catch (const std::exception&) {
+ m_this_worker_infer_request = nullptr;
+ release_execution_slot();
+ // report the failure through the pipeline, otherwise the request would never complete; the task is gone
+ // once it has been dispatched, so the exception must not be left behind on this thread in that case
+ if (pipeline_task) {
+ m_this_scheduling_exception = std::current_exception();
+ pipeline_task();
+ }
+ }
+}
+
+DeviceInformation AutoSchedule::select_dynamic_device() {
+ const auto start_time = std::chrono::steady_clock::now();
+ DeviceInformation device;
+ {
+ std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
+ const auto low_power_device =
+ m_context->m_low_power_device_unavailable ? std::nullopt : m_context->m_low_power_device;
+ // the low power device can run on its own once every other candidate has been excluded
+ OPENVINO_ASSERT(!m_context->m_device_priorities.empty() ||
+ (low_power_device && m_plugin->get_low_power_mode().value_or(false)),
+ get_log_tag(), ": no candidate device left to run the inference");
+ device = m_plugin->select_device(m_context->m_device_priorities,
+ m_context->m_model_precision,
+ m_context->m_model_priority,
+ m_context->m_selection_policy,
+ low_power_device);
+ }
+ // select_device() reserves nothing in the dynamic selection
+ LOG_DEBUG_TAG("[dynamic] re-selected device:%s in %lf ms",
+ device.device_name.c_str(),
+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start_time).count());
+ return device;
+}
+
+bool AutoSchedule::ensure_device_ready(DeviceInformation& device) {
+ if (m_dynamic_compiled_models.find(device.device_name) != m_dynamic_compiled_models.end()) {
+ return true;
+ }
+ const auto start_time = std::chrono::steady_clock::now();
+ const auto requested_device_name = device.device_name;
+ AutoCompileContext context;
+ context.m_device_info = device;
+ context.m_model_precision = m_context->m_model_precision;
+ {
+ std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
+ context.m_meta_devices = m_context->m_device_priorities;
+ }
+ const auto candidate_devices = context.m_meta_devices;
+ LOG_INFO_TAG("[dynamic] device:%s is used for the first time, compiling the model", device.device_name.c_str());
+ // select_dynamic_device() reserved nothing for the requested device
+ context.m_priority_released = true;
+ try_to_compile_model(context, m_dynamic_model ? m_dynamic_model->clone() : nullptr);
+ const bool fell_back_to_other_device = context.m_device_info.device_name != requested_device_name;
+ // try_to_compile_model() drops every device that failed to compile from its own candidate list
+ std::vector<std::string> failed_devices;
+ for (const auto& candidate : candidate_devices) {
+ const auto remaining = std::find_if(context.m_meta_devices.begin(),
+ context.m_meta_devices.end(),
+ [&candidate](const DeviceInformation& remaining_device) {
+ return remaining_device.device_name == candidate.device_name;
+ });
+ if (remaining == context.m_meta_devices.end()) {
+ failed_devices.push_back(candidate.device_name);
+ }
+ }
+ const auto add_failed_device = [&failed_devices](const std::string& name) {
+ if (std::find(failed_devices.begin(), failed_devices.end(), name) == failed_devices.end()) {
+ failed_devices.push_back(name);
+ }
+ };
+ if (fell_back_to_other_device || !context.m_is_load_success) {
+ add_failed_device(requested_device_name);
+ }
+ if (!context.m_is_load_success) {
+ // a failed CPU is never erased from the candidate list by try_to_compile_model(), so it is not found above
+ add_failed_device(context.m_device_info.device_name);
+ }
+ if (!failed_devices.empty()) {
+ // exclude them from the shared candidate list so future inferences stop retrying them
+ std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
+ for (const auto& failed_device : failed_devices) {
+ const auto iter = deviceChecker().check_and_return_if_device_in_list<DeviceInformation>(
+ failed_device, m_context->m_device_priorities, true);
+ if (iter != m_context->m_device_priorities.end()) {
+ m_context->m_device_priorities.erase(iter);
+ LOG_WARNING_TAG("[dynamic] device:%s failed to compile, excluding it from future selection",
+ failed_device.c_str());
+ }
+ }
+ }
+ if (!context.m_is_load_success) {
+ LOG_WARNING_TAG("[dynamic] compiling the model on device:%s failed, %s",
+ device.device_name.c_str(),
+ context.m_err_message.c_str());
+ return false;
+ }
+ device = context.m_device_info;
+ if (m_dynamic_compiled_models.find(device.device_name) == m_dynamic_compiled_models.end()) {
+ generate_workers(device.device_name, context.m_compiled_model);
+ m_dynamic_compiled_models[device.device_name] = context.m_compiled_model;
+ } else {
+ // the fallback landed on a device this schedule already compiled and has a worker for;
+ // reuse it instead of generating a second (duplicate) worker for the same device
+ LOG_DEBUG_TAG("[dynamic] fallback device:%s is already cached, reusing its compiled model/worker",
+ device.device_name.c_str());
+ }
+ LOG_INFO_TAG("[dynamic] device:%s is ready in %lf ms",
+ device.device_name.c_str(),
+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start_time).count());
+ return true;
+}
+
+void AutoSchedule::release_execution_slot() {
+ std::pair<ov::threading::Task, DeviceName> next;
+ std::shared_ptr<ov::threading::IStreamsExecutor> executor;
+ {
+ std::unique_lock<std::mutex> lock(m_gate_mutex);
+ if (m_dynamic_shutdown) {
+ // AutoSchedule is being torn down, do not touch m_dynamic_executor anymore; the queued requests can no
+ // longer run, so they are failed instead of being left to hang their callers.
+ // The gate stays busy meanwhile so that ~AutoSchedule() does not finish under them.
+ auto abandoned_tasks = std::move(m_gate_pending_tasks);
+ m_gate_pending_tasks.clear();
+ lock.unlock();
+ if (!abandoned_tasks.empty()) {
+ // it is surfaced to the caller as an ov::Exception by the scheduling stage of the pipeline
+ const auto cancelled =
+ std::make_exception_ptr(std::runtime_error("Model is being destroyed, the request is cancelled"));
+ for (auto& abandoned : abandoned_tasks) {
+ m_this_scheduling_exception = cancelled;
+ abandoned.first();
+ }
+ }
+ lock.lock();
+ m_gate_busy = false;
+ // notified under the lock: it is the last access of the device callback to this object
+ m_dispatch_done.notify_all();
+ return;
+ }
+ m_gate_busy = false;
+ if (m_gate_pending_tasks.empty()) {
+ // logged under the lock: once it is released ~AutoSchedule() may run, so this must not be touched
+ LOG_DEBUG_TAG("[dynamic] inference finished, no request is waiting");
+ return;
+ }
+ next = std::move(m_gate_pending_tasks.front());
+ m_gate_pending_tasks.pop_front();
+ m_gate_busy = true;
+ executor = m_dynamic_executor;
+ ++m_active_dispatch;
+ }
+ LOG_DEBUG_TAG("[dynamic] inference finished, dispatching the next queued request");
+ submit_dynamic_dispatch(executor, std::move(next.first), next.second);
+}
+
AutoSchedule::~AutoSchedule() {
+ std::shared_ptr<ov::threading::IStreamsExecutor> dynamic_executor;
+ {
+ // serialize with schedule_dynamic_task()/release_execution_slot(), which read/snapshot
+ // m_dynamic_executor under the same lock, so none of them races with resetting it below
+ std::unique_lock<std::mutex> lock(m_gate_mutex);
+ m_dynamic_shutdown = true;
+ dynamic_executor = std::move(m_dynamic_executor);
+ // in-flight dispatch tasks hold a raw this and may still finish a failed request, and the device completion
+ // callback of a running inference still uses this after it has notified the user request, so drain both
+ m_dispatch_done.wait(lock, [this] {
+ return m_active_dispatch == 0 && !m_gate_busy;
+ });
+ }
+ if (dynamic_executor) {
+ LOG_INFO_TAG("[dynamic] total inference:%zu, device switch:%zu",
+ m_dynamic_infer_count.load(),
+ m_dynamic_switch_count.load());
+ // do not clear the executor manager's "AutoDynamicSchedule" entry here: clear() works by name and would
+ // also evict the executors of other alive AutoSchedule instances. get_idle_cpu_streams_executor() only
+ // hands out an executor nobody else holds, so instances never share one; just drop our own reference
+ // and let the executor manager keep it for reuse.
+ dynamic_executor.reset();
+ }
// this is necessary to guarantee member destroyed after getting future
if (m_compile_context[CPU].m_is_enabled) {
m_exitflag = true;
@@ -507,9 +878,14 @@ AutoSchedule::~AutoSchedule() {
m_plugin->get_executor_manager()->clear("AutoDeviceAsyncCompile");
m_executor.reset();
}
- if (m_plugin)
+ if (m_plugin && !m_context->m_dynamic_device_selection) {
m_plugin->unregister_priority(m_context->m_model_priority,
m_compile_context[ACTUALDEVICE].m_device_info.unique_name);
+ const auto& fallback = m_compile_context[FALLBACKDEVICE];
+ if (!fallback.m_priority_released && !fallback.m_device_info.unique_name.empty()) {
+ m_plugin->unregister_priority(m_context->m_model_priority, fallback.m_device_info.unique_name);
+ }
+ }
if (m_context) {
std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
m_context->m_device_priorities.clear();
diff --git a/src/plugins/auto/src/auto_schedule.hpp b/src/plugins/auto/src/auto_schedule.hpp
index b415043f441..50f9366f1f6 100644
--- a/src/plugins/auto/src/auto_schedule.hpp
+++ b/src/plugins/auto/src/auto_schedule.hpp
@@ -5,6 +5,9 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
+#include <condition_variable>
+#include <deque>
+
#include "schedule.hpp"
#include "async_infer_request.hpp"
@@ -16,6 +19,8 @@ public:
using Ptr = std::shared_ptr<AutoSchedule>;
virtual ~AutoSchedule();
AutoCompileContext m_compile_context[CONTEXTNUM];
+ // device the latest dynamic inference was dispatched to, empty until one has been dispatched
+ DeviceName get_dynamic_active_device() const;
private:
void init() override;
@@ -31,6 +36,28 @@ private:
SoCompiledModel wait_first_compiled_model_ready() override;
void try_to_compile_model(AutoCompileContext& context, const std::shared_ptr<ov::Model>& model) override;
bool select_other_device(const std::string& cur_dev_name) override;
+ void release_execution_slot() override;
+ /**
+ * @brief Serialize the incoming request behind the execution gate when per inference device selection is on.
+ * @return true if the request was handed over for dispatching, false if it was queued.
+ */
+ bool schedule_dynamic_task(ov::threading::Task pipeline_task, const DeviceName& preferred_device);
+ void dispatch_dynamic_task(ov::threading::Task& pipeline_task, const DeviceName& preferred_device);
+ // runs dispatch_dynamic_task() on the executor;
+ // the caller must have incremented m_active_dispatch under m_gate_mutex
+ void submit_dynamic_dispatch(const std::shared_ptr<ov::threading::IStreamsExecutor>& executor,
+ ov::threading::Task pipeline_task,
+ const DeviceName& preferred_device);
+ void end_dynamic_dispatch();
+ DeviceInformation select_dynamic_device();
+ /**
+ * @brief Compile the model on the given device unless it is already cached, and create its workers.
+ * @note device is updated in place when the compilation falls back to another candidate device.
+ */
+ bool ensure_device_ready(DeviceInformation& device);
+ // disables the configured low_power_device override if it matches the failed device
+ // @return true only for the call that disabled it, i.e. the first failure of that device
+ bool check_and_disable_if_low_power_device_failed(const std::string& failed_device_name) const;
size_t m_cpuhelp_infer_count = 0;
double m_cpuhelp_fps = 0.0;
mutable std::once_flag m_oc;
@@ -38,6 +65,21 @@ private:
std::future<void> m_firstload_future;
std::promise<void> m_firstload_promise;
bool m_exitflag = {false};
+ std::shared_ptr<ov::threading::IStreamsExecutor> m_dynamic_executor;
+ std::shared_ptr<ov::Model> m_dynamic_model;
+ mutable std::mutex m_gate_mutex;
+ bool m_gate_busy = false;
+ // guarded by m_gate_mutex; set once in ~AutoSchedule() so in-flight dynamic tasks stop touching
+ // m_dynamic_executor once teardown has started
+ bool m_dynamic_shutdown = false;
+ // guarded by m_gate_mutex; dispatch tasks on m_dynamic_executor still running and holding a raw this
+ size_t m_active_dispatch = 0;
+ std::condition_variable m_dispatch_done;
+ DeviceName m_gate_current_device;
+ std::deque<std::pair<ov::threading::Task, DeviceName>> m_gate_pending_tasks;
+ DeviceMap<SoCompiledModel> m_dynamic_compiled_models;
+ std::atomic<size_t> m_dynamic_infer_count = {0};
+ std::atomic<size_t> m_dynamic_switch_count = {0};
};
} // namespace auto_plugin
} // namespace ov
diff --git a/src/plugins/auto/src/common.hpp b/src/plugins/auto/src/common.hpp
index 9e114c48a22..b1c6fbfa775 100644
--- a/src/plugins/auto/src/common.hpp
+++ b/src/plugins/auto/src/common.hpp
@@ -5,8 +5,10 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
+#include <atomic>
#include <filesystem>
#include <map>
+#include <optional>
#include <string>
#include "openvino/runtime/auto/properties.hpp"
@@ -68,6 +70,19 @@ struct WorkerInferRequest {
std::list<Time> m_end_times;
int m_index = 0;
AutoImmediateExecutor::Ptr m_fallback_exec;
+ // the request could not be started, so its completion callback will never hand this worker back
+ bool m_dispatch_failed = false;
+};
+
+// flags the worker as not dispatched unless dismissed, i.e. when its scope is left by an exception
+struct DispatchFailureGuard {
+ WorkerInferRequest* m_worker;
+ bool m_dismissed = false;
+ ~DispatchFailureGuard() {
+ if (!m_dismissed) {
+ m_worker->m_dispatch_failed = true;
+ }
+ }
};
struct ThisRequestExecutor : public ov::threading::ITaskExecutor {
@@ -77,7 +92,10 @@ struct ThisRequestExecutor : public ov::threading::ITaskExecutor {
void run(ov::threading::Task task) override {
(*m_workptrptr)->m_task = std::move(task);
(*m_workptrptr)->m_fallback_exec = m_fallback_exec;
+ // the completion callback may already own the worker once start_async() returns
+ DispatchFailureGuard guard{*m_workptrptr};
(*m_workptrptr)->m_inferrequest->start_async();
+ guard.m_dismissed = true;
};
WorkerInferRequest** m_workptrptr = nullptr;
AutoImmediateExecutor::Ptr m_fallback_exec;
@@ -203,6 +221,8 @@ class Plugin;
struct DeviceSelectionPolicy {
std::unordered_map<std::string, unsigned> utilization_thresholds;
ov::intel_auto::PerfCurveTable perf_curve_table;
+ // per inference selection takes no part in the model priority arbitration, so it reserves nothing
+ bool reserve_device = true;
};
class ScheduleContext : public std::enable_shared_from_this<ScheduleContext> {
@@ -231,7 +251,10 @@ public:
SoCompiledModel m_hw_compiled_model;
std::string m_model_precision;
DeviceSelectionPolicy m_selection_policy;
- std::string m_low_power_device;
+ std::optional<DeviceInformation> m_low_power_device;
+ std::atomic<bool> m_low_power_device_unavailable = false;
+ // re-select the target device for every incoming inference, turned on by the resource aware selection properties
+ bool m_dynamic_device_selection = false;
// hold the resource of static variable to avoid the unexpected destruction.
std::shared_ptr<std::mutex> m_mtx;
std::shared_ptr<std::map<unsigned int, std::list<std::string>>> m_priority_map;
@@ -253,6 +276,8 @@ struct AutoCompileContext {
std::string m_err_message;
ov::threading::Task m_task;
std::string m_worker_name = "";
+ // the priority registration of m_device_info has already been dropped by the caller
+ bool m_priority_released = false;
};
enum AutoCompileContextIndex {
diff --git a/src/plugins/auto/src/plugin.cpp b/src/plugins/auto/src/plugin.cpp
index fefdadef387..0e2522d00e4 100644
--- a/src/plugins/auto/src/plugin.cpp
+++ b/src/plugins/auto/src/plugin.cpp
@@ -462,8 +462,9 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model_impl(const std::filesy
bool is_cumulative =
(auto_s_context->m_performance_hint == ov::hint::PerformanceMode::CUMULATIVE_THROUGHPUT) ? true : false;
std::list<DeviceInformation> devices_with_priority(support_devices.begin(), support_devices.end());
+ bool is_stateful_model = false;
if (model_path.empty()) {
- support_devices = filter_device_by_model(support_devices_by_property, model, load_config);
+ support_devices = filter_device_by_model(support_devices_by_property, model, load_config, is_stateful_model);
} else {
// AUTO / MULTI don't support caching explicitly, but can redirect this functionality to actual HW plugin
LOG_INFO_TAG("compile model with model path");
@@ -510,11 +511,114 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model_impl(const std::filesy
}
auto low_power_device = load_config.get_property(ov::intel_auto::low_power_device);
if (!low_power_device.empty()) {
- auto_s_context->m_low_power_device = low_power_device;
- LOG_INFO_TAG("low_power_device is set to %s", low_power_device.c_str());
+ OPENVINO_ASSERT(!is_meta_device(low_power_device),
+ "The meta device should not be used as low_power_device: ",
+ low_power_device);
+ try {
+ // prefer a candidate matching by exact or base name, so "GPU" keeps resolving to the listed GPU
+ const auto candidate = std::find_if(
+ devices_with_priority.begin(),
+ devices_with_priority.end(),
+ [&low_power_device](const DeviceInformation& device) {
+ return device.device_name == low_power_device ||
+ ov::DeviceIDParser(device.device_name).get_device_name() == low_power_device;
+ });
+ if (candidate != devices_with_priority.end()) {
+ auto_s_context->m_low_power_device = *candidate;
+ } else {
+ auto resolved_low_power_device = parse_meta_devices(low_power_device, full_property);
+ if (!resolved_low_power_device.empty())
+ auto_s_context->m_low_power_device = resolved_low_power_device.front();
+ }
+ } catch (const ov::Exception& ex) {
+ LOG_WARNING_TAG("low_power_device '%s' is not available and will be ignored: %s",
+ low_power_device.c_str(),
+ ex.what());
+ }
+ if (auto_s_context->m_low_power_device)
+ LOG_INFO_TAG("low_power_device is set to %s", low_power_device.c_str());
}
auto_s_context->m_startup_fallback = load_config.get_property(ov::intel_auto::enable_startup_fallback);
auto_s_context->m_runtime_fallback = load_config.get_property(ov::intel_auto::enable_runtime_fallback);
+ auto_s_context->m_bind_buffer = load_config.get_property(ov::intel_auto::device_bind_buffer);
+ const bool has_resource_aware_property = !auto_s_context->m_selection_policy.utilization_thresholds.empty() ||
+ !auto_s_context->m_selection_policy.perf_curve_table.empty() ||
+ auto_s_context->m_low_power_device.has_value();
+ const auto& low_power_info = auto_s_context->m_low_power_device;
+ // there is nothing to switch to unless a second candidate or a low power device out of the candidates exists
+ const bool has_alternative_device =
+ support_devices.size() > 1 ||
+ (low_power_info.has_value() &&
+ std::none_of(support_devices.begin(), support_devices.end(), [&](const DeviceInformation& device) {
+ return device.unique_name == low_power_info->unique_name;
+ }));
+ const bool is_throughput = auto_s_context->m_performance_hint == ov::hint::PerformanceMode::THROUGHPUT;
+ const bool is_dynamic_candidate =
+ // dynamic selection requires an in-memory model and is incompatible with bind_buffer
+ model_path.empty() && !is_cumulative && !is_stateful_model && !auto_s_context->m_bind_buffer &&
+ !is_throughput && has_alternative_device && has_resource_aware_property;
+ // without the telemetry backend nothing could be evaluated, it would only serialize the inference
+ const bool telemetry_available = !is_dynamic_candidate || is_telemetry_available();
+ auto_s_context->m_dynamic_device_selection = is_dynamic_candidate && telemetry_available;
+ if (auto_s_context->m_dynamic_device_selection) {
+ auto_s_context->m_selection_policy.reserve_device = false;
+ LOG_INFO_TAG("[dynamic] per inference device selection enabled by the resource aware selection properties");
+ // load_config treats every property as user set by now, so read the explicit ones from the inputs
+ const auto is_enabled_by_user = [&](const auto& property) {
+ const auto iter = properties.find(property.name());
+ if (iter != properties.end()) {
+ return iter->second.template as<bool>();
+ }
+ return m_plugin_config.is_set_by_user(property) && m_plugin_config.get_property(property);
+ };
+ OPENVINO_ASSERT(!is_enabled_by_user(ov::intel_auto::enable_startup_fallback),
+ "ENABLE_STARTUP_FALLBACK is not supported together with the resource aware device selection");
+ OPENVINO_ASSERT(!is_enabled_by_user(ov::intel_auto::enable_runtime_fallback),
+ "ENABLE_RUNTIME_FALLBACK is not supported together with the resource aware device selection");
+ if (properties.count(ov::hint::model_priority.name()) || m_plugin_config.is_set_by_user(ov::hint::model_priority)) {
+ LOG_WARNING_TAG("MODEL_PRIORITY is ignored when the resource aware device selection is active");
+ }
+ const auto has_multiple_streams = [](const ov::AnyMap& config) {
+ const auto iter = config.find(ov::num_streams.name());
+ return iter != config.end() && iter->second.as<ov::streams::Num>().num > 1;
+ };
+ bool multiple_streams = has_multiple_streams(properties);
+ for (const auto& device : support_devices) {
+ multiple_streams = multiple_streams || has_multiple_streams(device.config);
+ }
+ multiple_streams =
+ multiple_streams || (low_power_info.has_value() && has_multiple_streams(low_power_info->config));
+ OPENVINO_ASSERT(!multiple_streams,
+ "More than one NUM_STREAMS is not supported together with the resource aware device selection");
+ // the inference is serialized, so unless the user chose a stream count one stream is enough
+ const auto set_single_stream = [&](DeviceInformation& device) {
+ if (properties.count(ov::num_streams.name()) || device.config.count(ov::num_streams.name())) {
+ return;
+ }
+ const auto supported = get_core()->get_supported_property(device.device_name, {ov::num_streams(1)});
+ device.config.insert(supported.begin(), supported.end());
+ };
+ for (auto& device : support_devices) {
+ set_single_stream(device);
+ }
+ if (auto_s_context->m_low_power_device) {
+ set_single_stream(*auto_s_context->m_low_power_device);
+ }
+ // disable startup fallback and runtime fallback
+ auto_s_context->m_startup_fallback = false;
+ auto_s_context->m_runtime_fallback = false;
+ } else if (has_resource_aware_property) {
+ if (is_stateful_model) {
+ LOG_WARNING_TAG("resource aware device selection properties are ignored for stateful models");
+ } else if (is_throughput) {
+ LOG_WARNING_TAG("resource aware device selection properties are ignored for THROUGHPUT performance hint");
+ } else if (!has_alternative_device) {
+ LOG_INFO_TAG("resource aware device selection properties are ignored, there is only one candidate device");
+ } else if (!telemetry_available) {
+ LOG_WARNING_TAG("resource aware device selection properties are ignored, the telemetry backend (IPF) is "
+ "not available");
+ }
+ }
// in case of mismatching shape conflict when AUTO creates the infer requests for actual device with reshaped model
auto_s_context->m_model = model_path.empty() ? std::const_pointer_cast<ov::Model>(model) : nullptr;
auto_s_context->m_model_path = model_path;
@@ -530,7 +634,6 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model_impl(const std::filesy
OPENVINO_ASSERT(auto_s_context->m_ov_core);
auto_s_context->m_log_tag = get_device_name();
auto_s_context->m_model_precision = model_precision;
- auto_s_context->m_bind_buffer = load_config.get_property(ov::intel_auto::device_bind_buffer);
auto_s_context->m_schedule_policy = load_config.get_property(ov::intel_auto::schedule_policy);
auto_s_context->m_mtx = m_mtx;
auto_s_context->m_priority_map = m_priority_map;
@@ -633,6 +736,13 @@ std::optional<bool> Plugin::get_low_power_mode() {
return m_telemetry_client->is_low_power_mode();
}
+bool Plugin::is_telemetry_available() const {
+ std::call_once(m_telemetry_client_init_once, [this]() {
+ m_telemetry_client = std::make_unique<device_monitor::TelemetryClient>();
+ });
+ return m_telemetry_client->is_available();
+}
+
std::list<DeviceInformation> Plugin::get_valid_device(const std::vector<DeviceInformation>& meta_devices,
const std::string& model_precision) const {
if (meta_devices.empty()) {
@@ -742,9 +852,17 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
const std::string& model_precision,
unsigned int priority,
const DeviceSelectionPolicy& selection_policy,
- const std::string& low_power_device) {
+ const std::optional<DeviceInformation>& low_power_device) {
OV_ITT_SCOPED_TASK(itt::domains::AutoPlugin, "Plugin::SelectDevice");
+ // every candidate has been excluded, only a low power device outside of the list can still run
+ if (meta_devices.empty() && low_power_device.has_value() && get_low_power_mode().value_or(false)) {
+ if (selection_policy.reserve_device) {
+ register_priority(priority, low_power_device->unique_name);
+ }
+ return *low_power_device;
+ }
+
const auto& utilization_thresholds = selection_policy.utilization_thresholds;
const auto& perf_curve_table = selection_policy.perf_curve_table;
std::list<DeviceInformation> valid_devices = get_valid_device(meta_devices, model_precision);
@@ -754,8 +872,8 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
// save the last device first
DeviceInformation last_device = valid_devices.back();
{
- // begin to filter devices
- if (m_mtx && m_priority_map) {
+ // begin to filter devices, a selection which reserves nothing takes no part in the priority arbitration
+ if (selection_policy.reserve_device && m_mtx && m_priority_map) {
std::lock_guard<std::mutex> lck(*m_mtx);
for (auto&& kvp : *m_priority_map) {
if (kvp.first >= priority) {
@@ -777,7 +895,7 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
}
}
- DeviceInformation* ptr_select_device = nullptr;
+ const DeviceInformation* ptr_select_device = nullptr;
std::list<DeviceInformation> perf_curve_sorted_devices;
// Resolve a device's effective utilization threshold: prefer an exact device-name match
// (e.g. "GPU.0"), then fall back to the base device name (e.g. "GPU").
@@ -797,28 +915,22 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
}
return std::nullopt;
};
- // Finds the configured low-power device by exact or base device name.
- auto find_low_power_device = [&]() -> DeviceInformation* {
- if (low_power_device.empty()) {
+ // Finds the configured low-power device
+ auto find_low_power_device = [&]() -> const DeviceInformation* {
+ if (!low_power_device.has_value() || !get_low_power_mode().value_or(false)) {
return nullptr;
}
auto it = std::find_if(valid_devices.begin(), valid_devices.end(), [&](const DeviceInformation& device) {
- if (device.device_name == low_power_device) {
- return true;
- }
- return ov::DeviceIDParser(device.device_name).get_device_name() == low_power_device;
+ return device.unique_name == low_power_device->unique_name;
});
- if (it == valid_devices.end() || !get_low_power_mode().value_or(false)) {
- return nullptr;
- }
- return &(*it);
+ return it != valid_devices.end() ? &(*it) : &low_power_device.value();
};
- if (valid_devices.empty()) {
+ if (auto* low_power_selected = find_low_power_device()) {
+ ptr_select_device = low_power_selected;
+ } else if (valid_devices.empty()) {
// after remove higher priority device,but the available devices is null,
// so select the last device of all available Devices.
ptr_select_device = &last_device;
- } else if (auto* low_power_selected = find_low_power_device()) {
- ptr_select_device = low_power_selected;
} else {
std::unordered_map<std::string, float> device_utilizations;
if (!utilization_thresholds.empty() || !perf_curve_table.empty()) {
@@ -857,6 +969,8 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
if (threshold_filtered_devices.empty()) {
// Fall back when all candidates exceed their thresholds.
+ LOG_DEBUG_TAG("All candidate devices exceed their utilization thresholds. Falling back to %s",
+ last_device.device_name.c_str());
ptr_select_device = &last_device;
} else {
valid_devices = std::move(threshold_filtered_devices);
@@ -879,7 +993,9 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
}
}
//recode the device priority
- register_priority(priority, ptr_select_device->unique_name);
+ if (selection_policy.reserve_device) {
+ register_priority(priority, ptr_select_device->unique_name);
+ }
return *ptr_select_device;
}
@@ -989,12 +1105,12 @@ void Plugin::unregister_priority(const unsigned int& priority, const std::string
if (m_mtx && m_priority_map) {
std::lock_guard<std::mutex> lck(*m_mtx);
auto& priority_devices = (*m_priority_map)[priority];
- for (auto iter = priority_devices.begin(); iter != priority_devices.end();) {
+ // remove the most recently registered matching entry
+ for (auto iter = priority_devices.rbegin(); iter != priority_devices.rend(); ++iter) {
if (*iter == device_name) {
- priority_devices.erase(iter);
+ priority_devices.erase(std::next(iter).base());
break;
}
- iter++;
}
}
}
@@ -1242,7 +1358,9 @@ std::vector<DeviceInformation> Plugin::filter_device(const std::vector<DeviceInf
std::vector<DeviceInformation> Plugin::filter_device_by_model(const std::vector<DeviceInformation>& meta_devices,
const std::shared_ptr<const ov::Model>& model,
- PluginConfig& load_config) const {
+ PluginConfig& load_config,
+ bool& is_stateful_model) const {
+ is_stateful_model = false;
if (meta_devices.empty()) {
OPENVINO_THROW("No available device to filter ", get_device_name(), " plugin");
}
@@ -1258,10 +1376,8 @@ std::vector<DeviceInformation> Plugin::filter_device_by_model(const std::vector<
}
};
- if (meta_devices.size() == 1) {
- return meta_devices;
- }
-
+ // detect statefulness before the single-candidate early return below, so callers that gate behavior on
+ // is_stateful_model (e.g. per inference dynamic device selection) get a correct answer even then
std::vector<std::string> stateful_node_names;
for (auto& op : model->get_ops()) {
if (ov::as_type_ptr<ov::op::util::AssignBase>(op) ||
@@ -1269,14 +1385,19 @@ std::vector<DeviceInformation> Plugin::filter_device_by_model(const std::vector<
stateful_node_names.push_back(op->get_friendly_name());
}
}
- if (stateful_node_names.empty()) {
- // not stateful model
+ is_stateful_model = !stateful_node_names.empty();
+
+ if (!is_stateful_model) {
return meta_devices;
}
- // disable CPU_HELP and runtime fallback if model is stateful
+ // disable CPU_HELP and runtime fallback if model is stateful, including the single candidate case
disable_startup_runtime_fallback();
+ if (meta_devices.size() == 1) {
+ return meta_devices;
+ }
+
bool isCumulative = (get_device_name() == "MULTI") || (load_config.get_property(ov::hint::performance_mode) ==
ov::hint::PerformanceMode::CUMULATIVE_THROUGHPUT);
if (isCumulative) {
diff --git a/src/plugins/auto/src/plugin.hpp b/src/plugins/auto/src/plugin.hpp
index 5848bb71922..c44aa37fd43 100644
--- a/src/plugins/auto/src/plugin.hpp
+++ b/src/plugins/auto/src/plugin.hpp
@@ -62,7 +62,7 @@ public:
const std::string& model_precision = "FP32",
unsigned int priority = 0,
const DeviceSelectionPolicy& selection_policy = {},
- const std::string& low_power_device = {});
+ const std::optional<DeviceInformation>& low_power_device = {});
MOCKTESTMACRO std::list<DeviceInformation> sort_device_by_perf_curve(
const std::unordered_map<std::string, float>& device_utilizations,
const std::list<DeviceInformation>& valid_devices,
@@ -89,6 +89,9 @@ public:
// Whether the platform is currently in low power mode; see device_monitor::TelemetryClient.
MOCKTESTMACRO std::optional<bool> get_low_power_mode();
+ // Whether the telemetry backend (IPF) is operational; without it the resource aware selection cannot work.
+ MOCKTESTMACRO bool is_telemetry_available() const;
+
std::shared_ptr<ov::ICompiledModel> import_model(const ov::Tensor& model,
const ov::AnyMap& properties) const override;
@@ -105,7 +108,8 @@ private:
const ov::AnyMap& properties) const;
std::vector<DeviceInformation> filter_device_by_model(const std::vector<DeviceInformation>& meta_devices,
const std::shared_ptr<const ov::Model>& model,
- PluginConfig& load_config) const;
+ PluginConfig& load_config,
+ bool& is_stateful_model) const;
std::string get_log_tag() const noexcept;
// Base family name, perf_curve_table lookup key ("iGPU"/"dGPU" for GPUs via ov::device::type,
// empty when it cannot be determined), and the ov::device::type string used to resolve a
@@ -120,8 +124,8 @@ private:
static std::shared_ptr<std::mutex> m_mtx;
static std::shared_ptr<std::map<unsigned int, std::list<std::string>>> m_priority_map;
PluginConfig m_plugin_config;
- std::once_flag m_telemetry_client_init_once;
- std::unique_ptr<device_monitor::TelemetryClient> m_telemetry_client;
+ mutable std::once_flag m_telemetry_client_init_once;
+ mutable std::unique_ptr<device_monitor::TelemetryClient> m_telemetry_client;
};
} // namespace auto_plugin
diff --git a/src/plugins/auto/src/schedule.cpp b/src/plugins/auto/src/schedule.cpp
index c515d71111f..032d8e9d5b4 100644
--- a/src/plugins/auto/src/schedule.cpp
+++ b/src/plugins/auto/src/schedule.cpp
@@ -9,6 +9,7 @@ namespace auto_plugin {
thread_local WorkerInferRequest* Schedule::m_this_worker_infer_request = nullptr;
// TODO: revert to the plain variable (see header file), when we moved to the next CentOS 8.x in our support matrix
thread_local const char* Schedule::m_this_preferred_device_name = "";
+thread_local std::exception_ptr Schedule::m_this_scheduling_exception = nullptr;
void Schedule::launch(const ScheduleContext::Ptr& context) {
m_context = context;
@@ -89,7 +90,14 @@ void Schedule::generate_workers(const std::string& device, const SoCompiledModel
(m_context->m_device_priorities.end() == it_numrequests || it_numrequests->num_requests_per_devices == -1)
? optimal_num
: it_numrequests->num_requests_per_devices;
- num_requests = (num_requests == 1) ? 2 : num_requests;
+ if (m_context->m_dynamic_device_selection) {
+ // inference is serialized per compiled model in this mode, so a single worker per device is enough and it
+ // guarantees the device carries no other inference when the next target device is re-selected
+ num_requests = 1;
+ LOG_DEBUG_TAG("device:%s, worker infer request number:%d", device.c_str(), static_cast<int>(num_requests));
+ } else {
+ num_requests = (num_requests == 1) ? 2 : num_requests;
+ }
auto& worker_requests = m_worker_requests[device];
auto& idle_worker_requests = m_idle_worker_requests[device];
worker_requests.resize(num_requests);
@@ -132,7 +140,12 @@ void Schedule::generate_workers(const std::string& device, const SoCompiledModel
stop_retry_and_continue();
}
// try to return the request to the idle list (fails if the overall object destruction has began)
- if (idleGuard.release()->try_push(std::make_pair(worker_request_ptr->m_index, worker_request_ptr))) {
+ bool returned_to_idle =
+ idleGuard.release()->try_push(std::make_pair(worker_request_ptr->m_index, worker_request_ptr));
+ if (m_context->m_dynamic_device_selection) {
+ // released unconditionally, otherwise queued requests would hang once destruction has began
+ release_execution_slot();
+ } else if (returned_to_idle) {
// let's try to pop a task, as we know there is at least one idle request, schedule if succeeded
// if no device-agnostic tasks, let's try pop the device specific task, schedule if succeeded
ov::threading::Task t;
@@ -206,26 +219,48 @@ Pipeline Schedule::get_async_pipeline(const ISyncInferPtr& infer_request, Worker
// by default, no preferred device:
m_this_preferred_device_name = "";
auto compiled_model = m_context->m_compiled_model.lock();
- // if any input is remote (e.g. was set with set_tensor), let' use the corresponding device
+ auto find_remote_device = [this](const ov::SoPtr<ov::ITensor>& tensor) -> const char* {
+ auto remote_tensor = std::dynamic_pointer_cast<ov::IRemoteTensor>(tensor._ptr);
+ if (!remote_tensor) {
+ return nullptr;
+ }
+ const auto name = remote_tensor->get_device_name();
+ auto matches = [&name](const DeviceInformation& d) {
+ return (d.default_device_id.empty() ? d.device_name
+ : (d.device_name + "." + d.default_device_id)) == name;
+ };
+ const auto res = std::find_if(m_context->m_device_priorities_initial.cbegin(),
+ m_context->m_device_priorities_initial.cend(),
+ matches);
+ if (res != m_context->m_device_priorities_initial.cend()) {
+ // it is ok to take the c_str() here (as pointed in the schedule.hpp we need to use
+ // const char*) as the original strings are from the "persistent" vector (with the right
+ // lifetime)
+ return res->device_name.c_str();
+ }
+ // the low power device can sit outside the candidates, it is only used when a tensor pins it
+ const auto& low_power = m_context->m_low_power_device;
+ if (low_power && !m_context->m_low_power_device_unavailable && matches(*low_power)) {
+ return low_power->device_name.c_str();
+ }
+ OPENVINO_THROW("None of the devices supports a remote tensor created on the device named ",
+ name);
+ };
+ // if any input is remote (e.g. was set with set_tensor), let's use the corresponding device
for (const auto& it : compiled_model->inputs()) {
- auto tensor = infer_request->get_tensor(it);
- if (auto remote_tensor = std::dynamic_pointer_cast<ov::IRemoteTensor>(tensor._ptr)) {
- const auto name = remote_tensor->get_device_name();
- const auto res = std::find_if(
- m_context->m_device_priorities_initial.cbegin(),
- m_context->m_device_priorities_initial.cend(),
- [&name](const DeviceInformation & d) {
- return (d.default_device_id.empty() ? d.device_name : (d.device_name + "." +
- d.default_device_id)) == name;
- });
- if (m_context->m_device_priorities_initial.cend() == res) {
- OPENVINO_THROW(
- "None of the devices supports a remote tensor created on the device named ", name);
- } else {
- // it is ok to take the c_str() here (as pointed in the schedule.hpp we need to use const char*)
- // as the original strings are from the "persistent" vector (with the right lifetime)
- m_this_preferred_device_name = res->device_name.c_str();
- break;
+ if (const char* device = find_remote_device(infer_request->get_tensor(it))) {
+ m_this_preferred_device_name = device;
+ break;
+ }
+ }
+ if (m_context->m_dynamic_device_selection) {
+ // the target device is re-selected per inference, so a remote output pins the request as well
+ for (const auto& it : compiled_model->outputs()) {
+ if (const char* device = find_remote_device(infer_request->get_tensor(it))) {
+ OPENVINO_ASSERT(m_this_preferred_device_name[0] == '\0' ||
+ std::string(m_this_preferred_device_name) == device,
+ "Remote tensors of the inputs and outputs are created on different devices");
+ m_this_preferred_device_name = device;
}
}
}
@@ -234,9 +269,23 @@ Pipeline Schedule::get_async_pipeline(const ISyncInferPtr& infer_request, Worker
// then sets the device-agnostic tensors to the actual (device-specific) request
Stage {
/*TaskExecutor*/std::dynamic_pointer_cast<ov::threading::ITaskExecutor>(shared_from_this()), /*task*/ [&infer_request, worker_infer_request]() {
+ if (m_this_scheduling_exception) {
+ auto scheduling_exception = m_this_scheduling_exception;
+ m_this_scheduling_exception = nullptr;
+ // the failure can come from a device plugin, so make sure an ov::Exception is surfaced
+ try {
+ std::rethrow_exception(scheduling_exception);
+ } catch (const ov::Exception&) {
+ throw;
+ } catch (const std::exception& ex) {
+ OPENVINO_THROW(ex.what());
+ }
+ }
*worker_infer_request = m_this_worker_infer_request;
auto auto_request = std::dynamic_pointer_cast<InferRequest>(infer_request);
+ DispatchFailureGuard guard{m_this_worker_infer_request};
auto_request->set_tensors_to_another_request(m_this_worker_infer_request->m_inferrequest);
+ guard.m_dismissed = true;
INFO_RUN([worker_infer_request]() {
(*worker_infer_request)->m_start_times.push_back(std::chrono::steady_clock::now());
});
@@ -299,7 +348,7 @@ Schedule::~Schedule() {
LOG_INFO_TAG("%s: first inference time:%lf ms",
worker_request.first.c_str(),
first_infer_duration.count());
- LOG_INFO_TAG("%s:infer:%ld", worker_request.first.c_str(), count);
+ LOG_INFO_TAG("%s:infer:%zu", worker_request.first.c_str(), count);
std::chrono::duration<double, std::milli> durtation =
req_all_end_times.back() - time;
LOG_INFO_TAG("%s:fps:%lf", worker_request.first.c_str(),
diff --git a/src/plugins/auto/src/schedule.hpp b/src/plugins/auto/src/schedule.hpp
index 461493bf714..b3f034423ce 100644
--- a/src/plugins/auto/src/schedule.hpp
+++ b/src/plugins/auto/src/schedule.hpp
@@ -26,9 +26,12 @@ public:
// the bug is e.g. manifesting on the old CentOS (and it's 4.8.x gcc) used in our testing
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81880
static thread_local const char* m_this_preferred_device_name;
+ // set when the scheduler cannot dispatch a request, rethrown by the scheduling stage of the pipeline
+ static thread_local std::exception_ptr m_this_scheduling_exception;
protected:
virtual void init() = 0;
+ virtual void release_execution_slot() {}
static bool run_pipeline_task(ov::threading::Task& pipeline_task, NotBusyPriorityWorkerRequests& idle_worker_request,
const DeviceName& preferred_device);
virtual void generate_workers(const std::string& device, const SoCompiledModel& compiled_model);
diff --git a/src/plugins/auto/src/utils/device_telemetry.cpp b/src/plugins/auto/src/utils/device_telemetry.cpp
index ff8046b41e5..28e2ac4abdb 100644
--- a/src/plugins/auto/src/utils/device_telemetry.cpp
+++ b/src/plugins/auto/src/utils/device_telemetry.cpp
@@ -175,6 +175,10 @@ public:
}
}
+ bool is_available() const {
+ return m_handle != nullptr;
+ }
+
// Single IPF round trip; the returned JSON snapshot covers every device's utilization at
// once, so callers should fetch it once per decision and reuse it for all candidates.
std::string fetch_utilization_snapshot() {
@@ -418,6 +422,10 @@ TelemetryClient::TelemetryClient() : m_impl(std::make_unique<Impl>()) {}
TelemetryClient::~TelemetryClient() = default;
+bool TelemetryClient::is_available() const {
+ return m_impl->is_available();
+}
+
std::unordered_map<std::string, float> TelemetryClient::utilizations(
const std::vector<std::pair<std::string, std::string>>& devices) {
return m_impl->utilizations(devices);
@@ -484,6 +492,10 @@ TelemetryClient::TelemetryClient() : m_impl(nullptr) {}
TelemetryClient::~TelemetryClient() = default;
+bool TelemetryClient::is_available() const {
+ return false;
+}
+
std::unordered_map<std::string, float> TelemetryClient::utilizations(const std::vector<std::pair<std::string, std::string>>&) {
return {};
}
diff --git a/src/plugins/auto/src/utils/device_telemetry.hpp b/src/plugins/auto/src/utils/device_telemetry.hpp
index 2c87fc87b40..52c37ba30fe 100644
--- a/src/plugins/auto/src/utils/device_telemetry.hpp
+++ b/src/plugins/auto/src/utils/device_telemetry.hpp
@@ -34,6 +34,9 @@ public:
TelemetryClient();
~TelemetryClient();
+ // Whether the telemetry backend (IPF) was initialized, i.e. utilization and low power mode can be queried.
+ bool is_available() const;
+
// Resolves utilization for multiple (device_name, device_type) devices, keyed by device_name.
// Fetches and parses the underlying IPF snapshot only once regardless of device count.
std::unordered_map<std::string, float> utilizations(const std::vector<std::pair<std::string, std::string>>& devices);
diff --git a/src/plugins/auto/tests/unit/auto_unit_test.cpp b/src/plugins/auto/tests/unit/auto_unit_test.cpp
index 0eb0d6569c7..c95aff9c231 100644
--- a/src/plugins/auto/tests/unit/auto_unit_test.cpp
+++ b/src/plugins/auto/tests/unit/auto_unit_test.cpp
@@ -112,6 +112,7 @@ ov::mock_auto_plugin::tests::BaseTest::BaseTest(const MODELTYPE modelType) {
const std::filesystem::path& model_path) {
return plugin->Plugin::get_device_list(config, model, {});
});
+ ON_CALL(*plugin, is_telemetry_available).WillByDefault(Return(true));
ON_CALL(*plugin, parse_meta_devices)
.WillByDefault([this](const std::string& priorityDevices, const ov::AnyMap& config) {
return plugin->Plugin::parse_meta_devices(priorityDevices, config);
@@ -122,7 +123,7 @@ ov::mock_auto_plugin::tests::BaseTest::BaseTest(const MODELTYPE modelType) {
const std::string& netPrecision,
unsigned int priority,
const ov::auto_plugin::DeviceSelectionPolicy& selection_policy,
- const std::string& low_power_device) {
+ const std::optional<DeviceInformation>& low_power_device) {
return plugin->Plugin::select_device(metaDevices, netPrecision, priority, selection_policy, low_power_device);
});
diff --git a/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp b/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp
new file mode 100644
index 00000000000..f31d7e1da2c
--- /dev/null
+++ b/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp
@@ -0,0 +1,1133 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/auto_unit_test.hpp"
+#include "openvino/opsets/opset11.hpp"
+#include "openvino/runtime/auto/properties.hpp"
+#include "openvino/runtime/iremote_tensor.hpp"
+#include "openvino/runtime/threading/immediate_executor.hpp"
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <future>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+using namespace ov::mock_auto_plugin;
+
+namespace ov::test {
+namespace {
+// Mirrors StatefulModelSupportedTest::create_stateful_model(): a minimal ReadValue/Assign
+// pair is enough for filter_device_by_model() to detect the model as stateful.
+std::shared_ptr<ov::Model> create_stateful_model() {
+ auto arg = std::make_shared<ov::opset11::Parameter>(ov::element::f32, ov::Shape{1, 1});
+ auto init_const = ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, 1}, {0});
+ const std::string variable_name("variable0");
+ auto variable = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{init_const->get_shape(), ov::element::f32, variable_name});
+ auto read = std::make_shared<ov::opset11::ReadValue>(init_const, variable);
+ auto add = std::make_shared<ov::opset11::Add>(arg, read);
+ add->set_friendly_name("add_sum");
+ auto assign = std::make_shared<ov::opset11::Assign>(add, variable);
+ assign->set_friendly_name("save");
+ auto res = std::make_shared<ov::opset11::Result>(add);
+ res->set_friendly_name("res");
+ return std::make_shared<ov::Model>(ov::ResultVector({res}), ov::SinkVector({assign}), ov::ParameterVector({arg}));
+}
+
+// Completes the callback task in place, then holds the calling thread, so that the code which follows the completion
+// of a user request on the device thread can be paused.
+class HoldingCallbackExecutor : public ov::threading::ITaskExecutor {
+public:
+ void run(ov::threading::Task task) override {
+ task();
+ std::unique_lock<std::mutex> lock(m_mutex);
+ m_held = true;
+ m_cv.notify_all();
+ m_cv.wait(lock, [this] {
+ return m_released;
+ });
+ }
+
+ bool wait_until_held(std::chrono::milliseconds timeout) {
+ std::unique_lock<std::mutex> lock(m_mutex);
+ return m_cv.wait_for(lock, timeout, [this] {
+ return m_held;
+ });
+ }
+
+ void release() {
+ {
+ std::lock_guard<std::mutex> lock(m_mutex);
+ m_released = true;
+ }
+ m_cv.notify_all();
+ }
+
+private:
+ std::mutex m_mutex;
+ std::condition_variable m_cv;
+ bool m_held = false;
+ bool m_released = false;
+};
+
+// set_callback_executor() is protected in ov::ICompiledModel; it is reached through a pointer to member.
+struct CallbackExecutorAccess : public ov::ICompiledModel {
+ using ov::ICompiledModel::set_callback_executor;
+};
+
+// Runs every task on its own thread, so a device completion callback is not issued from the dispatching thread.
+class ThreadPerTaskExecutor : public ov::threading::ITaskExecutor {
+public:
+ void run(ov::threading::Task task) override {
+ std::lock_guard<std::mutex> lock(m_mutex);
+ m_threads.emplace_back(std::move(task));
+ }
+
+ ~ThreadPerTaskExecutor() override {
+ for (auto& thread : m_threads) {
+ if (thread.get_id() == std::this_thread::get_id()) {
+ thread.detach();
+ } else if (thread.joinable()) {
+ thread.join();
+ }
+ }
+ }
+
+private:
+ std::mutex m_mutex;
+ std::vector<std::thread> m_threads;
+};
+
+// Fails the first start_async() calls the way a device does when it cannot accept a request.
+class FailingStartAsyncRequest : public ov::IAsyncInferRequest {
+public:
+ FailingStartAsyncRequest(const std::shared_ptr<ov::IInferRequest>& request,
+ const std::shared_ptr<ov::threading::ITaskExecutor>& task_executor,
+ const std::shared_ptr<ov::threading::ITaskExecutor>& callback_executor,
+ const std::shared_ptr<std::atomic<int>>& failures)
+ : ov::IAsyncInferRequest(request, task_executor, callback_executor),
+ m_failures(failures) {}
+
+ void start_async() override {
+ if (m_failures->load() > 0) {
+ --(*m_failures);
+ OPENVINO_THROW("mock start_async failure");
+ }
+ ov::IAsyncInferRequest::start_async();
+ }
+
+private:
+ std::shared_ptr<std::atomic<int>> m_failures;
+};
+
+// Carries nothing but the name of the device it was created on.
+class DeviceTaggedRemoteTensor : public ov::IRemoteTensor {
+public:
+ DeviceTaggedRemoteTensor(const std::string& device_name, const ov::element::Type& type, const ov::Shape& shape)
+ : m_device_name(device_name),
+ m_element_type(type),
+ m_shape(shape) {}
+
+ const ov::AnyMap& get_properties() const override {
+ return m_properties;
+ }
+ const std::string& get_device_name() const override {
+ return m_device_name;
+ }
+ void set_shape(ov::Shape) override {
+ OPENVINO_NOT_IMPLEMENTED;
+ }
+ const ov::element::Type& get_element_type() const override {
+ return m_element_type;
+ }
+ const ov::Shape& get_shape() const override {
+ return m_shape;
+ }
+ const ov::Strides& get_strides() const override {
+ OPENVINO_NOT_IMPLEMENTED;
+ }
+
+private:
+ ov::AnyMap m_properties;
+ std::string m_device_name;
+ ov::element::Type m_element_type;
+ ov::Shape m_shape;
+};
+} // namespace
+
+// Covers the per inference device selection which AUTO turns on as soon as one of the resource aware
+// selection properties is set: the target device is re-selected for every incoming inference, inference is
+// serialized per compiled model and every device is given a single worker infer request.
+class AutoDynamicDeviceSelectionTest : public tests::AutoTest, public ::testing::Test {
+public:
+ void SetUp() override {
+ plugin->set_device_name("AUTO");
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ _))
+ .WillByDefault(Return(mockExeNetworkActual));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(ov::test::utils::DEVICE_CPU)),
+ _))
+ .WillByDefault(Return(mockExeNetwork));
+ config.insert(ov::device::priorities("GPU.0,CPU"));
+ }
+
+ void TearDown() override {
+ testing::Mock::VerifyAndClearExpectations(core.get());
+ testing::Mock::VerifyAndClearExpectations(plugin.get());
+ }
+
+ // Pins the device returned by every select_device() call, so that the schedule behavior can be driven
+ // from the test instead of depending on the real telemetry backend.
+ void expect_selected_devices(const std::vector<std::string>& device_names) {
+ ON_CALL(*plugin, select_device)
+ .WillByDefault([this, device_names](const std::vector<DeviceInformation>& meta_devices,
+ const std::string&,
+ unsigned int,
+ const ov::auto_plugin::DeviceSelectionPolicy&,
+ const std::optional<DeviceInformation>&) {
+ const auto& expected = device_names[m_select_device_count++ % device_names.size()];
+ for (const auto& device : meta_devices) {
+ if (device.device_name == expected) {
+ return device;
+ }
+ }
+ return meta_devices.front();
+ });
+ }
+
+ void run_inferences(const std::shared_ptr<ov::ICompiledModel>& compiled_model, size_t count) {
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ for (size_t i = 0; i < count; i++) {
+ OV_ASSERT_NO_THROW(infer_request->infer());
+ }
+ }
+
+ // GPU.0 looks fine until the flag is raised, which forces the per inference target off it.
+ void mock_gpu0_over_threshold(const std::shared_ptr<std::atomic<bool>>& over_threshold) {
+ ON_CALL(*plugin, get_device_utilizations)
+ .WillByDefault([over_threshold](const std::list<DeviceInformation>& devices) {
+ std::unordered_map<std::string, float> result;
+ if (*over_threshold) {
+ for (const auto& device : devices) {
+ if (device.device_name == "GPU.0") {
+ result[device.device_name] = 95.0f;
+ }
+ }
+ }
+ return result;
+ });
+ }
+
+ // The per inference selection takes no part in the model priority arbitration: no device stays reserved, so a
+ // lower priority instance can pick any of them.
+ void expect_no_device_reserved(const std::vector<std::string>& device_names) {
+ ASSERT_GT(device_names.size(), 1u);
+ ov::auto_plugin::DeviceSelectionPolicy empty_policy;
+ for (size_t i = 0; i < device_names.size(); i++) {
+ const auto& device_name = device_names[i];
+ const auto& other_name = device_names[(i + 1) % device_names.size()];
+ auto devices = plugin->Plugin::parse_meta_devices(device_name + "," + other_name, config);
+ DeviceInformation result;
+ OV_ASSERT_NO_THROW(result = plugin->Plugin::select_device(devices, "FP32", 2, empty_policy, {}));
+ EXPECT_EQ(result.device_name, device_name);
+ plugin->unregister_priority(2, result.unique_name);
+ }
+ }
+
+ std::atomic<size_t> m_select_device_count{0};
+};
+
+TEST_F(AutoDynamicDeviceSelectionTest, disabled_by_default_keeps_more_than_one_worker) {
+ config.insert(ov::intel_auto::enable_startup_fallback(false));
+ // optimal_number_of_infer_requests is mocked to 1, which AUTO promotes to 2 in the classic schedule
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).Times(2).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, utilization_threshold_forces_single_worker) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).Times(1).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, low_power_device_forces_single_worker) {
+ config.insert(ov::intel_auto::low_power_device("CPU"));
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).Times(1).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, perf_curve_table_forces_single_worker) {
+ config.insert(ov::intel_auto::perf_curve_table(ov::intel_auto::PerfCurveTable{{"iGPU", {{0, 1.0f}, {100, 5.0f}}}}));
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).Times(1).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, device_is_reselected_for_every_inference) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ expect_selected_devices({"GPU.0"});
+ constexpr size_t infer_num = 3;
+ // one selection while compiling the model plus one selection per incoming inference
+ EXPECT_CALL(*plugin, select_device).Times(1 + infer_num);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, infer_num);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, staying_on_the_same_device_does_not_recompile) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ expect_selected_devices({"GPU.0"});
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(_),
+ ::testing::Matcher<const ov::AnyMap&>(_)))
+ .Times(1);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 3);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, each_device_is_compiled_only_once_when_switching_back_and_forth) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ expect_selected_devices({"GPU.0", "CPU"});
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(_),
+ ::testing::Matcher<const ov::AnyMap&>(_)))
+ .Times(2);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 4);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, fallback_onto_a_cached_device_does_not_compile_it_again) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure"));
+ // initial device, the device picked for the first inference, then the fallback after GPU.1 fails to compile
+ expect_selected_devices({"GPU.0", "GPU.1", "GPU.0"});
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ ::testing::Matcher<const ov::AnyMap&>(_)))
+ .Times(1);
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ ::testing::Matcher<const ov::AnyMap&>(_)))
+ .Times(1);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 1);
+}
+
+// A single worker per device used to be forbidden because the classic schedule could stall, the execution gate
+// makes it safe again, so a long sequence of inferences must keep completing.
+TEST_F(AutoDynamicDeviceSelectionTest, repeated_inferences_with_a_single_worker_do_not_stall) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ expect_selected_devices({"GPU.0", "GPU.0", "CPU"});
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 20);
+}
+
+// A stateful model must keep using the classic (non dynamic) schedule even when a resource
+// aware selection property is configured: filter_device_by_model() detects the state and
+// Plugin::compile_model_impl() must not turn per inference dynamic selection on for it.
+TEST_F(AutoDynamicDeviceSelectionTest, stateful_model_disables_dynamic_selection) {
+ model = create_stateful_model();
+ config.insert(ov::intel_auto::low_power_device("CPU"));
+ // optimal_number_of_infer_requests is mocked to 1, which the classic schedule promotes to
+ // 2; the dynamic schedule would instead keep a single worker per device.
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).Times(2).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+// filter_device_by_model() used to only classify a model as stateful after it had more than one
+// candidate device, so a single-candidate stateful model with a resource aware property configured slipped
+// through with dynamic selection enabled - breaking the passthrough guarantee that each user created
+// infer request gets its own, independent underlying request/state.
+TEST_F(AutoDynamicDeviceSelectionTest, stateful_model_with_a_single_candidate_disables_dynamic_selection) {
+ // overwrite the GPU.0,CPU priorities inserted by SetUp(): ov::AnyMap::insert() keeps the first entry
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0"));
+ model = create_stateful_model();
+ // the GPU mock was built around the default model; rebind its ports and sync request to the stateful one
+ ON_CALL(*mockIExeNetActual.get(), inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));
+ ON_CALL(*mockIExeNetActual.get(), outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));
+ inferReqInternalActual = std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(mockIExeNetActual);
+ config.insert(ov::intel_auto::low_power_device("CPU"));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ // select_device() is already called once by init() to pick the sole candidate; if dynamic selection were
+ // (incorrectly) left enabled it would be called again for every inference below.
+ EXPECT_CALL(*plugin, select_device).Times(0);
+ run_inferences(compiled_model, 3);
+}
+
+// A stateful model with a single candidate must keep startup/runtime fallback disabled, even though the
+// single candidate returns early from filter_device_by_model(). Explicitly enabled fallbacks must not survive.
+TEST_F(AutoDynamicDeviceSelectionTest, stateful_single_candidate_disables_startup_and_runtime_fallback) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0"));
+ model = create_stateful_model();
+ config.insert(ov::intel_auto::low_power_device(ov::test::utils::DEVICE_CPU));
+ config.insert(ov::intel_auto::enable_startup_fallback(true));
+ config.insert(ov::intel_auto::enable_runtime_fallback(true));
+ // the mocked GPU model is rebound to the stateful one, so the passthrough schedule can serve requests
+ ON_CALL(*mockIExeNetActual.get(), inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));
+ ON_CALL(*mockIExeNetActual.get(), outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));
+ inferReqInternalActual = std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(mockIExeNetActual);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ // stateful: no per inference selection
+ EXPECT_CALL(*plugin, select_device).Times(0);
+ run_inferences(compiled_model, 3);
+}
+
+// Regression for ensure_device_ready(): the fallback device chosen while compiling on demand must not stay reserved.
+TEST_F(AutoDynamicDeviceSelectionTest, no_device_is_reserved_after_a_successful_fallback) {
+ // overwrite the GPU.0,CPU priorities inserted by SetUp(): ov::AnyMap::insert() keeps the first entry
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,CPU"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure"));
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ gpu0_over_threshold->store(true);
+ run_inferences(compiled_model, 1);
+ expect_no_device_reserved({"GPU.0", "GPU.1", ov::test::utils::DEVICE_CPU});
+
+ compiled_model.reset();
+ expect_no_device_reserved({"GPU.0", "GPU.1", ov::test::utils::DEVICE_CPU});
+}
+
+// Regression for ensure_device_ready(): a fallback device whose compile fails too must not stay reserved either.
+TEST_F(AutoDynamicDeviceSelectionTest, no_device_is_reserved_after_a_failed_fallback) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,CPU"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure on GPU.1"));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(ov::test::utils::DEVICE_CPU)),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure on CPU"));
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ gpu0_over_threshold->store(true);
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ EXPECT_THROW(infer_request->infer(), ov::Exception);
+ expect_no_device_reserved({"GPU.0", "GPU.1", ov::test::utils::DEVICE_CPU});
+}
+
+// Regression for try_to_compile_model(): the configured low_power_device is a standing override
+// that is force-selected even when it is not part of the configured device priorities (see
+// SelectDeviceWithLowPowerDevicePrecedenceTest::lowPowerDeviceSelectedEvenWhenNotInCandidateList).
+// If that forced device fails to compile, try_to_compile_model() used to reselect with the same
+// low_power_device argument, which forced the very same failing device back in and recursed on it
+// forever instead of falling back to the configured device priorities.
+TEST_F(AutoDynamicDeviceSelectionTest, low_power_device_failure_falls_back_instead_of_looping_forever) {
+ // GPU.1 is never part of the configured priorities ("GPU.0,CPU" from SetUp()), so it can only
+ // be selected through the low_power_device override.
+ config.insert(ov::intel_auto::low_power_device("GPU.1"));
+ ON_CALL(*plugin, get_low_power_mode()).WillByDefault(Return(true));
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .Times(1)
+ .WillOnce(ov::Throw("mock compile failure on GPU.1"));
+ // once GPU.1 is excluded, compilation must fall back to the configured device priorities (GPU.0)
+ // instead of forcing GPU.1 again and recursing forever.
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ _))
+ .Times(1)
+ .WillOnce(Return(mockExeNetworkActual));
+ EXPECT_CALL(*mockIExeNetActual.get(), create_infer_request()).WillRepeatedly([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 1);
+}
+
+// Reproduces schedule_dynamic_task()'s queueing path: while one dynamic inference is still
+// being dispatched (the execution gate is busy), a second inference started concurrently must
+// be queued in m_gate_pending_tasks and only dispatched once release_execution_slot() picks it
+// up, instead of being dropped or racing the in-flight one. None of the other tests in this
+// file exercise this because they all issue requests through the synchronous infer() one at a
+// time via run_inferences().
+TEST_F(AutoDynamicDeviceSelectionTest, concurrent_requests_are_queued_and_dispatched_in_turn) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+
+ std::mutex mtx;
+ std::condition_variable cv;
+ bool first_inference_is_blocked = false;
+ bool release_first_inference = false;
+
+ ON_CALL(*plugin, select_device)
+ .WillByDefault([this, &mtx, &cv, &first_inference_is_blocked, &release_first_inference](
+ const std::vector<DeviceInformation>& meta_devices,
+ const std::string&,
+ unsigned int,
+ const ov::auto_plugin::DeviceSelectionPolicy&,
+ const std::optional<DeviceInformation>&) {
+ // call #0 happens during compile_model(); block only the first per inference
+ // reselection (call #1) so the second start_async() below is guaranteed to observe
+ // the execution gate as busy and go through the queueing path.
+ if (m_select_device_count++ == 1) {
+ std::unique_lock<std::mutex> lock(mtx);
+ first_inference_is_blocked = true;
+ cv.notify_all();
+ cv.wait(lock, [&release_first_inference] {
+ return release_first_inference;
+ });
+ }
+ for (const auto& device : meta_devices) {
+ if (device.device_name == "GPU.0") {
+ return device;
+ }
+ }
+ return meta_devices.front();
+ });
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ std::shared_ptr<ov::IAsyncInferRequest> first_request;
+ std::shared_ptr<ov::IAsyncInferRequest> second_request;
+ OV_ASSERT_NO_THROW(first_request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(second_request = compiled_model->create_infer_request());
+
+ OV_ASSERT_NO_THROW(first_request->start_async());
+ {
+ std::unique_lock<std::mutex> lock(mtx);
+ cv.wait(lock, [&first_inference_is_blocked] {
+ return first_inference_is_blocked;
+ });
+ }
+
+ // the execution gate is held by the still-dispatching first request, so this must be
+ // queued in m_gate_pending_tasks rather than dispatched (or dropped) right away.
+ OV_ASSERT_NO_THROW(second_request->start_async());
+ EXPECT_EQ(m_select_device_count.load(), 2u);
+
+ {
+ std::lock_guard<std::mutex> lock(mtx);
+ release_first_inference = true;
+ }
+ cv.notify_all();
+
+ OV_ASSERT_NO_THROW(first_request->wait());
+ OV_ASSERT_NO_THROW(second_request->wait());
+ EXPECT_EQ(m_select_device_count.load(), 3u);
+}
+
+// The low_power_device override must be dropped once its on-demand compilation fails, otherwise every
+// following inference keeps selecting the failed device instead of the working one.
+TEST_F(AutoDynamicDeviceSelectionTest, low_power_device_compile_failure_disables_the_override) {
+ config.insert(ov::intel_auto::low_power_device(ov::test::utils::DEVICE_CPU));
+ auto low_power_mode = std::make_shared<std::atomic<bool>>(false);
+ ON_CALL(*plugin, get_low_power_mode()).WillByDefault([low_power_mode]() {
+ return std::optional<bool>(low_power_mode->load());
+ });
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(ov::test::utils::DEVICE_CPU)),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure on CPU"));
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ low_power_mode->store(true);
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ EXPECT_THROW(infer_request->infer(), ov::Exception);
+ OV_ASSERT_NO_THROW(infer_request->infer());
+}
+
+// The reservation another model holds on the failing device must survive the failed on-demand compile.
+TEST_F(AutoDynamicDeviceSelectionTest, failed_on_demand_compile_keeps_the_reservation_of_another_model) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,CPU"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure"));
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ // another AUTO model with the default (MEDIUM) priority is running on GPU.1
+ const auto gpu1 = plugin->Plugin::parse_meta_devices("GPU.1", config).front();
+ plugin->register_priority(1, gpu1.unique_name);
+
+ gpu0_over_threshold->store(true);
+ run_inferences(compiled_model, 1);
+
+ // GPU.1 is still reserved by the other model, so a lower priority instance must not get it
+ auto verification_devices = plugin->Plugin::parse_meta_devices("GPU.1,CPU", config);
+ ov::auto_plugin::DeviceSelectionPolicy empty_policy;
+ DeviceInformation result;
+ OV_ASSERT_NO_THROW(result = plugin->Plugin::select_device(verification_devices, "FP32", 2, empty_policy, {}));
+ EXPECT_EQ(result.device_name, ov::test::utils::DEVICE_CPU);
+ plugin->unregister_priority(2, result.unique_name);
+ plugin->unregister_priority(1, gpu1.unique_name);
+}
+
+// AUTO/MULTI as low_power_device would make the plugin compile itself again and again.
+TEST_F(AutoDynamicDeviceSelectionTest, meta_device_as_low_power_device_is_rejected) {
+ ON_CALL(*plugin, is_meta_device).WillByDefault([this](const std::string& priorities) {
+ return plugin->Plugin::is_meta_device(priorities);
+ });
+ for (const auto* meta_device : {"AUTO", "MULTI:CPU"}) {
+ auto properties = config;
+ properties.insert(ov::intel_auto::low_power_device(meta_device));
+ EXPECT_THROW(plugin->compile_model(model, properties), ov::Exception) << meta_device;
+ }
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, explicit_startup_fallback_is_rejected) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::intel_auto::enable_startup_fallback(true));
+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);
+}
+
+// With a single candidate there is nothing to switch to, so the passthrough schedule must be kept.
+TEST_F(AutoDynamicDeviceSelectionTest, single_candidate_device_disables_dynamic_selection) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ // only the selection done while compiling the model, none per inference
+ EXPECT_CALL(*plugin, select_device).Times(1);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 3);
+}
+
+// A low power device out of the candidate list is still something to switch to.
+TEST_F(AutoDynamicDeviceSelectionTest, low_power_device_out_of_a_single_candidate_enables_dynamic_selection) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0"));
+ config.insert(ov::intel_auto::low_power_device(ov::test::utils::DEVICE_CPU));
+ constexpr size_t infer_num = 3;
+ EXPECT_CALL(*plugin, select_device).Times(1 + infer_num);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, infer_num);
+}
+
+// The per inference selection serializes the inferences, so THROUGHPUT is not honored and the properties are ignored.
+TEST_F(AutoDynamicDeviceSelectionTest, throughput_hint_disables_dynamic_selection) {
+ config.insert(ov::hint::performance_mode(ov::hint::PerformanceMode::THROUGHPUT));
+ config.insert(ov::intel_auto::enable_startup_fallback(false));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ EXPECT_CALL(*plugin, select_device).Times(1);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 3);
+}
+
+// Without the telemetry backend the utilization cannot be evaluated, so the properties are ignored instead of
+// serializing the inference for nothing.
+TEST_F(AutoDynamicDeviceSelectionTest, resource_aware_properties_are_ignored_without_telemetry) {
+ ON_CALL(*plugin, is_telemetry_available()).WillByDefault(Return(false));
+ config.insert(ov::intel_auto::enable_startup_fallback(false));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ EXPECT_CALL(*plugin, select_device).Times(1);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 3);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, optimal_number_of_infer_requests_is_one) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*mockIExeNetActual.get(), get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
+ .WillByDefault(Return(ov::Any(4u)));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ EXPECT_EQ(compiled_model->get_property(ov::optimal_number_of_infer_requests.name()).as<unsigned int>(), 1u);
+}
+
+// The only worker of a device must be given back when its request cannot be started, otherwise the execution
+// gate stays closed and every following inference is queued forever.
+TEST_F(AutoDynamicDeviceSelectionTest, failure_to_start_a_request_does_not_block_following_inferences) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ auto failures = std::make_shared<std::atomic<int>>(1);
+ ON_CALL(*mockIExeNetActual.get(), create_infer_request()).WillByDefault([this, failures]() {
+ return std::static_pointer_cast<ov::IAsyncInferRequest>(
+ std::make_shared<FailingStartAsyncRequest>(inferReqInternalActual,
+ std::make_shared<ov::threading::ImmediateExecutor>(),
+ nullptr,
+ failures));
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ std::shared_ptr<ov::IAsyncInferRequest> failed_request;
+ OV_ASSERT_NO_THROW(failed_request = compiled_model->create_infer_request());
+ EXPECT_THROW(failed_request->infer(), ov::Exception);
+
+ std::shared_ptr<ov::IAsyncInferRequest> next_request;
+ OV_ASSERT_NO_THROW(next_request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(next_request->start_async());
+ EXPECT_TRUE(next_request->wait_for(std::chrono::seconds(10)));
+}
+
+// The device completion callback keeps using the scheduler (it gives the execution slot back) after it has completed
+// the user request, so the scheduler must not be destroyed before that callback is out of it.
+TEST_F(AutoDynamicDeviceSelectionTest, destruction_waits_for_the_device_completion_callback) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ auto device_executor = std::make_shared<ThreadPerTaskExecutor>();
+ auto failures = std::make_shared<std::atomic<int>>(0);
+ ON_CALL(*mockIExeNetActual.get(), create_infer_request()).WillByDefault([this, device_executor, failures]() {
+ return std::static_pointer_cast<ov::IAsyncInferRequest>(
+ std::make_shared<FailingStartAsyncRequest>(inferReqInternalActual, device_executor, nullptr, failures));
+ });
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ // the user request is completed on the device thread, which is then held before it releases the execution slot
+ auto callback_executor = std::make_shared<HoldingCallbackExecutor>();
+ (compiled_model.get()->*(&CallbackExecutorAccess::set_callback_executor))(callback_executor);
+ std::shared_ptr<ov::IAsyncInferRequest> request;
+ OV_ASSERT_NO_THROW(request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(request->start_async());
+ ASSERT_TRUE(callback_executor->wait_until_held(std::chrono::seconds(10)));
+ ASSERT_TRUE(request->wait_for(std::chrono::seconds(10)));
+
+ auto teardown_started = std::make_shared<std::promise<void>>();
+ auto teardown_done = std::make_shared<std::promise<void>>();
+ auto started = teardown_started->get_future();
+ auto finished = teardown_done->get_future();
+ std::thread teardown([teardown_started,
+ teardown_done,
+ request = std::move(request),
+ compiled_model = std::move(compiled_model)]() mutable {
+ teardown_started->set_value();
+ request.reset();
+ compiled_model.reset();
+ teardown_done->set_value();
+ });
+ ASSERT_EQ(started.wait_for(std::chrono::seconds(10)), std::future_status::ready);
+ // destruction has to wait for the held device callback
+ EXPECT_EQ(finished.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout);
+
+ callback_executor->release();
+ if (finished.wait_for(std::chrono::seconds(10)) != std::future_status::ready) {
+ teardown.detach();
+ FAIL() << "destruction did not finish after the device completion callback was released";
+ }
+ teardown.join();
+}
+
+// The selection which reserves nothing must not be steered by the reservations of other models either.
+TEST_F(AutoDynamicDeviceSelectionTest, reservations_of_other_models_do_not_affect_the_selection) {
+ auto devices = plugin->Plugin::parse_meta_devices("GPU.0," + std::string(ov::test::utils::DEVICE_CPU), config);
+ const auto gpu0 = devices.front();
+ // a model of a higher priority holds GPU.0
+ plugin->register_priority(0, gpu0.unique_name);
+ ov::auto_plugin::DeviceSelectionPolicy policy;
+ DeviceInformation reserving;
+ OV_ASSERT_NO_THROW(reserving = plugin->Plugin::select_device(devices, "FP32", 2, policy, {}));
+ plugin->unregister_priority(2, reserving.unique_name);
+ EXPECT_EQ(reserving.device_name, ov::test::utils::DEVICE_CPU);
+
+ policy.reserve_device = false;
+ DeviceInformation ignoring;
+ OV_ASSERT_NO_THROW(ignoring = plugin->Plugin::select_device(devices, "FP32", 2, policy, {}));
+ EXPECT_EQ(ignoring.device_name, "GPU.0");
+ plugin->unregister_priority(0, gpu0.unique_name);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, no_device_is_reserved_while_switching_devices) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,CPU"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(Return(mockExeNetworkActual));
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ expect_no_device_reserved({"GPU.0", "GPU.1"});
+ gpu0_over_threshold->store(true);
+ run_inferences(compiled_model, 1);
+ expect_no_device_reserved({"GPU.0", "GPU.1"});
+}
+
+
+TEST_F(AutoDynamicDeviceSelectionTest, execution_devices_follows_the_active_device) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,CPU"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(Return(mockExeNetworkActual));
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ const auto execution_devices = [&compiled_model] {
+ return compiled_model->get_property(ov::execution_devices.name()).as<std::vector<std::string>>();
+ };
+ EXPECT_EQ(execution_devices(), std::vector<std::string>{"GPU.0"});
+
+ gpu0_over_threshold->store(true);
+ run_inferences(compiled_model, 1);
+ EXPECT_EQ(execution_devices(), std::vector<std::string>{"GPU.1"});
+}
+
+// The low power device may sit outside the candidates: a tensor created on it still has to pin the request there.
+TEST_F(AutoDynamicDeviceSelectionTest, remote_tensor_of_an_out_of_list_low_power_device_is_accepted) {
+ config.insert(ov::intel_auto::low_power_device("GPU.1"));
+ ON_CALL(*plugin, get_low_power_mode()).WillByDefault(Return(true));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(Return(mockExeNetworkActual));
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ const auto input = compiled_model->inputs().at(0);
+ auto remote_tensor = std::make_shared<DeviceTaggedRemoteTensor>("GPU.1", input.get_element_type(), input.get_shape());
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(infer_request->set_tensor(input, ov::SoPtr<ov::ITensor>{remote_tensor, nullptr}));
+ OV_ASSERT_NO_THROW(infer_request->start_async());
+ OV_ASSERT_NO_THROW(infer_request->wait());
+}
+
+// A remote output tensor pins the request to its device, the same way a remote input does.
+TEST_F(AutoDynamicDeviceSelectionTest, remote_output_tensor_pins_the_request_to_its_device) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(Return(mockExeNetworkActual));
+ // only the selection done while compiling the model: a pinned request skips the per inference selection
+ EXPECT_CALL(*plugin, select_device).Times(1);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ const auto output = compiled_model->outputs().at(0);
+ auto remote_tensor =
+ std::make_shared<DeviceTaggedRemoteTensor>("GPU.1", output.get_element_type(), output.get_shape());
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(infer_request->set_tensor(output, ov::SoPtr<ov::ITensor>{remote_tensor, nullptr}));
+ OV_ASSERT_NO_THROW(infer_request->start_async());
+ OV_ASSERT_NO_THROW(infer_request->wait());
+}
+
+// The request can only run on one device, so remote tensors from different devices cannot be mixed.
+TEST_F(AutoDynamicDeviceSelectionTest, remote_input_and_output_tensors_of_different_devices_are_rejected) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ const auto input = compiled_model->inputs().at(0);
+ const auto output = compiled_model->outputs().at(0);
+ auto remote_input =
+ std::make_shared<DeviceTaggedRemoteTensor>("GPU.0", input.get_element_type(), input.get_shape());
+ auto remote_output =
+ std::make_shared<DeviceTaggedRemoteTensor>("GPU.1", output.get_element_type(), output.get_shape());
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(infer_request->set_tensor(input, ov::SoPtr<ov::ITensor>{remote_input, nullptr}));
+ OV_ASSERT_NO_THROW(infer_request->set_tensor(output, ov::SoPtr<ov::ITensor>{remote_output, nullptr}));
+ OV_ASSERT_NO_THROW(infer_request->start_async());
+ EXPECT_THROW(infer_request->wait(), ov::Exception);
+}
+
+// Per inference selection is off here (THROUGHPUT), so the legacy runtime fallback handles the failure. The low power
+// device sits outside the candidates, so its very first failure must still fall back to the configured priorities.
+TEST_F(AutoDynamicDeviceSelectionTest, out_of_list_low_power_device_first_failure_falls_back_at_runtime) {
+ config.insert(ov::hint::performance_mode(ov::hint::PerformanceMode::THROUGHPUT));
+ config.insert(ov::intel_auto::enable_startup_fallback(false));
+ config.insert(ov::intel_auto::enable_runtime_fallback(true));
+ config.insert(ov::intel_auto::low_power_device("GPU.1"));
+ ON_CALL(*plugin, get_low_power_mode()).WillByDefault(Return(true));
+
+ auto mock_gpu1 = std::make_shared<NiceMock<ov::MockICompiledModel>>(model, plugin);
+ ON_CALL(*mock_gpu1, inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));
+ ON_CALL(*mock_gpu1, outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));
+ ON_CALL(*mock_gpu1, get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
+ .WillByDefault(Return(optimalNum));
+ auto executor = std::make_shared<ov::threading::ImmediateExecutor>();
+ // a weak reference avoids a cycle through the mock's own action, which gmock would report as a leak
+ ON_CALL(*mock_gpu1, create_infer_request()).WillByDefault([weak_gpu1 = std::weak_ptr(mock_gpu1), executor]() {
+ auto sync_request = std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(weak_gpu1.lock());
+ return std::make_shared<ov::mock_auto_plugin::MockAsyncInferRequest>(sync_request, executor, nullptr, true);
+ });
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault(Return(ov::SoPtr<ov::ICompiledModel>{mock_gpu1, {}}));
+ ON_CALL(*mockIExeNetActual.get(), create_infer_request()).WillByDefault([this]() {
+ return mockIExeNetActual->ICompiledModel::create_infer_request();
+ });
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ auto infer_request = compiled_model->create_infer_request();
+ OV_ASSERT_NO_THROW(infer_request->infer());
+
+ // destroying the model must release the reservation of the fallback device as well
+ infer_request.reset();
+ compiled_model.reset();
+ expect_no_device_reserved({"GPU.0", "GPU.1"});
+}
+
+// Every candidate fails to compile in turn, so the cascade runs out of devices and ends on the cached GPU.0.
+TEST_F(AutoDynamicDeviceSelectionTest, exhausted_compile_cascade_reserves_no_device) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,GPU.1,GPU.2"));
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ auto gpu0_compile_fails = std::make_shared<std::atomic<bool>>(false);
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ _))
+ .WillByDefault([this, gpu0_compile_fails](const std::shared_ptr<const ov::Model>&,
+ const std::string&,
+ const ov::AnyMap&) -> ov::SoPtr<ov::ICompiledModel> {
+ if (gpu0_compile_fails->load()) {
+ OPENVINO_THROW("mock compile failure on GPU.0");
+ }
+ return mockExeNetworkActual;
+ });
+ for (const auto* device : {"GPU.1", "GPU.2"}) {
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(device)),
+ _))
+ .WillByDefault(ov::Throw("mock compile failure"));
+ }
+ // every device is compiled exactly once, GPU.0 when the model is loaded and the failed ones on demand
+ for (const auto* device : {"GPU.0", "GPU.1", "GPU.2"}) {
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(device)),
+ ::testing::Matcher<const ov::AnyMap&>(_)))
+ .Times(1);
+ }
+ auto gpu0_over_threshold = std::make_shared<std::atomic<bool>>(false);
+ mock_gpu0_over_threshold(gpu0_over_threshold);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+
+ gpu0_compile_fails->store(true);
+ gpu0_over_threshold->store(true);
+ std::shared_ptr<ov::IAsyncInferRequest> infer_request;
+ OV_ASSERT_NO_THROW(infer_request = compiled_model->create_infer_request());
+ // GPU.1 and GPU.2 fail to compile, the cascade ends on the cached GPU.0 which must not be compiled again
+ OV_ASSERT_NO_THROW(infer_request->infer());
+ // both failed devices are excluded, so neither of them is compiled again
+ OV_ASSERT_NO_THROW(infer_request->infer());
+ expect_no_device_reserved({"GPU.0", "GPU.1", "GPU.2"});
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, explicit_runtime_fallback_is_rejected) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::intel_auto::enable_runtime_fallback(true));
+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, disabled_runtime_fallback_is_accepted) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::intel_auto::enable_runtime_fallback(false));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 1);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, explicit_model_priority_is_ignored) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::hint::model_priority(ov::hint::Priority::HIGH));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 1);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, more_than_one_stream_is_rejected) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::num_streams(2));
+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, single_stream_is_accepted) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::num_streams(1));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 1);
+}
+
+// Without the per inference selection these properties keep their usual meaning.
+TEST_F(AutoDynamicDeviceSelectionTest, fallback_priority_and_streams_are_accepted_without_resource_aware_properties) {
+ config.insert(ov::intel_auto::enable_runtime_fallback(true));
+ config.insert(ov::hint::model_priority(ov::hint::Priority::HIGH));
+ config.insert(ov::num_streams(2));
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+}
+
+// A failed inference is reported to the caller, it is not retried on another device and it does not block the gate.
+TEST_F(AutoDynamicDeviceSelectionTest, inference_failure_is_reported_instead_of_retried_on_another_device) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ auto executor = std::make_shared<ov::threading::ImmediateExecutor>();
+ ON_CALL(*mockIExeNetActual.get(), create_infer_request()).WillByDefault([this, executor]() {
+ auto sync_request = std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(mockIExeNetActual);
+ return std::make_shared<ov::mock_auto_plugin::MockAsyncInferRequest>(sync_request, executor, nullptr, true);
+ });
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ _))
+ .WillRepeatedly(Return(mockExeNetworkActual));
+ EXPECT_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(ov::test::utils::DEVICE_CPU)),
+ _))
+ .Times(0);
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ auto infer_request = compiled_model->create_infer_request();
+ EXPECT_THROW(infer_request->infer(), ov::Exception);
+ EXPECT_THROW(infer_request->infer(), ov::Exception);
+}
+
+// Records the NUM_STREAMS every compile_model() call of the device received, -100 if it was not passed at all.
+class StreamsRecorder {
+public:
+ void attach(tests::AutoTest& test, const std::string& device, const ov::SoPtr<ov::ICompiledModel>& compiled_model) {
+ ON_CALL(*test.core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq(device)),
+ _))
+ .WillByDefault([this, device, compiled_model](const std::shared_ptr<const ov::Model>&,
+ const std::string&,
+ const ov::AnyMap& properties) {
+ const auto iter = properties.find(ov::num_streams.name());
+ m_streams[device] = iter == properties.end() ? -100 : iter->second.as<ov::streams::Num>().num;
+ return compiled_model;
+ });
+ }
+ int32_t streams(const std::string& device) const {
+ const auto iter = m_streams.find(device);
+ return iter == m_streams.end() ? -200 : iter->second;
+ }
+
+private:
+ std::map<std::string, int32_t> m_streams;
+};
+
+TEST_F(AutoDynamicDeviceSelectionTest, one_stream_is_used_when_the_user_did_not_choose) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ StreamsRecorder recorder;
+ recorder.attach(*this, "GPU.0", mockExeNetworkActual);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ EXPECT_EQ(recorder.streams("GPU.0"), 1);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, one_stream_is_used_for_the_out_of_list_low_power_device) {
+ config.insert(ov::intel_auto::low_power_device("GPU.1"));
+ ON_CALL(*plugin, get_low_power_mode()).WillByDefault(Return(true));
+ StreamsRecorder recorder;
+ recorder.attach(*this, "GPU.1", mockExeNetworkActual);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ EXPECT_EQ(recorder.streams("GPU.1"), 1);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, explicit_streams_setting_is_kept) {
+ config.insert(ov::intel_auto::devices_utilization_threshold(std::map<std::string, unsigned>{{"GPU.0", 80}}));
+ config.insert(ov::num_streams(ov::streams::AUTO));
+ StreamsRecorder recorder;
+ recorder.attach(*this, "GPU.0", mockExeNetworkActual);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ EXPECT_EQ(recorder.streams("GPU.0"), ov::streams::AUTO.num);
+}
+
+TEST_F(AutoDynamicDeviceSelectionTest, streams_are_not_forced_without_the_per_inference_selection) {
+ StreamsRecorder recorder;
+ recorder.attach(*this, "GPU.0", mockExeNetworkActual);
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ EXPECT_EQ(recorder.streams("GPU.0"), -100);
+}
+} // namespace ov::test
diff --git a/src/plugins/auto/tests/unit/include/gmock_plugin.hpp b/src/plugins/auto/tests/unit/include/gmock_plugin.hpp
index a2fdb3c4357..18b8ae2c642 100644
--- a/src/plugins/auto/tests/unit/include/gmock_plugin.hpp
+++ b/src/plugins/auto/tests/unit/include/gmock_plugin.hpp
@@ -23,6 +23,7 @@ public:
(const std::list<DeviceInformation>&),
(override));
MOCK_METHOD((std::optional<bool>), get_low_power_mode, (), (override));
+ MOCK_METHOD((bool), is_telemetry_available, (), (const, override));
MOCK_METHOD((std::string),
get_device_list,
((ov::AnyMap&), const std::shared_ptr<const ov::Model>&, const std::filesystem::path&),
@@ -38,7 +39,7 @@ public:
const std::string&,
unsigned int,
(const DeviceSelectionPolicy&),
- const std::string&),
+ (const std::optional<DeviceInformation>&)),
(override));
MOCK_METHOD((std::list<DeviceInformation>),
sort_device_by_perf_curve,
diff --git a/src/plugins/auto/tests/unit/select_device_test.cpp b/src/plugins/auto/tests/unit/select_device_test.cpp
index 2c73048844b..2adf491fbdc 100644
--- a/src/plugins/auto/tests/unit/select_device_test.cpp
+++ b/src/plugins/auto/tests/unit/select_device_test.cpp
@@ -201,7 +201,7 @@ public:
const std::string& netPrecision,
unsigned int priority,
const ov::auto_plugin::DeviceSelectionPolicy& selection_policy,
- const std::string& low_power_device) {
+ const std::optional<DeviceInformation>& low_power_device) {
return plugin->Plugin::select_device(metaDevices, netPrecision, priority, selection_policy, low_power_device);
});
ON_CALL(*plugin, get_valid_device)
@@ -818,27 +818,35 @@ protected:
TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, lowPowerDeviceOverridesThreshold) {
EXPECT_CALL(*plugin, get_low_power_mode()).WillOnce(Return(true));
- auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, "NPU");
+ auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, devices[1]);
selectedUniqueName = result.unique_name;
EXPECT_EQ(result.unique_name, "NPU_01");
}
-TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, lowPowerDeviceMatchesViaBaseNameFallback) {
- // low_power_device="NPU" must still match a candidate whose device_name carries a HW id suffix.
- std::vector<std::string> npuHwIdCapability = {"FP32", "FP16", "INT8", "BIN"};
- ON_CALL(*core, get_property(StrEq("NPU.5010"), StrEq(ov::device::capabilities.name()), _))
- .WillByDefault(RETURN_MOCK_VALUE(npuHwIdCapability));
- std::vector<DeviceInformation> devicesWithHwId = {{"CPU", {}, -1, "01", "CPU_01", 0},
- {"NPU.5010", {}, -1, "01", "NPU_01", 0}};
+TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, lowPowerDeviceSelectedEvenWhenNotInCandidateList) {
+ // Device is blocklisted (not in valid_devices) but must still be queried and selected.
+ std::vector<DeviceInformation> devicesWithoutNpu = {{"CPU", {}, -1, "01", "CPU_01", 0}};
+ DeviceInformation npu{"NPU", {}, -1, "01", "NPU_01", 0};
EXPECT_CALL(*plugin, get_low_power_mode()).WillOnce(Return(true));
- auto result = plugin->select_device(devicesWithHwId, netPrecision, 0, {thresholds, {}}, "NPU");
+ auto result = plugin->select_device(devicesWithoutNpu, netPrecision, 0, {thresholds, {}}, npu);
selectedUniqueName = result.unique_name;
EXPECT_EQ(result.unique_name, "NPU_01");
}
+TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, lowPowerDeviceSelectedWhenPriorityFilteringRemovesAllCandidates) {
+ std::vector<DeviceInformation> cpuOnly = {{"CPU", {}, -1, "01", "CPU_01", 0}};
+ // a higher priority model holds the only candidate
+ plugin->register_priority(0, "CPU_01");
+ EXPECT_CALL(*plugin, get_low_power_mode()).WillOnce(Return(true));
+ auto result = plugin->select_device(cpuOnly, netPrecision, 2, {thresholds, {}}, devices[1]);
+ EXPECT_EQ(result.unique_name, "NPU_01");
+ plugin->unregister_priority(2, result.unique_name);
+ plugin->unregister_priority(0, "CPU_01");
+}
+
TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, fallsBackToThresholdWhenNotInLowPowerMode) {
EXPECT_CALL(*plugin, get_low_power_mode()).WillOnce(Return(false));
- auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, "NPU");
+ auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, devices[1]);
selectedUniqueName = result.unique_name;
// threshold logic excludes the over-utilized NPU once low_power_device is not applicable.
EXPECT_EQ(result.unique_name, "CPU_01");
@@ -846,21 +854,13 @@ TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, fallsBackToThresholdWhenNot
TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, unknownLowPowerModeTreatedAsNotLowPower) {
EXPECT_CALL(*plugin, get_low_power_mode()).WillOnce(Return(std::nullopt));
- auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, "NPU");
- selectedUniqueName = result.unique_name;
- EXPECT_EQ(result.unique_name, "CPU_01");
-}
-
-TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, lowPowerDeviceNotInCandidateListFallsThrough) {
- // get_low_power_mode() is not called when the preferred device is not a candidate.
- EXPECT_CALL(*plugin, get_low_power_mode()).Times(0);
- auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, "GPU.0");
+ auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, devices[1]);
selectedUniqueName = result.unique_name;
EXPECT_EQ(result.unique_name, "CPU_01");
}
TEST_F(SelectDeviceWithLowPowerDevicePrecedenceTest, getLowPowerModeNotQueriedWhenLowPowerDeviceUnset) {
- // Guarantees zero behavior/perf impact on all pre-existing callers that leave low_power_device empty.
+ // Guarantees zero behavior/perf impact on all pre-existing callers that leave low_power_device unset.
EXPECT_CALL(*plugin, get_low_power_mode()).Times(0);
auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, {});
selectedUniqueName = result.unique_name;
diff --git a/src/plugins/auto/tests/unit/sources.cmake b/src/plugins/auto/tests/unit/sources.cmake
index 05230a517ba..6e31f852bc6 100644
--- a/src/plugins/auto/tests/unit/sources.cmake
+++ b/src/plugins/auto/tests/unit/sources.cmake
@@ -9,6 +9,7 @@ set(OV_AUTO_UNIT_TESTS_SRC
${CMAKE_CURRENT_LIST_DIR}/ctput_test.cpp
${CMAKE_CURRENT_LIST_DIR}/default_perf_hint_test.cpp
${CMAKE_CURRENT_LIST_DIR}/device_telemetry_test.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/dynamic_device_selection_test.cpp
${CMAKE_CURRENT_LIST_DIR}/dynamic_output_test.cpp
${CMAKE_CURRENT_LIST_DIR}/get_device_list.cpp
${CMAKE_CURRENT_LIST_DIR}/include/auto_unit_test.hpp