Skip to content

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

[AUTO] Release compiled model of inactive device in dynamic selection (#39563)

guozhong wang90a5ddd79b05
diff --git a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/auto-device-selection.rst b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/auto-device-selection.rst
index a35332b732b..9f15e0bf495 100644
--- a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/auto-device-selection.rst
+++ b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/auto-device-selection.rst
@@ -211,6 +211,11 @@ the following setup options:
| | Enabling it disables ``ov::intel_auto::enable_startup_fallback`` |
| | and ``ov::intel_auto::enable_runtime_fallback``. |
| | |
+| | In dynamic device selection, a device that is no longer selected |
+| | releases its compiled model, which is loaded from the cache when |
+| | it is selected again. Devices without a cache location or a cache |
+| | blob are never released. |
+| | |
| | Requires ``ov::cache_dir`` or ``ov::cache_path``. Without them, |
| | compiling the model throws on every host. |
| | |
diff --git a/src/inference/include/openvino/runtime/auto/properties.hpp b/src/inference/include/openvino/runtime/auto/properties.hpp
index 38d89dd69be..9dc88fa61e7 100644
--- a/src/inference/include/openvino/runtime/auto/properties.hpp
+++ b/src/inference/include/openvino/runtime/auto/properties.hpp
@@ -37,6 +37,8 @@ static constexpr Property<bool> enable_runtime_fallback{"ENABLE_RUNTIME_FALLBACK
* Requires ov::cache_dir or ov::cache_path, otherwise compiling the model throws on every host. Ignored in
* cumulative throughput mode, when there is no other candidate device, and when
* ov::cache_blob_id is set. Devices are skipped when the cache path is a single-file cache (*.bin).
+ * In dynamic device selection, an inactive device, including the initial device, releases its compiled model only
+ * if it supports model caching and has a cache location with an existing blob. It is reloaded when selected again.
*
* When ov::device::priorities (or a device string such as "AUTO:GPU,NPU") is set, it determines the candidates;
* otherwise AUTO discovers its usual eligible devices. For example, to warm up the cache for GPU and NPU, so that
diff --git a/src/inference/tests/functional/caching_test.cpp b/src/inference/tests/functional/caching_test.cpp
index 8202e9015e6..759c5a31579 100644
--- a/src/inference/tests/functional/caching_test.cpp
+++ b/src/inference/tests/functional/caching_test.cpp
@@ -280,6 +280,9 @@ public:
.Times(AnyNumber())
.WillRepeatedly(Return(ov::Any{1u}));
EXPECT_CALL(*mock, get_property(ov::model_name.name())).Times(AnyNumber()).WillRepeatedly(Return("mock_net"));
+ EXPECT_CALL(*mock, get_property(ov::loaded_from_cache.name()))
+ .Times(AnyNumber())
+ .WillRepeatedly(Return(ov::Any{false}));
EXPECT_CALL(*mock, get_property(ov::supported_properties.name()))
.Times(AnyNumber())
.WillRepeatedly(Return(std::vector<ov::PropertyName>{ov::supported_properties.name(),
diff --git a/src/plugins/auto/src/auto_compiled_model.cpp b/src/plugins/auto/src/auto_compiled_model.cpp
index 12a24a1661f..f6c0b5d17f2 100644
--- a/src/plugins/auto/src/auto_compiled_model.cpp
+++ b/src/plugins/auto/src/auto_compiled_model.cpp
@@ -31,9 +31,12 @@ void AutoCompiledModel::set_property(const ov::AnyMap& properties) {
}
std::shared_ptr<const ov::Model> AutoCompiledModel::get_runtime_model() const {
- OPENVINO_ASSERT(m_context->m_hw_compiled_model);
- auto model = m_context->m_hw_compiled_model->get_runtime_model();
- set_model_shared_object(const_cast<ov::Model&>(*model), m_context->m_hw_compiled_model._so);
+ const auto hw_compiled_model = m_context->m_dynamic_device_selection
+ ? m_scheduler->get_dynamic_query_model().second
+ : m_context->m_hw_compiled_model;
+ OPENVINO_ASSERT(hw_compiled_model);
+ auto model = hw_compiled_model->get_runtime_model();
+ set_model_shared_object(const_cast<ov::Model&>(*model), hw_compiled_model._so);
return model;
}
@@ -72,6 +75,10 @@ ov::Any AutoCompiledModel::get_property(const std::string& name) const {
// device priority does not support change on-the-fly
return decltype(ov::device::priorities)::value_type(m_context->m_str_devices);
} else if (name == ov::device::properties) {
+ if (m_context->m_dynamic_device_selection) {
+ const auto query = m_scheduler->get_dynamic_query_model();
+ return get_device_supported_properties(query.first, query.second);
+ }
ov::AnyMap all_devices = {};
{
std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
@@ -237,6 +244,11 @@ ov::Any AutoCompiledModel::get_property(const std::string& name) const {
}
return execution_devices;
} else if (name == ov::model_name) {
+ if (m_context->m_dynamic_device_selection) {
+ const auto query = m_scheduler->get_dynamic_query_model();
+ OPENVINO_ASSERT(query.second);
+ return query.second->get_property(name);
+ }
std::lock_guard<std::mutex> lock(m_context->m_mutex);
{
if (m_scheduler->m_compile_context[CPU].m_is_enabled && m_scheduler->m_compile_context[CPU].m_is_already)
@@ -244,6 +256,16 @@ ov::Any AutoCompiledModel::get_property(const std::string& name) const {
return m_scheduler->m_compile_context[ACTUALDEVICE].m_compiled_model->get_property(name);
}
} else if (name == ov::loaded_from_cache) {
+ if (m_context->m_dynamic_device_selection) {
+ const auto query = m_scheduler->get_dynamic_query_model();
+ try {
+ OPENVINO_ASSERT(query.second);
+ return query.second->get_property(name).as<bool>();
+ } catch (const ov::Exception&) {
+ LOG_DEBUG_TAG("get_property loaded_from_cache from %s failed", query.first.c_str());
+ return false;
+ }
+ }
std::lock_guard<std::mutex> lock(m_context->m_fallback_mutex);
std::string device_name;
try {
diff --git a/src/plugins/auto/src/auto_schedule.cpp b/src/plugins/auto/src/auto_schedule.cpp
index 70bec3446f2..55c047f32b1 100644
--- a/src/plugins/auto/src/auto_schedule.cpp
+++ b/src/plugins/auto/src/auto_schedule.cpp
@@ -5,6 +5,7 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <chrono>
+#include <utility>
#include "auto_schedule.hpp"
@@ -108,6 +109,11 @@ DeviceName AutoSchedule::get_dynamic_active_device() const {
return m_gate_current_device;
}
+std::pair<DeviceName, SoCompiledModel> AutoSchedule::get_dynamic_query_model() const {
+ std::lock_guard<std::mutex> lock(m_context->m_mutex);
+ return {m_dynamic_query_device, m_context->m_hw_compiled_model};
+}
+
void AutoSchedule::init() {
if (m_context->m_bind_buffer) {
LOG_INFO_TAG("bind buffer supported only under cumulative mode, ignoring");
@@ -144,8 +150,7 @@ void AutoSchedule::init() {
return device.device_name != actual_device && ov::DeviceIDParser(device.device_name).get_device_name() != "CPU";
});
if (!has_warmup_candidate) {
- LOG_WARNING_TAG("compile_for_all is ignored: no other non-CPU candidate device to compile");
- m_context->m_compile_for_all = false;
+ LOG_INFO_TAG("compile_for_all cache warm-up is skipped: no other non-CPU candidate device to compile");
} else {
// Fallbacks switch devices non-deterministically and would overlap with the background warm-up.
LOG_INFO_TAG("compile_for_all disables startup and runtime fallback");
@@ -321,7 +326,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:%zu", m_cpuhelp_infer_count);
+ LOG_INFO_TAG("CPU_HELP:infer:%lu", static_cast<unsigned long>(m_cpuhelp_infer_count));
LOG_INFO_TAG("CPU_HELP:fps:%lf", m_cpuhelp_fps);
}
});
@@ -358,6 +363,7 @@ void AutoSchedule::init() {
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;
+ m_dynamic_query_device = initial_device;
LOG_INFO_TAG("[dynamic] initial target device:%s", initial_device.c_str());
}
} else {
@@ -426,7 +432,15 @@ void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::
auto compiled_time =
std::chrono::duration_cast<std::chrono::nanoseconds>(compile_end_time - compile_start_time).count() *
0.000001;
- LOG_INFO_TAG("Device: [%s]: Compile model took %lf ms", device.c_str(), compiled_time);
+ const char* loaded_from_cache = "unknown";
+ try {
+ loaded_from_cache = context.m_compiled_model->get_property(ov::loaded_from_cache.name()).as<bool>() ? "yes" : "no";
+ } catch (const ov::Exception&) {
+ }
+ LOG_INFO_TAG("Device: [%s]: Compile model took %lf ms, loaded from cache: %s",
+ device.c_str(),
+ compiled_time,
+ loaded_from_cache);
} catch (const ov::Exception& e) {
context.m_err_message += device + ":" + e.what();
LOG_WARNING_TAG("Device: [%s]: Compile model failure: %s", device.c_str(), e.what());
@@ -617,8 +631,8 @@ bool AutoSchedule::schedule_dynamic_task(ov::threading::Task pipeline_task, cons
}
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());
+ LOG_DEBUG_TAG("[dynamic] an inference is still running, request queued, queue size:%lu",
+ static_cast<unsigned long>(m_gate_pending_tasks.size()));
return false;
}
m_gate_busy = true;
@@ -677,16 +691,29 @@ void AutoSchedule::dispatch_dynamic_task(ov::threading::Task& pipeline_task, con
device = select_dynamic_device();
}
const bool is_pinned = !preferred_device.empty();
- const auto pinned_device_name = device.device_name;
+ const auto requested_device_name = device.device_name;
+ DeviceName previous_device;
+ double previous_infer_ms = -1.0;
+ {
+ std::lock_guard<std::mutex> lock(m_gate_mutex);
+ previous_device = m_gate_current_device;
+ previous_infer_ms = m_last_infer_ms;
+ }
+ if (previous_infer_ms >= 0.0) {
+ LOG_DEBUG_TAG("[dynamic] previous inference on device:%s took %lf ms",
+ previous_device.c_str(),
+ previous_infer_ms);
+ }
+ // the previous device stays usable for fallback until the new one is ready
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,
+ OPENVINO_ASSERT(!is_pinned || device.device_name == requested_device_name,
get_log_tag(),
": failed to compile the model on the device pinned by the remote tensor ",
- pinned_device_name);
+ requested_device_name);
const auto& device_name = device.device_name;
{
std::lock_guard<std::mutex> lock(m_gate_mutex);
@@ -717,6 +744,17 @@ void AutoSchedule::dispatch_dynamic_task(ov::threading::Task& pipeline_task, con
m_idle_worker_requests[device_name].try_push(std::make_pair(worker->m_index, worker));
release_execution_slot();
}
+ // off the critical path: the next dispatch runs on this single stream executor, so it waits for the release
+ if (previous_device != device_name) {
+ try {
+ release_inactive_device(previous_device, device_name);
+ } catch (const std::exception& ex) {
+ // releasing is only a memory optimization and must not fail a dispatched inference
+ LOG_WARNING_TAG("[dynamic] failed to release inactive device:%s: %s",
+ previous_device.c_str(),
+ ex.what());
+ }
+ }
} catch (const std::exception&) {
m_this_worker_infer_request = nullptr;
release_execution_slot();
@@ -747,7 +785,7 @@ DeviceInformation AutoSchedule::select_dynamic_device() {
low_power_device);
}
// select_device() reserves nothing in the dynamic selection
- LOG_DEBUG_TAG("[dynamic] re-selected device:%s in %lf ms",
+ LOG_DEBUG_TAG("[dynamic] 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;
@@ -767,7 +805,13 @@ bool AutoSchedule::ensure_device_ready(DeviceInformation& device) {
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());
+ // only devices released before have an entry there
+ if (m_released_infer_times.count(device.device_name)) {
+ LOG_INFO_TAG("[dynamic] device:%s was released before, reloading the model", device.device_name.c_str());
+ } else {
+ 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);
@@ -831,6 +875,108 @@ bool AutoSchedule::ensure_device_ready(DeviceInformation& device) {
return true;
}
+void AutoSchedule::release_inactive_device(const DeviceName& device_name, const DeviceName& active_device) {
+ if (!m_context->m_compile_for_all || device_name.empty() || device_name == active_device) {
+ return;
+ }
+ const auto cached = m_dynamic_compiled_models.find(device_name);
+ const auto active = m_dynamic_compiled_models.find(active_device);
+ if (cached == m_dynamic_compiled_models.end() || active == m_dynamic_compiled_models.end()) {
+ return;
+ }
+ // Without a cache for this device, a released model would need a full recompilation.
+ const auto info = std::find_if(m_context->m_device_priorities_initial.begin(),
+ m_context->m_device_priorities_initial.end(),
+ [&](const DeviceInformation& device) {
+ return device.device_name == device_name;
+ });
+ const ov::AnyMap no_config;
+ const auto& device_config =
+ info != m_context->m_device_priorities_initial.end()
+ ? info->config
+ : (m_context->m_low_power_device && m_context->m_low_power_device->device_name == device_name
+ ? m_context->m_low_power_device->config
+ : no_config);
+ auto supports_caching = m_device_supports_caching.find(device_name);
+ if (supports_caching == m_device_supports_caching.end()) {
+ bool supported = false;
+ try {
+ supported = m_context->m_ov_core->device_supports_model_caching(device_name);
+ } catch (const ov::Exception&) {
+ }
+ supports_caching = m_device_supports_caching.emplace(device_name, supported).first;
+ }
+ const auto cache_location =
+ CacheWarmupManager::get_cache_location(*m_context->m_ov_core, device_config, device_name);
+ if (!supports_caching->second || cache_location.empty()) {
+ return;
+ }
+ bool has_cache_blob = false;
+ try {
+ auto blob_id = m_dynamic_cache_blob_ids.find(device_name);
+ if (blob_id == m_dynamic_cache_blob_ids.end()) {
+ blob_id = m_dynamic_cache_blob_ids
+ .emplace(device_name,
+ CacheWarmupManager::get_blob_id(*m_context->m_ov_core,
+ device_name,
+ device_config,
+ m_dynamic_model,
+ m_context->m_model_path))
+ .first;
+ }
+ // Keep the filesystem check fresh in case the cache entry was removed after the key was computed.
+ has_cache_blob = CacheWarmupManager::is_blob_cached(cache_location, blob_id->second);
+ } catch (const std::exception& ex) {
+ // A cache probe is only an optimization; retain the compiled model if the probe fails.
+ LOG_DEBUG_TAG("[dynamic] cache probe failed for %s: %s", device_name.c_str(), ex.what());
+ }
+ if (!has_cache_blob) {
+ return;
+ }
+ const auto workers_it = m_worker_requests.find(device_name);
+ const auto idle_workers_it = m_idle_worker_requests.find(device_name);
+ if (workers_it == m_worker_requests.end() || idle_workers_it == m_idle_worker_requests.end()) {
+ return;
+ }
+ auto& workers = workers_it->second;
+ auto& idle_workers = idle_workers_it->second;
+ // the dynamic selection runs one worker per device, so an empty idle queue means it is still running
+ std::pair<int, WorkerInferRequest*> worker;
+ if (workers.size() != 1 || !idle_workers.try_pop(worker)) {
+ return;
+ }
+ // unmap first so a throwing teardown leaves the device to be rebuilt by generate_workers(); the model dies last
+ auto model_to_release = std::move(cached->second);
+ m_dynamic_compiled_models.erase(cached);
+ // the other references of the released model are dropped together with it, after its requests
+ SoCompiledModel initial_model;
+ SoCompiledModel query_model;
+ {
+ std::lock_guard<std::mutex> lock(m_context->m_mutex);
+ if (device_name == m_compile_context[ACTUALDEVICE].m_device_info.device_name) {
+ initial_model = std::exchange(m_compile_context[ACTUALDEVICE].m_compiled_model, {});
+ }
+ if (device_name == m_dynamic_query_device) {
+ query_model = std::exchange(m_context->m_hw_compiled_model, active->second);
+ m_dynamic_query_device = active_device;
+ }
+ }
+ // the requests go first, they keep the compiled model alive; their timings are kept for the final summary
+ auto& released_times = m_released_infer_times[device_name];
+ released_times.first.splice(released_times.first.end(), workers.front().m_start_times);
+ released_times.second.splice(released_times.second.end(), workers.front().m_end_times);
+ workers.clear();
+ idle_workers.set_capacity(0);
+ if (const auto tasks_it = m_infer_pipeline_tasks_device_specific.find(device_name);
+ tasks_it != m_infer_pipeline_tasks_device_specific.end()) {
+ tasks_it->second = nullptr;
+ }
+ query_model = {};
+ initial_model = {};
+ model_to_release = {};
+ LOG_INFO_TAG("[dynamic] device:%s is inactive, its compiled model is released", device_name.c_str());
+}
+
void AutoSchedule::release_execution_slot() {
std::pair<ov::threading::Task, DeviceName> next;
std::shared_ptr<ov::threading::IStreamsExecutor> executor;
@@ -860,8 +1006,6 @@ void AutoSchedule::release_execution_slot() {
}
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());
@@ -889,9 +1033,9 @@ AutoSchedule::~AutoSchedule() {
});
}
if (dynamic_executor) {
- LOG_INFO_TAG("[dynamic] total inference:%zu, device switch:%zu",
- m_dynamic_infer_count.load(),
- m_dynamic_switch_count.load());
+ LOG_INFO_TAG("[dynamic] total inference:%lu, device switch:%lu",
+ static_cast<unsigned long>(m_dynamic_infer_count.load()),
+ static_cast<unsigned long>(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
diff --git a/src/plugins/auto/src/auto_schedule.hpp b/src/plugins/auto/src/auto_schedule.hpp
index 6b672110f9f..c9502a00c35 100644
--- a/src/plugins/auto/src/auto_schedule.hpp
+++ b/src/plugins/auto/src/auto_schedule.hpp
@@ -22,6 +22,9 @@ public:
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;
+ // dynamic selection only: the device and compiled model answering the model level queries;
+ // the initial device until it is released, then a device that is still loaded
+ std::pair<DeviceName, SoCompiledModel> get_dynamic_query_model() const;
private:
void init() override;
@@ -58,6 +61,12 @@ private:
* @note device is updated in place when the compilation falls back to another candidate device.
*/
bool ensure_device_ready(DeviceInformation& device);
+ /**
+ * @brief Drop the compiled model and workers of a device that is no longer the active one.
+ * @note Only done with compile_for_all, and only for devices that support model caching and have a cache location
+ * to reload from. The model level queries are moved to active_device when the released device answered them.
+ */
+ void release_inactive_device(const DeviceName& device_name, const DeviceName& active_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;
@@ -81,6 +90,12 @@ private:
DeviceName m_gate_current_device;
std::deque<std::pair<ov::threading::Task, DeviceName>> m_gate_pending_tasks;
DeviceMap<SoCompiledModel> m_dynamic_compiled_models;
+ // guarded by m_context->m_mutex together with m_context->m_hw_compiled_model, which is its compiled model
+ DeviceName m_dynamic_query_device;
+ // whether Core writes a cache blob for the device, queried once per device
+ DeviceMap<bool> m_device_supports_caching;
+ // Cache keys are immutable for this compiled model/device configuration; file existence is still probed per release.
+ DeviceMap<std::string> m_dynamic_cache_blob_ids;
std::atomic<size_t> m_dynamic_infer_count = {0};
std::atomic<size_t> m_dynamic_switch_count = {0};
};
diff --git a/src/plugins/auto/src/cache_warmup.cpp b/src/plugins/auto/src/cache_warmup.cpp
index 62636a5f201..3e035d521e8 100644
--- a/src/plugins/auto/src/cache_warmup.cpp
+++ b/src/plugins/auto/src/cache_warmup.cpp
@@ -112,7 +112,7 @@ void CacheWarmup::start(const std::string& actual_device, const std::vector<Devi
}
m_state = State::Idle;
m_devices = std::move(devices);
- LOG_INFO_TAG("start cache pre-compilation for %zu device(s)", m_devices.size());
+ LOG_INFO_TAG("start cache pre-compilation for %lu device(s)", static_cast<unsigned long>(m_devices.size()));
}
m_manager.enqueue(shared_from_this());
}
@@ -166,15 +166,20 @@ void CacheWarmup::run() {
cache_location.string().c_str());
} else {
// The compiled model is dropped on purpose: Core writes the cache blob as a side effect.
- if (model) {
- core->compile_model(model, device.device_name, config);
- } else {
- core->compile_model(m_model_path, device.device_name, config);
+ const auto compiled_model = model ? core->compile_model(model, device.device_name, config)
+ : core->compile_model(m_model_path, device.device_name, config);
+ const char* loaded_from_cache = "unknown";
+ try {
+ loaded_from_cache =
+ compiled_model->get_property(ov::loaded_from_cache.name()).as<bool>() ? "yes" : "no";
+ } catch (const ov::Exception&) {
}
- LOG_INFO_TAG("cache pre-compilation finished for device: %s, compile time: %lf ms",
+ LOG_INFO_TAG("cache pre-compilation finished for device: %s, compile time: %lf ms, loaded from "
+ "cache: %s",
device.device_name.c_str(),
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin)
- .count());
+ .count(),
+ loaded_from_cache);
}
}
} catch (const std::exception& e) {
@@ -265,32 +270,42 @@ std::filesystem::path CacheWarmupManager::get_cache_location(const ov::ICore& co
return query("").value_or(std::filesystem::path{});
}
+std::string CacheWarmupManager::get_blob_id(const ov::ICore& core,
+ const std::string& device_name,
+ const ov::AnyMap& config,
+ const std::shared_ptr<const ov::Model>& model,
+ const std::filesystem::path& model_path) {
+ OPENVINO_ASSERT(model || !model_path.empty(), "A model or model path is required to compute a cache blob ID");
+ const auto compile_config =
+ create_compile_config(core, device_name, core.get_supported_property(device_name, config));
+ // Same precedence as Core: a user blob ID wins, then the hash (which covers ov::cache_model_path for a model).
+ if (const auto it = config.find(ov::cache_blob_id.name()); it != config.end()) {
+ return it->second.as<std::string>();
+ }
+ if (model) {
+ const auto it = config.find(ov::cache_model_path.name());
+ const auto cache_model_path =
+ it == config.end() ? std::filesystem::path{} : it->second.as<std::filesystem::path>();
+ return ov::ModelCache::compute_hash(model, cache_model_path, compile_config);
+ }
+ return ov::ModelCache::compute_hash(model_path, compile_config);
+}
+
+bool CacheWarmupManager::is_blob_cached(const std::filesystem::path& cache_location, const std::string& blob_id) {
+ // The cache location is a directory with one <blob_id>.blob per model; a single-file cache is never a hit here.
+ return !cache_location.empty() && ov::util::file_exists(cache_location / (blob_id + ".blob"));
+}
+
bool CacheWarmupManager::is_blob_cached(const ov::ICore& core,
const std::string& device_name,
const ov::AnyMap& config,
const std::shared_ptr<const ov::Model>& model,
const std::filesystem::path& model_path,
const std::filesystem::path& cache_location) {
- // The cache location is a directory with one <blob_id>.blob per model; a single-file cache is never a hit here.
if (cache_location.empty() || (!model && model_path.empty())) {
return false;
}
- const auto compile_config =
- create_compile_config(core, device_name, core.get_supported_property(device_name, config));
- // Same precedence as Core: a user blob ID wins, then the hash (which covers ov::cache_model_path for a model).
- const auto blob_id = [&]() -> std::string {
- if (const auto it = config.find(ov::cache_blob_id.name()); it != config.end()) {
- return it->second.as<std::string>();
- }
- if (model) {
- const auto it = config.find(ov::cache_model_path.name());
- const auto cache_model_path =
- it == config.end() ? std::filesystem::path{} : it->second.as<std::filesystem::path>();
- return ov::ModelCache::compute_hash(model, cache_model_path, compile_config);
- }
- return ov::ModelCache::compute_hash(model_path, compile_config);
- }();
- return ov::util::file_exists(cache_location / (blob_id + ".blob"));
+ return is_blob_cached(cache_location, get_blob_id(core, device_name, config, model, model_path));
}
} // namespace auto_plugin
diff --git a/src/plugins/auto/src/cache_warmup.hpp b/src/plugins/auto/src/cache_warmup.hpp
index 6a896985101..0abb09e85af 100644
--- a/src/plugins/auto/src/cache_warmup.hpp
+++ b/src/plugins/auto/src/cache_warmup.hpp
@@ -29,7 +29,8 @@ class CacheWarmupManager;
// object to CacheWarmupManager (once per object).
// 2. The manager's single worker thread calls run(), which handles the devices one by one:
// - caching disabled for the device (no cache dir/path) -> skip;
-// - the blob for this model/config is already in the cache -> skip;
+// - a single-file cache (*.bin) -> skip with a warning, its writes are not safe to run in the background;
+// - an existing blob is not probed for: Core decides whether it is still usable, so a stale one is rewritten;
// - otherwise call core->compile_model() with a low-priority, reduced-thread config that keeps the cache key
// unchanged, so Core itself writes the blob; the resulting compiled model is dropped immediately.
// A failure on one device is logged and does not affect the other devices or the user's compiled model.
@@ -105,6 +106,12 @@ public:
static std::filesystem::path get_cache_location(const ov::ICore& core,
const ov::AnyMap& config,
const std::string& device_name = {});
+ static std::string get_blob_id(const ov::ICore& core,
+ const std::string& device_name,
+ const ov::AnyMap& config,
+ const std::shared_ptr<const ov::Model>& model,
+ const std::filesystem::path& model_path);
+ static bool is_blob_cached(const std::filesystem::path& cache_location, const std::string& blob_id);
static bool is_blob_cached(const ov::ICore& core,
const std::string& device_name,
const ov::AnyMap& config,
diff --git a/src/plugins/auto/src/compiled_model.cpp b/src/plugins/auto/src/compiled_model.cpp
index 3365122f7ce..aca25fcff17 100644
--- a/src/plugins/auto/src/compiled_model.cpp
+++ b/src/plugins/auto/src/compiled_model.cpp
@@ -24,18 +24,22 @@ ov::auto_plugin::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>&
: ov::ICompiledModel(model, plugin, remote_context),
m_context(schedule_context),
m_scheduler(scheduler) {
- m_inputs_outputs_from_hardware = (model == nullptr);
+ m_inputs_outputs_from_hardware = (model == nullptr) && m_context->m_hw_compiled_model;
+ if (m_inputs_outputs_from_hardware) {
+ m_hw_inputs = m_context->m_hw_compiled_model->inputs();
+ m_hw_outputs = m_context->m_hw_compiled_model->outputs();
+ }
}
const std::vector<ov::Output<const ov::Node>>& ov::auto_plugin::CompiledModel::outputs() const {
- if (m_inputs_outputs_from_hardware && m_context->m_hw_compiled_model)
- return m_context->m_hw_compiled_model->outputs();
+ if (m_inputs_outputs_from_hardware)
+ return m_hw_outputs;
return ov::ICompiledModel::outputs();
}
const std::vector<ov::Output<const ov::Node>>& ov::auto_plugin::CompiledModel::inputs() const {
- if (m_inputs_outputs_from_hardware && m_context->m_hw_compiled_model)
- return m_context->m_hw_compiled_model->inputs();
+ if (m_inputs_outputs_from_hardware)
+ return m_hw_inputs;
return ov::ICompiledModel::inputs();
}
@@ -58,16 +62,21 @@ std::string ov::auto_plugin::CompiledModel::get_log_tag() const noexcept {
}
ov::AnyMap ov::auto_plugin::CompiledModel::get_device_supported_properties(AutoCompileContext& context) {
- ov::AnyMap all_devices;
+ return get_device_supported_properties(context.m_device_info.device_name, context.m_compiled_model);
+}
+
+ov::AnyMap ov::auto_plugin::CompiledModel::get_device_supported_properties(const std::string& device_name,
+ const SoCompiledModel& compiled_model) {
+ ov::AnyMap all_devices;
ov::AnyMap device_properties = {};
- OPENVINO_ASSERT(context.m_compiled_model);
- auto device_supported_properties = context.m_compiled_model->get_property(ov::supported_properties.name());
+ OPENVINO_ASSERT(compiled_model);
+ auto device_supported_properties = compiled_model->get_property(ov::supported_properties.name());
for (auto&& property_name : device_supported_properties.as<std::vector<ov::PropertyName>>()) {
// For LTO issue, explicitly do the conversion here
std::string query_name = property_name;
- device_properties[property_name] = context.m_compiled_model->get_property(query_name);
+ device_properties[property_name] = compiled_model->get_property(query_name);
}
- all_devices[context.m_device_info.device_name] = device_properties;
+ all_devices[device_name] = device_properties;
return all_devices;
}
diff --git a/src/plugins/auto/src/compiled_model.hpp b/src/plugins/auto/src/compiled_model.hpp
index 26af595b818..da9f641f493 100644
--- a/src/plugins/auto/src/compiled_model.hpp
+++ b/src/plugins/auto/src/compiled_model.hpp
@@ -26,12 +26,17 @@ protected:
std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;
std::string get_log_tag() const noexcept;
static ov::AnyMap get_device_supported_properties(AutoCompileContext& context);
+ static ov::AnyMap get_device_supported_properties(const std::string& device_name,
+ const SoCompiledModel& compiled_model);
ScheduleContext::Ptr m_context;
private:
Schedule::Ptr m_scheduler;
std::once_flag m_oc;
bool m_inputs_outputs_from_hardware;
+ // copied so that they outlive the hardware compiled model, which the dynamic selection may release
+ std::vector<ov::Output<const ov::Node>> m_hw_inputs;
+ std::vector<ov::Output<const ov::Node>> m_hw_outputs;
void set_compile_model_for_context();
};
} // namespace auto_plugin
diff --git a/src/plugins/auto/src/infer_request.cpp b/src/plugins/auto/src/infer_request.cpp
index 57e12b0ade1..1db52e0b3bc 100644
--- a/src/plugins/auto/src/infer_request.cpp
+++ b/src/plugins/auto/src/infer_request.cpp
@@ -77,8 +77,24 @@ const ov::auto_plugin::SoAsyncInferRequest& ov::auto_plugin::InferRequest::get_s
return m_shared_request;
}
+void ov::auto_plugin::InferRequest::set_scheduled_profiling_info(std::vector<ov::ProfilingInfo> info) {
+ m_scheduled_profiling_info = std::move(info);
+ m_scheduled_profiling_error = nullptr;
+}
+
void ov::auto_plugin::InferRequest::set_scheduled_request(SoAsyncInferRequest request) {
- m_scheduled_request = request;
+ m_scheduled_request = std::move(request);
+}
+
+void ov::auto_plugin::InferRequest::reset_scheduled_profiling() {
+ m_scheduled_request = {};
+ m_scheduled_profiling_info.reset();
+ m_scheduled_profiling_error = nullptr;
+}
+
+void ov::auto_plugin::InferRequest::set_scheduled_profiling_error(std::exception_ptr error) {
+ m_scheduled_profiling_info.reset();
+ m_scheduled_profiling_error = std::move(error);
}
void ov::auto_plugin::InferRequest::set_tensors_to_another_request(const SoAsyncInferRequest& req) {
@@ -120,6 +136,10 @@ void ov::auto_plugin::InferRequest::infer() {
std::vector<ov::ProfilingInfo> ov::auto_plugin::InferRequest::get_profiling_info() const {
if (m_shared_request)
return m_shared_request->get_profiling_info();
+ if (m_scheduled_profiling_error)
+ std::rethrow_exception(m_scheduled_profiling_error);
+ if (m_scheduled_profiling_info)
+ return *m_scheduled_profiling_info;
if (m_scheduled_request)
return m_scheduled_request->get_profiling_info();
OPENVINO_NOT_IMPLEMENTED;
diff --git a/src/plugins/auto/src/infer_request.hpp b/src/plugins/auto/src/infer_request.hpp
index 404e35f0e28..d27728932eb 100644
--- a/src/plugins/auto/src/infer_request.hpp
+++ b/src/plugins/auto/src/infer_request.hpp
@@ -6,6 +6,7 @@
#pragma once
#include <atomic>
+#include <exception>
#include <mutex>
#include <queue>
#include <unordered_map>
@@ -13,6 +14,7 @@
#include <vector>
#include <utility>
#include <memory>
+#include <optional>
#include <string>
#include "plugin.hpp"
@@ -30,14 +32,21 @@ public:
std::vector<ov::ProfilingInfo> get_profiling_info() const override;
const SoAsyncInferRequest& get_shared_request();
+ void set_scheduled_profiling_info(std::vector<ov::ProfilingInfo> info);
+ void set_scheduled_profiling_error(std::exception_ptr error);
void set_scheduled_request(SoAsyncInferRequest request);
+ void reset_scheduled_profiling();
// Auto-Device impl specific: sets the data (tensors from the device-less requests to the specific device request)
void set_tensors_to_another_request(const SoAsyncInferRequest& req);
void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override;
private:
SoAsyncInferRequest m_shared_request;
+ // non-dynamic modes only: the worker request is never released, so profiling is read lazily
SoAsyncInferRequest m_scheduled_request;
+ // a snapshot, so that the backend request, and the compiled model behind it, is not kept alive
+ std::optional<std::vector<ov::ProfilingInfo>> m_scheduled_profiling_info;
+ std::exception_ptr m_scheduled_profiling_error;
};
} // namespace auto_plugin
} // namespace ov
diff --git a/src/plugins/auto/src/plugin.cpp b/src/plugins/auto/src/plugin.cpp
index 56dc768621f..f91897c48a1 100644
--- a/src/plugins/auto/src/plugin.cpp
+++ b/src/plugins/auto/src/plugin.cpp
@@ -751,12 +751,12 @@ std::unordered_map<std::string, float> Plugin::get_device_utilizations(const std
for (const auto& device : devices) {
device_name_and_type.emplace_back(device.device_name, resolve_device_key(device.device_name).device_type);
}
+ const auto query_start_time = std::chrono::steady_clock::now();
const auto result = m_telemetry_client->utilizations(device_name_and_type);
+ LOG_DEBUG_TAG("[IPF] utilization query took %lf ms",
+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - query_start_time).count());
for (const auto& device : devices) {
- const auto it = result.find(device.device_name);
- if (it != result.end()) {
- LOG_DEBUG_TAG("[IPF] Device %s utilization: %s", device.device_name.c_str(), std::to_string(it->second).c_str());
- } else {
+ if (result.find(device.device_name) == result.end()) {
LOG_DEBUG_TAG("[IPF] Device %s utilization query failed/unavailable", device.device_name.c_str());
}
}
@@ -984,16 +984,12 @@ DeviceInformation Plugin::select_device(const std::vector<DeviceInformation>& me
if (utilization_it == device_utilizations.end()) {
LOG_DEBUG_TAG("Cannot get utilization for %s. Will keep it in the list", device.device_name.c_str());
} else {
- LOG_DEBUG_TAG("Device: %s\tutilization: %s",
+ is_excluded = utilization_it->second >= device_threshold.value();
+ LOG_DEBUG_TAG("Device: %s utilization: %s, threshold: %s%s",
device.device_name.c_str(),
- std::to_string(utilization_it->second).c_str());
- if (utilization_it->second >= device_threshold.value()) {
- is_excluded = true;
- LOG_DEBUG_TAG("[%s] Current utilization [%s] exceeds the threshold[%s]",
- device.device_name.c_str(),
- std::to_string(utilization_it->second).c_str(),
- std::to_string(device_threshold.value()).c_str());
- }
+ std::to_string(utilization_it->second).c_str(),
+ std::to_string(device_threshold.value()).c_str(),
+ is_excluded ? ", exceeded" : "");
}
}
if (!is_excluded) {
@@ -1002,8 +998,17 @@ 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",
+ // Nothing is under its threshold, so take the device with the lowest absolute utilization instead of
+ // the highest priority one. Every candidate has a known utilization here (only those were excluded),
+ // and std::min_element keeps the priority order on ties.
+ last_device = *std::min_element(valid_devices.begin(),
+ valid_devices.end(),
+ [&](const DeviceInformation& a, const DeviceInformation& b) {
+ return device_utilizations.at(a.device_name) <
+ device_utilizations.at(b.device_name);
+ });
+ LOG_DEBUG_TAG("All candidate devices exceed their utilization thresholds. Falling back to the least "
+ "loaded one: %s",
last_device.device_name.c_str());
ptr_select_device = &last_device;
} else {
diff --git a/src/plugins/auto/src/schedule.cpp b/src/plugins/auto/src/schedule.cpp
index 032d8e9d5b4..e9bf4db6995 100644
--- a/src/plugins/auto/src/schedule.cpp
+++ b/src/plugins/auto/src/schedule.cpp
@@ -143,6 +143,15 @@ void Schedule::generate_workers(const std::string& device, const SoCompiledModel
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) {
+ // only recorded here, it is logged by the next dispatch so the slot is released without delay
+ INFO_RUN([&] {
+ if (!worker_request_ptr->m_start_times.empty()) {
+ m_last_infer_ms = std::chrono::duration<double, std::milli>(
+ std::chrono::steady_clock::now() -
+ worker_request_ptr->m_start_times.back())
+ .count();
+ }
+ });
// released unconditionally, otherwise queued requests would hang once destruction has began
release_execution_slot();
} else if (returned_to_idle) {
@@ -216,6 +225,7 @@ Pipeline Schedule::get_async_pipeline(const ISyncInferPtr& infer_request, Worker
// if the request is coming with device-specific remote tensors make sure it is scheduled to the specific device only:
Stage {
/*TaskExecutor*/ first_executor, /*task*/ [this, &infer_request]() {
+ std::static_pointer_cast<InferRequest>(infer_request)->reset_scheduled_profiling();
// by default, no preferred device:
m_this_preferred_device_name = "";
auto compiled_model = m_context->m_compiled_model.lock();
@@ -304,7 +314,18 @@ Pipeline Schedule::get_async_pipeline(const ISyncInferPtr& infer_request, Worker
if (m_context->m_need_perf_counters) {
auto auto_request = std::dynamic_pointer_cast<InferRequest>
(infer_request);
- auto_request->set_scheduled_request((*worker_infer_request)->m_inferrequest);
+ if (!m_context->m_dynamic_device_selection) {
+ auto_request->set_scheduled_request((*worker_infer_request)->m_inferrequest);
+ return;
+ }
+ // dynamic selection may release the device, so snapshot instead of pinning it
+ try {
+ auto_request->set_scheduled_profiling_info(
+ (*worker_infer_request)->m_inferrequest->get_profiling_info());
+ } catch (...) {
+ // surfaced from get_profiling_info(), the inference itself succeeded
+ auto_request->set_scheduled_profiling_error(std::current_exception());
+ }
}
}}
};
@@ -321,6 +342,11 @@ Schedule::~Schedule() {
for (auto&& worker_request : m_worker_requests) {
std::list<Time> req_all_start_times;
std::list<Time> req_all_end_times;
+ if (const auto released = m_released_infer_times.find(worker_request.first);
+ released != m_released_infer_times.end()) {
+ req_all_start_times.splice(req_all_start_times.end(), released->second.first);
+ req_all_end_times.splice(req_all_end_times.end(), released->second.second);
+ }
for (auto& request : worker_request.second) {
req_all_start_times.splice(req_all_start_times.end(), request.m_start_times);
req_all_end_times.splice(req_all_end_times.end(), request.m_end_times);
@@ -332,6 +358,15 @@ Schedule::~Schedule() {
: std::chrono::duration<double, std::milli>(0.0);
req_all_start_times.sort(std::less<Time>());
req_all_end_times.sort(std::less<Time>());
+ // the inferences are serialized there, so the sum is the time the device was busy
+ std::chrono::duration<double, std::milli> busy_duration{0.0};
+ if (m_context && m_context->m_dynamic_device_selection) {
+ for (auto start = req_all_start_times.begin(), end = req_all_end_times.begin();
+ start != req_all_start_times.end();
+ ++start, ++end) {
+ busy_duration += *end - *start;
+ }
+ }
{
auto n = req_all_start_times.size();
Time time;
@@ -348,9 +383,9 @@ 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:%zu", worker_request.first.c_str(), count);
+ LOG_INFO_TAG("%s:infer:%lu", worker_request.first.c_str(), static_cast<unsigned long>(count));
std::chrono::duration<double, std::milli> durtation =
- req_all_end_times.back() - time;
+ busy_duration.count() > 0.0 ? busy_duration : req_all_end_times.back() - time;
LOG_INFO_TAG("%s:fps:%lf", worker_request.first.c_str(),
n * 1000 / durtation.count());
}
diff --git a/src/plugins/auto/src/schedule.hpp b/src/plugins/auto/src/schedule.hpp
index b3f034423ce..fcf4b83f346 100644
--- a/src/plugins/auto/src/schedule.hpp
+++ b/src/plugins/auto/src/schedule.hpp
@@ -43,6 +43,8 @@ protected:
std::shared_ptr<ov::threading::IStreamsExecutor> m_executor;
DeviceMap<NotBusyPriorityWorkerRequests> m_idle_worker_requests;
DeviceMap<std::vector<WorkerInferRequest>> m_worker_requests;
+ // start/end times of the workers released with their compiled model, merged into the summary of ~Schedule()
+ DeviceMap<std::pair<std::list<Time>, std::list<Time>>> m_released_infer_times;
TaskQueue m_infer_pipeline_tasks;
DeviceMap<std::unique_ptr<TaskQueue>> m_infer_pipeline_tasks_device_specific;
SoCompiledModel m_passthrough_compiled_model;
@@ -52,6 +54,8 @@ protected:
Time m_cpuhelp_release_time;
mutable std::atomic<std::size_t> m_request_id = {0};
std::mutex m_dev_infer_mutex;
+ // dynamic selection only: written before the execution slot is released, read by the next dispatch
+ double m_last_infer_ms = -1.0;
std::unordered_map<IASyncInferPtr, WorkerInferRequest*> m_dev_infer;
};
diff --git a/src/plugins/auto/src/utils/device_telemetry.cpp b/src/plugins/auto/src/utils/device_telemetry.cpp
index 28e2ac4abdb..163770cad7a 100644
--- a/src/plugins/auto/src/utils/device_telemetry.cpp
+++ b/src/plugins/auto/src/utils/device_telemetry.cpp
@@ -86,7 +86,6 @@ std::optional<float> extract_utilization(const nlohmann::json& performance,
}
float value = metric_it->get<float>();
const std::string value_as_string = std::to_string(value);
- LOG_DEBUG_TAG("TelemetryClient: parsed utilization=%s for device=%s", value_as_string.c_str(), device_name.c_str());
if (!std::isfinite(value) || value < 0.0f || value > 100.0f) {
LOG_WARNING_TAG("TelemetryClient: utilization value out of supported range [0,100], value=%s for device=%s",
value_as_string.c_str(),
@@ -186,7 +185,6 @@ public:
LOG_DEBUG_TAG("TelemetryClient::fetch_utilization_snapshot: client not initialized");
return {};
}
- LOG_DEBUG_TAG("TelemetryClient::fetch_utilization_snapshot: querying IPF for AISelector snapshot");
return get_node("Platform.Features.AISelector");
}
@@ -220,7 +218,10 @@ public:
return std::nullopt;
}
const bool low_power = is_low_power_gear(gear);
- LOG_DEBUG_TAG("TelemetryClient: EPO gear=%d, low_power_mode=%s", gear, low_power ? "true" : "false");
+ // called for every device selection, so only a change is worth a log line
+ if (m_last_logged_gear.exchange(gear) != gear) {
+ LOG_DEBUG_TAG("TelemetryClient: EPO gear=%d, low_power_mode=%s", gear, low_power ? "true" : "false");
+ }
return low_power;
}
@@ -387,6 +388,7 @@ private:
void* m_handle = nullptr;
std::atomic<bool> m_gear_tracking_initialized{false};
+ std::atomic<int> m_last_logged_gear{-1};
bool m_gear_event_registered = false;
std::mutex m_low_power_init_mutex;
std::shared_ptr<std::atomic<int>> m_shared_gear;
diff --git a/src/plugins/auto/tests/unit/compile_model_metric_test.cpp b/src/plugins/auto/tests/unit/compile_model_metric_test.cpp
index 35bc3c50602..51ff0a6a7e4 100644
--- a/src/plugins/auto/tests/unit/compile_model_metric_test.cpp
+++ b/src/plugins/auto/tests/unit/compile_model_metric_test.cpp
@@ -239,6 +239,9 @@ TEST_P(ExecNetworkget_propertyOptimalNumInferReq, OPTIMAL_NUMBER_OF_INFER_REQUES
EXPECT_CALL(*mockIExeNetActual.get(), get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
.Times(AtLeast(1));
+ // only logged by AUTO after a compile
+ EXPECT_CALL(*mockIExeNet.get(), get_property(StrEq(ov::loaded_from_cache.name()))).Times(AnyNumber());
+ EXPECT_CALL(*mockIExeNetActual.get(), get_property(StrEq(ov::loaded_from_cache.name()))).Times(AnyNumber());
EXPECT_CALL(*core,
compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
diff --git a/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp b/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp
index f31d7e1da2c..880f6453249 100644
--- a/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp
+++ b/src/plugins/auto/tests/unit/dynamic_device_selection_test.cpp
@@ -5,12 +5,17 @@
#include "include/auto_unit_test.hpp"
#include "openvino/opsets/opset11.hpp"
#include "openvino/runtime/auto/properties.hpp"
+#include "openvino/runtime/compilation_context.hpp"
+#include "openvino/runtime/device_id_parser.hpp"
#include "openvino/runtime/iremote_tensor.hpp"
#include "openvino/runtime/threading/immediate_executor.hpp"
#include <atomic>
#include <chrono>
+#include <functional>
#include <condition_variable>
+#include <filesystem>
+#include <fstream>
#include <future>
#include <mutex>
#include <thread>
@@ -124,6 +129,33 @@ private:
std::shared_ptr<std::atomic<int>> m_failures;
};
+// Runs a hook right before the request is started on the device.
+class HookedStartAsyncRequest : public ov::IAsyncInferRequest {
+public:
+ HookedStartAsyncRequest(const std::shared_ptr<ov::IInferRequest>& request,
+ const std::shared_ptr<ov::threading::ITaskExecutor>& task_executor,
+ std::function<void()> on_start)
+ : ov::IAsyncInferRequest(request, task_executor, nullptr),
+ m_on_start(std::move(on_start)) {}
+
+ void start_async() override {
+ m_on_start();
+ ov::IAsyncInferRequest::start_async();
+ }
+
+private:
+ std::function<void()> m_on_start;
+};
+
+struct OnDestruction {
+ std::function<void()> callback;
+ ~OnDestruction() {
+ if (callback) {
+ callback();
+ }
+ }
+};
+
// Carries nothing but the name of the device it was created on.
class DeviceTaggedRemoteTensor : public ov::IRemoteTensor {
public:
@@ -1130,4 +1162,434 @@ TEST_F(AutoDynamicDeviceSelectionTest, streams_are_not_forced_without_the_per_in
OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
EXPECT_EQ(recorder.streams("GPU.0"), -100);
}
+
+class AutoDynamicInactiveDeviceReleaseTest : public AutoDynamicDeviceSelectionTest {
+public:
+ void SetUp() override {
+ AutoDynamicDeviceSelectionTest::SetUp();
+ m_cache_dir = std::filesystem::temp_directory_path() /
+ ("ov_auto_inactive_device_release_" +
+ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
+ std::filesystem::create_directories(m_cache_dir);
+ ON_CALL(*core, get_property(_, StrEq(ov::cache_dir.name()), _))
+ .WillByDefault(Return(ov::Any(m_cache_dir.string())));
+ ON_CALL(*core, get_property(_, StrEq(ov::cache_path.name()), _))
+ .WillByDefault(Return(ov::Any(std::filesystem::path())));
+ ON_CALL(*core, create_compile_config(_, _))
+ .WillByDefault([this](const std::string& device, const ov::AnyMap& compile_config) {
+ if (device == "CPU") {
+ ++m_cpu_cache_key_compute_count;
+ }
+ // as in Core, different devices never share a cache blob
+ ov::AnyMap key{{"TEST_CACHE_KEY_DEVICE", device}};
+ if (const auto id = compile_config.find(ov::device::id.name()); id != compile_config.end()) {
+ key.emplace(*id);
+ }
+ return key;
+ });
+ ON_CALL(*core, device_supports_model_caching(_)).WillByDefault(Return(true));
+ 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.0")),
+ _))
+ .WillByDefault([this](const std::shared_ptr<const ov::Model>&, const std::string&, const ov::AnyMap&) {
+ ++m_gpu0_compile_count;
+ return mockExeNetworkActual;
+ });
+ // GPU.1 is only a warmup candidate, but warmup dereferences the compiled model it gets back
+ 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));
+ 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([this](const std::shared_ptr<const ov::Model>& compiled_model,
+ const std::string&,
+ const ov::AnyMap& compile_config) {
+ ++m_cpu_compile_count;
+ // what was compiled for CPU before must be gone by now, nothing but AUTO holds it
+ if (m_expect_released_before_recompile) {
+ EXPECT_TRUE(m_cpu_model.expired());
+ EXPECT_TRUE(m_cpu_worker_request.expired());
+ }
+ if (m_write_cpu_cache_blob) {
+ write_cache_blob("CPU", compiled_model, compile_config);
+ }
+ return make_tracked_cpu_model();
+ });
+ }
+
+ // mirrors the cache key AUTO probes: the device ID goes into the config of the base device name
+ void write_cache_blob(const std::string& device_name,
+ const std::shared_ptr<const ov::Model>& compiled_model,
+ const ov::AnyMap& compile_config) {
+ const ov::DeviceIDParser parser(device_name);
+ auto key_config = core->get_supported_property(device_name, compile_config, true);
+ if (!parser.get_device_id().empty()) {
+ key_config.emplace(ov::device::id.name(), parser.get_device_id());
+ }
+ const auto cache_key_config = core->create_compile_config(parser.get_device_name(), key_config);
+ const auto blob_id = ov::ModelCache::compute_hash(compiled_model, cache_key_config);
+ std::ofstream(m_cache_dir / (blob_id + ".blob"), std::ios::binary).put('\0');
+ }
+
+ // GPU.0 writes a cache blob and returns a fresh model, so the initial device becomes releasable
+ void track_gpu0_with_cache_blob() {
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),
+ _))
+ .WillByDefault([this](const std::shared_ptr<const ov::Model>& compiled_model,
+ const std::string&,
+ const ov::AnyMap& compile_config) {
+ ++m_gpu0_compile_count;
+ if (m_expect_released_before_recompile) {
+ EXPECT_TRUE(m_gpu0_model.expired());
+ }
+ write_cache_blob("GPU.0", compiled_model, compile_config);
+ auto gpu_model = std::make_shared<NiceMock<ov::MockICompiledModel>>(model, mock_plugin_gpu);
+ const std::weak_ptr<ov::MockICompiledModel> weak_model = gpu_model;
+ ON_CALL(*gpu_model, inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));
+ ON_CALL(*gpu_model, outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));
+ ON_CALL(*gpu_model, get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
+ .WillByDefault(Return(optimalNum));
+ ON_CALL(*gpu_model, get_property(StrEq(ov::supported_properties.name())))
+ .WillByDefault(Return(ov::Any(std::vector<ov::PropertyName>{})));
+ ON_CALL(*gpu_model, create_sync_infer_request()).WillByDefault([weak_model]() {
+ return std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(weak_model.lock());
+ });
+ ON_CALL(*gpu_model, create_infer_request()).WillByDefault([weak_model]() {
+ return weak_model.lock()->ICompiledModel::create_infer_request();
+ });
+ m_gpu0_model = gpu_model;
+ return ov::SoPtr<ov::ICompiledModel>{gpu_model, {}};
+ });
+ }
+
+ void TearDown() override {
+ AutoDynamicDeviceSelectionTest::TearDown();
+ std::error_code error;
+ std::filesystem::remove_all(m_cache_dir, error);
+ }
+
+ ov::SoPtr<ov::ICompiledModel> make_tracked_cpu_model() {
+ auto cpu_model = std::make_shared<NiceMock<ov::MockICompiledModel>>(model, mock_plugin_cpu);
+ const std::weak_ptr<ov::MockICompiledModel> weak_model = cpu_model;
+ ON_CALL(*cpu_model, inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));
+ ON_CALL(*cpu_model, outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));
+ ON_CALL(*cpu_model, get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
+ .WillByDefault(Return(optimalNum));
+ ON_CALL(*cpu_model, get_property(StrEq(ov::supported_properties.name())))
+ .WillByDefault(Return(ov::Any(std::vector<ov::PropertyName>{})));
+ ON_CALL(*cpu_model, create_sync_infer_request()).WillByDefault([this, weak_model]() {
+ auto request = std::make_shared<ov::mock_auto_plugin::MockISyncInferRequest>(weak_model.lock());
+ m_cpu_worker_request = request;
+ if (m_cpu_profiling_info) {
+ ON_CALL(*request, get_profiling_info()).WillByDefault([this]() {
+ return m_cpu_profiling_info();
+ });
+ }
+ return request;
+ });
+ ON_CALL(*cpu_model, create_infer_request()).WillByDefault([weak_model]() {
+ return weak_model.lock()->ICompiledModel::create_infer_request();
+ });
+ m_cpu_model = cpu_model;
+ return ov::SoPtr<ov::ICompiledModel>{cpu_model, {}};
+ }
+
+ // GPU.0 is the initial device; CPU is the one that goes inactive and is never warmed up
+ void switch_between_devices(bool compile_for_all, std::shared_ptr<ov::ICompiledModel>* result = nullptr) {
+ if (compile_for_all) {
+ config.insert(ov::intel_auto::compile_for_all(true));
+ }
+ expect_selected_devices({"GPU.0", "CPU", "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, 3);
+ if (result) {
+ *result = std::move(compiled_model);
+ }
+ }
+
+ std::atomic<int> m_gpu0_compile_count{0};
+ std::atomic<int> m_cpu_compile_count{0};
+ std::atomic<int> m_cpu_cache_key_compute_count{0};
+ std::filesystem::path m_cache_dir;
+ bool m_write_cpu_cache_blob = true;
+ // a concurrent model level query may hold the released model a little longer
+ bool m_expect_released_before_recompile = true;
+ std::weak_ptr<ov::MockICompiledModel> m_cpu_model;
+ std::weak_ptr<ov::MockICompiledModel> m_gpu0_model;
+ std::weak_ptr<ov::mock_auto_plugin::MockISyncInferRequest> m_cpu_worker_request;
+ std::function<std::vector<ov::ProfilingInfo>()> m_cpu_profiling_info;
+
+ // returns the request that ran on CPU, after CPU was released by a request that ran on GPU.0
+ std::shared_ptr<ov::IAsyncInferRequest> infer_then_release_cpu() {
+ const std::vector<ov::PropertyName> supported_properties = {ov::compilation_num_threads,
+ ov::enable_profiling};
+ ON_CALL(*core, get_property(_, StrEq(ov::supported_properties.name()), _))
+ .WillByDefault(Return(ov::Any(supported_properties)));
+ config.insert(ov::enable_profiling(true));
+ config.insert(ov::intel_auto::compile_for_all(true));
+ expect_selected_devices({"GPU.0", "CPU", "GPU.0"});
+ auto compiled_model = plugin->compile_model(model, config);
+ // the first request ran on CPU and is kept alive without running again
+ auto cpu_request = compiled_model->create_infer_request();
+ cpu_request->infer();
+ EXPECT_FALSE(m_cpu_model.expired());
+ // a second request switches to GPU.0, which releases CPU
+ auto gpu_request = compiled_model->create_infer_request();
+ gpu_request->infer();
+ EXPECT_TRUE(wait_until([this] {
+ return m_cpu_model.expired() && m_cpu_worker_request.expired();
+ }));
+ return cpu_request;
+ }
+
+ // the previous device is released on the dispatch thread after the inference has already been started
+ static bool wait_until(const std::function<bool()>& condition) {
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
+ while (!condition()) {
+ if (std::chrono::steady_clock::now() > deadline) {
+ return false;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+ return true;
+ }
+};
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, inactive_device_is_compiled_again_when_selected_again) {
+ switch_between_devices(true);
+ EXPECT_EQ(m_cpu_compile_count.load(), 2);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, cpu_is_released_without_a_non_cpu_warmup_candidate) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,CPU"));
+ switch_between_devices(true);
+ EXPECT_EQ(m_cpu_compile_count.load(), 2);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, cpu_is_kept_when_cache_blob_was_not_written) {
+ m_write_cpu_cache_blob = false;
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ switch_between_devices(true, &compiled_model);
+ EXPECT_EQ(m_cpu_compile_count.load(), 1);
+ EXPECT_FALSE(m_cpu_model.expired());
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, cpu_cache_key_is_computed_once_across_releases) {
+ config.erase(ov::device::priorities.name());
+ config.insert(ov::device::priorities("GPU.0,CPU"));
+ config.insert(ov::intel_auto::compile_for_all(true));
+ expect_selected_devices({"GPU.0", "CPU", "GPU.0", "CPU", "GPU.0"});
+
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 4);
+
+ EXPECT_EQ(m_cpu_compile_count.load(), 2);
+ // Two CPU compiles write the mock cache entry; the release probe computes the key only once.
+ EXPECT_EQ(m_cpu_cache_key_compute_count.load(), 3);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, profiling_does_not_keep_the_inactive_device_alive) {
+ m_cpu_profiling_info = [] {
+ ov::ProfilingInfo info;
+ info.status = ov::ProfilingInfo::Status::EXECUTED;
+ info.real_time = std::chrono::microseconds(7);
+ info.cpu_time = std::chrono::microseconds(5);
+ info.node_name = "cpu_node";
+ info.exec_type = "cpu_exec";
+ info.node_type = "cpu_type";
+ return std::vector<ov::ProfilingInfo>{info};
+ };
+ auto cpu_request = infer_then_release_cpu();
+ std::vector<ov::ProfilingInfo> profiling;
+ OV_ASSERT_NO_THROW(profiling = cpu_request->get_profiling_info());
+ ASSERT_EQ(profiling.size(), 1u);
+ EXPECT_EQ(profiling[0].status, ov::ProfilingInfo::Status::EXECUTED);
+ EXPECT_EQ(profiling[0].real_time, std::chrono::microseconds(7));
+ EXPECT_EQ(profiling[0].cpu_time, std::chrono::microseconds(5));
+ EXPECT_EQ(profiling[0].node_name, "cpu_node");
+ EXPECT_EQ(profiling[0].exec_type, "cpu_exec");
+ EXPECT_EQ(profiling[0].node_type, "cpu_type");
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, profiling_error_is_deferred_to_the_profiling_query) {
+ m_cpu_profiling_info = []() -> std::vector<ov::ProfilingInfo> {
+ OPENVINO_THROW("backend profiling failure");
+ };
+ // infer() succeeds even though the backend fails to build the profiling report
+ auto cpu_request = infer_then_release_cpu();
+ try {
+ cpu_request->get_profiling_info();
+ FAIL() << "the captured profiling error must be rethrown";
+ } catch (const ov::Exception& ex) {
+ EXPECT_NE(std::string(ex.what()).find("backend profiling failure"), std::string::npos);
+ }
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, profiling_of_a_failed_inference_does_not_return_the_previous_one) {
+ m_cpu_profiling_info = [] {
+ ov::ProfilingInfo info;
+ info.node_name = "cpu_node";
+ return std::vector<ov::ProfilingInfo>{info};
+ };
+ auto request = infer_then_release_cpu();
+ EXPECT_EQ(request->get_profiling_info().size(), 1u);
+
+ // remote tensors of different devices make the request fail before it reaches any device
+ const auto input = request->get_inputs().at(0);
+ const auto output = request->get_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>("CPU", output.get_element_type(), output.get_shape());
+ OV_ASSERT_NO_THROW(request->set_tensor(input, ov::SoPtr<ov::ITensor>{remote_input, nullptr}));
+ OV_ASSERT_NO_THROW(request->set_tensor(output, ov::SoPtr<ov::ITensor>{remote_output, nullptr}));
+ OV_ASSERT_NO_THROW(request->start_async());
+ EXPECT_THROW(request->wait(), ov::Exception);
+
+ EXPECT_THROW(request->get_profiling_info(), ov::Exception);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, device_without_cache_is_kept) {
+ // The mock Core handles nested device properties, not the DEVICE_PROPERTIES_CPU shorthand.
+ config.insert(ov::device::properties(ov::AnyMap{{"CPU", ov::AnyMap{ov::cache_dir("")}}}));
+ switch_between_devices(true);
+ EXPECT_EQ(m_cpu_compile_count.load(), 1);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, device_without_caching_support_is_kept) {
+ ON_CALL(*core, device_supports_model_caching(StrEq(ov::test::utils::DEVICE_CPU))).WillByDefault(Return(false));
+ switch_between_devices(true);
+ EXPECT_EQ(m_cpu_compile_count.load(), 1);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, previous_device_is_kept_when_the_new_device_fails_to_compile) {
+ ON_CALL(*core,
+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),
+ ::testing::Matcher<const std::string&>(StrEq("GPU.1")),
+ _))
+ .WillByDefault([](const std::shared_ptr<const ov::Model>&, const std::string&, const ov::AnyMap&)
+ -> ov::SoPtr<ov::ICompiledModel> {
+ OPENVINO_THROW("mock GPU.1 compile failure");
+ });
+ config.insert(ov::intel_auto::compile_for_all(true));
+ // GPU.1 fails on the switch away from CPU, and the fallback selects CPU again
+ expect_selected_devices({"GPU.0", "CPU", "GPU.1", "CPU"});
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ run_inferences(compiled_model, 2);
+ EXPECT_EQ(m_cpu_compile_count.load(), 1);
+ EXPECT_FALSE(m_cpu_model.expired());
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, initial_device_is_kept_without_cache_blob) {
+ switch_between_devices(true);
+ EXPECT_EQ(m_gpu0_compile_count.load(), 1);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, initial_device_is_released_when_it_has_cache_blob) {
+ track_gpu0_with_cache_blob();
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ // GPU.0 is released on the switch to CPU, compiled again on the way back and released again
+ switch_between_devices(true, &compiled_model);
+ ASSERT_TRUE(compiled_model);
+ EXPECT_EQ(m_gpu0_compile_count.load(), 2);
+ EXPECT_TRUE(wait_until([this] {
+ return m_gpu0_model.expired();
+ }));
+
+ // the ports and the model level queries outlive the initial device
+ ASSERT_EQ(compiled_model->inputs().size(), model->inputs().size());
+ ASSERT_EQ(compiled_model->outputs().size(), model->outputs().size());
+ EXPECT_EQ(compiled_model->inputs()[0].get_element_type(), model->inputs()[0].get_element_type());
+ EXPECT_EQ(compiled_model->outputs()[0].get_partial_shape(), model->outputs()[0].get_partial_shape());
+ ov::Any device_properties;
+ OV_ASSERT_NO_THROW(device_properties = compiled_model->get_property(ov::device::properties.name()));
+ EXPECT_EQ(device_properties.as<ov::AnyMap>().count("CPU"), 1u);
+ OV_ASSERT_NO_THROW(compiled_model->get_property(ov::model_name.name()));
+ OV_ASSERT_NO_THROW(compiled_model->get_property(ov::loaded_from_cache.name()));
+ run_inferences(compiled_model, 1);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, model_level_queries_run_concurrently_with_the_initial_device_release) {
+ track_gpu0_with_cache_blob();
+ m_expect_released_before_recompile = false;
+ config.insert(ov::intel_auto::compile_for_all(true));
+ expect_selected_devices({"GPU.0", "CPU", "GPU.0", "CPU"});
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ std::atomic<bool> done{false};
+ std::thread querier([&] {
+ while (!done) {
+ EXPECT_NO_THROW(compiled_model->get_property(ov::model_name.name()));
+ EXPECT_NO_THROW(compiled_model->get_property(ov::loaded_from_cache.name()));
+ EXPECT_NO_THROW(compiled_model->get_property(ov::device::properties.name()));
+ EXPECT_EQ(compiled_model->inputs().size(), model->inputs().size());
+ }
+ });
+ run_inferences(compiled_model, 8);
+ done = true;
+ querier.join();
+ EXPECT_GE(m_gpu0_compile_count.load(), 2);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, inactive_device_is_released_after_the_inference_is_started) {
+ auto gpu0_started = std::make_shared<std::atomic<bool>>(false);
+ ON_CALL(*mockIExeNetActual.get(), create_infer_request()).WillByDefault([this, gpu0_started]() {
+ return std::static_pointer_cast<ov::IAsyncInferRequest>(std::make_shared<HookedStartAsyncRequest>(
+ inferReqInternalActual,
+ std::make_shared<ov::threading::ImmediateExecutor>(),
+ [gpu0_started] {
+ *gpu0_started = true;
+ }));
+ });
+ config.insert(ov::intel_auto::compile_for_all(true));
+ expect_selected_devices({"GPU.0", "CPU", "GPU.0"});
+ std::shared_ptr<ov::ICompiledModel> compiled_model;
+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));
+ std::shared_ptr<ov::IAsyncInferRequest> request;
+ OV_ASSERT_NO_THROW(request = compiled_model->create_infer_request());
+ OV_ASSERT_NO_THROW(request->infer());
+ ASSERT_FALSE(gpu0_started->load());
+
+ // -1: CPU not released yet, 0: released before GPU.0 was started, 1: released after it
+ auto release_order = std::make_shared<std::atomic<int>>(-1);
+ {
+ auto cpu_model = m_cpu_model.lock();
+ ASSERT_TRUE(cpu_model);
+ // the action, and so the sentinel, dies together with the CPU compiled model
+ auto sentinel = std::make_shared<OnDestruction>();
+ sentinel->callback = [release_order, gpu0_started] {
+ *release_order = *gpu0_started ? 1 : 0;
+ };
+ ON_CALL(*cpu_model, get_property(StrEq("TEST_RELEASE_SENTINEL")))
+ .WillByDefault([sentinel](const std::string&) {
+ return ov::Any();
+ });
+ }
+ // switches to GPU.0, which releases CPU
+ OV_ASSERT_NO_THROW(request->infer());
+ EXPECT_TRUE(wait_until([release_order] {
+ return *release_order != -1;
+ }));
+ EXPECT_EQ(release_order->load(), 1);
+}
+
+TEST_F(AutoDynamicInactiveDeviceReleaseTest, inactive_device_is_kept_without_compile_for_all) {
+ switch_between_devices(false);
+ EXPECT_EQ(m_cpu_compile_count.load(), 1);
+ EXPECT_EQ(m_gpu0_compile_count.load(), 1);
+}
} // namespace ov::test
diff --git a/src/plugins/auto/tests/unit/select_device_failed_test.cpp b/src/plugins/auto/tests/unit/select_device_failed_test.cpp
index 1214cfde7e0..002cd47ff3c 100644
--- a/src/plugins/auto/tests/unit/select_device_failed_test.cpp
+++ b/src/plugins/auto/tests/unit/select_device_failed_test.cpp
@@ -161,6 +161,8 @@ TEST_P(AutoLoadFailedTest, LoadCNNetWork) {
// if loadSuccess will get the optimalNum requset of per device, in this test is 2;
EXPECT_CALL(*mockIExeNet.get(), get_property(StrEq(ov::optimal_number_of_infer_requests.name())))
.Times(loadSuccessCount);
+ // only logged by AUTO after a compile
+ EXPECT_CALL(*mockIExeNet.get(), get_property(StrEq(ov::loaded_from_cache.name()))).Times(AnyNumber());
EXPECT_CALL(*mockIExeNet.get(), create_infer_request()).Times(loadSuccessCount * 2);
if (continueRun) {
OV_ASSERT_NO_THROW(plugin->compile_model(model, config));
diff --git a/src/plugins/auto/tests/unit/select_device_test.cpp b/src/plugins/auto/tests/unit/select_device_test.cpp
index 2adf491fbdc..526a192fbc5 100644
--- a/src/plugins/auto/tests/unit/select_device_test.cpp
+++ b/src/plugins/auto/tests/unit/select_device_test.cpp
@@ -331,6 +331,8 @@ TEST_P(SelectDeviceWithUtilizationTest, selectDeviceWithUtilization) {
std::string netPrecision = "FP32";
auto result = plugin->select_device(devices, netPrecision, 0, {threshold, {}}, {});
compare(result, selectedDeviceInfo);
+ // m_priority_map is process-wide static state; clean up to avoid leaking into other suites.
+ plugin->unregister_priority(0, result.unique_name);
}
const std::unordered_map<std::string, unsigned> testUtilizThreshold_15 = {{"CPU", 15},
@@ -393,7 +395,7 @@ const std::vector<ConfigFilterParams> testValidConfigs = {
ConfigFilterParams{testUtilizThreshold_15,
{{"CPU", {}, -1, "01", "CPU_01", 1}, {"GPU", {}, -1, "01", "GPU", 2}},
{{"CPU", 85.5f}, {"GPU", 20.5f}},
- {"CPU", {}, -1, "01", "CPU_01", 1}},
+ {"GPU", {}, -1, "01", "GPU", 2}},
ConfigFilterParams{testUtilizThreshold_15,
{{"CPU", {}, -1, "01", "CPU_01", 0}, {"GPU.0", {}, -1, "01", "iGPU_01", 0}},
{{"CPU", 85.5f}, {"GPU.0", 20.5f}},
@@ -403,7 +405,7 @@ const std::vector<ConfigFilterParams> testValidConfigs = {
{"GPU.0", {}, -1, "01", "iGPU_01", 0},
{"GPU.1", {}, -1, "01", "dGPU_01", 0}},
{{"CPU", 85.5f}, {"GPU.0", 20.5f}, {"GPU.1", 50.5f}},
- {"GPU.1", {}, -1, "01", "dGPU_01", 0}},
+ {"GPU.0", {}, -1, "01", "iGPU_01", 0}},
ConfigFilterParams{testUtilizThreshold_80,
{{"CPU", {}, -1, "01", "CPU_01", 0},
{"GPU.0", {}, -1, "01", "iGPU_01", 0},
@@ -630,6 +632,9 @@ public:
std::vector<std::string> npuCapability = {"FP32", "FP16", "INT8", "BIN"};
ON_CALL(*core, get_property(StrEq(ov::test::utils::DEVICE_NPU), StrEq(ov::device::capabilities.name()), _))
.WillByDefault(RETURN_MOCK_VALUE(npuCapability));
+ // without it CPU is dropped as not supporting the precision, leaving only NPU to choose from
+ ON_CALL(*core, get_property(StrEq(ov::test::utils::DEVICE_CPU), StrEq(ov::device::capabilities.name()), _))
+ .WillByDefault(RETURN_MOCK_VALUE(npuCapability));
ON_CALL(*plugin, get_device_utilizations)
.WillByDefault([this](const std::list<DeviceInformation>& devices) -> std::unordered_map<std::string, float> {
std::unordered_map<std::string, float> result;
@@ -678,6 +683,30 @@ TEST_F(SelectDeviceThresholdBeforePerfCurveTableTest, thresholdResultIsKeptWhenP
plugin->unregister_priority(0, result.unique_name);
}
+TEST_F(SelectDeviceThresholdBeforePerfCurveTableTest, leastLoadedDeviceIsSelectedWhenAllExceedThresholds) {
+ std::string netPrecision = "FP32";
+ std::vector<DeviceInformation> devices = {{"CPU", {}, -1, "01", "CPU_01", 1}, {"NPU", {}, -1, "01", "NPU_01", 2}};
+ std::unordered_map<std::string, unsigned> thresholds = {{"CPU", 20}, {"NPU", 20}};
+ deviceUtilization = {{"CPU", 90.f}, {"NPU", 40.f}};
+
+ // Both exceed their thresholds; NPU is less loaded although CPU has the higher priority.
+ auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, {});
+ EXPECT_EQ(result.unique_name, "NPU_01");
+ plugin->unregister_priority(0, result.unique_name);
+}
+
+TEST_F(SelectDeviceThresholdBeforePerfCurveTableTest, priorityOrderBreaksTieWhenAllExceedThresholds) {
+ std::string netPrecision = "FP32";
+ // an explicit priority list is needed, the default order puts CPU behind every other device
+ std::vector<DeviceInformation> devices = {{"CPU", {}, -1, "01", "CPU_01", 1}, {"NPU", {}, -1, "01", "NPU_01", 2}};
+ std::unordered_map<std::string, unsigned> thresholds = {{"CPU", 20}, {"NPU", 20}};
+ deviceUtilization = {{"CPU", 50.f}, {"NPU", 50.f}};
+
+ auto result = plugin->select_device(devices, netPrecision, 0, {thresholds, {}}, {});
+ EXPECT_EQ(result.unique_name, "CPU_01");
+ plugin->unregister_priority(0, result.unique_name);
+}
+
// ------------------------------------------------------------------------------------------
// sort_device_by_perf_curve() unit tests: verify score computation (exact match, interpolation),
// stable ordering (scored-ascending first, unscored trailing in original relative order), and