OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[AUTO] Create model cache for all devices (#39407)
guozhong wangccad1b951347
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.rstindex c9f7f2e7496..a35332b732b 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@@ -169,6 +169,9 @@ the following setup options:| | Enables/disables CPU as acceleration (or the helper device) in the || | beginning. The default value is ``true``, indicating that CPU is || | used as acceleration by default. |+| | |+| | As a trade-off, two model instances will be kept, resulting in |+| | additional memory usage of approximately one model’s size. |+----------------------------------------------+--------------------------------------------------------------------+| ``ov::intel_auto::enable_runtime_fallback`` | **Values**: || | |@@ -193,6 +196,42 @@ the following setup options:| | || | The default value is ``DEVICE_PRIORITY``. |+----------------------------------------------+--------------------------------------------------------------------++| ``ov::intel_auto::compile_for_all`` | **Values**: |+| | |+| | ``true`` |+| | |+| | ``false`` |+| | |+| | Compiles the model to the remaining candidate devices in the |+| | background, after the actual device is ready, to populate cache |+| | blobs for faster device switching later. Devices whose cache blob |+| | already exists are skipped. CPU candidates are excluded from |+| | background pre-compilation. |+| | |+| | Enabling it disables ``ov::intel_auto::enable_startup_fallback`` |+| | and ``ov::intel_auto::enable_runtime_fallback``. |+| | |+| | Requires ``ov::cache_dir`` or ``ov::cache_path``. Without them, |+| | compiling the model throws on every host. |+| | |+| | Ignored in cumulative throughput mode, when there is no |+| | other candidate device to compile, and when ``ov::cache_blob_id`` |+| | is set for AUTO or for any candidate device. |+| | |+| | A device whose cache path is a single-file cache (``*.bin``) is |+| | skipped with a warning. |+| | |+| | Only the devices listed in ``ov::device::priorities`` or in the |+| | device string, for example ``AUTO:GPU,NPU``, are compiled; other |+| | available devices are not. With ``AUTO:GPU,NPU``, if GPU becomes |+| | actual device, NPU is compiled in the background (and vice versa). |+| | |+| | Warm-up compiles one device at a time and releases each compiled |+| | model right away. The memory needed by the background compilation |+| | itself is not included. |+| | |+| | The default value is ``false``. |++----------------------------------------------+--------------------------------------------------------------------+Inference with AUTO is configured similarly to when device plugins are used:you compile the model on the plugin with configuration and execute inference.diff --git a/src/bindings/c/docs/api_overview.md b/src/bindings/c/docs/api_overview.mdindex 460b423c310..afc95d4ef47 100644--- a/src/bindings/c/docs/api_overview.md+++ b/src/bindings/c/docs/api_overview.md@@ -350,6 +350,7 @@ OPENVINO_C_VAR(const char*) ov_property_key_intel_auto_device_bind_buffer;OPENVINO_C_VAR(const char*) ov_property_key_intel_auto_enable_startup_fallback;OPENVINO_C_VAR(const char*) ov_property_key_intel_auto_enable_runtime_fallback;+OPENVINO_C_VAR(const char*) ov_property_key_intel_auto_compile_for_all;```### GPU plugin specified propertiesdiff --git a/src/bindings/c/include/openvino/c/auto/properties.h b/src/bindings/c/include/openvino/c/auto/properties.hindex e952bfbf992..d312438c8a9 100644--- a/src/bindings/c/include/openvino/c/auto/properties.h+++ b/src/bindings/c/include/openvino/c/auto/properties.h@@ -31,4 +31,12 @@ ov_property_key_intel_auto_enable_startup_fallback;* @ingroup ov_property_c_api*/OPENVINO_C_VAR(const char*)-ov_property_key_intel_auto_enable_runtime_fallback;\ No newline at end of file+ov_property_key_intel_auto_enable_runtime_fallback;++/**+ * @brief Read-write property<string> to enable/disable compiling the model to all candidate devices in the+ * background to populate cache blobs for faster subsequent loading (requires ov::cache_dir or ov::cache_path)+ * @ingroup ov_property_c_api+ */+OPENVINO_C_VAR(const char*)+ov_property_key_intel_auto_compile_for_all;\ No newline at end of filediff --git a/src/bindings/c/src/ov_auto_property.cpp b/src/bindings/c/src/ov_auto_property.cppindex 14751fcc7ca..3118469a36d 100644--- a/src/bindings/c/src/ov_auto_property.cpp+++ b/src/bindings/c/src/ov_auto_property.cpp@@ -8,3 +8,4 @@const char* ov_property_key_intel_auto_device_bind_buffer = "DEVICE_BIND_BUFFER";const char* ov_property_key_intel_auto_enable_startup_fallback = "ENABLE_STARTUP_FALLBACK";const char* ov_property_key_intel_auto_enable_runtime_fallback = "ENABLE_RUNTIME_FALLBACK";+const char* ov_property_key_intel_auto_compile_for_all = "COMPILE_FOR_ALL";diff --git a/src/bindings/c/tests/ov_auto_property_test.cpp b/src/bindings/c/tests/ov_auto_property_test.cppindex 0648ba2a855..5858e036ba3 100644--- a/src/bindings/c/tests/ov_auto_property_test.cpp+++ b/src/bindings/c/tests/ov_auto_property_test.cpp@@ -46,6 +46,9 @@ const std::vector<test_params> test_property_config = {test_params{"AUTO", ov_property_key_intel_auto_enable_runtime_fallback, "YES", false},test_params{"AUTO", ov_property_key_intel_auto_enable_runtime_fallback, "NO", false},test_params{"AUTO", ov_property_key_intel_auto_enable_runtime_fallback, "TEST", true},+ test_params{"AUTO", ov_property_key_intel_auto_compile_for_all, "YES", false},+ test_params{"AUTO", ov_property_key_intel_auto_compile_for_all, "NO", false},+ test_params{"AUTO", ov_property_key_intel_auto_compile_for_all, "TEST", true},};INSTANTIATE_TEST_SUITE_P(ov_auto_plugin_test_properties,diff --git a/src/bindings/python/src/pyopenvino/core/properties/properties.cpp b/src/bindings/python/src/pyopenvino/core/properties/properties.cppindex 80863009c0f..7977b37b11d 100644--- a/src/bindings/python/src/pyopenvino/core/properties/properties.cpp+++ b/src/bindings/python/src/pyopenvino/core/properties/properties.cpp@@ -340,6 +340,7 @@ void regmodule_properties(py::module m) {wrap_property_RW(m_intel_auto, ov::intel_auto::device_bind_buffer, "device_bind_buffer");wrap_property_RW(m_intel_auto, ov::intel_auto::enable_startup_fallback, "enable_startup_fallback");wrap_property_RW(m_intel_auto, ov::intel_auto::enable_runtime_fallback, "enable_runtime_fallback");+ wrap_property_RW(m_intel_auto, ov::intel_auto::compile_for_all, "compile_for_all");wrap_property_RW(m_intel_auto, ov::intel_auto::schedule_policy, "schedule_policy");wrap_property_RW(m_intel_auto, ov::intel_auto::devices_utilization_threshold, "devices_utilization_threshold");// perf_curve_table: name/string/map overloads (map form uses pybind11's default STL caster).diff --git a/src/bindings/python/tests/test_runtime/test_properties.py b/src/bindings/python/tests/test_runtime/test_properties.pyindex 35e7d07f103..9df9622fd8f 100644--- a/src/bindings/python/tests/test_runtime/test_properties.py+++ b/src/bindings/python/tests/test_runtime/test_properties.py@@ -420,6 +420,16 @@ def test_properties_ro(ov_property_ro, expected_value):(0, False),),),+ (+ intel_auto.compile_for_all,+ "COMPILE_FOR_ALL",+ (+ (True, True),+ (False, False),+ (1, True),+ (0, False),+ ),+ ),(device.id, "DEVICE_ID", (("0", "0"),)),(log.level,diff --git a/src/inference/include/openvino/runtime/auto/properties.hpp b/src/inference/include/openvino/runtime/auto/properties.hppindex 1be8d97a929..38d89dd69be 100644--- a/src/inference/include/openvino/runtime/auto/properties.hpp+++ b/src/inference/include/openvino/runtime/auto/properties.hpp@@ -30,6 +30,27 @@ static constexpr Property<bool> enable_startup_fallback{"ENABLE_STARTUP_FALLBACK*/static constexpr Property<bool> enable_runtime_fallback{"ENABLE_RUNTIME_FALLBACK"};+/**+ * @brief auto device setting that enables compiling the model to the remaining candidate devices in the background,+ * after the actual device is ready, to populate cache blobs for faster device switching.+ * Enabling it disables ov::intel_auto::enable_startup_fallback and ov::intel_auto::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).+ *+ * 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+ * the one not selected by AUTO is compiled in the background:+ * @code+ * core.compile_model(model,+ * "AUTO",+ * ov::device::priorities("GPU,NPU"),+ * ov::cache_dir("model_cache"),+ * ov::intel_auto::compile_for_all(true));+ * @endcode+ */+static constexpr Property<bool> compile_for_all{"COMPILE_FOR_ALL"};+/*** @brief Enum to define the policy of scheduling inference request to target device in cumulative throughput mode on* AUTOdiff --git a/src/inference/src/dev/core_impl.hpp b/src/inference/src/dev/core_impl.hppindex 40ccf07e6be..1443abd8973 100644--- a/src/inference/src/dev/core_impl.hpp+++ b/src/inference/src/dev/core_impl.hpp@@ -272,7 +272,7 @@ private:ov::AnyMap create_compile_config(const ov::Plugin& plugin, const ov::AnyMap& orig_config) const;ov::AnyMap create_compile_config(const std::string& device_name, const ov::AnyMap& orig_config) const override {- return create_compile_config(get_plugin(device_name), orig_config);+ return create_compile_config(get_plugin(device_name, orig_config), orig_config);}bool is_hidden_device(const std::string& device_name) const;diff --git a/src/plugins/auto/CMakeLists.txt b/src/plugins/auto/CMakeLists.txtindex 580507f90ed..7c462466e4e 100644--- a/src/plugins/auto/CMakeLists.txt+++ b/src/plugins/auto/CMakeLists.txt@@ -12,6 +12,7 @@ set(SOURCES${CMAKE_CURRENT_SOURCE_DIR}/src/async_infer_request.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/auto_compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/auto_schedule.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/cache_warmup.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/cumulative_compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/cumulative_schedule.cppdiff --git a/src/plugins/auto/src/auto_schedule.cpp b/src/plugins/auto/src/auto_schedule.cppindex 693f71ae84b..70bec3446f2 100644--- a/src/plugins/auto/src/auto_schedule.cpp+++ b/src/plugins/auto/src/auto_schedule.cpp@@ -3,13 +3,14 @@/////////////////////////////////////////////////////////////////////////////////////////////////////+#include <algorithm>+#include <chrono>+#include "auto_schedule.hpp"#include <stdexcept>#include "async_infer_request.hpp"-#include "openvino/runtime/compilation_context.hpp"-#include "openvino/util/file_util.hpp"#include "plugin.hpp"// ------------------------------AutoSchedule----------------------------@@ -124,9 +125,6 @@ void AutoSchedule::init() {// loadContext[ACTUALDEVICE] is always enabled,// when there is CPU and there are more than two devices, loadContext[CPU] is enabledm_compile_context[ACTUALDEVICE].m_is_enabled = true;- if (m_context->m_runtime_fallback) {- m_compile_context[FALLBACKDEVICE].m_is_enabled = true;- }m_compile_context[ACTUALDEVICE].m_model_precision = m_context->m_model_precision;m_compile_context[ACTUALDEVICE].m_meta_devices = m_context->m_device_priorities;m_compile_context[ACTUALDEVICE].m_device_info =@@ -139,6 +137,31 @@ void AutoSchedule::init() {// nothing was reserved by select_device() in this modem_compile_context[ACTUALDEVICE].m_priority_released = true;}+ if (m_context->m_compile_for_all) {+ const auto& actual_device = m_compile_context[ACTUALDEVICE].m_device_info.device_name;+ const auto& candidates = m_compile_context[ACTUALDEVICE].m_meta_devices;+ const bool has_warmup_candidate = std::any_of(candidates.begin(), candidates.end(), [&](const auto& device) {+ 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;+ } 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");+ m_context->m_startup_fallback = false;+ m_context->m_runtime_fallback = false;+ // Capture before the actual-device task releases the model.+ m_cache_warmup = std::make_shared<CacheWarmup>(m_plugin->get_cache_warmup_manager(),+ m_context->m_ov_core,+ m_context->m_model,+ m_context->m_model_path,+ get_log_tag());+ }+ }+ if (m_context->m_runtime_fallback) {+ m_compile_context[FALLBACKDEVICE].m_is_enabled = true;+ }auto load_device_task = [&](AutoCompileContext* context_ptr, const std::shared_ptr<ov::Model>& model) {try_to_compile_model(*context_ptr, model);@@ -350,6 +373,12 @@ void AutoSchedule::init() {}}m_context->m_hw_compiled_model = wait_first_compiled_model_ready();+ // compile_for_all disables the CPU helper, so the warm-up can start as soon as the actual device is ready.+ if (m_cache_warmup && m_compile_context[ACTUALDEVICE].m_is_already) {+ // Failed startup devices were already removed from the actual context's candidates.+ m_cache_warmup->start(m_compile_context[ACTUALDEVICE].m_device_info.device_name,+ m_compile_context[ACTUALDEVICE].m_meta_devices);+ }}void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::shared_ptr<ov::Model>& model) {@@ -455,9 +484,9 @@ void AutoSchedule::try_to_compile_model(AutoCompileContext& context, const std::}}// 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+ // if they are same, do not need to compile again (only when the CPU helper is enabled)cur_dev_is_cpu = (context.m_device_info.device_name.find("CPU") != std::string::npos);- if (cur_dev_is_cpu) {+ if (cur_dev_is_cpu && m_compile_context[CPU].m_is_enabled) {auto compare = [](ov::AnyMap& a, ov::AnyMap& b) -> bool {if (a.size() != b.size()) {return false;@@ -878,6 +907,10 @@ AutoSchedule::~AutoSchedule() {m_plugin->get_executor_manager()->clear("AutoDeviceAsyncCompile");m_executor.reset();}+ // After the recycle task has stopped, so no new warm-up can be queued.+ if (m_cache_warmup) {+ m_cache_warmup->stop();+ }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);diff --git a/src/plugins/auto/src/auto_schedule.hpp b/src/plugins/auto/src/auto_schedule.hppindex 50f9366f1f6..6b672110f9f 100644--- a/src/plugins/auto/src/auto_schedule.hpp+++ b/src/plugins/auto/src/auto_schedule.hpp@@ -10,6 +10,7 @@#include "schedule.hpp"#include "async_infer_request.hpp"+#include "cache_warmup.hpp"namespace ov {namespace auto_plugin {@@ -36,6 +37,8 @@ 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;+ // Null unless ov::intel_auto::compile_for_all is enabled; set before any background task starts.+ std::shared_ptr<CacheWarmup> m_cache_warmup;void release_execution_slot() override;/*** @brief Serialize the incoming request behind the execution gate when per inference device selection is on.diff --git a/src/plugins/auto/src/cache_warmup.cpp b/src/plugins/auto/src/cache_warmup.cppnew file mode 100644index 00000000000..62636a5f201--- /dev/null+++ b/src/plugins/auto/src/cache_warmup.cpp@@ -0,0 +1,297 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "cache_warmup.hpp"++#include <algorithm>+#include <chrono>+#include <map>+#include <optional>++#include "openvino/runtime/compilation_context.hpp"+#include "openvino/runtime/device_id_parser.hpp"+#include "openvino/runtime/intel_gpu/properties.hpp"+#include "openvino/util/container_util.hpp"+#include "openvino/util/file_util.hpp"++namespace ov {+namespace auto_plugin {+namespace {+// Core keeps all blobs of a *.bin cache path in one archive. Its writes are only locked per blob ID, so a background+// warm-up must not write into it concurrently with other compilations.+bool is_single_file_cache(const std::filesystem::path& cache_location) {+ std::error_code ec;+ const auto status = std::filesystem::status(cache_location, ec);+ if (!ec && std::filesystem::exists(status)) {+ return !std::filesystem::is_directory(status);+ }+ // Core creates the cache directory on the first write and picks the storage by extension until then.+ return cache_location.extension() == ".bin";+}++// Core moves the ID of e.g. "GPU.1" into ov::device::id, so the cache key must be built for that device instance.+ov::AnyMap create_compile_config(const ov::ICore& core, const std::string& device_name, const ov::AnyMap& config) {+ const ov::DeviceIDParser parser(device_name);+ auto device_config = config;+ if (!parser.get_device_id().empty()) {+ device_config.emplace(ov::device::id.name(), parser.get_device_id());+ }+ return core.create_compile_config(parser.get_device_name(), device_config);+}++// Keys are compared as strings, like the cache hash does: ov::Any::operator== throws for values such as ov::device::UUID.+std::map<std::string, std::string> get_cache_key(const ov::ICore& core,+ const std::string& device_name,+ const ov::AnyMap& config) {+ std::map<std::string, std::string> key;+ for (const auto& [name, value] : create_compile_config(core, device_name, config)) {+ key.emplace(name, value.as<std::string>());+ }+ return key;+}++// Lowers the host-side cost of the background compilation without changing the cache key.+ov::AnyMap make_warmup_config(const ov::ICore& core, const DeviceInformation& device) {+ std::vector<ov::PropertyName> supported;+ try {+ supported = core.get_property(device.device_name, ov::supported_properties);+ } catch (const ov::Exception&) {+ return device.config;+ }+ auto config = device.config;+ if (ov::util::contains(supported, ov::intel_gpu::hint::host_task_priority.name())) {+ config.emplace(ov::intel_gpu::hint::host_task_priority(ov::hint::Priority::LOW));+ }+ if (ov::util::contains(supported, ov::compilation_num_threads.name())) {+ config.emplace(ov::compilation_num_threads(std::max(1, static_cast<int>(std::thread::hardware_concurrency()) / 4)));+ }+ if (config.size() == device.config.size()) {+ return config;+ }+ if (get_cache_key(core, device.device_name, config) != get_cache_key(core, device.device_name, device.config)) {+ return device.config;+ }+ return config;+}+} // namespace++// The caller may modify its model once compile_model() returns, so warm-up works on a private clone; a clone failure+// propagates to the caller.+CacheWarmup::CacheWarmup(CacheWarmupManager& manager,+ std::weak_ptr<ov::ICore> core,+ std::shared_ptr<const ov::Model> model,+ std::filesystem::path model_path,+ std::string log_tag)+ : m_manager(manager),+ m_core(std::move(core)),+ m_model(model ? model->clone() : nullptr),+ m_model_path(std::move(model_path)),+ m_log_tag(std::move(log_tag)) {}++const std::string& CacheWarmup::get_log_tag() const noexcept {+ return m_log_tag;+}++void CacheWarmup::start(const std::string& actual_device, const std::vector<DeviceInformation>& candidates) {+ std::vector<DeviceInformation> devices;+ for (const auto& device : candidates) {+ if (device.device_name != actual_device && ov::DeviceIDParser(device.device_name).get_device_name() != "CPU") {+ devices.push_back(device);+ }+ }+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ if (m_state != State::Created) {+ return;+ }+ if (devices.empty() || (!m_model && m_model_path.empty())) {+ m_model.reset();+ m_state = State::Done;+ return;+ }+ m_state = State::Idle;+ m_devices = std::move(devices);+ LOG_INFO_TAG("start cache pre-compilation for %zu device(s)", m_devices.size());+ }+ m_manager.enqueue(shared_from_this());+}++void CacheWarmup::request_stop_unsafe() {+ m_model.reset();+ if (m_state == State::Compiling) {+ m_state = State::Stopping;+ } else if (m_state != State::Stopping) {+ m_state = State::Stopped;+ }+}++void CacheWarmup::stop() {+ std::unique_lock<std::mutex> lock(m_mutex);+ request_stop_unsafe();+ m_cv.wait(lock, [this] {+ return m_state != State::Stopping;+ });+}++void CacheWarmup::run() {+ std::shared_ptr<const ov::Model> model;+ std::vector<DeviceInformation> devices;+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ model = std::move(m_model);+ devices = std::move(m_devices);+ }+ for (const auto& device : devices) {+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ if (m_state != State::Idle) {+ return;+ }+ m_state = State::Compiling;+ }+ const auto begin = std::chrono::steady_clock::now();+ try {+ if (auto core = m_core.lock()) {+ const auto config = make_warmup_config(*core, device);+ const auto cache_location =+ CacheWarmupManager::get_cache_location(*core, config, device.device_name);+ if (cache_location.empty()) {+ LOG_INFO_TAG("cache pre-compilation skipped for device: %s, caching is disabled for it",+ device.device_name.c_str());+ } else if (is_single_file_cache(cache_location)) {+ LOG_WARNING_TAG("cache pre-compilation skipped for device: %s, single-file cache %s is not "+ "supported",+ device.device_name.c_str(),+ 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);+ }+ LOG_INFO_TAG("cache pre-compilation finished for device: %s, compile time: %lf ms",+ device.device_name.c_str(),+ std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin)+ .count());+ }+ }+ } catch (const std::exception& e) {+ LOG_WARNING_TAG("cache pre-compilation failed for device: %s, %s", device.device_name.c_str(), e.what());+ } catch (...) {+ LOG_WARNING_TAG("cache pre-compilation failed for device: %s, unknown exception",+ device.device_name.c_str());+ }+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ m_state = m_state == State::Stopping ? State::Stopped : State::Idle;+ }+ m_cv.notify_all();+ }+ std::lock_guard<std::mutex> lock(m_mutex);+ if (m_state == State::Idle) {+ m_state = State::Done;+ }+}++CacheWarmupManager::~CacheWarmupManager() {+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ m_stop = true;+ }+ m_cv.notify_all();+ if (m_worker.joinable()) {+ m_worker.join();+ }+}++void CacheWarmupManager::enqueue(std::shared_ptr<CacheWarmup> warmup) {+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ if (!m_worker.joinable()) {+ m_worker = std::thread([this] {+ worker_loop();+ });+ }+ m_queue.push_back(std::move(warmup));+ }+ m_cv.notify_one();+}++void CacheWarmupManager::worker_loop() {+ while (true) {+ std::shared_ptr<CacheWarmup> warmup;+ {+ std::unique_lock<std::mutex> lock(m_mutex);+ m_cv.wait(lock, [this] {+ return m_stop || !m_queue.empty();+ });+ if (m_stop) {+ return;+ }+ warmup = std::move(m_queue.front());+ m_queue.pop_front();+ }+ warmup->run();+ }+}++std::filesystem::path CacheWarmupManager::get_cache_location(const ov::ICore& core,+ const ov::AnyMap& config,+ const std::string& device_name) {+ if (const auto it = config.find(ov::cache_dir.name()); it != config.end()) {+ return ov::util::make_path(it->second.as<std::string>());+ }+ if (const auto it = config.find(ov::cache_path.name()); it != config.end()) {+ return it->second.as<std::filesystem::path>();+ }++ const auto query = [&core](const std::string& scope) -> std::optional<std::filesystem::path> {+ try {+ if (const auto cache_dir = core.get_property(scope, ov::cache_dir); !cache_dir.empty()) {+ return ov::util::make_path(cache_dir);+ }+ return std::filesystem::path(core.get_property(scope, ov::cache_path));+ } catch (const std::exception&) {+ return std::nullopt;+ }+ };+ if (!device_name.empty()) {+ if (auto location = query(device_name)) {+ return *location;+ }+ }+ return query("").value_or(std::filesystem::path{});+}++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"));+}++} // namespace auto_plugin+} // namespace ovdiff --git a/src/plugins/auto/src/cache_warmup.hpp b/src/plugins/auto/src/cache_warmup.hppnew file mode 100644index 00000000000..6a896985101--- /dev/null+++ b/src/plugins/auto/src/cache_warmup.hpp@@ -0,0 +1,127 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <condition_variable>+#include <deque>+#include <filesystem>+#include <memory>+#include <mutex>+#include <string>+#include <thread>+#include <vector>++#include "common.hpp"++namespace ov {+namespace auto_plugin {++class CacheWarmupManager;++// Cache warm-up state of one compiled model, used when ov::intel_auto::compile_for_all is enabled. While AUTO serves+// requests on the actual device, the other candidate devices are compiled in the background so that their cache blobs+// exist the next time the model is loaded (e.g. when a different device is picked later). Needs a cache dir/path.+//+// Flow:+// 1. start() is called once the actual device is known. It filters out the actual device and CPU, then hands this+// 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;+// - 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.+// 3. stop() (owning compiled model destroyed) skips the not yet started devices and waits for the compilation in+// flight, so the core and the model are not used after the owner is gone.+//+// State transitions (guarded by m_mutex):+//+// Created --start(): nothing to warm up--> Done+// |+// +--start(): devices queued--> Idle <--------------------++// | | compile finished+// +--run(): device--> Compiling+// | |+// | all devices done | stop()+// v v+// Done Stopping --compile finished--> Stopped+//+// stop() in Created, Idle or Done goes straight to Stopped; start() is accepted only in Created.+class CacheWarmup : public std::enable_shared_from_this<CacheWarmup> {+public:+ CacheWarmup(CacheWarmupManager& manager,+ std::weak_ptr<ov::ICore> core,+ std::shared_ptr<const ov::Model> model,+ std::filesystem::path model_path,+ std::string log_tag);++ // Queues the warm-up of the candidates other than the actual device; only the first call counts.+ void start(const std::string& actual_device, const std::vector<DeviceInformation>& candidates);+ // Skips the remaining devices and waits for the in-flight compilation; idempotent.+ void stop();+ // Compiles the queued devices one by one; called by the CacheWarmupManager worker thread only.+ void run();++private:+ void request_stop_unsafe();+ const std::string& get_log_tag() const noexcept;++ CacheWarmupManager& m_manager;+ // The owning compiled model keeps the core alive until stop() returns.+ std::weak_ptr<ov::ICore> m_core;+ std::shared_ptr<const ov::Model> m_model;+ std::filesystem::path m_model_path;+ std::string m_log_tag;+ std::vector<DeviceInformation> m_devices;+ std::mutex m_mutex;+ std::condition_variable m_cv;+ enum class State {+ Created, // start() has not been called+ Idle, // queued, or between two device compilations+ Compiling, // a device compilation is in flight+ Stopping, // stop() arrived during a compilation; run() completes the stop+ Stopped, // stop() completed; nothing will be compiled anymore+ Done // all devices processed, or there was nothing to warm up+ };+ State m_state = State::Created;+};++// Plugin-wide queue; a single worker thread serializes the warm-up compilations of all compiled models.+class CacheWarmupManager {+public:+ CacheWarmupManager() = default;+ CacheWarmupManager(const CacheWarmupManager&) = delete;+ CacheWarmupManager& operator=(const CacheWarmupManager&) = delete;+ CacheWarmupManager(CacheWarmupManager&&) = delete;+ CacheWarmupManager& operator=(CacheWarmupManager&&) = delete;+ ~CacheWarmupManager();++ void enqueue(std::shared_ptr<CacheWarmup> warmup);++ // Cache location resolved like the Core does: ov::cache_dir / ov::cache_path in config, then the setting of the+ // device (when given), then the global one. An empty result means caching is disabled.+ static std::filesystem::path get_cache_location(const ov::ICore& core,+ const ov::AnyMap& config,+ const std::string& device_name = {});+ static bool 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);++private:+ void worker_loop();++ std::mutex m_mutex;+ std::condition_variable m_cv;+ std::deque<std::shared_ptr<CacheWarmup>> m_queue;+ bool m_stop = false;+ std::thread m_worker;+ std::shared_ptr<Log> m_logger = Log::instance();+};++} // namespace auto_plugin+} // namespace ovdiff --git a/src/plugins/auto/src/common.hpp b/src/plugins/auto/src/common.hppindex b1c6fbfa775..36d6f58ae22 100644--- a/src/plugins/auto/src/common.hpp+++ b/src/plugins/auto/src/common.hpp@@ -238,6 +238,7 @@ public:bool m_startup_fallback = true;bool m_runtime_fallback = true;bool m_bind_buffer = false;+ bool m_compile_for_all = false;std::shared_ptr<ov::Model> m_model;std::filesystem::path m_model_path;std::shared_ptr<const ov::IPlugin> m_plugin;diff --git a/src/plugins/auto/src/plugin.cpp b/src/plugins/auto/src/plugin.cppindex 0e2522d00e4..56dc768621f 100644--- a/src/plugins/auto/src/plugin.cpp+++ b/src/plugins/auto/src/plugin.cpp@@ -634,6 +634,40 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model_impl(const std::filesyOPENVINO_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_compile_for_all = load_config.get_property(ov::intel_auto::compile_for_all);+ if (auto_s_context->m_compile_for_all) {+ std::vector<const DeviceInformation*> warmup_candidates;+ for (const auto& device : auto_s_context->m_device_priorities_initial) {+ if (ov::DeviceIDParser(device.device_name).get_device_name() != "CPU")+ warmup_candidates.push_back(&device);+ }+ // A user blob ID does not identify a device, so blobs warmed up for other devices would overwrite each other.+ const bool has_blob_id =+ full_property.count(ov::cache_blob_id.name()) != 0 ||+ std::any_of(auto_s_context->m_device_priorities_initial.begin(),+ auto_s_context->m_device_priorities_initial.end(),+ [](const DeviceInformation& device) {+ return device.config.count(ov::cache_blob_id.name()) != 0;+ });+ if (is_cumulative || has_blob_id) {+ LOG_WARNING_TAG("compile_for_all is ignored: %s",+ is_cumulative ? "not supported in cumulative mode" : "not supported with ov::cache_blob_id");+ auto_s_context->m_compile_for_all = false;+ } else if (!std::any_of(auto_s_context->m_device_priorities_initial.begin(),+ auto_s_context->m_device_priorities_initial.end(),+ [this](const DeviceInformation& device) {+ return !CacheWarmupManager::get_cache_location(*get_core(),+ device.config,+ device.device_name)+ .empty();+ })) {+ // Independent of how many devices the host has, so the contract of an explicit true is the same everywhere.+ OPENVINO_THROW(ov::intel_auto::compile_for_all.name(), " requires ov::cache_dir or ov::cache_path to be set");+ } else if (warmup_candidates.empty() || auto_s_context->m_device_priorities_initial.size() < 2) {+ LOG_WARNING_TAG("compile_for_all is ignored: no other candidate device to compile");+ auto_s_context->m_compile_for_all = false;+ }+ }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;@@ -1149,38 +1183,66 @@ std::string Plugin::get_device_list(ov::AnyMap& properties,get_device_name() != "AUTO" ||(properties.count(ov::hint::performance_mode.name()) &&properties.at(ov::hint::performance_mode.name()).as<std::string>() == "CUMULATIVE_THROUGHPUT");+ const bool preserve_cpu_for_compile_retry = !is_cumulative_tput &&+ properties.count(ov::cache_blob_id.name()) == 0 &&+ properties.count(ov::intel_auto::compile_for_all.name()) &&+ properties.at(ov::intel_auto::compile_for_all.name()).as<bool>();if (device_list_config != properties.end() && !(device_list_config->second.as<std::string>().empty())) {auto priorities = device_list_config->second;// parsing the string and splitting the comma-separated tokensstd::vector<std::string> devices_to_be_merged =m_plugin_config.parse_priorities_devices(priorities.as<std::string>());+ bool can_preserve_cpu_for_compile_retry = preserve_cpu_for_compile_retry;+ if (can_preserve_cpu_for_compile_retry) {+ for (const auto& device : devices_to_be_merged) {+ if (device.empty())+ continue;+ if (device.front() == '-')+ continue;+ try {+ const auto device_config = get_core()->get_supported_property(device, properties);+ if (device_config.count(ov::cache_blob_id.name())) {+ can_preserve_cpu_for_compile_retry = false;+ break;+ }+ } catch (const std::exception&) {+ can_preserve_cpu_for_compile_retry = false;+ break;+ }+ }+ }std::size_t num_blob_files = 0;- std::string cache_dir = properties.count(ov::cache_dir.name())- ? properties.at(ov::cache_dir.name()).as<std::string>()- : get_core()->get_property("", ov::cache_dir);- bool if_need_cache_check =- !is_cumulative_tput && enable_startup_cpu && (model || !model_path.empty()) && !cache_dir.empty();+ bool if_need_cache_check = !is_cumulative_tput && enable_startup_cpu && !can_preserve_cpu_for_compile_retry &&+ (model || !model_path.empty()) && properties.count(ov::cache_blob_id.name()) == 0;if (if_need_cache_check) {for (auto&& device : devices_to_be_merged) {+ // Skip the excluded device+ if (device.front() == '-')+ continue;ov::DeviceIDParser parsed{device};if (parsed.get_device_name().find("CPU") != std::string::npos)continue;// check if cached model exists for other devices- auto dev_properties = get_core()->get_supported_property(parsed.get_device_name(), properties);- dev_properties = get_core()->create_compile_config(parsed.get_device_name(), dev_properties);- std::string blobId;-- if (model)- blobId = ov::ModelCache::compute_hash(model, dev_properties);- else- blobId = ov::ModelCache::compute_hash(model_path, dev_properties);- const auto cached_model_path = ov::util::make_path(cache_dir) / (blobId + ".blob");- bool is_blob_file_exist = ov::util::file_exists(cached_model_path);+ bool is_blob_file_exist = false;+ try {+ // Device-scoped settings take precedence over the global ones.+ const auto device_config = get_core()->get_supported_property(device, properties);+ const auto cache_location =+ CacheWarmupManager::get_cache_location(*get_core(), device_config, device);+ if (cache_location.empty() || device_config.count(ov::cache_blob_id.name()))+ continue;+ is_blob_file_exist = CacheWarmupManager::is_blob_cached(*get_core(),+ device,+ device_config,+ model,+ model_path,+ cache_location);+ } catch (const std::exception& ex) {+ // The probe is an optimization only; a failing device must not break compilation.+ LOG_DEBUG_TAG("cache probe failed for %s: %s", device.c_str(), ex.what());+ }num_blob_files += is_blob_file_exist;- LOG_DEBUG_TAG("device: %s %s cached blob: %s ",- device.c_str(),- is_blob_file_exist ? "found" : "not found",- ov::util::path_to_string(cached_model_path).c_str());+ LOG_DEBUG_TAG("device: %s %s cached blob", device.c_str(), is_blob_file_exist ? "found" : "not found");}if (enable_startup_cpu && num_blob_files) {@@ -1248,7 +1310,7 @@ std::string Plugin::get_device_list(ov::AnyMap& properties,continue;}// Disable CPU if enable_startup_cpu and enable_runtime_cpu are both disabled- if (!enable_startup_cpu && !enable_runtime_cpu) {+ if (!enable_startup_cpu && !enable_runtime_cpu && !can_preserve_cpu_for_compile_retry) {continue;}}diff --git a/src/plugins/auto/src/plugin.hpp b/src/plugins/auto/src/plugin.hppindex c44aa37fd43..1c92a6bdd9a 100644--- a/src/plugins/auto/src/plugin.hpp+++ b/src/plugins/auto/src/plugin.hpp@@ -14,6 +14,7 @@#include <unordered_map>#include <vector>+#include "cache_warmup.hpp"#include "common.hpp"#include "compiled_model.hpp"#include "openvino/runtime/iplugin.hpp"@@ -99,6 +100,14 @@ public:const ov::SoPtr<ov::IRemoteContext>& context,const ov::AnyMap& properties) const override;+ CacheWarmupManager& get_cache_warmup_manager() {+ return *m_cache_warmup_manager;+ }++ const CacheWarmupManager& get_cache_warmup_manager() const {+ return *m_cache_warmup_manager;+ }+private:std::shared_ptr<ov::ICompiledModel> compile_model_impl(const std::filesystem::path& model_path,const std::shared_ptr<const ov::Model>& model,@@ -126,6 +135,7 @@ private:PluginConfig m_plugin_config;mutable std::once_flag m_telemetry_client_init_once;mutable std::unique_ptr<device_monitor::TelemetryClient> m_telemetry_client;+ std::unique_ptr<CacheWarmupManager> m_cache_warmup_manager = std::make_unique<CacheWarmupManager>();};} // namespace auto_plugindiff --git a/src/plugins/auto/src/plugin_config.cpp b/src/plugins/auto/src/plugin_config.cppindex 7a3b81f799e..78c0d48ef66 100644--- a/src/plugins/auto/src/plugin_config.cpp+++ b/src/plugins/auto/src/plugin_config.cpp@@ -27,9 +27,11 @@ void PluginConfig::set_default() {std::make_tuple(ov::hint::num_requests, 0, UnsignedTypeValidator()),std::make_tuple(ov::intel_auto::enable_startup_fallback, true),std::make_tuple(ov::intel_auto::enable_runtime_fallback, true),+ std::make_tuple(ov::intel_auto::compile_for_all, false),std::make_tuple(ov::intel_auto::devices_utilization_threshold, std::map<std::string, unsigned>{}, DeviceUtilizationThresholdValidator()),std::make_tuple(ov::intel_auto::perf_curve_table, ov::intel_auto::PerfCurveTable{}, PerfCurveTableValidator()),std::make_tuple(ov::intel_auto::low_power_device, std::string{}),+// RO for register onlystd::make_tuple(ov::device::full_name),std::make_tuple(ov::device::capabilities),diff --git a/src/plugins/auto/src/plugin_config.hpp b/src/plugins/auto/src/plugin_config.hppindex 98ed7cd07d0..50b53e7c03e 100644--- a/src/plugins/auto/src/plugin_config.hpp+++ b/src/plugins/auto/src/plugin_config.hpp@@ -212,6 +212,9 @@ public:multi_supported_configKeys.erase(std::remove(multi_supported_configKeys.begin(), multi_supported_configKeys.end(), ov::intel_auto::enable_runtime_fallback.name()),multi_supported_configKeys.end());+ multi_supported_configKeys.erase(std::remove(+ multi_supported_configKeys.begin(), multi_supported_configKeys.end(), ov::intel_auto::compile_for_all.name()),+ multi_supported_configKeys.end());multi_supported_configKeys.erase(std::remove(multi_supported_configKeys.begin(), multi_supported_configKeys.end(), ov::intel_auto::devices_utilization_threshold.name()),multi_supported_configKeys.end());@@ -236,6 +239,9 @@ public:multi_supported_properties.erase(std::remove(multi_supported_properties.begin(), multi_supported_properties.end(), ov::intel_auto::enable_runtime_fallback),multi_supported_properties.end());+ multi_supported_properties.erase(std::remove(+ multi_supported_properties.begin(), multi_supported_properties.end(), ov::intel_auto::compile_for_all),+ multi_supported_properties.end());multi_supported_properties.erase(std::remove(multi_supported_properties.begin(),multi_supported_properties.end(),ov::intel_auto::devices_utilization_threshold),diff --git a/src/plugins/auto/tests/functional/behavior/caching_test.cpp b/src/plugins/auto/tests/functional/behavior/caching_test.cppindex 7a664ab95be..b27fe2d4b81 100644--- a/src/plugins/auto/tests/functional/behavior/caching_test.cpp+++ b/src/plugins/auto/tests/functional/behavior/caching_test.cpp@@ -2,6 +2,9 @@// SPDX-License-Identifier: Apache-2.0//+#include <chrono>+#include <thread>+#include "auto_func_test.hpp"#include "common_test_utils/include/common_test_utils/file_utils.hpp"#include "openvino/pass/serialize.hpp"@@ -165,6 +168,35 @@ TEST_F(AutoFuncTests, load_cached_model_to_actual_device_and_disable_CPU_accelercore.set_property(ov::cache_dir(""));}+TEST_F(AutoFuncTests, compile_for_all_populates_cache_reused_by_later_loads) {+ core.compile_model(model_cannot_batch, "MOCK_CPU");+ core.compile_model(model_cannot_batch, "MOCK_GPU"); // need to initialize the order of plugins in mock_engine+ register_plugin_mock_gpu(core, "MOCK_3", {});+ core.set_property(ov::cache_path(cache_path));+ // distinct device ids give each device its own blob+ core.set_property("MOCK_GPU", ov::device::id("gpu"));+ core.set_property("MOCK_3", ov::device::id("3"));+ {+ auto compiled_model =+ core.compile_model(model_cannot_batch,+ "AUTO",+ {ov::device::priorities("MOCK_GPU", "MOCK_3"), ov::intel_auto::compile_for_all(true)});+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);+ while (ov::test::utils::listFilesWithExt(cache_path, "blob").size() < 2 &&+ std::chrono::steady_clock::now() < deadline) {+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ }+ }+ // Releasing AUTO waits for an in-flight warm-up, so both blobs are fully written here.+ ASSERT_EQ(ov::test::utils::listFilesWithExt(cache_path, "blob").size(), 2);+ for (const std::string device : {"MOCK_GPU", "MOCK_3"}) {+ auto compiled_model = core.compile_model(model_cannot_batch, device);+ EXPECT_TRUE(compiled_model.get_property(ov::loaded_from_cache)) << device;+ }+ ASSERT_EQ(ov::test::utils::listFilesWithExt(cache_path, "blob").size(), 2);+ core.set_property(ov::cache_path(""));+}+TEST_F(AutoFuncTests, compiled_with_cache_enabled_batch_enabled) {#ifdef ENABLE_AUTO_BATCHcore.set_property(ov::cache_dir(cache_path));diff --git a/src/plugins/auto/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp b/src/plugins/auto/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cppindex 43882627fae..78a8c4227eb 100644--- a/src/plugins/auto/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp+++ b/src/plugins/auto/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp@@ -35,6 +35,8 @@ const std::vector<ov::AnyMap> multi_Auto_properties = {{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::intel_auto::device_bind_buffer("NO")},{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::intel_auto::enable_startup_fallback("YES")},{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::intel_auto::enable_startup_fallback("NO")},+ {ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::intel_auto::compile_for_all("YES")},+ {ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::intel_auto::compile_for_all("NO")},{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::enable_profiling(true)},{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::enable_profiling(false)}};@@ -102,6 +104,7 @@ const std::vector<ov::AnyMap> default_properties = {{ov::hint::execution_mode(ov::hint::ExecutionMode::PERFORMANCE)},{ov::intel_auto::device_bind_buffer(false)},{ov::intel_auto::enable_startup_fallback(true)},+ {ov::intel_auto::compile_for_all(false)},{ov::intel_auto::schedule_policy(ov::intel_auto::SchedulePolicy::DEVICE_PRIORITY)},{ov::device::priorities("")}};INSTANTIATE_TEST_SUITE_P(smoke_AutoBehaviorTests,diff --git a/src/plugins/auto/tests/unit/cache_compile_for_all_test.cpp b/src/plugins/auto/tests/unit/cache_compile_for_all_test.cppnew file mode 100644index 00000000000..71fdd14aa0c--- /dev/null+++ b/src/plugins/auto/tests/unit/cache_compile_for_all_test.cpp@@ -0,0 +1,917 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <atomic>+#include <chrono>+#include <filesystem>+#include <fstream>+#include <functional>+#include <future>+#include <list>+#include <sstream>+#include <string>+#include <thread>+#include <tuple>+#include <vector>++#include "include/auto_unit_test.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/relu.hpp"+#include "openvino/op/result.hpp"+#include "openvino/runtime/compilation_context.hpp"+#include "openvino/runtime/threading/immediate_executor.hpp"++using namespace ov::mock_auto_plugin;++namespace cache_warmup_test {+class ThrowOnCloneRelu : public ov::op::v0::Relu {+public:+ OPENVINO_OP("ThrowOnCloneRelu", "test", ov::op::v0::Relu);+ ThrowOnCloneRelu() = default;+ explicit ThrowOnCloneRelu(const ov::Output<ov::Node>& arg) : ov::op::v0::Relu(arg) {}+ std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector&) const override {+ OPENVINO_THROW("clone is not supported");+ }+};+} // namespace cache_warmup_test++namespace {+bool wait_until(const std::function<bool()>& condition,+ std::chrono::milliseconds timeout = std::chrono::milliseconds(5000)) {+ const auto deadline = std::chrono::steady_clock::now() + timeout;+ while (!condition()) {+ if (std::chrono::steady_clock::now() > deadline) {+ return false;+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ }+ return true;+}++enum class CacheKind { NONE, CACHE_DIR, CACHE_PATH_DIR, CACHE_PATH_FILE };++std::string to_string(CacheKind kind) {+ switch (kind) {+ case CacheKind::NONE:+ return "noCache";+ case CacheKind::CACHE_DIR:+ return "cacheDir";+ case CacheKind::CACHE_PATH_DIR:+ return "cachePathDir";+ default:+ return "cachePathFile";+ }+}+} // namespace++class AutoCacheWarmupTestBase : public tests::AutoTest {+protected:+ const std::string cpu_device = ov::test::utils::DEVICE_CPU;+ const std::string actual_device = "GPU.1";++ // Like the Core, every device inherits the global setting unless it has its own.+ void set_global_cache(const std::string& cache_dir, const std::filesystem::path& cache_path = {}) {+ ON_CALL(*core, get_property(_, StrEq(ov::cache_dir.name()), _)).WillByDefault(Return(ov::Any(cache_dir)));+ ON_CALL(*core, get_property(_, StrEq(ov::cache_path.name()), _)).WillByDefault(Return(ov::Any(cache_path)));+ }++ void set_device_cache(const std::string& device, const std::string& cache_dir) {+ ON_CALL(*core, get_property(StrEq(device), StrEq(ov::cache_dir.name()), _))+ .WillByDefault(Return(ov::Any(cache_dir)));+ ON_CALL(*core, get_property(StrEq(device), StrEq(ov::cache_path.name()), _))+ .WillByDefault(Return(ov::Any(std::filesystem::path(cache_dir))));+ }++ // The last device is selected as the actual device.+ void set_devices(const std::vector<std::string>& devices) {+ metaDevices.clear();+ std::string priorities;+ for (const auto& device : devices) {+ metaDevices.push_back({device, {}, -1});+ priorities += (priorities.empty() ? "" : ",") + device;+ }+ ON_CALL(*plugin, parse_meta_devices(_, _)).WillByDefault(Return(metaDevices));+ ON_CALL(*plugin, select_device(_, _, _, _, _)).WillByDefault(Return(metaDevices.back()));+ config.insert(ov::device::priorities(priorities));+ }++ void on_compile(const std::string& device, std::function<ov::SoPtr<ov::ICompiledModel>()> action) {+ ON_CALL(*core,+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),+ ::testing::Matcher<const std::string&>(StrEq(device)),+ _))+ .WillByDefault(InvokeWithoutArgs(std::move(action)));+ }++ std::shared_ptr<NiceMock<ov::MockICompiledModel>> make_compiled_model() {+ auto compiled_model = std::make_shared<NiceMock<ov::MockICompiledModel>>(model, mock_plugin_gpu);+ ON_CALL(*compiled_model, inputs()).WillByDefault(ReturnRefOfCopy(model->inputs()));+ ON_CALL(*compiled_model, outputs()).WillByDefault(ReturnRefOfCopy(model->outputs()));+ return compiled_model;+ }++ // The actual device takes a while to compile.+ void use_default_startup_compilation() {+ on_compile(cpu_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ return {mockIExeNetActual, {}};+ });+ }+};++using CacheWarmupParams = std::tuple<CacheKind, bool>;++class AutoCacheCompileForAllTest : public AutoCacheWarmupTestBase,+ public ::testing::TestWithParam<CacheWarmupParams> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<CacheWarmupParams>& obj) {+ const auto& [cache_kind, compile_for_all] = obj.param;+ return to_string(cache_kind) + "_" + (compile_for_all ? "compileForAll" : "compileForActual");+ }+};++TEST_P(AutoCacheCompileForAllTest, compileForAllCompilesOtherDevicesWhenEnabled) {+ const auto& [cache_kind, compile_for_all] = this->GetParam();+ switch (cache_kind) {+ case CacheKind::NONE:+ set_global_cache("");+ break;+ case CacheKind::CACHE_DIR:+ set_global_cache("test_cache_dir");+ break;+ case CacheKind::CACHE_PATH_DIR:+ set_global_cache("", "test_cache_dir");+ break;+ case CacheKind::CACHE_PATH_FILE:+ set_global_cache("", "test_cache.bin");+ break;+ }+ set_devices({cpu_device, "GPU.0", actual_device});+ use_default_startup_compilation();+ auto warmup_compiled_model = make_compiled_model();+ std::atomic<int> warmup_count{0};+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(compile_for_all));+ const auto baseline = warmup_compiled_model.use_count();++ if (cache_kind == CacheKind::NONE && compile_for_all) {+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);+ return;+ }+ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ // A single-file cache is not warmed up because concurrent writes into one archive are unsafe.+ if (cache_kind != CacheKind::NONE && cache_kind != CacheKind::CACHE_PATH_FILE && compile_for_all) {+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1 && warmup_compiled_model.use_count() == baseline;+ }));+ } else {+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ EXPECT_EQ(warmup_count.load(), 0);+ }+}++INSTANTIATE_TEST_SUITE_P(smoke_Auto_BehaviorTests,+ AutoCacheCompileForAllTest,+ ::testing::Combine(::testing::Values(CacheKind::NONE,+ CacheKind::CACHE_DIR,+ CacheKind::CACHE_PATH_DIR,+ CacheKind::CACHE_PATH_FILE),+ ::testing::Bool()),+ AutoCacheCompileForAllTest::getTestCaseName);++class AutoCacheWarmupTest : public AutoCacheWarmupTestBase, public ::testing::Test {};++TEST_F(AutoCacheWarmupTest, ignoredWhenNoOtherCandidateDevice) {+ set_global_cache("test_cache_dir");+ set_devices({actual_device});+ use_default_startup_compilation();+ config.insert(ov::intel_auto::compile_for_all(true));+ OV_ASSERT_NO_THROW(plugin->compile_model(model, config));+}++TEST_F(AutoCacheWarmupTest, excludesCpuFromBackgroundPreCompilation) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ std::atomic<int> cpu_count{0};+ std::atomic<int> warmup_count{0};+ on_compile(cpu_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ cpu_count++;+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNetActual, {}};+ });+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+ EXPECT_FALSE(wait_until([&] {+ return cpu_count.load() > 0;+ }, std::chrono::milliseconds(200)));+}++TEST_F(AutoCacheWarmupTest, doesNotDisableCpuHelperWhenOnlyCpuWouldBeWarmedUp) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, actual_device});+ use_default_startup_compilation();+ std::atomic<int> cpu_count{0};+ on_compile(cpu_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ cpu_count++;+ return {mockIExeNet, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return cpu_count.load() == 1;+ }));+}++TEST_F(AutoCacheWarmupTest, disablesStartupAndRuntimeFallback) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ std::atomic<int> cpu_count{0};+ std::atomic<int> warmup_count{0};+ on_compile(cpu_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ cpu_count++;+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNetActual, {}};+ });+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ auto executor = std::make_shared<ov::threading::ImmediateExecutor>();+ ON_CALL(*mockIExeNetActual, create_infer_request())+ .WillByDefault([this, executor]() -> std::shared_ptr<ov::IAsyncInferRequest> {+ 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);+ });+ config.insert(ov::intel_auto::compile_for_all(true));+ config.insert(ov::intel_auto::enable_startup_fallback(true));+ config.insert(ov::intel_auto::enable_runtime_fallback(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ std::shared_ptr<ov::IAsyncInferRequest> request;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ request = compiled_model->create_infer_request();+ // No runtime fallback: the failure of the actual device reaches the caller.+ EXPECT_THROW(request->infer(), ov::Exception);+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+ // The CPU helper and CPU background pre-compilation are both disabled.+ EXPECT_EQ(cpu_count.load(), 0);+}++TEST_F(AutoCacheWarmupTest, delegatesCachedBlobValidationToCore) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_warmup_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ // The mocked core returns an empty compile config, so the blob id only depends on the model.+ std::ofstream(cache_dir / (ov::ModelCache::compute_hash(model, ov::AnyMap{}) + ".blob")) << "blob";+ set_global_cache(cache_dir.string());+ set_devices({cpu_device, "GPU.0", "NPU", actual_device});+ use_default_startup_compilation();+ std::atomic<int> gpu_count{0};+ std::atomic<int> npu_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ gpu_count++;+ return {warmup_compiled_model, {}};+ });+ on_compile("NPU", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ npu_count++;+ return {warmup_compiled_model, {}};+ });+ // Core decides whether the existing GPU.0 blob is usable; NPU has a different cache key and also compiles.+ ON_CALL(*core, create_compile_config(StrEq("NPU"), _)).WillByDefault(Return(ov::AnyMap{{"NPU_KEY", "1"}}));+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return npu_count.load() == 1;+ }));+ EXPECT_EQ(gpu_count.load(), 1);+ compiled_model.reset();+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, excludedDeviceIsNotProbedForCachedBlob) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_excluded_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ // The mocked core returns an empty compile config, so the blob id only depends on the model.+ std::ofstream(cache_dir / (ov::ModelCache::compute_hash(model, ov::AnyMap{}) + ".blob")) << "blob";+ ov::AnyMap properties = {ov::device::priorities("CPU,-GPU"), ov::cache_path(cache_dir)};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_EQ(devices, cpu_device);+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, deviceWithCachingDisabledIsNotProbedForCachedBlob) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_device_disabled_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ // The mocked core returns an empty compile config, so the blob id only depends on the model.+ std::ofstream(cache_dir / (ov::ModelCache::compute_hash(model, ov::AnyMap{}) + ".blob")) << "blob";+ // The matching blob sits in the global cache, but caching is disabled for GPU itself.+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"),+ ov::cache_path(cache_dir),+ ov::device::properties(ov::AnyMap{{"GPU", ov::AnyMap{{ov::cache_path.name(), std::string{}}}}})};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_startup_fallback.name()), 0u);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_runtime_fallback.name()), 0u);+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, cacheProbeKeepsDeviceId) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_probe_device_id_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ std::string probed_id;+ ON_CALL(*core, create_compile_config(StrEq("GPU"), _))+ .WillByDefault(::testing::Invoke([&probed_id](const std::string&, const ov::AnyMap& config) -> ov::AnyMap {+ if (const auto it = config.find(ov::device::id.name()); it != config.end()) {+ probed_id = it->second.as<std::string>();+ }+ return {};+ }));+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU.1"), ov::cache_path(cache_dir)};+ OV_ASSERT_NO_THROW(plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_EQ(probed_id, "1");+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, failingCacheProbeDoesNotBreakDeviceList) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_probe_failure_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ ON_CALL(*core, create_compile_config(_, _)).WillByDefault(::testing::Invoke([](const std::string&, const ov::AnyMap&) -> ov::AnyMap {+ OPENVINO_THROW("no plugin");+ }));+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"), ov::cache_path(cache_dir)};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_startup_fallback.name()), 0u);+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, failingConfigLookupDoesNotBreakDeviceList) {+ set_global_cache("");+ // e.g. GPU.1 configured with a conflicting ov::device::id; parse_meta_devices() discards it later.+ ON_CALL(*core, get_supported_property(StrEq("GPU.1"), _, _))+ .WillByDefault(::testing::Invoke([](const std::string&, const ov::AnyMap&, const bool) -> ov::AnyMap {+ OPENVINO_THROW("conflicting device id");+ }));+ ov::AnyMap properties = {ov::device::priorities("GPU.1,CPU")};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+}++TEST_F(AutoCacheWarmupTest, nonOvExceptionInCacheProbeDoesNotBreakDeviceList) {+ ON_CALL(*core, get_supported_property(StrEq("GPU.1"), _, _))+ .WillByDefault(::testing::Invoke([](const std::string&, const ov::AnyMap&, const bool) -> ov::AnyMap {+ throw std::bad_cast();+ }));+ ov::AnyMap properties = {ov::device::priorities("GPU.1,CPU"), ov::cache_path("test_cache_dir")};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+}++TEST_F(AutoCacheWarmupTest, customBlobIdDoesNotPruneCpuFallback) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_blob_id_prune_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ // A custom ID carries no device information, so this file must not count as a GPU cache hit.+ std::ofstream(cache_dir / "746352.blob") << "blob";+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"), ov::cache_path(cache_dir), ov::cache_blob_id(746352)};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_startup_fallback.name()), 0u);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_runtime_fallback.name()), 0u);+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, compileForAllKeepsCpuRetryCandidateWhenOtherDeviceHasCachedBlob) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_keep_cpu_blob_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ std::ofstream(cache_dir / (ov::ModelCache::compute_hash(model, ov::AnyMap{}) + ".blob")) << "blob";+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"),+ ov::cache_path(cache_dir),+ ov::intel_auto::compile_for_all(true)};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);+ EXPECT_NE(devices.find("GPU"), std::string::npos);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_startup_fallback.name()), 0u);+ EXPECT_EQ(properties.count(ov::intel_auto::enable_runtime_fallback.name()), 0u);+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, compileForAllKeepsCpuRetryCandidateWhenBothFallbacksAreDisabled) {+ set_global_cache("test_cache_dir");+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"),+ ov::intel_auto::compile_for_all(true),+ ov::intel_auto::enable_startup_fallback(false),+ ov::intel_auto::enable_runtime_fallback(false)};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_NE(devices.find(cpu_device), std::string::npos);++ ov::AnyMap legacy_properties = {ov::device::priorities("CPU,GPU"),+ ov::intel_auto::enable_startup_fallback(false),+ ov::intel_auto::enable_runtime_fallback(false)};+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(legacy_properties, model, {}));+ EXPECT_EQ(devices.find(cpu_device), std::string::npos);+}++TEST_F(AutoCacheWarmupTest, deviceScopedBlobIdKeepsLegacyCpuPruning) {+ ON_CALL(*core, get_supported_property(StrEq("GPU"), _, _))+ .WillByDefault(Return(ov::AnyMap{{ov::cache_blob_id.name(), std::string{"746352"}}}));+ ov::AnyMap properties = {ov::device::priorities("CPU,GPU"),+ ov::cache_path("test_cache_dir"),+ ov::intel_auto::compile_for_all(true),+ ov::intel_auto::enable_startup_fallback(false),+ ov::intel_auto::enable_runtime_fallback(false),+ ov::device::properties(+ ov::AnyMap{{"GPU", ov::AnyMap{{ov::cache_blob_id.name(), std::string{"746352"}}}}})};+ std::string devices;+ OV_ASSERT_NO_THROW(devices = plugin->Plugin::get_device_list(properties, model, {}));+ EXPECT_EQ(devices.find(cpu_device), std::string::npos);+ EXPECT_NE(devices.find("GPU"), std::string::npos);+}++class AutoCacheWarmupSharedManagerTest : public AutoCacheWarmupTestBase, public ::testing::Test {+protected:+ std::promise<void> gate;+ std::shared_future<void> gate_future = gate.get_future().share();+ std::once_flag gate_opened;+ std::atomic<int> actual_count{0};+ std::atomic<int> warmup_count{0};+ std::atomic<int> in_flight{0};+ std::atomic<int> max_in_flight{0};+ std::shared_ptr<NiceMock<ov::MockICompiledModel>> warmup_compiled_model;+ // Must be destroyed after the gate is opened, otherwise CacheWarmup::stop() blocks.+ std::shared_ptr<ov::ICompiledModel> first;+ std::shared_ptr<ov::ICompiledModel> second;++ // The first warm-up compilation blocks until the gate is opened.+ void SetUp() override {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ on_compile(cpu_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ actual_count++;+ return {mockIExeNetActual, {}};+ });+ warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [this]() -> ov::SoPtr<ov::ICompiledModel> {+ const auto current = ++in_flight;+ max_in_flight = std::max(max_in_flight.load(), current);+ if (++warmup_count == 1) {+ gate_future.wait();+ }+ --in_flight;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));+ }++ void open_gate() {+ std::call_once(gate_opened, [this] {+ gate.set_value();+ });+ }++ void TearDown() override {+ open_gate();+ }+};++TEST_F(AutoCacheWarmupSharedManagerTest, warmUpsOfDifferentModelsDoNotOverlap) {+ OV_ASSERT_NO_THROW(first = plugin->compile_model(model, config));+ ASSERT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+ OV_ASSERT_NO_THROW(second = plugin->compile_model(model->clone(), config));+ ASSERT_TRUE(wait_until([&] {+ return actual_count.load() == 2;+ }));+ // The second warm-up is queued behind the blocked first one.+ EXPECT_FALSE(wait_until(+ [&] {+ return warmup_count.load() > 1;+ },+ std::chrono::milliseconds(500)));+ open_gate();+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 2;+ }));+ EXPECT_EQ(max_in_flight.load(), 1);+}++TEST_F(AutoCacheWarmupSharedManagerTest, destroyingQueuedModelCancelsItsWarmUp) {+ OV_ASSERT_NO_THROW(first = plugin->compile_model(model, config));+ ASSERT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+ OV_ASSERT_NO_THROW(second = plugin->compile_model(model->clone(), config));+ ASSERT_TRUE(wait_until([&] {+ return actual_count.load() == 2;+ }));+ // Give the second warm-up time to be queued behind the blocked first one.+ std::this_thread::sleep_for(std::chrono::milliseconds(300));+ auto destroyed = std::async(std::launch::async, [this] {+ second.reset();+ });+ EXPECT_EQ(destroyed.wait_for(std::chrono::seconds(2)), std::future_status::ready);+ open_gate();+ first.reset();+ // Neither the cancelled model nor the one just destroyed may compile GPU.0 again.+ std::this_thread::sleep_for(std::chrono::milliseconds(300));+ EXPECT_EQ(warmup_count.load(), 1);+ EXPECT_EQ(max_in_flight.load(), 1);+}++TEST_F(AutoCacheWarmupTest, destructionSkipsRemainingDevices) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", "NPU", actual_device});+ use_default_startup_compilation();+ std::promise<void> warmup_started;+ std::atomic<int> npu_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_started.set_value();+ std::this_thread::sleep_for(std::chrono::milliseconds(300));+ return {warmup_compiled_model, {}};+ });+ on_compile("NPU", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ npu_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ ASSERT_EQ(warmup_started.get_future().wait_for(std::chrono::seconds(5)), std::future_status::ready);+ compiled_model.reset();+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ EXPECT_EQ(npu_count.load(), 0);+}++TEST_F(AutoCacheWarmupTest, failedActualDeviceIsNotWarmedUp) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ std::atomic<int> select_count{0};+ ON_CALL(*plugin, select_device(_, _, _, _, _)).WillByDefault(InvokeWithoutArgs([&]() {+ return select_count++ == 0 ? metaDevices[2] : metaDevices[1];+ }));+ on_compile(cpu_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNet, {}};+ });+ std::atomic<int> actual_count{0};+ on_compile(actual_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ actual_count++;+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ OPENVINO_THROW("compile failure on ", actual_device);+ });+ std::atomic<int> retry_count{0};+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ retry_count++;+ return {mockIExeNetActual, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ ASSERT_TRUE(wait_until([&] {+ return retry_count.load() == 1;+ }));+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ EXPECT_EQ(actual_count.load(), 1);+ EXPECT_EQ(retry_count.load(), 1);+}++TEST_F(AutoCacheWarmupTest, emptyConfigCpuIsRetriedWhenActualDeviceFails) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, actual_device});+ config.insert(ov::intel_auto::enable_startup_fallback(false));+ std::atomic<int> select_count{0};+ ON_CALL(*plugin, select_device(_, _, _, _, _)).WillByDefault(InvokeWithoutArgs([&]() {+ return select_count++ == 0 ? metaDevices[1] : metaDevices[0];+ }));+ std::atomic<int> cpu_count{0};+ on_compile(cpu_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ cpu_count++;+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ OPENVINO_THROW("compile failure on ", actual_device);+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return cpu_count.load() == 1;+ }));+}++TEST_F(AutoCacheWarmupTest, warmsUpOtherDeviceWhenActualFailsAndCpuTakesOver) {+ set_global_cache("test_cache_dir");+ set_devices({actual_device, cpu_device, "GPU.0"});+ std::atomic<int> select_count{0};+ ON_CALL(*plugin, select_device(_, _, _, _, _)).WillByDefault(InvokeWithoutArgs([&]() {+ return select_count++ == 0 ? metaDevices[0] : metaDevices[1];+ }));+ std::atomic<int> cpu_count{0};+ on_compile(cpu_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ cpu_count++;+ return {mockIExeNet, {}};+ });+ on_compile(actual_device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ std::this_thread::sleep_for(std::chrono::milliseconds(50));+ OPENVINO_THROW("compile failure on ", actual_device);+ });+ std::atomic<int> warmup_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+ EXPECT_EQ(cpu_count.load(), 1);+}++TEST_F(AutoCacheWarmupTest, warmsUpOtherDeviceWhenCpuIsActualDevice) {+ set_global_cache("test_cache_dir");+ set_devices({"GPU.0", cpu_device});+ on_compile(cpu_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNet, {}};+ });+ std::atomic<int> warmup_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+}++TEST_F(AutoCacheWarmupTest, singleNonCpuCandidateWithoutCacheThrows) {+ set_global_cache("");+ set_devices({"GPU.0", cpu_device});+ on_compile(cpu_device, [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNet, {}};+ });+ on_compile("GPU.0", [this]() -> ov::SoPtr<ov::ICompiledModel> {+ return {mockIExeNetActual, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);+}++TEST_F(AutoCacheWarmupTest, noOtherCandidateWithoutCacheThrows) {+ set_global_cache("");+ set_devices({cpu_device, actual_device});+ use_default_startup_compilation();+ config.insert(ov::intel_auto::compile_for_all(true));+ EXPECT_THROW(plugin->compile_model(model, config), ov::Exception);+}++TEST_F(AutoCacheWarmupTest, ignoredWhenCacheBlobIdIsSet) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ use_default_startup_compilation();+ std::atomic<int> warmup_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));+ config.insert(ov::cache_blob_id(746352));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_FALSE(wait_until([&] {+ return warmup_count.load() > 0;+ }, std::chrono::milliseconds(500)));+}++TEST_F(AutoCacheWarmupTest, ignoredWhenCandidateHasCacheBlobId) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ metaDevices[1].config = ov::AnyMap{{ov::cache_blob_id.name(), std::string{"746352"}}};+ ON_CALL(*plugin, parse_meta_devices(_, _)).WillByDefault(Return(metaDevices));+ use_default_startup_compilation();+ std::atomic<int> warmup_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_FALSE(wait_until([&] {+ return warmup_count.load() > 0;+ }, std::chrono::milliseconds(500)));+}++TEST_F(AutoCacheWarmupTest, blobProbeHonorsCacheBlobId) {+ const auto cache_dir = std::filesystem::temp_directory_path() /+ ("ov_auto_cache_blob_id_" ++ std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ std::filesystem::create_directories(cache_dir);+ std::ofstream(cache_dir / "746352.blob") << "blob";+ const auto is_cached = [&](const ov::AnyMap& properties) {+ return ov::auto_plugin::CacheWarmupManager::is_blob_cached(*core, "GPU.0", properties, model, {}, cache_dir);+ };+ EXPECT_TRUE(is_cached({ov::cache_blob_id(746352)}));+ EXPECT_FALSE(is_cached({ov::cache_blob_id(1)}));+ // Without a user ID the hash is used, and no blob exists for it.+ EXPECT_FALSE(is_cached({}));+ std::filesystem::remove_all(cache_dir);+}++TEST_F(AutoCacheWarmupTest, skipsDeviceWithCachingDisabled) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", "NPU", actual_device});+ metaDevices[2].config = ov::AnyMap{{ov::cache_dir.name(), std::string{}}};+ ON_CALL(*plugin, parse_meta_devices(_, _)).WillByDefault(Return(metaDevices));+ use_default_startup_compilation();+ std::atomic<int> gpu_count{0};+ std::atomic<int> npu_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ gpu_count++;+ return {warmup_compiled_model, {}};+ });+ on_compile("NPU", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ npu_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return gpu_count.load() == 1;+ }));+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ EXPECT_EQ(npu_count.load(), 0);+}++TEST_F(AutoCacheWarmupTest, skipsDeviceWithCachingDisabledInCore) {+ set_global_cache("test_cache_dir");+ set_device_cache("NPU", "");+ set_devices({cpu_device, "GPU.0", "NPU", actual_device});+ use_default_startup_compilation();+ std::atomic<int> gpu_count{0};+ std::atomic<int> npu_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ gpu_count++;+ return {warmup_compiled_model, {}};+ });+ on_compile("NPU", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ npu_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return gpu_count.load() == 1;+ }));+ std::this_thread::sleep_for(std::chrono::milliseconds(200));+ EXPECT_EQ(npu_count.load(), 0);+}++TEST_F(AutoCacheWarmupTest, usesDeviceScopedCacheSetting) {+ set_global_cache("");+ set_device_cache("GPU.0", "device_cache_dir");+ set_device_cache(actual_device, "device_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ use_default_startup_compilation();+ std::atomic<int> warmup_count{0};+ auto warmup_compiled_model = make_compiled_model();+ on_compile("GPU.0", [&]() -> ov::SoPtr<ov::ICompiledModel> {+ warmup_count++;+ return {warmup_compiled_model, {}};+ });+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ EXPECT_TRUE(wait_until([&] {+ return warmup_count.load() == 1;+ }));+}++TEST_F(AutoCacheWarmupTest, warmsUpPrivateModelSnapshot) {+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ use_default_startup_compilation();+ std::mutex captured_mutex;+ std::shared_ptr<const ov::Model> captured_model;+ auto warmup_compiled_model = make_compiled_model();+ ON_CALL(*core,+ compile_model(::testing::Matcher<const std::shared_ptr<const ov::Model>&>(_),+ ::testing::Matcher<const std::string&>(StrEq("GPU.0")),+ _))+ .WillByDefault(::testing::Invoke(+ [&](const std::shared_ptr<const ov::Model>& compiled, const std::string&, const ov::AnyMap&) {+ std::lock_guard<std::mutex> lock(captured_mutex);+ captured_model = compiled;+ return ov::SoPtr<ov::ICompiledModel>{warmup_compiled_model, {}};+ }));+ config.insert(ov::intel_auto::compile_for_all(true));++ std::shared_ptr<ov::ICompiledModel> compiled_model;+ OV_ASSERT_NO_THROW(compiled_model = plugin->compile_model(model, config));+ ASSERT_TRUE(wait_until([&] {+ std::lock_guard<std::mutex> lock(captured_mutex);+ return captured_model != nullptr;+ }));+ std::lock_guard<std::mutex> lock(captured_mutex);+ EXPECT_NE(captured_model, model);+}++TEST_F(AutoCacheWarmupTest, modelCloneFailureIsReportedToCaller) {+ auto parameter = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 3, 2, 2});+ auto relu = std::make_shared<cache_warmup_test::ThrowOnCloneRelu>(parameter);+ auto result = std::make_shared<ov::op::v0::Result>(relu);+ auto uncloneable_model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{parameter});+ set_global_cache("test_cache_dir");+ set_devices({cpu_device, "GPU.0", actual_device});+ std::atomic<int> compile_count{0};+ for (const auto& device : {cpu_device, std::string("GPU.0"), actual_device}) {+ on_compile(device, [&]() -> ov::SoPtr<ov::ICompiledModel> {+ compile_count++;+ return {mockIExeNetActual, {}};+ });+ }+ config.insert(ov::intel_auto::compile_for_all(true));++ // The snapshot is taken before any compilation starts, so the failure reaches the caller.+ EXPECT_THROW(plugin->compile_model(uncloneable_model, config), ov::Exception);+ EXPECT_EQ(compile_count.load(), 0);+}diff --git a/src/plugins/auto/tests/unit/sources.cmake b/src/plugins/auto/tests/unit/sources.cmakeindex 6e31f852bc6..1e501a72a15 100644--- a/src/plugins/auto/tests/unit/sources.cmake+++ b/src/plugins/auto/tests/unit/sources.cmake@@ -4,6 +4,7 @@set(OV_AUTO_UNIT_TESTS_SRC${CMAKE_CURRENT_LIST_DIR}/auto_unit_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/cache_compile_for_all_test.cpp${CMAKE_CURRENT_LIST_DIR}/compile_model_metric_test.cpp${CMAKE_CURRENT_LIST_DIR}/compile_model_property_test.cpp${CMAKE_CURRENT_LIST_DIR}/ctput_test.cpp@@ -36,6 +37,8 @@ set(OV_AUTO_UNIT_TESTS_SRC${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/auto_compiled_model.hpp${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/auto_schedule.cpp${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/auto_schedule.hpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/cache_warmup.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/cache_warmup.hpp${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/common.hpp${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/auto/src/compiled_model.hpp