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
NPUW: Failsafe integration (#35096)
Dmitry Matveev74c0aa5e1753
diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cppindex 91ae7d66910..b9780d31acc 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp@@ -1,6 +1,7 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//+//#include "base_sync_infer_request.hpp"@@ -21,7 +22,6 @@ ov::npuw::IBaseInferRequest::IBaseInferRequest(const std::shared_ptr<ov::npuw::Cm_npuw_model(compiled_model),m_num_submodels(m_npuw_model->m_compiled_submodels.size()) {m_subrequests.resize(m_num_submodels, {});- m_subrequest_devices.resize(m_num_submodels, {});m_completion_cbs.resize(m_num_submodels, {});if (m_npuw_model->m_acc_check) {m_ref_subrequests.resize(m_num_submodels);@@ -50,8 +50,7 @@ ov::npuw::IBaseInferRequest::IBaseInferRequest(const std::shared_ptr<ov::npuw::C}ov::npuw::IBaseInferRequest::RqPtrs ov::npuw::IBaseInferRequest::create_infer_requests(std::size_t id,- std::size_t nireq,- bool* recompiled) {+ std::size_t nireq) {NPUW_ASSERT(nireq > 0);RqPtrs rqs;rqs.reserve(nireq);@@ -60,39 +59,9 @@ ov::npuw::IBaseInferRequest::RqPtrs ov::npuw::IBaseInferRequest::create_infer_reauto& comp_model_desc = m_npuw_model->m_compiled_submodels[id];NPUW_ASSERT(comp_model_desc.replaced_by.value_or(id) == id);- bool successful = false;- bool can_try_again = true;-- // Altering iterators here!! Contracts should be changed!- while (!successful && can_try_again) {- bool should_recompile = false;- try {- // FIXME: As the model may recompile, reference- // shouldn't be lifted from the loop- auto& comp_model = comp_model_desc.compiled_model;- rqs.clear();- for (std::size_t i = 0u; i < nireq; i++) {- rqs.emplace_back(comp_model->create_infer_request(), comp_model._so);- }- successful = true;- } catch (const std::exception& ex) {- LOG_WARN("Subgraph [" << id << "] - Failed to create infer request:" << std::endl << ex.what());- should_recompile = true;- } catch (...) {- LOG_WARN("Subgraph [" << id << "] - Failed to create infer request: REASON UNKNOWN");- should_recompile = true;- }- if (should_recompile) {- LOG_INFO("- Trying next device...");- comp_model_desc.device_it++;- can_try_again = m_npuw_model->compile_for_success(id);- if (can_try_again && recompiled) {- *recompiled = true;- }- }- } // while(!new_ireq && can_try_again)- if (!successful) {- OPENVINO_THROW("NPUW: Fatal - couldn't create infer request for Subgraph[", id, "]");+ auto& comp_model = comp_model_desc.compiled_model;+ for (std::size_t i = 0u; i < nireq; i++) {+ rqs.emplace_back(comp_model->create_infer_request(), comp_model._so);}NPUW_ASSERT(rqs.size() == nireq);@@ -121,10 +90,9 @@ ov::npuw::IBaseInferRequest::RqPtrs ov::npuw::IBaseInferRequest::create_infer_rereturn rqs;}-void ov::npuw::IBaseInferRequest::ensure_subrequest_is_accurate(std::size_t idx, bool& failover) {+void ov::npuw::IBaseInferRequest::ensure_subrequest_is_accurate(std::size_t idx) {LOG_INFO("Check if subrequest[" << idx << "] is accurate...");LOG_BLOCK();- failover = false;if (m_ref_subrequests.at(idx) != nullptr && m_subrequests.at(idx)._ptr != m_ref_subrequests.at(idx)._ptr) {NPUW_ASSERT(m_npuw_model->m_compiled_submodels.at(idx).switched_to_ref == false);NPUW_ASSERT(m_npuw_model->m_compiled_submodels.at(idx).replaced_by.value_or(idx) == idx);@@ -164,7 +132,6 @@ void ov::npuw::IBaseInferRequest::ensure_subrequest_is_accurate(std::size_t idx,m_npuw_model->m_compiled_submodels.at(idx).switched_to_ref = true;m_subrequests.at(idx) = m_ref_subrequests.at(idx);update_subrequest_links(idx);- failover = true;}LOG_INFO("Done");@@ -314,40 +281,29 @@ std::vector<ov::ProfilingInfo> ov::npuw::IBaseInferRequest::get_profiling_info()std::string ov::npuw::IBaseInferRequest::profile_tag(std::size_t idx) const {// So far accumulate over devices involved- const auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real(idx)];- return *proto_comp_model_desc.device_it;+ return m_npuw_model->submodel_device(real(idx));}void ov::npuw::IBaseInferRequest::infer() {m_now_idx.reset();prepare_for_infer();- bool failover_happened = false;for (std::size_t idx = 0u; idx < m_num_submodels; idx++) {m_now_idx = idx;if (!valid_subrequest(idx)) {continue;}subscribe_subrequest(idx, [](std::exception_ptr) {});- bool failover = false;m_profile[profile_tag(idx)].record([&]() {- run_subrequest_for_success(idx, failover);+ run_subrequest_for_success(idx);});- failover_happened |= failover;complete_subrequest(idx);if (m_npuw_model->m_acc_check) {- ensure_subrequest_is_accurate(idx, failover);- failover_happened |= failover;+ ensure_subrequest_is_accurate(idx);}}// Increment counter regardless if dumps etc are enabled or not.m_run_iter++;-- if (failover_happened) {- LOG_INFO("Refined device distribution:");- LOG_BLOCK();- m_npuw_model->log_device_dist();- }m_now_idx.reset();}@@ -378,8 +334,7 @@ std::string ov::npuw::IBaseInferRequest::global_input_mem_device(std::size_t idxconst auto& to_submodel = m_npuw_model->m_inputs_to_submodels_inputs.at(idx);if (to_submodel != CompiledModel::NO_LINK) {- const auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real(to_submodel.first)];- return *proto_comp_model_desc.device_it;+ return m_npuw_model->submodel_device(real(to_submodel.first));}// Resort to global again@@ -389,8 +344,7 @@ std::string ov::npuw::IBaseInferRequest::global_input_mem_device(std::size_t idxstd::string ov::npuw::IBaseInferRequest::global_output_mem_device(std::size_t idx) const {// Pick the affinitiy based on the producer subgraphconst auto& from_submodel = m_npuw_model->m_outputs_to_submodels_outputs.at(idx);- const auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real(from_submodel.first)];- return *proto_comp_model_desc.device_it;+ return m_npuw_model->submodel_device(real(from_submodel.first));}void ov::npuw::IBaseInferRequest::alloc_quant_gather() {@@ -809,7 +763,7 @@ void ov::npuw::IBaseInferRequest::bind_attention_inputs(std::size_t idx, RqPtr rdst->set_shape(shape);const auto new_ptr = dst->data();if (old_ptr != new_ptr) {- m_footprint[*comp_model_desc.device_it] += dst->get_byte_size();+ m_footprint[m_npuw_model->submodel_device(real(idx))] += dst->get_byte_size();}LOG_DEBUG("Do copy: " << shape << "...");view->copy_to(dst._ptr);@@ -1119,7 +1073,7 @@ bool ov::npuw::IBaseInferRequest::needs_copy(std::size_t idx) const {// the set/get_ tensor APIauto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];const auto real_idx = comp_model_desc.replaced_by.value_or(idx);- if (ov::npuw::util::starts_with(m_subrequest_devices[real_idx], "CPU")) {+ if (ov::npuw::util::starts_with(m_npuw_model->submodel_device(real_idx), "CPU")) {return false;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hppindex a8bfe6880da..9e7111cbe50 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp@@ -1,6 +1,7 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//+//#pragma once@@ -66,7 +67,7 @@ public:virtual bool valid_subrequest(std::size_t idx) const = 0; // FIXME: Get rid of this!virtual void start_subrequest(std::size_t idx) = 0;virtual void subscribe_subrequest(std::size_t idx, Completed cb) = 0;- virtual void run_subrequest_for_success(std::size_t idx, bool& failover) = 0;+ virtual void run_subrequest_for_success(std::size_t idx) = 0;virtual void complete_subrequest(std::size_t idx) = 0;virtual void cancel_subrequest(std::size_t idx) = 0;virtual std::size_t total_subrequests() const;@@ -90,20 +91,14 @@ protected:// function bodies. Function calls are not allowed to have// their inference requests anymore - they must be stored// only once in the subrequests list- RqPtrs create_infer_requests(std::size_t id, size_t nireq = 1, bool* recompiled = nullptr);- void ensure_subrequest_is_accurate(std::size_t idx, bool& failover);+ RqPtrs create_infer_requests(std::size_t id, size_t nireq = 1);+ void ensure_subrequest_is_accurate(std::size_t idx);virtual void update_subrequest_links(std::size_t idx) = 0;std::shared_ptr<ov::npuw::CompiledModel> m_npuw_model;std::vector<IBaseInferRequest::Completed> m_completion_cbs;RqPtrs m_subrequests;- // This vector is used to track devices for individual subrequests- // here locally. Note that the models can be recompiled in- // contexts of other requests (if multiple of those are created)- // so this cached information is used to detect these situations.- std::vector<std::string> m_subrequest_devices;-struct TensorStorage {ov::SoPtr<ov::ITensor> tensor;bool persistent = false; // true for the parent I/O tensorsdiff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex e21630e1429..d8fc99affb5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -26,6 +26,7 @@#include "plugin.hpp"#include "unfold_sync_infer_request.hpp"#include "util.hpp"+#include "v1/elements/failsafe.hpp"// required for get_properties_per_device()#include "intel_npu/config/config.hpp"@@ -86,6 +87,17 @@ bool should_use_weightless_flow(const ov::AnyMap& non_npuw_props,return is_weightless;}++std::set<std::string> device_list_to_set(const std::string& device_list) {+ std::set<std::string> result;+ if (!device_list.empty()) {+ const auto devices = ov::DeviceIDParser::get_hetero_devices(device_list);+ for (auto&& d : devices) {+ result.insert(std::move(d));+ }+ }+ return result;+}} // anonymous namespacenamespace ov {@@ -435,7 +447,7 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,if (fcn_template._moe_experts) {m_compiled_submodels[id].moe_experts = compiled::MoEExperts(fcn_template._moe_experts.value());- // Point model to first chunk size model (actual compilation handled by compile_moe_models)+ // Point model to first chunk size model (actual compilation handled by compile_for_success)const auto& models_to_compile = m_compiled_submodels[id].moe_experts.value()._models_to_compile;NPUW_ASSERT(!models_to_compile.empty() && "Fatal: MoEExperts has no models to compile!");m_compiled_submodels[id].model = models_to_compile.begin()->second;@@ -520,8 +532,7 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,fsd_opt.erase(last_pos, 4);fsd_opt.insert(last_pos, std::to_string(end_sub_idx));}-- forced_sub_devices = ::intel_npu ::OptionParser<std::map<std::size_t, std::string>>::parse(fsd_opt);+ forced_sub_devices = ::intel_npu::OptionParser<std::map<std::size_t, std::string>>::parse(fsd_opt);// Exclude optimized out subgraphs from compilation target beforehand - otherwise we might get head and repeated// block in the same chunk@@ -543,34 +554,39 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,NPUW_ASSERT(!subgraph._optimized_out);const std::size_t real_id = m_compiled_submodels[id].replaced_by.value_or(id);- if (!orderedSubgraphs[real_id]._avoid_list.empty()) {- const auto devices_to_avoid = ov::DeviceIDParser::get_hetero_devices(orderedSubgraphs[real_id]._avoid_list);- for (auto&& d : devices_to_avoid) {- m_compiled_submodels[real_id].devices_to_avoid.insert(std::move(d));- }- }-- m_compiled_submodels[id].device_it =- id != real_id ? m_compiled_submodels[real_id].device_it : m_dev_list.cbegin();+ m_compiled_submodels[real_id].devices_to_avoid = device_list_to_set(orderedSubgraphs[real_id]._avoid_list);+ // Build the filtered device list before passing to compile_for_success.+ // A forced device (if valid) produces a single-element list; otherwise the full+ // m_dev_list is used with avoided devices removed.+ std::vector<std::string> devices;if (forced_sub_devices.count(id)) {- std::string forced_device = forced_sub_devices[id];+ const std::string& forced_device = forced_sub_devices[id];auto forced_dev_it = std::find(m_dev_list.begin(), m_dev_list.end(), forced_device);if (forced_dev_it == m_dev_list.end()) {LOG_WARN("Target device for Subgraph[" << id << "] was set to " << forced_device<< ", but was not found in the device list: " << "["<< dev_list_str << "] -- ignoring");} else {- // FIXME: This is not really a device enforcement as the fallback- // procedure will be in place stillLOG_INFO("Force Subgraph[" << id << "] target device to " << *forced_dev_it);- m_compiled_submodels[real_id].device_it = forced_dev_it;+ devices.push_back(*forced_dev_it);+ }+ }+ if (devices.empty()) {+ const auto& avoid = m_compiled_submodels[real_id].devices_to_avoid;+ for (const auto& device_name : m_dev_list) {+ if (avoid.count(device_name) > 0) {+ LOG_BLOCK();+ LOG_INFO(device_name << " was found in the 'Avoid' list for this subgraph, skipping...");+ } else {+ devices.push_back(device_name);+ }}- } // if(forced_device_opt)+ }LOG_INFO("Compiling Subgraph[" << id << "]: " << m_compiled_submodels[real_id].model->get_friendly_name()<< "...");- if (!compile_for_success(id)) {+ if (!compile_for_success(id, devices)) {OPENVINO_THROW("Failed to compile ",m_compiled_submodels[real_id].model->get_friendly_name()," for all devices in [",@@ -598,10 +614,7 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,if (par_opt) {ov::parallel_for(idx_subgraph_to_compile.size(), compile);} else {- // TODO: Introduce npuw::serial(i, f) instead where f is a _funcall- for (std::size_t i = 0u; i < idx_subgraph_to_compile.size(); i++) {- compile(i);- }+ ov::npuw::util::non_parallel_for(idx_subgraph_to_compile.size(), compile);}// Finalize memory in closures and weight banks@@ -1265,8 +1278,12 @@ void ov::npuw::CompiledModel::serialize(std::ostream& stream, const ov::npuw::s1auto real_idx = subm.replaced_by.value_or(i);// Write device idx// FIXME: if there is no compiled submodel, device_it is not set.- std::size_t device_idx = m_compiled_submodels[real_idx].device_it - m_dev_list.begin();- write(model_stream, real_idx == i ? device_idx : 0);+ auto dev_idx = [&]() {+ auto it = std::find(m_dev_list.begin(), m_dev_list.end(), submodel_device(real_idx));+ NPUW_ASSERT(it != m_dev_list.end());+ return it - m_dev_list.begin();+ };+ write(model_stream, real_idx == i ? dev_idx() : 0);// Write ICompiledModel if it's thereif (subm.compiled_model) {write(model_stream, true);@@ -1464,7 +1481,6 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(compiled->m_compiled_submodels[i].compiled_model =plugin->get_core()->import_model(buffer, device, import_config);}- compiled->m_compiled_submodels[i].device_it = compiled->m_dev_list.begin() + device_idx;// Create unified deserialization context for submodels with dynamic mechanisms// (Pyramid Attention, Host Flash Attention, etc.)@@ -1506,7 +1522,6 @@ void ov::npuw::CompiledModel::reconstruct_closure() {}const auto real_idx = comp_model_desc.replaced_by.value_or(idx);- auto& func_desc = m_compiled_submodels[real_idx];auto& desc_closure = comp_model_desc.closure.get();for (std::size_t cidx = 0; cidx < desc_closure.closure.size(); ++cidx) {@@ -1516,7 +1531,7 @@ void ov::npuw::CompiledModel::reconstruct_closure() {continue;}NPUW_ASSERT(desc_closure.closure_uid[cidx] != -1);- desc_closure.closure[cidx] = m_weights_bank->get(desc_closure.closure_uid[cidx], *func_desc.device_it);+ desc_closure.closure[cidx] = m_weights_bank->get(desc_closure.closure_uid[cidx], submodel_device(real_idx));}}}@@ -1546,14 +1561,13 @@ void ov::npuw::CompiledModel::finalize_weights_bank() {}const auto real_idx = comp_model_desc.replaced_by.value_or(idx);- auto& func_desc = m_compiled_submodels[real_idx];for (std::size_t tidx = 0; tidx < comp_model_desc.lazy_closure.size(); ++tidx) {if (comp_model_desc.closure.unsafe_get().closure[tidx]) {continue; // host-side closure}comp_model_desc.closure.unsafe_get().closure_uid[tidx] =- m_weights_bank->registerLT(comp_model_desc.lazy_closure[tidx], *func_desc.device_it);+ m_weights_bank->registerLT(comp_model_desc.lazy_closure[tidx], submodel_device(real_idx));}}@@ -1570,7 +1584,6 @@ void ov::npuw::CompiledModel::finalize_weights_bank() {}const auto real_idx = comp_model_desc.replaced_by.value_or(idx);- auto& func_desc = m_compiled_submodels[real_idx];auto& desc_closure = comp_model_desc.closure.unsafe_get();for (std::size_t tidx = 0; tidx < desc_closure.closure.size(); ++tidx) {@@ -1581,7 +1594,7 @@ void ov::npuw::CompiledModel::finalize_weights_bank() {}const auto& uid = desc_closure.closure_uid[tidx];NPUW_ASSERT(uid != -1); // All tensors should be registered at this point- desc_closure.closure[tidx] = m_weights_bank->get(uid, *func_desc.device_it);+ desc_closure.closure[tidx] = m_weights_bank->get(uid, submodel_device(real_idx));// FIXME: find a more reliable way to do sodesc_closure.is_remote[tidx] = m_weights_bank->is_remote(uid);}@@ -1638,9 +1651,23 @@ void ov::npuw::CompiledModel::detach_memory() {if (!proto_comp_model_desc.model || !proto_comp_model_desc.compiled_model) {continue; // optimized-out OR already cleared - skip}- if ((proto_comp_model_desc.device_it + 1 == m_dev_list.end()) || no_runtime_fallback) {++ // Ask the failsafe wrapper whether runtime fallover to another device is still+ // possible. If it is, keep the ov::Model alive so the factory (which captures+ // it by weak_ptr) can recompile. For non-failsafe compiled models (single+ // device) there is no fallback, so we can always release.+ bool can_clear = true;+ auto failsafe =+ std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(proto_comp_model_desc.compiled_model._ptr);+ if (failsafe && !failsafe->is_at_last_device() && !no_runtime_fallback) {+ can_clear = false;+ }++ if (can_clear) {LOG_INFO("No fallback expected - clear the OV model for Subgraph[" << idx << "]");proto_comp_model_desc.model.reset();+ } else {+ LOG_INFO("Runtime fallback still possible - keeping OV model for Subgraph[" << idx << "]");}// No need to clear pyramid attention data - it's self-contained!@@ -1663,7 +1690,7 @@ std::string ov::npuw::CompiledModel::global_mem_device() const {if (!comp_model_desc.compiled_model) {continue;}- if (ov::npuw::util::starts_with(*comp_model_desc.device_it, "NPU")) {+ if (ov::npuw::util::starts_with(submodel_device(idx), "NPU")) {return "NPU";}}@@ -1678,8 +1705,7 @@ std::string ov::npuw::CompiledModel::funcall_mem_device(const std::size_t idx) creturn device_alloc;}- auto& comp_model_desc = m_compiled_submodels[idx];- return *comp_model_desc.device_it;+ return submodel_device(idx);}void ov::npuw::CompiledModel::remove_long_output_names(const std::shared_ptr<ov::Model>& model) {@@ -1746,9 +1772,7 @@ void ov::npuw::CompiledModel::report_io() const {}}-bool ov::npuw::CompiledModel::compile_for_success(std::size_t id) {- // Assume device_it is some always-valid starting point.- // FIXME: And who guarantees it? Abstraction leaks are everywhere+bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::vector<std::string>& devices) {if (m_compiled_submodels[id].replaced_by && m_compiled_submodels[id].replaced_by != id) {LOG_BLOCK();LOG_INFO("Skip compilation for Subgraph[" << id@@ -1757,275 +1781,171 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id) {return true;}- for (auto iter = m_compiled_submodels[id].device_it; iter != m_dev_list.cend(); ++iter) {- LOG_BLOCK();- const auto& device_name = *iter;- if (m_compiled_submodels[id].devices_to_avoid.count(device_name) > 0) {- LOG_INFO(device_name << " was found in the 'Avoid' list for this subgraph, skipping...");- } else if (compile_for_device(id, device_name)) {- m_compiled_submodels[id].device_it = iter;- return true; // success!- }+ auto& desc = m_compiled_submodels[id];+ if (devices.empty()) {+ return false;}- return false;-}-bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::string& device_to_try) {- // The API of this method is ugly but it is what it is- // NOTE(dm): Hetero plugin disables caching here, but we'll keep this to be done- // at the individual plugins level.- auto plugin = get_npuw_plugin();-- LOG_INFO("Trying to compile for " << device_to_try << "...");-- // Only function bodies can reach this point.- // compile_for_device() behavior is not specified for funcalls.- NPUW_ASSERT(m_compiled_submodels[id].replaced_by.value_or(id) == id);-- // Early exit conditions for NPU devices where try..catch doesn't work- // These are workarounds for known compilation issues that cause crashes- if (npuw::util::starts_with(device_to_try, "NPU")) {- // Check for empty input models - NPU plugin crashes on models without inputs- // Note: Ideally these should be eliminated via constant folding, but with offline partitioning- // it is not possible + not clear what to do with dynamic shapes.- // So for now, skip this case explicitly.- if (m_compiled_submodels[id].model->inputs().empty()) {- LOG_INFO("Avoid compilation for " << device_to_try << " as the model should be constant-folded");- dump_on_fail(id, device_to_try, "Avoided due to workaround");- return false;- }-- // Check for dynamic shapes in attention models- // Skip this case explicitly because dynamic shapes in attention models trigger LLVM abort and try..catch- // doesn't work.- if (m_compiled_submodels[id].attention.has_value()) {- for (const auto& input : m_compiled_submodels[id].model->inputs()) {- if (input.get_partial_shape().is_dynamic()) {- LOG_INFO("Avoid compilation for " << device_to_try << " as attention model has dynamic shapes");- dump_on_fail(id, device_to_try, "Avoided due to dynamic shapes");- return false;+ // Apply NPU workarounds: pre-filter devices that would trigger unrecoverable failures.+ // These checks apply only to the main model compilation (not MoE/pyramid/HFA sub-models).+ std::vector<std::string> main_candidates;+ for (const auto& device : devices) {+ if (npuw::util::starts_with(device, "NPU")) {+ if (desc.model->inputs().empty()) {+ LOG_INFO("Avoid compilation for " << device << " as the model should be constant-folded");+ dump_on_fail(id, device, "Avoided due to workaround");+ continue;+ }+ if (desc.attention.has_value()) {+ bool has_dynamic = false;+ for (const auto& input : desc.model->inputs()) {+ if (input.get_partial_shape().is_dynamic()) {+ has_dynamic = true;+ break;+ }+ }+ if (has_dynamic) {+ LOG_INFO("Avoid compilation for " << device << " as attention model has dynamic shapes");+ dump_on_fail(id, device, "Avoided due to dynamic shapes");+ continue;}}}+ main_candidates.push_back(device);}-- try {- // WARNING: These requests can be issued in parallel, so timer should be thread-safe-- // Compile main model (normal models only)- compile_main_model(id, device_to_try);-- // Compile special model types- compile_moe_models(id, device_to_try);- compile_pyramid_attention_models(id, device_to_try);- compile_host_flash_attention_model(id, device_to_try);- } catch (const std::exception& ex) {- LOG_ERROR("Subgraph [" << id << "] Failed to compile: " << std::endl << ex.what());- dump_on_fail(id, device_to_try, ex.what());- return false;- } catch (...) {- LOG_ERROR("Subgraph [" << id << "] Failed to compile: Unknown error");- dump_on_fail(id, device_to_try, "Unknown error");+ if (main_candidates.empty()) {return false;}- // Reached this point - all ok, stop the search- LOG_INFO("Done (" << device_to_try << ")");- return true;-}-void ov::npuw::CompiledModel::compile_main_model(std::size_t id, const std::string& device) {- // Skip if this is a MoE model - handled separately- if (m_compiled_submodels[id].moe_experts.has_value() ||- m_compiled_submodels[id].moe_experts_downstream.has_value()) {- return;- }+ // Factory builder: returns a failsafe::CompiledModel::Factory for the given model+suffix.+ // Captures the model as weak_ptr so that detach_memory() can truly release it when+ // no runtime fallback is expected. If the model has been cleared and failover fires+ // anyway, the lock() fails and the factory throws, which failsafe propagates correctly.+ auto make_factory = [this](const std::shared_ptr<ov::Model>& model,+ const std::string& profile_suffix) -> ov::npuw::failsafe::CompiledModel::Factory {+ std::weak_ptr<ov::Model> weak_model = model;+ return [this, weak_model, profile_suffix](const std::string& device) -> ov::SoPtr<ov::ICompiledModel> {+ auto locked_model = weak_model.lock();+ OPENVINO_ASSERT(locked_model, "Failsafe factory: ov::Model was released before recompilation");+ ov::SoPtr<ov::ICompiledModel> compiled;+ // FIXME: Concurrent write access to the profile map, if compiled in parallel+ m_profile["compile/" + device + profile_suffix].record([&]() {+ compiled = compile_submodel(locked_model, device);+ });+ return compiled;+ };+ };- // Normal compilation for standard models- m_profile["compile/" + device].record([&]() {- m_compiled_submodels[id].compiled_model = compile_submodel(m_compiled_submodels[id].model, device);- });-}+ auto make_wrapped = [&](const std::shared_ptr<ov::Model>& model,+ const std::string& profile_suffix,+ const std::vector<std::string>& devs) -> ov::SoPtr<ov::ICompiledModel> {+ return ov::npuw::failsafe::CompiledModel::create(model,+ get_plugin(),+ devs,+ make_factory(model, profile_suffix));+ };-void ov::npuw::CompiledModel::compile_moe_models(std::size_t id, const std::string& device) {- // Check if we have MoE experts to compile- if (auto& moe_experts_opt = m_compiled_submodels[id].moe_experts; moe_experts_opt.has_value()) {- LOG_INFO("Compiling MoE expert models for different chunk sizes...");+ if (auto& moe_experts_opt = desc.moe_experts; moe_experts_opt.has_value()) {+ LOG_INFO("Compiling MoE expert models for Subgraph[" << id << "]...");LOG_BLOCK();auto& moe_experts = moe_experts_opt.value();- const auto& models_to_compile = moe_experts._models_to_compile;+ LOG_INFO("Total MoE models to compile: " << moe_experts._models_to_compile.size());- LOG_INFO("Total MoE models to compile: " << models_to_compile.size());-- // Compile each chunk size model- for (const auto& entry : models_to_compile) {+ for (const auto& entry : moe_experts._models_to_compile) {LOG_INFO("Compiling MoE expert model for chunk_size=" << entry.first);-- m_profile["compile/" + device + "/moe_chunk_" + std::to_string(entry.first)].record([&, entry]() {- auto compiled = compile_submodel(entry.second, device);- moe_experts.set_compiled_model(entry.first, std::move(compiled));- });-+ moe_experts.set_compiled_model(+ entry.first,+ make_wrapped(entry.second, "/moe_chunk_" + std::to_string(entry.first), devices));LOG_INFO("Successfully compiled MoE expert model for chunk_size=" << entry.first);}- // Set compiled_model to first compiled model for backward compatibility- // Inference requests will be created from _compiled_models in MoEExpertsconst auto& compiled_models = moe_experts._compiled_models;- if (!compiled_models.empty()) {- m_compiled_submodels[id].compiled_model = compiled_models.begin()->second;- }-+ OPENVINO_ASSERT(!compiled_models.empty(), "Expected at least one compiled MoE expert model");+ desc.compiled_model = compiled_models.begin()->second;LOG_INFO("MoE expert compilation complete for Subgraph[" << id << "]");- return;- }-- // Check if we have MoE downstream to compile- if (auto& moe_downstream_opt = m_compiled_submodels[id].moe_experts_downstream; moe_downstream_opt.has_value()) {- LOG_INFO("Compiling MoE downstream model for Subgraph[" << id << "]...");-- m_profile["compile/" + device].record([&]() {- auto compiled = compile_submodel(m_compiled_submodels[id].model, device);- m_compiled_submodels[id].compiled_model = compiled;- moe_downstream_opt->set_compiled_model(std::move(compiled));- });-- LOG_INFO("MoE downstream compilation complete for Subgraph[" << id << "]");+ } else {+ desc.compiled_model = make_wrapped(desc.model, "", main_candidates);}-}-void ov::npuw::CompiledModel::compile_pyramid_attention_models(std::size_t id, const std::string& device) {- // Check if we have pyramid attention to compile- if (!m_compiled_submodels[id].pyramid_attention.has_value()) {- return;+ if (auto& moe_downstream_opt = desc.moe_experts_downstream; moe_downstream_opt.has_value()) {+ LOG_INFO("Wrapping compiled model into MoE downstream for Subgraph[" << id << "]...");+ OPENVINO_ASSERT(desc.compiled_model, "Expected compiled model before wrapping MoE downstream");+ moe_downstream_opt->set_compiled_model(std::move(desc.compiled_model));+ desc.compiled_model = moe_downstream_opt->_compiled_model;}- LOG_INFO("Compiling pyramid attention submodels for Subgraph[" << id << "]...");- LOG_BLOCK();-- auto& pyramid_attn = m_compiled_submodels[id].pyramid_attention.value();- const auto& pyramid_attn_models = pyramid_attn._models_to_compile;- const size_t total_models = pyramid_attn_models.size();-- LOG_INFO("Total pyramid models to compile: " << total_models);-- // Pre-allocate the compiled models vector- std::vector<ov::SoPtr<ov::ICompiledModel>> compiled_models(total_models);-- // Compile all pyramid models except the last one in parallel- // The last model will reuse the already compiled original model- const size_t models_to_compile = total_models > 0 ? total_models - 1 : 0;-- if (models_to_compile > 0) {- LOG_INFO("Compiling " << models_to_compile << " pyramid models in parallel...");-- auto compile_one_model = [&](size_t model_id) {- try {- const auto& model = pyramid_attn_models[model_id];- LOG_DEBUG("Compiling pyramid attention submodel[" << model_id << "]: " << model->get_friendly_name());+ if (desc.pyramid_attention.has_value()) {+ LOG_INFO("Compiling pyramid attention submodels for Subgraph[" << id << "]...");+ LOG_BLOCK();- auto compiled = compile_submodel(model, device);- OPENVINO_ASSERT(compiled, "Failed to compile pyramid attention submodel");+ auto& pyramid_attn = desc.pyramid_attention.value();+ const auto& pyramid_attn_models = pyramid_attn._models_to_compile;+ const size_t total_models = pyramid_attn_models.size();+ const size_t models_to_compile = total_models > 0 ? total_models - 1 : 0;- compiled_models[model_id] = compiled;+ std::vector<ov::SoPtr<ov::ICompiledModel>> compiled_models(total_models);- LOG_INFO("Compiled pyramid attention submodel[" << model_id << "]");- } catch (const std::exception& ex) {- OPENVINO_THROW("Pyramid attention submodel[", model_id, "] compilation failed: ", ex.what());- } catch (...) {- OPENVINO_THROW("Pyramid attention submodel[", model_id, "] compilation failed with unknown error");- }+ auto compile_one = [&](size_t model_id) {+ compiled_models[model_id] =+ make_wrapped(pyramid_attn_models[model_id], "/pyramid_" + std::to_string(model_id), devices);};const bool par_opt = m_cfg.get<::intel_npu::NPUW_PARALLEL_COMPILE>();- if (par_opt) {- ov::parallel_for(models_to_compile, compile_one_model);+ if (par_opt && models_to_compile > 0) {+ ov::parallel_for(models_to_compile, compile_one);} else {- for (std::size_t model_id = 0u; model_id < models_to_compile; model_id++) {- compile_one_model(model_id);+ for (size_t model_id = 0; model_id < models_to_compile; ++model_id) {+ compile_one(model_id);}}- }-- // Handle the last model: reuse the already compiled original model- if (total_models > 0) {- LOG_INFO("Reusing already compiled original model for pyramid attention submodel[" << (total_models - 1)- << "] (optimization)");- OPENVINO_ASSERT(m_compiled_submodels[id].compiled_model, "Original compiled model should exist");- compiled_models[total_models - 1] = m_compiled_submodels[id].compiled_model;- }-- // Set compiled models - this also clears _models_to_compile internally- LOG_INFO("Setting compiled models into compiled::PyramidAttention...");- pyramid_attn.set_compiled_models(std::move(compiled_models));- LOG_INFO("Pyramid attention compilation complete for Subgraph[" << id << "]");-}--void ov::npuw::CompiledModel::compile_host_flash_attention_model(std::size_t id, const std::string& device) {- // Check if we have host flash attention to compile- if (!m_compiled_submodels[id].host_flash_attention.has_value()) {- return;- }-- LOG_INFO("Compiling host flash attention tile models for Subgraph[" << id << "]...");- LOG_BLOCK();-- auto& hfa = m_compiled_submodels[id].host_flash_attention.value();+ if (total_models > 0) {+ OPENVINO_ASSERT(desc.compiled_model, "Original compiled model should exist");+ compiled_models[total_models - 1] = desc.compiled_model;+ }- // Check if we have tile model to compile- if (!hfa._tile_model_to_compile) {- LOG_WARN("Host flash attention tile model is null, skipping compilation");- return;+ pyramid_attn.set_compiled_models(std::move(compiled_models));+ LOG_INFO("Pyramid attention compilation complete for Subgraph[" << id << "]");}- // Set the flag for using tensor view based on device capabilities- if (ov::npuw::util::starts_with(device, "NPU")) {- const auto supported_properties = get_npuw_plugin()->get_core()->get_property(device, ov::supported_properties);- const auto support_strides_for =- std::find(supported_properties.begin(),- supported_properties.end(),- ov::intel_npu::enable_strides_for.name()) != supported_properties.end();- if (support_strides_for) {- hfa._can_use_tensor_view = true;- auto strided_inputs_name = std::string(hfa_tile_input_id_to_string(HFATileInputId::K_TILE)) + "," +- std::string(hfa_tile_input_id_to_string(HFATileInputId::V_TILE));- m_meta_devices[device][ov::intel_npu::enable_strides_for.name()] = strided_inputs_name;- LOG_INFO("Enabled using tensor view for device: " << device << " for inputs: " << strided_inputs_name);- }- }+ if (desc.host_flash_attention.has_value()) {+ LOG_INFO("Compiling host flash attention tile models for Subgraph[" << id << "]...");+ LOG_BLOCK();- // Note: The final tile model has already been compiled via compile_submodel(m_compiled_submodels[id].model, ...)- // because m_compiled_submodels[id].model points to _final_tile_model for HFA- // So we only need to compile the regular tile model here+ auto& hfa = desc.host_flash_attention.value();+ if (!hfa._tile_model_to_compile) {+ LOG_WARN("Host flash attention tile model is null, skipping compilation");+ } else {+ for (const auto& device : devices) {+ if (!ov::npuw::util::starts_with(device, "NPU")) {+ continue;+ }- // Compile regular tile model- LOG_INFO("Compiling flash attention regular tile model on " << device);- try {- auto compiled_tile_model = compile_submodel(hfa._tile_model_to_compile, device);- OPENVINO_ASSERT(compiled_tile_model, "Failed to compile host flash attention tile model");+ const auto supported_properties =+ get_npuw_plugin()->get_core()->get_property(device, ov::supported_properties);+ const auto support_strides_for =+ std::find(supported_properties.begin(),+ supported_properties.end(),+ ov::intel_npu::enable_strides_for.name()) != supported_properties.end();+ if (!support_strides_for) {+ continue;+ }- hfa.set_compiled_tile_model(std::move(compiled_tile_model));+ hfa._can_use_tensor_view = true;+ auto strided_inputs_name = std::string(hfa_tile_input_id_to_string(HFATileInputId::K_TILE)) + "," ++ std::string(hfa_tile_input_id_to_string(HFATileInputId::V_TILE));+ m_meta_devices[device][ov::intel_npu::enable_strides_for.name()] = strided_inputs_name;+ LOG_INFO("Enabled using tensor view for device: " << device << " for inputs: " << strided_inputs_name);+ }- LOG_INFO("Successfully compiled host flash attention regular tile model");- } catch (const std::exception& ex) {- LOG_ERROR("Failed to compile host flash attention tile model: " << ex.what());- OPENVINO_THROW("Host flash attention tile model compilation failed: ", ex.what());- } catch (...) {- LOG_ERROR("Failed to compile host flash attention tile model: Unknown error");- OPENVINO_THROW("Host flash attention tile model compilation failed with unknown error");+ hfa.set_compiled_tile_model(make_wrapped(hfa._tile_model_to_compile, "/hfa_tile", devices));+ hfa.set_compiled_final_tile_model(desc.compiled_model);+ LOG_INFO("Host flash attention compilation complete for Subgraph[" << id << "]");+ }}- // Store the already-compiled final tile model reference- // The final tile model was compiled at line ~1676 and stored in compiled_model- hfa.set_compiled_final_tile_model(m_compiled_submodels[id].compiled_model);-- LOG_INFO("Host flash attention compilation complete for Subgraph[" << id << "]");-- // Memory cleanup notes:- // 1. _tile_model_to_compile is released by set_compiled_tile_model()- // 2. _final_tile_model_to_compile is released by set_compiled_final_tile_model()- // 3. m_compiled_submodels[id].model points to _final_tile_model and will be managed by detach_memory()+ return true;}ov::SoPtr<ov::ICompiledModel> ov::npuw::CompiledModel::compile_submodel(const std::shared_ptr<ov::Model>& submodel,@@ -2035,7 +1955,8 @@ ov::SoPtr<ov::ICompiledModel> ov::npuw::CompiledModel::compile_submodel(const st// set exclusive_async_requests in case when model is split// NOTE(dm): Not sure if it is required for the NPUW plugin, but likely it is- auto& device_config = m_meta_devices[device];+ // Make a device config COPY here!+ auto device_config = m_meta_devices[device];if (ov::npuw::util::starts_with(device, "NPU") && m_cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>()) {device_config["NPU_RUN_INFERENCES_SEQUENTIALLY"] = "YES";@@ -2304,8 +2225,16 @@ std::shared_ptr<ov::npuw::IBaseInferRequest> ov::npuw::CompiledModel::create_basreturn true; // no spatial & subgraphs requiring unpack found};+ // UnfoldInferRequest caches direct references into compiled submodels; it is not safe+ // to use when runtime device failover is in play (failsafe wrapper may swap the inner+ // compiled model mid-inference). Safe when either: only one device is configured,+ // or the user has explicitly disabled runtime fallback.+ auto no_failsafe_concern = [&]() {+ return m_dev_list.size() == 1 || !m_cfg.get<::intel_npu::NPUW_FALLBACK_EXEC>();+ };+std::shared_ptr<ov::npuw::IBaseInferRequest> result;- if (m_cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>() && no_spatial_unpack()) {+ if (m_cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>() && no_spatial_unpack() && no_failsafe_concern()) {result = std::make_shared<ov::npuw::UnfoldInferRequest>(non_const_this_sptr);} else {result = std::make_shared<ov::npuw::JustInferRequest>(non_const_this_sptr);@@ -2370,8 +2299,9 @@ std::string ov::npuw::CompiledModel::submodel_device(const std::size_t idx) consreturn m_ref_device;}- NPUW_ASSERT(comp_subm_desc.device_it != m_dev_list.end());- return *comp_subm_desc.device_it;+ const auto exec_devs =+ comp_subm_desc.compiled_model->get_property(ov::execution_devices.name()).as<std::vector<std::string>>();+ return exec_devs.empty() ? "" : exec_devs.front();}bool ov::npuw::CompiledModel::unpack_required(const std::size_t idx) const {diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hppindex ee80060cc77..3ec230f5207 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp@@ -124,14 +124,9 @@ private:friend class LLMInferRequest;friend class moe::MoEExecutor;- bool compile_for_success(std::size_t id);- bool compile_for_device(std::size_t id, const std::string& device_to_try);+ bool compile_for_success(std::size_t id, const std::vector<std::string>& devices);ov::SoPtr<ov::ICompiledModel> compile_submodel(const std::shared_ptr<ov::Model>& submodel,const std::string& device);- void compile_main_model(std::size_t id, const std::string& device);- void compile_moe_models(std::size_t id, const std::string& device);- void compile_pyramid_attention_models(std::size_t id, const std::string& device);- void compile_host_flash_attention_model(std::size_t id, const std::string& device);void dump_on_fail(std::size_t id, const std::string& device_to_stry, const char* extra);std::string format_subgraph_name(std::size_t id, const std::string& funcall) const;@@ -217,7 +212,6 @@ private:void init_profiling();struct CompiledModelDesc {- DevList::const_iterator device_it;std::set<std::string> devices_to_avoid;std::shared_ptr<ov::Model> model;ov::SoPtr<ov::ICompiledModel> compiled_model;diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cppindex e0c3e4ac5a8..fb298bb28e4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp@@ -17,6 +17,7 @@#include "openvino/runtime/iasync_infer_request.hpp"#include "plugin.hpp"#include "pyramid_attention.hpp"+#include "v1/elements/failsafe.hpp"#include "weights_bank.hpp"// ====================================================================================================@@ -49,6 +50,10 @@ bool ov::npuw::JustInferRequest::needs_copy_closure(size_t idx, size_t cidx) {return IBaseInferRequest::needs_copy(idx, cidx);}+std::string ov::npuw::JustInferRequest::subgraph_device(size_t idx) {+ return m_npuw_model->submodel_device(idx);+}+// ====================================================================================================// Memory Access Simulation & Function Memory Management// ====================================================================================================@@ -245,7 +250,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com// Create infer requests// Preallocate funcall tensors & substitute function call requests- bool failover_happened = false;bool has_spatial = false;bool has_dynamic = false;bool has_pyramid = false;@@ -359,11 +363,8 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com// Special cases are handled -- so nothing to do hereconst bool is_piped = is_pipelined(i);- bool recompiled = false;- auto rqs = create_infer_requests(i, is_piped ? 2 : 1, &recompiled);- failover_happened |= recompiled;+ auto rqs = create_infer_requests(i, is_piped ? 2 : 1);m_subrequests[i] = rqs.at(0);- m_subrequest_devices[i] = *comp_model_desc.device_it;if (is_piped) {m_funcall_pipeline[i].subrequest = rqs.at(1);}@@ -375,13 +376,12 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Comconst auto real_idx = comp_model_desc.replaced_by.value();auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];if (proto_comp_model_desc.pyramid_attention) {- setup_pyramid_infer_requests(real_idx, is_piped, false);+ setup_pyramid_infer_requests(real_idx, is_piped);}// Create HFA tile infer requests if this function has host flash attentionif (proto_comp_model_desc.host_flash_attention) {setup_hfa_infer_requests(real_idx,is_piped,- /* is_recreate */ false,/* enable_hfa_optimizations */ true);}}@@ -389,12 +389,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::ComLOG_INFO("DONE");} // for(submodels)- if (failover_happened) {- LOG_INFO("Refined device distribution:");- LOG_BLOCK();- m_npuw_model->log_device_dist();- }-// Identify connections for the funcall pipeline, if neededif (m_use_function_pipelining) {LOG_INFO("Setting up the funcall pipeline...");@@ -1025,48 +1019,6 @@ void ov::npuw::JustInferRequest::function_prologue_pyramid_attn(std::size_t real}}-void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];- auto real_idx = comp_model_desc.replaced_by.value_or(idx);-- const auto is_piped = is_pipelined(idx);- auto new_rqs = create_infer_requests(idx, is_piped ? 2 : 1);-- // NB: Regardless if this subrequest was a function call- // or not, always use the real_idx here - for regular- // subrequests, real_id == idx, but for function calls it- // is critical here to update the function body, not the- // function calls (which are left empty now in the vector)- m_subrequests[real_idx] = new_rqs.at(0);- if (is_piped) {- m_funcall_pipeline[real_idx].subrequest = new_rqs.at(1);- }-- // Recreate pyramid infer requests if this function has pyramid attention- if (comp_model_desc.replaced_by) {- auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];- if (proto_comp_model_desc.pyramid_attention) {- setup_pyramid_infer_requests(real_idx, is_piped, true);- }- // Recreate HFA tile infer requests if this function has host flash attention- if (proto_comp_model_desc.host_flash_attention) {- setup_hfa_infer_requests(real_idx, is_piped, /* is_recreate */ true, /* enable_hfa_optimizations */ true);- }- // Recreate MoE resources if this function has MoE- if (proto_comp_model_desc.moe_experts) {- recreate_moe_resources(idx, real_idx);- }- }-- // After an infer request is recreated, the internal cross-request- // connections should be re-established (in/out tensors reset properly)- // Note: these two proceduers do the full I/O reset procedure what's- // overkill - only affected subrequest(s) could be updated instead,- // but it is a more complex thing and can be implemented separately- connect_subrequests();- m_subrequest_devices[idx] = *comp_model_desc.device_it;-}-void ov::npuw::JustInferRequest::initialize_moe_executor() {LOG_INFO("Creating MoE executor...");@@ -1097,42 +1049,18 @@ void ov::npuw::JustInferRequest::initialize_moe_executor() {LOG_INFO("MoE executor initialized successfully");}-void ov::npuw::JustInferRequest::recreate_moe_resources(std::size_t idx, std::size_t real_idx) {- LOG_INFO("Recreating MoE resources for submodel[" << idx << "] (real_idx=" << real_idx << ")...");- LOG_BLOCK();-- // Re-prepare MoE resources for this specific submodel- size_t pool_size = m_npuw_model->m_cfg.get<::intel_npu::NPUW_MOE_POOL_SIZE>();- m_moe_executor->prepare(idx, real_idx, m_num_submodels, pool_size);-- LOG_INFO("MoE resources recreated successfully");-}--void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped, bool is_recreate) {+void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped) {auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];if (!submodel_desc.pyramid_attention.has_value()) {return;}- LOG_INFO((is_recreate ? "Recreating" : "Creating") << " pyramid infer requests...");+ LOG_INFO("Creating pyramid infer requests...");LOG_BLOCK();const auto& pyramid_models = submodel_desc.pyramid_attention.value()._compiled_models;const size_t num_pyramid_models = pyramid_models.size();- // Clear existing requests if recreating- if (is_recreate) {- submodel_desc.pyramid_infer_requests.clear();- submodel_desc.pyramid_pipeline_requests.clear();- // Also release anchor tensors for this submodel so stale buffers are not retained- m_pyramid_anchor_tensors.erase(std::remove_if(m_pyramid_anchor_tensors.begin(),- m_pyramid_anchor_tensors.end(),- [real_idx](const auto& e) {- return e.first == real_idx;- }),- m_pyramid_anchor_tensors.end());- }-// Allocate storage for infer requestssubmodel_desc.pyramid_infer_requests.resize(num_pyramid_models);if (is_piped) {@@ -1141,21 +1069,9 @@ void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_i// Create infer requests for all but the last pyramid modelfor (size_t model_idx = 0; model_idx + 1 < num_pyramid_models; ++model_idx) {- try {- // Create main infer request- submodel_desc.pyramid_infer_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();- // Create pipeline infer request if pipelined- if (is_piped) {- submodel_desc.pyramid_pipeline_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();- }- } catch (const std::exception& ex) {- LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create") << " infer request for pyramid model["- << model_idx << "]: " << ex.what());- NPUW_ASSERT(false && "Pyramid model infer request creation/recreation failed");- } catch (...) {- LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create") << " infer request for pyramid model["- << model_idx << "]: Unknown error");- NPUW_ASSERT(false && "Pyramid model infer request creation/recreation failed with unknown error");+ submodel_desc.pyramid_infer_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();+ if (is_piped) {+ submodel_desc.pyramid_pipeline_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();}// Share input tensors between pyramid and main infer requests@@ -1186,8 +1102,7 @@ void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_i// For the last pyramid model, reuse the original model's infer requestsif (num_pyramid_models > 0) {const size_t last_model_idx = num_pyramid_models - 1;- LOG_INFO("Reusing " << (is_recreate ? "recreated " : "") << "original infer requests for last pyramid model["- << last_model_idx << "]");+ LOG_INFO("Reusing original infer requests for last pyramid model[" << last_model_idx << "]");submodel_desc.pyramid_infer_requests[last_model_idx] = m_subrequests[real_idx];if (is_piped) {submodel_desc.pyramid_pipeline_requests[last_model_idx] = m_funcall_pipeline[real_idx].subrequest;@@ -1205,7 +1120,7 @@ void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_i}}- if (!is_recreate && num_pyramid_models > 0) {+ if (num_pyramid_models > 0) {LOG_INFO("Successfully created " << (num_pyramid_models - 1)<< " new pyramid infer requests and reused 1 original request");}@@ -1213,52 +1128,34 @@ void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_ivoid ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,bool is_piped,- bool is_recreate,bool enable_hfa_optimizations) {auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];if (!submodel_desc.host_flash_attention.has_value()) {return;}- LOG_INFO((is_recreate ? "Recreating" : "Creating") << " HFA tile infer requests...");+ LOG_INFO("Creating HFA tile infer requests...");LOG_BLOCK();const auto& hfa = submodel_desc.host_flash_attention.value();- // Clear existing requests if recreating- if (is_recreate) {- submodel_desc.hfa_infer_requests.clear();- submodel_desc.hfa_pipeline_requests.clear();- }-// Allocate storage for infer requests: [REGULAR_TILE] and [FINAL_TILE]submodel_desc.hfa_infer_requests.resize(CompiledModel::CompiledModelDesc::HFATileIdx::COUNT);if (is_piped) {submodel_desc.hfa_pipeline_requests.resize(CompiledModel::CompiledModelDesc::HFATileIdx::COUNT);}- // Create infer request for regular tile model- try {- LOG_INFO("Creating infer request for HFA regular tile model...");- submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =+ LOG_INFO("Creating infer request for HFA regular tile model...");+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =+ hfa._compiled_tile_model->create_infer_request();+ if (is_piped) {+ submodel_desc.hfa_pipeline_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =hfa._compiled_tile_model->create_infer_request();- if (is_piped) {- submodel_desc.hfa_pipeline_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =- hfa._compiled_tile_model->create_infer_request();- }- } catch (const std::exception& ex) {- LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create")- << " infer request for HFA regular tile model: " << ex.what());- OPENVINO_THROW("HFA regular tile model infer request creation failed: ", ex.what());- } catch (...) {- LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create")- << " infer request for HFA regular tile model: Unknown error");- OPENVINO_THROW("HFA regular tile model infer request creation failed with unknown error");}// For final tile model, reuse the main compiled_model's infer request// because compiled_model points to _compiled_final_tile_model for HFA- LOG_INFO("Reusing " << (is_recreate ? "recreated " : "") << "main infer request for HFA final tile model");+ LOG_INFO("Reusing main infer request for HFA final tile model");submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::FINAL_TILE] =m_subrequests[real_idx];if (is_piped) {@@ -1288,8 +1185,7 @@ void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,}}- LOG_INFO("Successfully " << (is_recreate ? "recreated" : "created")- << " HFA tile infer requests with shared input tensors");+ LOG_INFO("Successfully created HFA tile infer requests with shared input tensors");// Initialize HFA optimizations (mask cache + state double-buffering) if enabledif (enable_hfa_optimizations) {@@ -1300,16 +1196,12 @@ void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,m_hfa_runtime_ctx.emplace();}- if (is_recreate) {- m_hfa_runtime_ctx->reset();- }-LOG_INFO("Pre-allocating HFA mask tile buffers...");// Initialize pre-allocated buffersm_hfa_runtime_ctx->initialize_mask_cache(hfa,- *submodel_desc.device_it,+ m_npuw_model->submodel_device(real_idx),[this](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {return allocMem(dtype, shape, device);});@@ -1342,7 +1234,7 @@ void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,m_hfa_runtime_ctx->initialize_state_buffers(initial_buffers,hfa,- *submodel_desc.device_it,+ m_npuw_model->submodel_device(real_idx),[this](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {return allocMem(dtype, shape, device);});@@ -1358,82 +1250,33 @@ void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,}}-void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, bool& failover) {- failover = false;+void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];- auto real_idx = comp_model_desc.replaced_by.value_or(idx);-- // Infer is also fail-safe...- bool job_done = false;- bool dump_in = false;+ const auto real_idx = comp_model_desc.replaced_by.value_or(idx);bool next_prepared = false;- while (!job_done) {- bool should_recreate = false;- if (m_subrequest_devices[real_idx] != *m_npuw_model->m_compiled_submodels[real_idx].device_it) {- // This may happen when there's multiple NPUW's infer- // requests created and some failure occurs in one of- // those before another reaches this point.- LOG_INFO("Recreating subrequest[" << real_idx << "] because model was recompiled for "- << *m_npuw_model->m_compiled_submodels[real_idx].device_it << " device.");- recreate_subrequests(real_idx);- }- // Feeding the global Parameters is now part of the common- // execution pipeline: See how it is done in- // `unsafe_run_this_prep_next()`. Now we only need to bind- // the subrequest' outputs to global Results, if relevant.- bind_global_results(idx);+ // Feeding the global Parameters is now part of the common+ // execution pipeline: See how it is done in+ // `unsafe_run_this_prep_next()`. Now we only need to bind+ // the subrequest' outputs to global Results, if relevant.+ bind_global_results(idx);- if (comp_model_desc.replaced_by) {- function_prologue(idx);- }- if (!dump_in) {- dump_in = true;- dump_input_tensors(idx);- }+ if (comp_model_desc.replaced_by) {+ function_prologue(idx);+ }+ dump_input_tensors(idx);- std::string error_text;- try {- LOG_DEBUG("Trying to run subrequest[" << idx << "]...");- LOG_BLOCK();- unsafe_run_this_prep_next(idx, next_prepared);- job_done = true;- LOG_DEBUG("Done: " << idx << "(exec subrequest)");- } catch (const std::exception& ex) {- error_text = ex.what();- LOG_ERROR("Subgraph [" << idx << "] - FAILED to run infer request:" << std::endl- << error_text << std::endl);- should_recreate = true;- } catch (...) {- LOG_ERROR("Subgraph [" << idx << "] - FAILED to run infer request: REASON UNKNOWN");- should_recreate = true;- }- if (should_recreate) {- // Altering iterators here!! Contracts should be changed!- comp_model_desc.device_it++;-- // Check if failover is actually possible- if ((m_npuw_model->m_dev_list.cend() == comp_model_desc.device_it) ||- !m_npuw_model->m_cfg.get<::intel_npu::NPUW_FALLBACK_EXEC>()) {- OPENVINO_THROW("Execution error: \"", error_text, "\" - no fallback possible");- }+ LOG_DEBUG("Trying to run subrequest[" << idx << "]...");+ LOG_BLOCK();+ unsafe_run_this_prep_next(idx, next_prepared);- failover = true;- LOG_INFO("- Trying next device...");- if (!m_npuw_model->compile_for_success(real_idx)) {- OPENVINO_THROW("Execution error: \"", error_text, "\" - failed to recompile the model in runtime");- }- recreate_subrequests(idx);- }- } // while(job_done)-- if (job_done) {- dump_output_tensors(idx); // FIXME: Called here unconditionally, need to refactor- if (is_pipelined(idx) && m_funcall_pipeline[idx].next) {- // Swap the next (pipelined, semi-prepared) infer request in the chain- // with the default (to be accessed next) one.- std::swap(m_subrequests[real_idx], m_funcall_pipeline[real_idx].subrequest);- }+ LOG_DEBUG("Done: " << idx << "(exec subrequest)");++ dump_output_tensors(idx); // FIXME: Called here unconditionally, need to refactor+ if (is_pipelined(idx) && m_funcall_pipeline[idx].next) {+ // Swap the next (pipelined, semi-prepared) infer request in the chain+ // with the default (to be accessed next) one.+ std::swap(m_subrequests[real_idx], m_funcall_pipeline[real_idx].subrequest);}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hppindex ee34d96242a..c1916e0911e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp@@ -81,6 +81,7 @@ public:bool is_gather_closure(size_t idx, size_t cidx) override;bool unpack_required(size_t idx, size_t cidx) override;bool needs_copy_closure(size_t idx, size_t cidx) override;+ std::string subgraph_device(size_t idx) override;protected:////////////////////////////////////@@ -88,7 +89,7 @@ protected:void prepare_for_infer() override;bool valid_subrequest(std::size_t idx) const override;void start_subrequest(std::size_t idx) override;- void run_subrequest_for_success(std::size_t idx, bool& failover) override;+ void run_subrequest_for_success(std::size_t idx) override;void subscribe_subrequest(std::size_t idx, Completed cb) override;void complete_subrequest(std::size_t idx) override;void cancel_subrequest(std::size_t idx) override;@@ -135,23 +136,16 @@ protected:int64_t tile_length);void connect_subrequests();- void recreate_subrequests(std::size_t idx);// Helper function to setup pyramid attention infer requests- void setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped, bool is_recreate);+ void setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped);// Helper function to setup host flash attention tile infer requests- void setup_hfa_infer_requests(std::size_t real_idx,- bool is_piped,- bool is_recreate,- bool enable_hfa_optimizations = true);+ void setup_hfa_infer_requests(std::size_t real_idx, bool is_piped, bool enable_hfa_optimizations = true);// Helper function to initialize/reinitialize MoE executorvoid initialize_moe_executor();- // Helper function to recreate MoE resources after subrequest recreation- void recreate_moe_resources(std::size_t idx, std::size_t real_idx);-FuncMemMgr m_func_mem_mgr; // Owns memorystd::map<LinkFrom, TensorPtr> m_funcall_result; // Provides a convenient linkdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 6b7b388e312..92ef105aea2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -197,7 +197,13 @@ std::optional<NPUDesc> extract_npu_descriptor(const std::shared_ptr<const ov::IPif (!plugin->get_core()) {return std::nullopt;}- const auto all_devices = plugin->get_core()->get_property("NPU", ov::available_devices);+ std::vector<std::string> all_devices;+ try {+ all_devices = plugin->get_core()->get_property("NPU", ov::available_devices);+ } catch (const ov::Exception& ex) {+ LOG_WARN("Failed to query NPU capabilities, defaulting LLM config to backend-agnostic path: " << ex.what());+ return std::nullopt;+ }if (all_devices.empty()) {return std::nullopt;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cppindex 7fe719e8cec..cfc46862cbc 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp@@ -81,38 +81,27 @@ void MoEExecutor::prepare(size_t idx, size_t real_idx, size_t num_sublayers, sizrequests.resize(pool_size);// Create first request separately (needed for tensor sharing)- try {- requests[0] = desc.compiled_model->create_infer_request();- requests[0]->infer(); // Warmup- LOG_DEBUG("Created and warmed up request[0]");- } catch (const std::exception& ex) {- LOG_ERROR("Failed to create MoE pool request[0] for sublayer[" << idx << "]: " << ex.what());- throw;- }+ requests[0] = desc.compiled_model->create_infer_request();+ requests[0]->infer(); // Warmup+ LOG_DEBUG("Created and warmed up request[0]");// Create remaining requests in parallel, sharing tensors from first requestov::parallel_for(pool_size - 1, [&](size_t i) {const size_t req_idx = i + 1;- try {- auto request = desc.compiled_model->create_infer_request();-- // Share all input & output tensors from first request to save memory- const auto& inputs = desc.compiled_model->inputs();- for (size_t input_idx = 0; input_idx < inputs.size(); ++input_idx) {- request->set_tensor(inputs[input_idx], requests[0]->get_tensor(inputs[input_idx]));- }- const auto& outputs = desc.compiled_model->outputs();- for (size_t output_idx = 0; output_idx < outputs.size(); ++output_idx) {- request->set_tensor(outputs[output_idx], requests[0]->get_tensor(outputs[output_idx]));- }+ auto request = desc.compiled_model->create_infer_request();- request->infer(); // Warmup- requests[req_idx] = std::move(request);- } catch (const std::exception& ex) {- LOG_ERROR("Failed to create MoE pool request[" << req_idx << "] for sublayer[" << idx- << "]: " << ex.what());- throw;+ // Share all input & output tensors from first request to save memory+ const auto& inputs = desc.compiled_model->inputs();+ for (size_t input_idx = 0; input_idx < inputs.size(); ++input_idx) {+ request->set_tensor(inputs[input_idx], requests[0]->get_tensor(inputs[input_idx]));+ }+ const auto& outputs = desc.compiled_model->outputs();+ for (size_t output_idx = 0; output_idx < outputs.size(); ++output_idx) {+ request->set_tensor(outputs[output_idx], requests[0]->get_tensor(outputs[output_idx]));}++ request->infer(); // Warmup+ requests[req_idx] = std::move(request);});// Initialize cache layer with pre-allocated requests@@ -577,11 +566,8 @@ void MoEExecutor::set_router_scores(size_t idx,}}-std::string MoEExecutor::get_device_name(size_t idx, const void* compiled_model_desc_ptr) const {- const auto& desc = compiled_model_desc_ptr- ? *static_cast<const CompiledModel::CompiledModelDesc*>(compiled_model_desc_ptr)- : *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(idx));- return *desc.device_it;+std::string MoEExecutor::get_device_name(size_t idx, const void*) const {+ return m_accessor.subgraph_device(idx);}void MoEExecutor::unpack_single_expert_closure(std::size_t idx, RqPtr request, size_t expert_id) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hppindex 47d4ce6f3a6..4f690e29fa4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp@@ -96,6 +96,12 @@ public:* @return True if copy is needed*/virtual bool needs_copy_closure(size_t idx, size_t cidx) = 0;++ /**+ * @param idx Submodel index+ * @return Device identifier for the given subgraph+ */+ virtual std::string subgraph_device(size_t idx) = 0;};namespace moe {diff --git a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cppindex c7190772134..b850f2ca025 100644--- a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp@@ -39,7 +39,6 @@ ov::npuw::UnfoldInferRequest::UnfoldInferRequest(const std::shared_ptr<ov::npuw:auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];// NB: UnfoldInferRequest is _NOT_ fail-safe! Fail means fail herem_subrequests[i] = proto_comp_model_desc.compiled_model->create_infer_request();- m_subrequest_devices[i] = *proto_comp_model_desc.device_it;LOG_INFO("DONE");} // for(submodels)diff --git a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.hppindex f61f9eb34f3..e5bece33e2d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.hpp@@ -25,7 +25,7 @@ public:void prepare_for_infer() override {}bool valid_subrequest(std::size_t idx) const override;void start_subrequest(std::size_t) override {}- void run_subrequest_for_success(std::size_t, bool&) override {}+ void run_subrequest_for_success(std::size_t) override {}void subscribe_subrequest(std::size_t, Completed cb) override {}void complete_subrequest(std::size_t) override {}void cancel_subrequest(std::size_t) override {}diff --git a/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cpp b/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cppindex b8790fcfc44..8ca976051ec 100644--- a/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.cpp@@ -26,54 +26,37 @@ namespace {OPENVINO_THROW("Failsafe ", stage, " fallback exhausted");}-ov::SoPtr<ov::ITensor> allocate_tensor_like(const ov::SoPtr<ov::ITensor>& tensor) {- return ov::get_tensor_impl(ov::Tensor(tensor->get_element_type(), tensor->get_shape()));-}--// The wrapper keeps public output tensors stable across failover. For plain-// host tensors the generic ITensor::copy_to path is not consistently available-// in lightweight test doubles, so use memcpy for the common contiguous case and-// fall back to plugin-provided copy_to for non-contiguous / remote tensors.-void copy_tensor_data(const ov::SoPtr<ov::ITensor>& src, const ov::SoPtr<ov::ITensor>& dst) {- OPENVINO_ASSERT(src->get_byte_size() == dst->get_byte_size(), "Failsafe tensor copy size mismatch");- if (src->is_continuous() && dst->is_continuous()) {- std::memcpy(dst->data(), src->data(), src->get_byte_size());- return;- }- src->copy_to(dst._ptr);-}-} // namespace-std::shared_ptr<ov::ICompiledModel> ov::npuw::failsafe::CompiledModel::create(+ov::SoPtr<ov::ICompiledModel> ov::npuw::failsafe::CompiledModel::create(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,- std::vector<std::string> devices,- Factory factory) {+ const std::vector<std::string>& devices,+ const Factory& factory) {OPENVINO_ASSERT(!devices.empty(), "Failsafe compiled model requires at least one device");OPENVINO_ASSERT(static_cast<bool>(factory), "Failsafe compiled model requires a factory");if (devices.size() == 1u) {auto compiled_model = factory(devices.front());- OPENVINO_ASSERT(compiled_model != nullptr,+ OPENVINO_ASSERT(compiled_model._ptr != nullptr,"Failsafe factory returned null compiled model for device ",devices.front());return compiled_model;}- auto compiled_model = std::make_shared<CompiledModel>(model, plugin, std::move(devices), std::move(factory));+ auto compiled_model = std::make_shared<CompiledModel>(model, plugin, devices, factory);std::lock_guard<std::mutex> lock(compiled_model->m_mutex);compiled_model->ensure_active_compiled_model_locked();- return compiled_model;+ return {compiled_model, {}};}ov::npuw::failsafe::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,- std::vector<std::string> devices,- Factory factory)+ const std::vector<std::string>& devices,+ const Factory& factory): ov::ICompiledModel(model, plugin),- m_devices(std::move(devices)),- m_factory(std::move(factory)) {+ m_devices(devices),+ m_factory(factory) {OPENVINO_ASSERT(!m_devices.empty(), "Failsafe compiled model requires at least one device");OPENVINO_ASSERT(static_cast<bool>(m_factory), "Failsafe compiled model requires a factory");}@@ -88,7 +71,7 @@ ov::npuw::failsafe::CompiledModel::ActiveState ov::npuw::failsafe::CompiledModelfor (std::size_t idx = 0; idx < m_devices.size(); ++idx) {try {auto compiled_model = m_factory(m_devices[idx]);- OPENVINO_ASSERT(compiled_model != nullptr,+ OPENVINO_ASSERT(compiled_model._ptr != nullptr,"Failsafe factory returned null compiled model for device ",m_devices[idx]);m_active_state = ActiveState{idx, 0u, std::move(compiled_model)};@@ -113,7 +96,7 @@ ov::npuw::failsafe::CompiledModel::ActiveState ov::npuw::failsafe::CompiledModelfor (std::size_t idx = current.device_index + 1; idx < m_devices.size(); ++idx) {try {auto compiled_model = m_factory(m_devices[idx]);- OPENVINO_ASSERT(compiled_model != nullptr,+ OPENVINO_ASSERT(compiled_model._ptr != nullptr,"Failsafe factory returned null compiled model for device ",m_devices[idx]);m_active_state = ActiveState{idx, current.generation + 1u, std::move(compiled_model)};@@ -161,6 +144,10 @@ std::string ov::npuw::failsafe::CompiledModel::active_device_name() const {return m_devices[current.device_index];}+bool ov::npuw::failsafe::CompiledModel::is_at_last_device() const {+ return active_device_index() + 1 == m_devices.size();+}+void ov::npuw::failsafe::CompiledModel::export_model(std::ostream& model) const {std::lock_guard<std::mutex> lock(m_mutex);ensure_active_compiled_model_locked().compiled_model->export_model(model);@@ -204,7 +191,6 @@ void ov::npuw::failsafe::InferRequest::ensure_inner_request_locked() const {}m_request = m_failsafe_compiled_model->create_request(m_generation);- rebind_public_input_tensors_locked();}ov::npuw::failsafe::InferRequest::PortKey ov::npuw::failsafe::InferRequest::port_key_locked(@@ -218,107 +204,35 @@ bool ov::npuw::failsafe::InferRequest::is_output_port_locked(const ov::Output<coreturn port_key_locked(port).is_output;}-ov::npuw::failsafe::InferRequest::PortTensors& ov::npuw::failsafe::InferRequest::get_or_create_port_tensors_locked(- const ov::Output<const ov::Node>& port) const {- auto [it, _] = m_public_tensors.try_emplace(port_key_locked(port), PortTensors{port, {}});- auto& stored = it->second;- if (!stored.tensors.empty()) {- return stored;- }-- auto tensors = m_request->get_tensors(port);- if (!tensors.empty()) {- stored.tensors.reserve(tensors.size());- for (const auto& tensor : tensors) {- stored.tensors.push_back(allocate_tensor_like(tensor));- }- } else {- stored.tensors.push_back(allocate_tensor_like(m_request->get_tensor(port)));- }-- if (is_output_port_locked(port)) {- auto current_tensors = m_request->get_tensors(port);- if (!current_tensors.empty()) {- OPENVINO_ASSERT(current_tensors.size() == stored.tensors.size(),- "Failsafe output tensor count mismatch for port ",- port);- for (std::size_t idx = 0; idx < current_tensors.size(); ++idx) {- copy_tensor_data(current_tensors[idx], stored.tensors[idx]);- }- } else {- copy_tensor_data(m_request->get_tensor(port), stored.tensors.front());- }- } else {- bind_public_input_tensors_locked(stored.port, stored.tensors);- }-- return stored;-}--void ov::npuw::failsafe::InferRequest::bind_public_input_tensors_locked(- const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) const {- if (tensors.empty()) {- return;- }-- // Output tensors stay wrapper-owned/public. If the caller overrides an- // output buffer via set_tensor()/set_tensors(), infer() copies the current- // inner-request outputs into that buffer after execution and after failover.- if (is_output_port_locked(port)) {- return;- }-- if (tensors.size() == 1u) {- m_request->set_tensor(port, tensors.front());- } else {- m_request->set_tensors(port, tensors);- }-}--void ov::npuw::failsafe::InferRequest::sync_public_output_tensors_locked() const {- for (const auto& [_, stored] : m_public_tensors) {- if (!is_output_port_locked(stored.port) || stored.tensors.empty()) {- continue;- }+void ov::npuw::failsafe::InferRequest::infer() {+ std::lock_guard<std::mutex> lock(m_mutex);- auto current_tensors = m_request->get_tensors(stored.port);- if (!current_tensors.empty()) {- OPENVINO_ASSERT(current_tensors.size() == stored.tensors.size(),- "Failsafe output tensor count mismatch for port ",- stored.port);- for (std::size_t idx = 0; idx < current_tensors.size(); ++idx) {- if (current_tensors[idx]._ptr != stored.tensors[idx]._ptr) {- copy_tensor_data(current_tensors[idx], stored.tensors[idx]);- }- }- continue;- }+ using Binding = std::pair<ov::Output<const ov::Node>, ov::SoPtr<ov::ITensor>>;+ std::vector<Binding> input_tensors;+ std::vector<Binding> output_tensors;+ bool need_rebind = false;- const auto current = m_request->get_tensor(stored.port);- if (current._ptr != stored.tensors.front()._ptr) {- copy_tensor_data(current, stored.tensors.front());- }+ ensure_inner_request_locked();+ for (auto&& port : m_failsafe_compiled_model->inputs()) {+ input_tensors.push_back(Binding{port, m_request->get_tensor(port)});}-}--void ov::npuw::failsafe::InferRequest::rebind_public_input_tensors_locked() const {- for (const auto& [_, stored] : m_public_tensors) {- if (stored.tensors.empty()) {- continue;- }- bind_public_input_tensors_locked(stored.port, stored.tensors);+ for (auto&& port : m_failsafe_compiled_model->outputs()) {+ output_tensors.push_back(Binding{port, m_request->get_tensor(port)});}-}--void ov::npuw::failsafe::InferRequest::infer() {- std::lock_guard<std::mutex> lock(m_mutex);while (true) {ensure_inner_request_locked();try {+ if (need_rebind) {+ for (auto&& binding : input_tensors) {+ m_request->set_tensor(binding.first, binding.second);+ }+ for (auto&& binding : output_tensors) {+ m_request->set_tensor(binding.first, binding.second);+ }+ }m_request->infer();- sync_public_output_tensors_locked();+ need_rebind = false;return;} catch (...) {{@@ -327,6 +241,7 @@ void ov::npuw::failsafe::InferRequest::infer() {}m_request.reset();m_generation = std::numeric_limits<std::size_t>::max();+ need_rebind = true;}}}@@ -334,38 +249,17 @@ void ov::npuw::failsafe::InferRequest::infer() {ov::SoPtr<ov::ITensor> ov::npuw::failsafe::InferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {std::lock_guard<std::mutex> lock(m_mutex);ensure_inner_request_locked();- return get_or_create_port_tensors_locked(port).tensors.front();+ return m_request->get_tensor(port);}void ov::npuw::failsafe::InferRequest::set_tensor(const ov::Output<const ov::Node>& port,const ov::SoPtr<ov::ITensor>& tensor) {std::lock_guard<std::mutex> lock(m_mutex);- const auto key = port_key_locked(port);- m_public_tensors[key] = PortTensors{port, {tensor}};- ensure_inner_request_locked();- bind_public_input_tensors_locked(port, {tensor});-}--std::vector<ov::SoPtr<ov::ITensor>> ov::npuw::failsafe::InferRequest::get_tensors(- const ov::Output<const ov::Node>& port) const {- std::lock_guard<std::mutex> lock(m_mutex);ensure_inner_request_locked();- return get_or_create_port_tensors_locked(port).tensors;+ m_request->set_tensor(port, tensor);}-void ov::npuw::failsafe::InferRequest::set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) {- std::lock_guard<std::mutex> lock(m_mutex);- const auto key = port_key_locked(port);- m_public_tensors[key] = PortTensors{port, tensors};- ensure_inner_request_locked();- bind_public_input_tensors_locked(port, tensors);-}--void ov::npuw::failsafe::InferRequest::check_tensors() const {- std::lock_guard<std::mutex> lock(m_mutex);- ensure_inner_request_locked();-}+void ov::npuw::failsafe::InferRequest::check_tensors() const {}std::vector<ov::SoPtr<ov::IVariableState>> ov::npuw::failsafe::InferRequest::query_state() const {std::lock_guard<std::mutex> lock(m_mutex);diff --git a/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.hpp b/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.hppindex e4dcd5d0f29..7800494b8be 100644--- a/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/v1/elements/failsafe.hpp@@ -17,6 +17,7 @@#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/icompiled_model.hpp"#include "openvino/runtime/isync_infer_request.hpp"+#include "openvino/runtime/so_ptr.hpp"namespace ov::npuw::failsafe {@@ -24,17 +25,17 @@ class InferRequest;class CompiledModel final : public ov::ICompiledModel {public:- using Factory = std::function<std::shared_ptr<ov::ICompiledModel>(const std::string& device)>;+ using Factory = std::function<ov::SoPtr<ov::ICompiledModel>(const std::string& device)>;- static std::shared_ptr<ov::ICompiledModel> create(const std::shared_ptr<ov::Model>& model,- const std::shared_ptr<const ov::IPlugin>& plugin,- std::vector<std::string> devices,- Factory factory);+ static ov::SoPtr<ov::ICompiledModel> create(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const std::vector<std::string>& devices,+ const Factory& factory);CompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,- std::vector<std::string> devices,- Factory factory);+ const std::vector<std::string>& devices,+ const Factory& factory);void export_model(std::ostream& model) const override;std::shared_ptr<const ov::Model> get_runtime_model() const override;@@ -47,6 +48,7 @@ public:std::size_t active_device_index() const;std::string active_device_name() const;+ bool is_at_last_device() const;private:friend class InferRequest;@@ -54,7 +56,7 @@ private:struct ActiveState {std::size_t device_index = 0;std::size_t generation = 0;- std::shared_ptr<ov::ICompiledModel> compiled_model;+ ov::SoPtr<ov::ICompiledModel> compiled_model;};ActiveState ensure_active_compiled_model_locked() const;@@ -76,11 +78,6 @@ public:ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override;-- std::vector<ov::SoPtr<ov::ITensor>> get_tensors(const ov::Output<const ov::Node>& port) const override;- void set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) override;-void check_tensors() const override;std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override;@@ -104,25 +101,14 @@ private:}};- struct PortTensors {- ov::Output<const ov::Node> port;- std::vector<ov::SoPtr<ov::ITensor>> tensors;- };-void ensure_inner_request_locked() const;PortKey port_key_locked(const ov::Output<const ov::Node>& port) const;bool is_output_port_locked(const ov::Output<const ov::Node>& port) const;- PortTensors& get_or_create_port_tensors_locked(const ov::Output<const ov::Node>& port) const;- void bind_public_input_tensors_locked(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) const;- void sync_public_output_tensors_locked() const;- void rebind_public_input_tensors_locked() const;std::shared_ptr<const CompiledModel> m_failsafe_compiled_model;mutable std::mutex m_mutex;mutable std::shared_ptr<ov::IAsyncInferRequest> m_request;mutable std::size_t m_generation = std::numeric_limits<std::size_t>::max();- mutable std::map<PortKey, PortTensors> m_public_tensors;};} // namespace ov::npuw::failsafediff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_accuracy_tests.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_accuracy_tests.cppindex 8748342beac..99749d81e99 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_accuracy_tests.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/llm_smoke_accuracy_tests.cpp@@ -6,6 +6,8 @@#include <algorithm>#include <filesystem>+#include <optional>+#include <vector>#include "functional_test_utils/skip_tests_config.hpp"#include "intel_npu/npuw_private_properties.hpp"@@ -43,7 +45,26 @@ using LLMTestParams = std::tuple<std::string, ov::AnyMap, GroundTruth>;class LLMSmokeAccuracyTestsNPUW : public ::testing::TestWithParam<LLMTestParams> {public:void SetUp() override {- SKIP_IF_CURRENT_TEST_IS_DISABLED();+ auto param = GetParam();+ std::string model_name;+ ov::AnyMap config;+ GroundTruth input_and_reference_ids;+ std::tie(model_name, config, input_and_reference_ids) = param;++ // Resolve the model before any Core/plugin work in this fixture. In backend-less+ // environments the NPU test infrastructure may touch backend-dependent paths during+ // generic setup, but this CPU-only smoke test is expected to skip cleanly when the+ // model is unavailable.+ model_path = find_model(model_name);+ if (model_path == "") {+ GTEST_SKIP() << "Test model is not found, skipping the test!";+ }++ input_ids = input_and_reference_ids.prompt;+ reference_ids = input_and_reference_ids.answer;++ core.emplace();+// NOTE: TEMPLATE plugin in OpenVINO works for ~20 minute to generate// first token from prefill model and crashes on launch of// 3rd subrequest in generate model.@@ -55,7 +76,7 @@ public:const char* cpu_plugin_file_name = "openvino_intel_cpu_plugin";// Register CPU plugin in OpenVINO:try {- core.register_plugin(std::string(cpu_plugin_file_name) + OV_BUILD_POSTFIX, "CPU");+ core->register_plugin(std::string(cpu_plugin_file_name) + OV_BUILD_POSTFIX, "CPU");} catch (ov::Exception& ex) {if (std::string{ex.what()}.find("Device with \"CPU\" is already registered in the OpenVINO Runtime")== std::string::npos) {@@ -67,28 +88,14 @@ public:#endif // not OPENVINO_STATIC_LIBRARY && WITH_CPU_PLUGIN &&// (defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64))- auto param = GetParam();- std::string model_name;- ov::AnyMap config;- GroundTruth input_and_reference_ids;- std::tie(model_name, config, input_and_reference_ids) = param;-- model_path = find_model(model_name);- if (model_path == "") {- GTEST_SKIP() << "Test model is not found, skipping the test!";- }-- input_ids = input_and_reference_ids.prompt;- reference_ids = input_and_reference_ids.answer;-config["NPUW_DEVICES"] = "CPU";config["NPUW_LLM_MAX_PROMPT_LEN"] = 128;config["NPUW_LLM_MIN_RESPONSE_LEN"] = 4;- simple_llm.initialize(model_path, core, config);+ simple_llm.initialize(model_path, *core, config);}protected:- ov::Core core;+ std::optional<ov::Core> core;SimpleLLMPipeline simple_llm;std::string model_path;std::vector<int64_t> input_ids;diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.cppindex 04d02a17f55..9f54d5f32a6 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.cpp@@ -56,7 +56,8 @@ MockCompiledModelBase::MockCompiledModelBase(: ov::ICompiledModel(model, plugin),m_infer_reqs_to_expectations_ptr(infer_reqs_to_expectations_ptr),m_model(model),- m_config(config) {}+ m_config(config),+ m_execution_device(plugin ? plugin->get_device_name() : std::string{}) {}void MockCompiledModelBase::create_implementation() {ON_CALL(*this, inputs()).WillByDefault(testing::ReturnRefOfCopy(m_model->inputs()));@@ -87,6 +88,8 @@ void MockCompiledModelBase::create_implementation() {: ov::streams::Num(1);} else if (name == ov::enable_profiling) {return this->m_config.count(ov::enable_profiling.name()) ? m_config.at(ov::enable_profiling.name()) : false;+ } else if (name == ov::execution_devices) {+ return std::vector<std::string>{m_execution_device};} else {OPENVINO_THROW("get property: " + name);}diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.hppindex 0c79b90f803..502e78f0671 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/mocks/mock_plugins.hpp@@ -97,6 +97,7 @@ private:std::shared_ptr<const ov::Model> m_model;ov::AnyMap m_config;+ std::string m_execution_device;};template<typename DeviceType>diff --git a/src/plugins/intel_npu/tests/unit/npuw/failsafe.cpp b/src/plugins/intel_npu/tests/unit/npuw/failsafe.cppindex d0b0f7db250..9f835fe605c 100644--- a/src/plugins/intel_npu/tests/unit/npuw/failsafe.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/failsafe.cpp@@ -16,6 +16,7 @@#include "v1/elements/failsafe.hpp"#include "openvino/opsets/opset10.hpp"#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/properties.hpp"namespace {@@ -94,9 +95,6 @@ public:void infer() override;ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override;- std::vector<ov::SoPtr<ov::ITensor>> get_tensors(const ov::Output<const ov::Node>& port) const override;- void set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) override;void check_tensors() const override {}std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {return {};@@ -131,6 +129,9 @@ public:if (name == kCandidateProperty) {return m_state->name;}+ if (name == ov::execution_devices.name()) {+ return std::vector<std::string>{m_state->name};+ }OPENVINO_THROW("Unsupported property: ", name);}@@ -200,27 +201,13 @@ void TestInferRequest::set_tensor(const ov::Output<const ov::Node>& port, constov::ISyncInferRequest::set_tensor(port, tensor);}-std::vector<ov::SoPtr<ov::ITensor>> TestInferRequest::get_tensors(const ov::Output<const ov::Node>& port) const {- return ov::ISyncInferRequest::get_tensors(port);-}--void TestInferRequest::set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) {- if (is_input_port(port)) {- for (const auto& tensor : tensors) {- m_state->bound_input_ptrs.push_back(tensor->data());- }- }- ov::ISyncInferRequest::set_tensors(port, tensors);-}-ov::npuw::failsafe::CompiledModel::Factory make_factory(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,std::map<std::string, std::shared_ptr<CandidateState>> states,std::set<std::string> compile_failures = {}) {return [model, plugin, states = std::move(states), compile_failures = std::move(compile_failures)](- const std::string& device) -> std::shared_ptr<ov::ICompiledModel> {+ const std::string& device) -> ov::SoPtr<ov::ICompiledModel> {const auto it = states.find(device);OPENVINO_ASSERT(it != states.end(), "Missing test state for device ", device);@@ -231,7 +218,7 @@ ov::npuw::failsafe::CompiledModel::Factory make_factory(if (compile_failures.count(device) > 0) {OPENVINO_THROW("compile failed for ", state->name);}- return std::make_shared<TestCompiledModel>(model, plugin, state);+ return {std::make_shared<TestCompiledModel>(model, plugin, state), {}};};}@@ -239,16 +226,6 @@ std::string error_message(const ov::Exception& ex) {return ex.what() == nullptr ? std::string{} : std::string(ex.what());}-std::shared_ptr<ov::npuw::failsafe::CompiledModel> make_wrapped_compiled_model(- const std::shared_ptr<ov::Model>& model,- const std::shared_ptr<const ov::IPlugin>& plugin,- std::vector<std::string> devices,- ov::npuw::failsafe::CompiledModel::Factory factory) {- auto compiled = std::make_shared<ov::npuw::failsafe::CompiledModel>(model, plugin, std::move(devices), std::move(factory));- (void)compiled->active_device_name();- return compiled;-}-} // namespaceTEST(FailsafeCompiledModelTest, CompileFailureFallsBackToLaterCandidate) {@@ -258,11 +235,10 @@ TEST(FailsafeCompiledModelTest, CompileFailureFallsBackToLaterCandidate) {auto first = std::make_shared<CandidateState>(CandidateState{"NPU", &events});auto second = std::make_shared<CandidateState>(CandidateState{"CPU", &events});- auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", first}, {"CPU", second}}, {"NPU"})));+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", first}, {"CPU", second}}, {"NPU"}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);ASSERT_NE(compiled, nullptr);EXPECT_EQ(compiled->active_device_name(), "CPU");@@ -277,11 +253,10 @@ TEST(FailsafeCompiledModelTest, CreateInferRequestFailureFallsBackToLaterCandidaauto first = std::make_shared<CandidateState>(CandidateState{"NPU", &events, 1});auto second = std::make_shared<CandidateState>(CandidateState{"CPU", &events});- auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", first}, {"CPU", second}})));+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", first}, {"CPU", second}}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);ASSERT_NE(compiled, nullptr);auto request = compiled->create_sync_infer_request();@@ -299,11 +274,10 @@ TEST(FailsafeCompiledModelTest, InferenceFailureFallsBackAndRebindsTensors) {auto first = std::make_shared<CandidateState>(CandidateState{"NPU", &events, 0, 1, 10.f});auto second = std::make_shared<CandidateState>(CandidateState{"CPU", &events, 0, 0, 20.f});- auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", first}, {"CPU", second}})));+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", first}, {"CPU", second}}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);ASSERT_NE(compiled, nullptr);auto request = compiled->create_sync_infer_request();@@ -334,11 +308,10 @@ TEST(FailsafeCompiledModelTest, UserProvidedOutputBufferReceivesFailoverResult)auto first = std::make_shared<CandidateState>(CandidateState{"NPU", &events, 0, 1, 10.f});auto second = std::make_shared<CandidateState>(CandidateState{"CPU", &events, 0, 0, 20.f});- auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", first}, {"CPU", second}})));+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", first}, {"CPU", second}}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);ASSERT_NE(compiled, nullptr);auto request = compiled->create_sync_infer_request();@@ -369,20 +342,18 @@ TEST(FailsafeCompiledModelTest, ChainedInferenceSurvivesUpstreamAndDownstreamFaistd::vector<std::string> first_events;auto first_npu = std::make_shared<CandidateState>(CandidateState{"NPU", &first_events, 0, 1, 10.f});auto first_cpu = std::make_shared<CandidateState>(CandidateState{"CPU", &first_events, 0, 0, 20.f});- auto first_compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", first_npu}, {"CPU", first_cpu}})));+ auto first_so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", first_npu}, {"CPU", first_cpu}}));+ auto first_compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(first_so._ptr);std::vector<std::string> second_events;auto second_npu = std::make_shared<CandidateState>(CandidateState{"NPU", &second_events, 0, 1, 1.f});auto second_cpu = std::make_shared<CandidateState>(CandidateState{"CPU", &second_events, 0, 0, 2.f});- auto second_compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(ov::npuw::failsafe::CompiledModel::create(- model,- plugin,- {"NPU", "CPU"},- make_factory(model, plugin, {{"NPU", second_npu}, {"CPU", second_cpu}})));+ auto second_so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", second_npu}, {"CPU", second_cpu}}));+ auto second_compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(second_so._ptr);ASSERT_NE(first_compiled, nullptr);ASSERT_NE(second_compiled, nullptr);@@ -418,14 +389,14 @@ TEST(FailsafeCompiledModelTest, CompileFailureWithoutFallbackPropagatesError) {auto first = std::make_shared<CandidateState>(CandidateState{"NPU"});try {- (void)make_wrapped_compiled_model(+ (void)ov::npuw::failsafe::CompiledModel::create(model,plugin,{"NPU"},make_factory(model, plugin, {{"NPU", first}}, {"NPU"}));FAIL() << "Expected compile failure";} catch (const ov::Exception& ex) {- EXPECT_NE(error_message(ex).find("Failsafe compile fallback exhausted"), std::string::npos);+ EXPECT_NE(error_message(ex).find("compile failed for NPU"), std::string::npos);}}@@ -434,17 +405,17 @@ TEST(FailsafeCompiledModelTest, CreateInferRequestFailureWithoutFallbackPropagatauto plugin = std::make_shared<NullPlugin>();auto first = std::make_shared<CandidateState>(CandidateState{"NPU", nullptr, 1});- auto compiled = make_wrapped_compiled_model(- model,- plugin,- {"NPU"},+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU"},make_factory(model, plugin, {{"NPU", first}}));+ auto compiled = so._ptr;+ ASSERT_NE(compiled, nullptr);try {- (void)compiled->create_sync_infer_request();+ (void)compiled->create_infer_request();FAIL() << "Expected infer-request creation failure";} catch (const ov::Exception& ex) {- EXPECT_NE(error_message(ex).find("Failsafe infer-request creation fallback exhausted"), std::string::npos);+ EXPECT_NE(error_message(ex).find("create request failed for NPU"), std::string::npos);}}@@ -453,17 +424,68 @@ TEST(FailsafeCompiledModelTest, InferFailureWithoutFallbackPropagatesError) {auto plugin = std::make_shared<NullPlugin>();auto first = std::make_shared<CandidateState>(CandidateState{"NPU", nullptr, 0, 1});- auto compiled = make_wrapped_compiled_model(- model,- plugin,- {"NPU"},+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU"},make_factory(model, plugin, {{"NPU", first}}));- auto request = compiled->create_sync_infer_request();+ auto compiled = so._ptr;+ ASSERT_NE(compiled, nullptr);+ auto request = compiled->create_infer_request();try {request->infer();FAIL() << "Expected inference failure";} catch (const ov::Exception& ex) {- EXPECT_NE(error_message(ex).find("Failsafe infer fallback exhausted"), std::string::npos);+ EXPECT_NE(error_message(ex).find("infer failed for NPU"), std::string::npos);}}++TEST(FailsafeCompiledModelTest, SingleDeviceReturnsRawCompiledModel) {+ auto model = make_test_model();+ auto plugin = std::make_shared<NullPlugin>();+ auto first = std::make_shared<CandidateState>(CandidateState{"CPU"});++ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"CPU"},+ make_factory(model, plugin, {{"CPU", first}}));++ EXPECT_EQ(std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr), nullptr);+ ASSERT_NE(so._ptr, nullptr);+ EXPECT_EQ(so->get_property(kCandidateProperty).as<std::string>(), "CPU");+ auto devices = so->get_property(ov::execution_devices.name()).as<std::vector<std::string>>();+ EXPECT_EQ(devices, (std::vector<std::string>{"CPU"}));+}++TEST(FailsafeCompiledModelTest, ExecutionDevicesReturnsActiveDevice) {+ auto model = make_test_model();+ auto plugin = std::make_shared<NullPlugin>();+ auto npu = std::make_shared<CandidateState>(CandidateState{"NPU"});+ auto cpu = std::make_shared<CandidateState>(CandidateState{"CPU"});++ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", npu}, {"CPU", cpu}}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);++ ASSERT_NE(compiled, nullptr);+ EXPECT_EQ(compiled->active_device_name(), "NPU");+ auto devices = compiled->get_property(ov::execution_devices.name()).as<std::vector<std::string>>();+ EXPECT_EQ(devices, (std::vector<std::string>{"NPU"}));+}++TEST(FailsafeCompiledModelTest, ExecutionDevicesUpdatesAfterFailover) {+ auto model = make_test_model();+ auto plugin = std::make_shared<NullPlugin>();+ auto npu = std::make_shared<CandidateState>(CandidateState{"NPU"});+ auto cpu = std::make_shared<CandidateState>(CandidateState{"CPU"});++ // NPU compile fails → failsafe falls back to CPU at creation time.+ auto so = ov::npuw::failsafe::CompiledModel::create(+ model, plugin, {"NPU", "CPU"},+ make_factory(model, plugin, {{"NPU", npu}, {"CPU", cpu}}, {"NPU"}));+ auto compiled = std::dynamic_pointer_cast<ov::npuw::failsafe::CompiledModel>(so._ptr);++ ASSERT_NE(compiled, nullptr);+ EXPECT_EQ(compiled->active_device_name(), "CPU");+ auto devices = compiled->get_property(ov::execution_devices.name()).as<std::vector<std::string>>();+ EXPECT_EQ(devices, (std::vector<std::string>{"CPU"}));+}diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cppindex 0cd2ba34579..db183991ad0 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp@@ -15,6 +15,7 @@#include "llm_test_helpers.hpp"#include "whisper/prepare_whisper_model.hpp"#include "openvino/pass/stateful_to_stateless.hpp"+#include "unit_test_utils/mocks/openvino/runtime/mock_icore.hpp"namespace {using ov::test::npuw::CompileCall;@@ -324,7 +325,7 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, CommonRuntimeAndDebugOptionsForwardTo}}-TEST_F(LLMCompiledModelFactoryOptionsTest, FastCompileGenerateHintKeepsUnfoldedGenerateDefaults) {+TEST_F(LLMCompiledModelFactoryOptionsTest, FastCompileGenerateHintKeepsCurrentGenerateDefaults) {RecordingFactory recorder;std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;@@ -335,9 +336,32 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, FastCompileGenerateHintKeepsUnfoldedGASSERT_NE(compiled, nullptr);const auto& generate = require_call_containing(recorder, "_kv");expect_prop(generate.props, "NPUW_UNFOLD_IREQS", "YES");+ expect_prop(generate.props, "NPUW_DQ", "YES");expect_missing_prop(generate.props, "NPUW_SLICE_OUT");}+TEST_F(LLMCompiledModelFactoryOptionsTest, MissingNpuBackendKeepsCurrentGenerateDefaults) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ auto core = std::make_shared<testing::NiceMock<ov::MockICore>>();+ m_plugin->set_core(core);+ ON_CALL(*core, get_property(testing::StrEq("NPU"), testing::StrEq(ov::available_devices.name()), testing::_))+ .WillByDefault([](const std::string&, const std::string&, const ov::AnyMap&) -> ov::Any {+ OPENVINO_THROW("No available backend");+ });++ ASSERT_NO_THROW(compiled = create_compiled_model(build_llm_model(),+ {{"NPUW_LLM_SHARED_HEAD", "NO"},+ {"NPUW_LLM_GENERATE_HINT", "FAST_COMPILE"}},+ recorder));+ ASSERT_NE(compiled, nullptr);++ const auto& generate = require_call_containing(recorder, "_kv");+ expect_prop(generate.props, "NPUW_UNFOLD_IREQS", "YES");+ expect_prop(generate.props, "NPUW_DQ", "YES");+}+TEST_F(LLMCompiledModelFactoryOptionsTest, BestPerfGenerateHintForcesStandaloneGeneratePartitioning) {RecordingFactory recorder;std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;