Skip to content

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

[NPU] Add support of VM runtime 2.0 API (#37159)

Xin Wang36980725bbb0
diff --git a/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp b/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
index 7df9045df5d..e329e3a4bb6 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
@@ -6,6 +6,7 @@
#include "intel_npu/common/network_metadata.hpp"
#include "intel_npu/utils/vm/mem_ref_type.hpp"
+#include "intel_npu/utils/vm/npu_vm_runtime_utils.hpp"
#include "zero_pipeline.hpp"
namespace intel_npu {
@@ -22,13 +23,25 @@ struct VMExecutionContext {
VMExecutionContext& operator=(VMExecutionContext&&) = delete;
~VMExecutionContext();
- // Create the context for vmRuntime if not created yet; returns the handle.
npu_vm_runtime_execution_context_handle_t ensure(npu_vm_runtime_handle_t vmRuntime);
+ npu_vm_runtime_execution_context_handle_t ensureV2(npu_vm_runtime_handle_t vmRuntime,
+ ze_context_handle_t ctx,
+ ze_device_handle_t device,
+ ze_command_queue_handle_t commandQueue,
+ ze_graph_dditable_ext_t* graphDdiTableExt,
+ ze_command_queue_npu_dditable_ext_t* queueDdiTableExt);
+ npu_vm_runtime_execution_context_handle_t handle() const {
+ return _handle;
+ }
};
struct DynamicArguments {
std::vector<MemRefType> _inputsMemRef;
std::vector<MemRefType> _outputsMemRef;
+ // These handles need be stored to ensure the memory they reference remains valid when we call HostSync function
+ std::vector<npu_vm_runtime_mem_ref_handle_t> _inputMemRefHandles;
+ std::vector<npu_vm_runtime_mem_ref_handle_t> _outputMemRefHandles;
+ npu_vm_runtime_execute_params2_t _executeParams2 = {};
// True once the command lists have been recorded by a first npuVMRuntimeExecute call. Subsequent
// executions can be replayed without re-recording when no tensor changed (see execute_vm_runtime).
@@ -55,27 +68,24 @@ class DynamicPipeline final : public IPipeline {
// Store command list handles to pass it to ExecutionEngine
std::vector<ze_command_list_handle_t> _commandListHandles;
- PipelinedCommandLists(size_t numCommandLists, const std::shared_ptr<ZeroInitStructsHolder>& init_structs) {
- _commandLists.reserve(numCommandLists);
- for (size_t i = 0; i < numCommandLists; i++) {
- _commandLists.emplace_back(std::make_unique<CommandList>(init_structs));
- }
+ PipelinedCommandLists(size_t numCommandLists,
+ const std::shared_ptr<ZeroInitStructsHolder>& init_structs,
+ bool useV2 = false) {
+ if (!useV2) {
+ // Only initialize command lists for v1, v2 handles command lists inside runtime
+ _commandLists.reserve(numCommandLists);
+ for (size_t i = 0; i < numCommandLists; i++) {
+ _commandLists.emplace_back(std::make_unique<CommandList>(init_structs));
+ }
- for (size_t i = 0; i < numCommandLists; i++) {
- _commandListHandles.push_back(_commandLists[i]->handle());
+ for (size_t i = 0; i < numCommandLists; i++) {
+ _commandListHandles.push_back(_commandLists[i]->handle());
+ }
}
_arguments = std::make_shared<DynamicArguments>();
}
- size_t size() const {
- return _commandListHandles.size();
- }
-
- ze_command_list_handle_t* data() {
- return _commandListHandles.data();
- }
-
// Use metadata to initialize, which will later be updated again by setArgumentProperties
void initArguments(const NetworkMetadata& metadata) {
_arguments->_inputsMemRef.resize(metadata.inputs.size());
@@ -84,9 +94,7 @@ class DynamicPipeline final : public IPipeline {
// Use size as placeholder of stride
// For now, only considering the usage and subsequent comparison of shape, and strides
const auto& shape = metadata.inputs[i].shapeFromCompiler.get_shape();
- inputs[i]._dimsCount = static_cast<int64_t>(shape.size());
- inputs[i]._sizes.assign(shape.begin(), shape.end());
- inputs[i]._strides.resize(shape.size());
+ inputs[i].setSize(shape);
inputs[i].updateStride();
}
@@ -94,9 +102,7 @@ class DynamicPipeline final : public IPipeline {
auto& outputs = _arguments->_outputsMemRef;
for (size_t i = 0; i < outputs.size(); ++i) {
const auto& shape = metadata.outputs[i].shapeFromCompiler.get_shape();
- outputs[i]._dimsCount = static_cast<int64_t>(shape.size());
- outputs[i]._sizes.assign(shape.begin(), shape.end());
- outputs[i]._strides.resize(shape.size());
+ outputs[i].setSize(shape);
outputs[i].updateStride();
}
}
@@ -164,9 +170,19 @@ private:
ze_command_queue_handle_t commandQueue,
ze_fence_handle_t fence,
ze_event_handle_t event);
+ void execute_vm_runtime_v2(npu_vm_runtime_handle_t vmRuntime,
+ DynamicArguments& args,
+ ze_command_queue_handle_t commandQueue,
+ const npu_vm_runtime_config_desc_t* pConfig);
+ const npu_vm_runtime_config_desc_t* update_runtime_config(const CommandQueueDesc& previousCommandQueueDesc,
+ const CommandQueueDesc& currentCommandQueueDesc);
// VM execution context owned by this pipeline; shared between shape prediction and execution.
VMExecutionContext _executionContext;
+ npu_vm_runtime_version_t _apiVersion = NPU_VM_RUNTIME_VERSION_1_0;
+ NpuVMRuntimeConfigChain _runtimeConfigChain;
+ CommandQueueDesc _runtime_config_command_queue_desc;
+ bool _runtime_config_command_queue_desc_valid = false;
std::unique_ptr<PipelinedCommandLists> _command_list_group;
};
diff --git a/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
index e0c543253ed..9023eef7b8d 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
@@ -23,11 +23,9 @@
#include "zero_infer_request.hpp"
namespace intel_npu {
+
struct MemRefTypeImpl {
npu_vm_runtime_mem_ref_handle_t _memRef;
- bool _ptrUpdated = false;
- bool _shapeUpdated = false;
- bool _strideUpdated = false;
MemRefTypeImpl() : _memRef(nullptr) {}
@@ -51,60 +49,40 @@ struct MemRefTypeImpl {
}
}
- void UpdateMemRefHandleStatus(MemRefType& memref) {
+ bool UpdateMemRefHandleStatus(MemRefType& memref, bool useV2Api = false) {
// Update current MemRef handle to use latest metadata
+ bool newMemRefHandleCreated = false;
if (_memRef == nullptr) {
createMemRef(memref._dimsCount);
- } else {
- // Create a temporary MemRefType based on current handle and compare, use arg to create right size
- MemRefType tempMemRef(memref._basePtr,
- memref._data,
- memref._offset,
- memref._sizes,
- memref._strides,
- memref._dimsCount);
- alignWithHandle(tempMemRef);
- // Check ptr
- if (memref._basePtr != tempMemRef._basePtr || memref._data != tempMemRef._data ||
- memref._offset != tempMemRef._offset) {
- _ptrUpdated = true;
- } else {
- _ptrUpdated = false;
- }
-
- // Check shape
- if (memref._sizes != tempMemRef._sizes) {
- _shapeUpdated = true;
- } else {
- _shapeUpdated = false;
- }
-
- // Check strides
- if (memref._strides != tempMemRef._strides) {
- _strideUpdated = true;
- } else {
- _strideUpdated = false;
- }
+ newMemRefHandleCreated = true;
}
- auto result = npuVMRuntimeSetMemRef(_memRef,
- memref._basePtr,
- memref._data,
- memref._offset,
- memref._sizes.data(),
- memref._strides.data(),
- memref._dimsCount);
- if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to update MemRef handle");
+ // Determine the dirty flag based on whether a new MemRef handle was created or existing metadata was modified.
+ const uint32_t dirtyFlag = newMemRefHandleCreated ? MemRefType::ALL_DIRTY : memref.getDirtyFlag();
+ if (dirtyFlag != 0) {
+ // V2 runtime accepts nullptr for metadata fields that were not changed.
+ const auto sizes = useV2Api && !(dirtyFlag & MemRefType::SHAPE_DIRTY) ? nullptr : memref._sizes.data();
+ const auto strides = useV2Api && !(dirtyFlag & MemRefType::STRIDE_DIRTY) ? nullptr : memref._strides.data();
+ auto result = npuVMRuntimeSetMemRef(_memRef,
+ memref._basePtr,
+ memref._data,
+ memref._offset,
+ sizes,
+ strides,
+ memref._dimsCount);
+ if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
+ memref.markDirty(dirtyFlag);
+ OPENVINO_THROW("Failed to update MemRef handle");
+ }
+ memref.clearDirty();
}
+ return dirtyFlag != 0;
}
private:
void createMemRef(int64_t dimsCount) {
if (_memRef == nullptr) {
auto result = npuVMRuntimeCreateMemRef(dimsCount, &_memRef);
- if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to create MemRef handle");
- }
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS, "Failed to create MemRef handle");
}
}
@@ -125,9 +103,27 @@ VMExecutionContext::~VMExecutionContext() {
npu_vm_runtime_execution_context_handle_t VMExecutionContext::ensure(npu_vm_runtime_handle_t vmRuntime) {
if (_handle == nullptr) {
- if (npuVMRuntimeCreateExecutionContext(vmRuntime, &_handle) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to create a VM execution context");
- }
+ const npu_vm_runtime_result_t result = npuVMRuntimeCreateExecutionContext(vmRuntime, &_handle);
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS, "Failed to create a VM execution context");
+ }
+ return _handle;
+}
+
+npu_vm_runtime_execution_context_handle_t VMExecutionContext::ensureV2(
+ npu_vm_runtime_handle_t vmRuntime,
+ ze_context_handle_t ctx,
+ ze_device_handle_t device,
+ ze_command_queue_handle_t commandQueue,
+ ze_graph_dditable_ext_t* graphDdiTableExt,
+ ze_command_queue_npu_dditable_ext_t* queueDdiTableExt) {
+ if (_handle == nullptr) {
+ npu_vm_runtime_create_execution_context_params_t params = {ctx,
+ device,
+ commandQueue,
+ graphDdiTableExt,
+ queueDdiTableExt};
+ const npu_vm_runtime_result_t result = npuVMRuntimeCreateExecutionContext2(vmRuntime, &params, &_handle);
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS, "Failed to create a VM execution context (v2)");
}
return _handle;
}
@@ -138,26 +134,14 @@ void DynamicArguments::setArgumentProperties(uint32_t argi,
const ov::Shape& sizes,
const std::vector<size_t>& strides) {
auto assign_slot = [&](MemRefType& slot) {
- slot._basePtr = slot._data = const_cast<void*>(argv);
- if (slot._dimsCount == 0) {
- slot._dimsCount = static_cast<int64_t>(sizes.size());
- slot._sizes.resize(sizes.size());
- slot._strides.resize(strides.size());
- } else if (slot._dimsCount != static_cast<int64_t>(sizes.size())) {
- OPENVINO_THROW("Dimension count mismatch. Current dimension count: ",
- slot._dimsCount,
- ", new dimension count: ",
- sizes.size());
- } else if (strides.size() != static_cast<size_t>(sizes.size())) {
- OPENVINO_THROW("Updated shape and stride count mismatch: shape rank and stride count differ. Shape rank: ",
- sizes.size(),
- ", stride count: ",
- strides.size());
- }
- for (int64_t i = 0; i < slot._dimsCount; i++) {
- slot._sizes[i] = static_cast<int64_t>(sizes[i]);
- slot._strides[i] = static_cast<int64_t>(strides[i]);
- }
+ OPENVINO_ASSERT(strides.size() == sizes.size(),
+ "Updated shape and stride count mismatch: shape rank and stride count differ. Shape rank: ",
+ sizes.size(),
+ ", stride count: ",
+ strides.size());
+ slot.setArg(argv);
+ slot.setSize(sizes);
+ slot.setStrides(ov::Strides(strides));
};
if (argi < _inputsMemRef.size()) {
@@ -182,20 +166,48 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& i
_logger.debug("Initialization started");
- if (!_sync_output_with_fences) {
+ const auto versionResult = npuVMRuntimeGetAPIVersion(&_apiVersion);
+ OPENVINO_ASSERT(versionResult == NPU_VM_RUNTIME_RESULT_SUCCESS,
+ "Failed to get VM runtime version, error code: ",
+ versionResult);
+
+ // v2 lets the runtime manage command-list recording and execution-context setup;
+ // v1 requires the plugin to create the execution context and provide command lists.
+ if (use_npu_vm_runtime_v2_api(_apiVersion)) {
+ _logger.debug("DynamicPipeline: using v2.0 VM runtime API");
+ const npu_vm_runtime_handle_t vmRuntime = static_cast<npu_vm_runtime_handle_t>(_graph->get_handle());
+ const auto commandQueueDesc = _graph->get_command_queue_desc();
+ _executionContext.ensureV2(vmRuntime,
+ init_structs->getContext(),
+ init_structs->getDevice(),
+ commandQueueDesc.shared_common_queue() ? _command_queue->handle() : nullptr,
+ _init_structs->getGraphDdiTable().getImpl(),
+ _init_structs->getCommandQueueDdiTable().getImpl());
+ _runtime_config_command_queue_desc = commandQueueDesc;
+ _runtime_config_command_queue_desc_valid = true;
+ } else {
+ _logger.debug("DynamicPipeline: using v1.x VM runtime API");
+ const npu_vm_runtime_handle_t vmRuntime = static_cast<npu_vm_runtime_handle_t>(_graph->get_handle());
+ _executionContext.ensure(vmRuntime);
+ }
+
+ // v2 synchronizes through npuVMRuntimeHostSync, so only v1 needs plugin-side
+ // events or fences for output synchronization.
+ if (!use_npu_vm_runtime_v2_api(_apiVersion) && !_sync_output_with_fences) {
_event_pool = std::make_shared<EventPool>(_init_structs, 1);
_events.emplace_back(std::make_shared<Event>(_event_pool, 0));
}
_logger.debug("Event pool and command queue setup completed");
const uint64_t num_of_subgraphs = _graph->get_metadata().numberOfSubgraphs;
-
- _command_list_group = std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs);
-
- if (_sync_output_with_fences) {
+ if (!use_npu_vm_runtime_v2_api(_apiVersion) && _sync_output_with_fences) {
_fences.emplace_back(std::make_unique<Fence>(_command_queue));
}
+ _command_list_group = std::make_unique<PipelinedCommandLists>(num_of_subgraphs,
+ _init_structs,
+ use_npu_vm_runtime_v2_api(_apiVersion));
+
auto& commandLists = _command_list_group;
commandLists->initArguments(_graph->get_metadata());
auto& dynamicArguments = commandLists->getArguments();
@@ -240,10 +252,27 @@ void DynamicPipeline::push() {
const npu_vm_runtime_handle_t vmRuntime = static_cast<npu_vm_runtime_handle_t>(_graph->get_handle());
OPENVINO_ASSERT(vmRuntime != nullptr, "DynamicPipeline requires a valid VM runtime engine");
- const auto command_queue_desc = _graph->get_command_queue_desc();
- const bool command_queue_version_changed = (command_queue_desc.key() != _command_queue->desc().key());
- if (command_queue_version_changed) {
- _command_queue = ZeroCmdQueuePool::getInstance().getCommandQueue(_init_structs, command_queue_desc);
+ // v2 passes queue property changes as runtime config descriptors (and only
+ // refreshes the queue handle when a shared queue changes); v1 recreates the
+ // plugin-owned queue and, when needed, its fences.
+ const auto useV2Api = use_npu_vm_runtime_v2_api(_apiVersion);
+ const auto commandQueueDesc = _graph->get_command_queue_desc();
+ const bool commandQueueVersionChanged = (commandQueueDesc.key() != _command_queue->desc().key());
+
+ const npu_vm_runtime_config_desc_t* runtimeConfig = nullptr;
+ if (useV2Api) {
+ if (commandQueueVersionChanged && commandQueueDesc.shared_common_queue()) {
+ _command_queue = ZeroCmdQueuePool::getInstance().getCommandQueue(_init_structs, commandQueueDesc);
+ }
+
+ if (_runtime_config_command_queue_desc_valid) {
+ runtimeConfig = update_runtime_config(_runtime_config_command_queue_desc, commandQueueDesc);
+ } else {
+ _runtime_config_command_queue_desc = commandQueueDesc;
+ _runtime_config_command_queue_desc_valid = true;
+ }
+ } else if (commandQueueVersionChanged) {
+ _command_queue = ZeroCmdQueuePool::getInstance().getCommandQueue(_init_structs, commandQueueDesc);
if (_sync_output_with_fences) {
for (size_t i = 0; i < _fences.size(); i++) {
@@ -252,8 +281,9 @@ void DynamicPipeline::push() {
}
}
+ const auto commandQueueHandle =
+ useV2Api && !commandQueueDesc.shared_common_queue() ? nullptr : _command_queue->handle();
OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PUSH, itt::domains::LevelZeroBackend, "Pipeline", "push");
- const ze_fence_handle_t fence = _sync_output_with_fences ? _fences.front()->handle() : nullptr;
auto& commandLists = _command_list_group;
auto& dynamicArguments = commandLists->getArguments();
if (_logger.level() >= ov::log::Level::DEBUG) {
@@ -267,16 +297,40 @@ void DynamicPipeline::push() {
}
}
- execute_vm_runtime(vmRuntime,
- dynamicArguments,
- commandLists->getHandles(),
- _command_queue->handle(),
- fence,
- nullptr);
+ // Keep the v2 execute parameters in DynamicArguments because HostSync uses
+ // the same parameter structure after push() returns.
+ if (useV2Api) {
+ execute_vm_runtime_v2(vmRuntime, dynamicArguments, commandQueueHandle, runtimeConfig);
+ _runtime_config_command_queue_desc = commandQueueDesc;
+ _runtime_config_command_queue_desc_valid = true;
+ } else {
+ const ze_fence_handle_t fence = _sync_output_with_fences ? _fences.front()->handle() : nullptr;
+ execute_vm_runtime(vmRuntime, dynamicArguments, commandLists->getHandles(), commandQueueHandle, fence, nullptr);
+ }
_logger.debug("push - completed");
}
+const npu_vm_runtime_config_desc_t* DynamicPipeline::update_runtime_config(
+ const CommandQueueDesc& previousCommandQueueDesc,
+ const CommandQueueDesc& currentCommandQueueDesc) {
+ _runtimeConfigChain.clear();
+ if (previousCommandQueueDesc.priority() != currentCommandQueueDesc.priority()) {
+ _runtimeConfigChain.append(NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY,
+ static_cast<npu_vm_runtime_config_value_t>(currentCommandQueueDesc.priority()));
+ }
+ if (previousCommandQueueDesc.workload() != currentCommandQueueDesc.workload() &&
+ currentCommandQueueDesc.workload().has_value()) {
+ _runtimeConfigChain.append(
+ NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE,
+ static_cast<npu_vm_runtime_config_value_t>(currentCommandQueueDesc.workload().value()));
+ }
+ if (previousCommandQueueDesc.options() != currentCommandQueueDesc.options()) {
+ _runtimeConfigChain.append(NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS, currentCommandQueueDesc.options());
+ }
+ return _runtimeConfigChain.head();
+}
+
void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,
DynamicArguments& args,
std::vector<ze_command_list_handle_t>& commandLists,
@@ -303,12 +357,12 @@ void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,
impl = std::make_shared<MemRefTypeImpl>();
memref._impl = impl;
}
- impl->UpdateMemRefHandleStatus(memref);
+ const bool memRefUpdated = impl->UpdateMemRefHandleStatus(memref);
// VM runtime execute path always needs current memref handles.
targetMemRefHandles.push_back(impl->_memRef);
- if (impl->_ptrUpdated || impl->_shapeUpdated || impl->_strideUpdated) {
+ if (memRefUpdated) {
noTensorChange = false;
}
}
@@ -323,9 +377,7 @@ void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,
static_cast<uint32_t>(commandLists.size()),
commandLists.data(),
fence);
- if (result != ZE_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to submit command lists");
- }
+ OPENVINO_ASSERT(result == ZE_RESULT_SUCCESS, "Failed to submit command lists");
return;
}
@@ -334,9 +386,7 @@ void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,
// list with update
for (auto& cmdList : commandLists) {
const auto result = zeCommandListReset(cmdList);
- if (result != ZE_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to reset command list");
- }
+ OPENVINO_ASSERT(result == ZE_RESULT_SUCCESS, "Failed to reset command list");
}
npu_vm_runtime_execute_params_t params = {};
@@ -355,15 +405,60 @@ void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,
params.event = event;
_logger.debug("Execute graph with runtime engine");
- if (npuVMRuntimeExecute(vmRuntime, &params) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to execute VM runtime engine");
- }
+ const auto result = npuVMRuntimeExecute(vmRuntime, &params);
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS,
+ "Failed to execute VM runtime engine, error code: ",
+ result);
_logger.debug("Execution runtime engine is created successfully.");
args._commandListsRecorded = true;
_logger.debug("Completed to execute graph with runtime engine");
}
+void DynamicPipeline::execute_vm_runtime_v2(npu_vm_runtime_handle_t vmRuntime,
+ DynamicArguments& args,
+ ze_command_queue_handle_t commandQueue,
+ const npu_vm_runtime_config_desc_t* pConfig) {
+ _logger.debug("execute_vm_runtime_v2 - started");
+
+ // Keep these arrays in DynamicArguments: the v2 execute parameters are reused
+ // by HostSync after this function returns, so their pInputs/pOutputs pointers
+ // must remain valid until synchronization completes.
+ auto processMemRefs = [&](auto& memRefs, auto& targetHandles) {
+ targetHandles.clear();
+ targetHandles.reserve(memRefs.size());
+ for (auto& memref : memRefs) {
+ auto impl = std::static_pointer_cast<MemRefTypeImpl>(memref._impl);
+ if (impl == nullptr) {
+ impl = std::make_shared<MemRefTypeImpl>();
+ memref._impl = impl;
+ }
+ impl->UpdateMemRefHandleStatus(memref, true);
+ targetHandles.push_back(impl->_memRef);
+ }
+ };
+
+ processMemRefs(args._inputsMemRef, args._inputMemRefHandles);
+ processMemRefs(args._outputsMemRef, args._outputMemRefHandles);
+
+ auto& params = args._executeParams2;
+ params.commandQueue = commandQueue;
+ params.pConfig = pConfig;
+ params.pInputs = args._inputMemRefHandles.data();
+ params.numOfInputs = static_cast<uint32_t>(args._inputMemRefHandles.size());
+ params.pOutputs = args._outputMemRefHandles.data();
+ params.numOfOutputs = static_cast<uint32_t>(args._outputMemRefHandles.size());
+ params.executionContext = _executionContext.handle();
+
+ _logger.debug("execute_vm_runtime_v2 - calling npuVMRuntimeExecute2");
+ const auto result = npuVMRuntimeExecute2(vmRuntime, &params);
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS,
+ "Failed to execute VM runtime engine (v2), error code: ",
+ result);
+
+ _logger.debug("execute_vm_runtime_v2 - completed");
+}
+
std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
const std::vector<std::shared_ptr<ov::ITensor>>& inputTensors,
const std::vector<std::shared_ptr<ov::ITensor>>& outputTensors) {
@@ -391,7 +486,7 @@ std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
} else {
// If all tensors are not set, use metadata
memRefs[i].setArg(nullptr);
- memRefs[i]._offset = 0;
+ memRefs[i].setOffset(0);
// TODO : BatchSize not checked here
memRefs[i].setSize(descriptors.at(i).shapeFromCompiler.get_max_shape());
memRefs[i].updateStride();
@@ -418,7 +513,7 @@ std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
impl = std::make_shared<MemRefTypeImpl>();
memref._impl = impl;
}
- impl->UpdateMemRefHandleStatus(memref);
+ impl->UpdateMemRefHandleStatus(memref, use_npu_vm_runtime_v2_api(_apiVersion));
destMemRefHandles.push_back(impl->_memRef);
}
};
@@ -427,13 +522,9 @@ std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
processMemRefs(outputsMemRefs, outputMemRefHandles);
npu_vm_runtime_result_t result = NPU_VM_RUNTIME_RESULT_SUCCESS;
- npu_vm_runtime_version_t version{};
- if ((result = npuVMRuntimeGetAPIVersion(&version)) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to get VM runtime version, error code: ", result);
- }
- _logger.debug("VM runtime version: %u.%u", ZE_MAJOR_VERSION(version), ZE_MINOR_VERSION(version));
+ _logger.debug("VM runtime version: %u.%u", ZE_MAJOR_VERSION(_apiVersion), ZE_MINOR_VERSION(_apiVersion));
- if (version == NPU_VM_RUNTIME_VERSION_1_0) {
+ if (_apiVersion == NPU_VM_RUNTIME_VERSION_1_0) {
npu_vm_runtime_predict_output_shape_params_t params{};
params.pInputs = inputMemRefHandles.data();
params.numOfInputs = static_cast<uint32_t>(inputMemRefHandles.size());
@@ -447,21 +538,28 @@ std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
params.numOfInputs = static_cast<uint32_t>(inputMemRefHandles.size());
params.pOutputs = outputMemRefHandles.data();
params.numOfOutputs = static_cast<uint32_t>(outputMemRefHandles.size());
- params.executionContext = _executionContext.ensure(vmRuntime);
+ if (use_npu_vm_runtime_v2_api(_apiVersion)) {
+ const auto commandQueueDesc = _graph->get_command_queue_desc();
+ if (commandQueueDesc.shared_common_queue() && commandQueueDesc.key() != _command_queue->desc().key()) {
+ _command_queue = ZeroCmdQueuePool::getInstance().getCommandQueue(_init_structs, commandQueueDesc);
+ }
+ }
+ params.executionContext =
+ use_npu_vm_runtime_v2_api(_apiVersion) ? _executionContext.handle() : _executionContext.ensure(vmRuntime);
result = npuVMRuntimePredictOutputShape2(vmRuntime, &params);
}
- if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
- OPENVINO_THROW("Failed to predict output shape with VM runtime engine, error code: ", result);
- } else {
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS,
+ "Failed to predict output shape with VM runtime engine, error code: ",
+ result);
+ {
for (size_t i = 0; i < outputsMemRefs.size(); ++i) {
auto& out = outputsMemRefs[i];
auto outImpl = std::static_pointer_cast<MemRefTypeImpl>(out._impl);
- if (outImpl == nullptr) {
- OPENVINO_THROW("MemRefType implementation is broken, unknown error happens in shape prediction.");
- }
+ OPENVINO_ASSERT(outImpl != nullptr,
+ "MemRefType implementation is broken, unknown error happens in shape prediction.");
outImpl->alignWithHandle(out);
}
_logger.debug("Output shape prediction is done successfully.");
@@ -502,7 +600,16 @@ void DynamicPipeline::pull() {
_logger.debug("pull - started");
OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PULL, itt::domains::LevelZeroBackend, "DynamicPipeline", "pull");
- if (_sync_output_with_fences) {
+ const npu_vm_runtime_handle_t vmRuntime =
+ use_npu_vm_runtime_v2_api(_apiVersion) ? static_cast<npu_vm_runtime_handle_t>(_graph->get_handle()) : nullptr;
+
+ // v2 exposes host synchronization through the runtime; v1 completes through
+ // the event or fence created by the plugin.
+ if (use_npu_vm_runtime_v2_api(_apiVersion)) {
+ auto& dynamicArguments = _command_list_group->getArguments();
+ const auto result = npuVMRuntimeHostSync(vmRuntime, &dynamicArguments._executeParams2);
+ OPENVINO_ASSERT(result == NPU_VM_RUNTIME_RESULT_SUCCESS, "npuVMRuntimeHostSync failed, error code: ", result);
+ } else if (_sync_output_with_fences) {
_fences.front()->hostSynchronize();
} else {
_events.front()->hostSynchronize();
@@ -517,10 +624,12 @@ void DynamicPipeline::pull() {
void DynamicPipeline::reset() const {
_logger.debug("reset - started");
- if (_sync_output_with_fences) {
- _fences.front()->reset();
- } else {
- _events.front()->reset();
+ if (!use_npu_vm_runtime_v2_api(_apiVersion)) {
+ if (_sync_output_with_fences) {
+ _fences.front()->reset();
+ } else {
+ _events.front()->reset();
+ }
}
_logger.debug("reset - completed");
}
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
index 53862a1fb35..c08eed812f2 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
@@ -60,8 +60,8 @@ private:
void initialize_impl(const FilteredConfig& config) override;
bool release_blob(const FilteredConfig& config);
- void initialize_engine();
- void create_execution_engine();
+ void initialize_engine(const FilteredConfig& config);
+ void create_execution_engine(const FilteredConfig& config);
void prepare_metadata();
std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
@@ -91,6 +91,7 @@ private:
npu_vm_runtime_handle_t _engine = nullptr;
npu_vm_runtime_properties_t _engineProperties{};
+ npu_vm_runtime_version_t _apiVersion = NPU_VM_RUNTIME_VERSION_1_0;
bool _engineInitialized = false;
};
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
index 595e62ea358..0c0e5f1dd8f 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
@@ -4,7 +4,6 @@
#include "dynamic_graph.hpp"
-#include <array>
#include <iterator>
#include <ostream>
@@ -12,18 +11,56 @@
#include "intel_npu/config/options.hpp"
#include "intel_npu/prefix.hpp"
#include "intel_npu/utils/utils.hpp"
+#include "intel_npu/utils/vm/npu_vm_runtime_utils.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_cmd_queue_pool.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
namespace intel_npu {
-void DynamicGraph::create_execution_engine() {
+namespace {
+void populateRuntimeConfigChain(NpuVMRuntimeConfigChain& configChain, const FilteredConfig& config) {
+ configChain.append(
+ NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY,
+ static_cast<npu_vm_runtime_config_value_t>(zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>())));
+ if (config.has<WORKLOAD_TYPE>()) {
+ const auto workloadType = zeroUtils::toZeQueueWorkloadType(config.get<WORKLOAD_TYPE>());
+ if (workloadType.has_value()) {
+ configChain.append(NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE,
+ static_cast<npu_vm_runtime_config_value_t>(workloadType.value()));
+ }
+ }
+ uint32_t commandQueueOptions = 0;
+ if (config.has<TURBO>() && config.get<TURBO>()) {
+ commandQueueOptions = commandQueueOptions | ZE_NPU_COMMAND_QUEUE_OPTION_TURBO;
+ }
+ if (config.has<RUN_INFERENCES_SEQUENTIALLY>() && config.get<RUN_INFERENCES_SEQUENTIALLY>()) {
+ commandQueueOptions = commandQueueOptions | ZE_NPU_COMMAND_QUEUE_OPTION_DEVICE_SYNC;
+ }
+ configChain.append(NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS, commandQueueOptions);
+}
+
+} // namespace
+
+void DynamicGraph::create_execution_engine(const FilteredConfig& config) {
npu_vm_runtime_blob_desc_t blobDesc;
blobDesc.pInput = reinterpret_cast<const uint8_t*>(_blob.value().data());
blobDesc.inputSize = _blob.value().get_byte_size();
- if (npuVMRuntimeCreate(&blobDesc, &_engine, &_engineProperties) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
+ if (npuVMRuntimeGetAPIVersion(&_apiVersion) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
+ OPENVINO_THROW("Failed to get VM runtime API version");
+ }
+
+ const auto result = [&]() {
+ if (use_npu_vm_runtime_v2_api(_apiVersion)) {
+ NpuVMRuntimeConfigChain runtimeConfig;
+ populateRuntimeConfigChain(runtimeConfig, config);
+ return npuVMRuntimeCreate2(&blobDesc, runtimeConfig.head(), &_engine, &_engineProperties);
+ }
+ return npuVMRuntimeCreate(&blobDesc, &_engine, &_engineProperties);
+ }();
+
+ if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
OPENVINO_THROW("Failed to create VM runtime engine");
}
}
@@ -149,9 +186,9 @@ void DynamicGraph::prepare_metadata() {
_metadata.bindRelatedDescriptors();
}
-void DynamicGraph::initialize_engine() {
+void DynamicGraph::initialize_engine(const FilteredConfig& config) {
if (!_engineInitialized) {
- create_execution_engine();
+ create_execution_engine(config);
prepare_metadata();
_engineInitialized = true;
_metadata.numberOfSubgraphs = _engineProperties.numOfSubGraphs;
@@ -195,7 +232,7 @@ DynamicGraph::DynamicGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroIni
// Metadata comes from the VM runtime parsing the blob; unlike a regular Graph, it is not prefetched by the
// compiler/parser and must be available before plugin builds a dummy ov::Model for the CompiledModel.
// This is CPU-side parsing only - no L0/device setup.
- initialize_engine();
+ initialize_engine(config);
}
std::pair<uint64_t, std::optional<std::vector<uint64_t>>> DynamicGraph::export_blob(std::ostream& stream) const {
@@ -320,7 +357,7 @@ void DynamicGraph::initialize_impl(const FilteredConfig& config) {
if (!_engineInitialized) {
// initialize VM execution engine, metadata, input&output descriptors
- initialize_engine();
+ initialize_engine(config);
}
if (!_zeroInitStruct) {
@@ -354,7 +391,7 @@ void DynamicGraph::initialize_impl(const FilteredConfig& config) {
this,
sharedCommonQueue};
- if (sharedCommonQueue == false) {
+ if (!use_npu_vm_runtime_v2_api(_apiVersion) && sharedCommonQueue == false) {
// Keep it alive per compiled model when the shared common queue feature is disabled.
_commandQueue = ZeroCmdQueuePool::getInstance().getCommandQueue(_zeroInitStruct, _commandQueueDesc);
}
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
index fee89ab1707..7196804764a 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
@@ -18,6 +18,11 @@
namespace intel_npu {
struct MemRefType {
+ static constexpr uint32_t PTR_DIRTY = 1U << 0;
+ static constexpr uint32_t SHAPE_DIRTY = 1U << 1;
+ static constexpr uint32_t STRIDE_DIRTY = 1U << 2;
+ static constexpr uint32_t ALL_DIRTY = PTR_DIRTY | SHAPE_DIRTY | STRIDE_DIRTY;
+
const void* _basePtr;
const void* _data;
int64_t _offset;
@@ -25,8 +30,9 @@ struct MemRefType {
std::vector<int64_t> _strides;
int64_t _dimsCount;
std::shared_ptr<void> _impl;
+ uint32_t _dirtyFlag;
- MemRefType() : _basePtr(nullptr), _data(nullptr), _offset(0), _sizes(), _strides(), _dimsCount(0) {}
+ MemRefType() : _basePtr(nullptr), _data(nullptr), _offset(0), _sizes(), _strides(), _dimsCount(0), _dirtyFlag(0) {}
MemRefType(const void* basePtr,
const void* data,
@@ -39,7 +45,8 @@ struct MemRefType {
_offset(offset),
_sizes(sizes),
_strides(strides),
- _dimsCount(dimsCount) {}
+ _dimsCount(dimsCount),
+ _dirtyFlag(0) {}
// Copy intentionally drops the runtime impl: VM MemRef handles must not be aliased
// across copies (would cause double-destroy / shared device state).
@@ -49,7 +56,8 @@ struct MemRefType {
_offset(other._offset),
_sizes(other._sizes),
_strides(other._strides),
- _dimsCount(other._dimsCount) {}
+ _dimsCount(other._dimsCount),
+ _dirtyFlag(other._dirtyFlag) {}
MemRefType& operator=(const MemRefType& other) {
if (this != &other) {
_basePtr = other._basePtr;
@@ -58,6 +66,7 @@ struct MemRefType {
_sizes = other._sizes;
_strides = other._strides;
_dimsCount = other._dimsCount;
+ _dirtyFlag = other._dirtyFlag;
_impl.reset();
}
return *this;
@@ -67,10 +76,15 @@ struct MemRefType {
~MemRefType() = default;
void setArg(const void* arg);
+ void setOffset(int64_t offset);
void setSize(const ov::Shape& shape);
void setStrides(const ov::Strides& strides, int32_t elementSize = 1);
void set(const void* basePtr, int64_t offset, std::shared_ptr<ov::ITensor> tensor);
void updateStride();
+ bool isDirty() const;
+ uint32_t getDirtyFlag() const;
+ void markDirty(uint32_t dirtyFlag);
+ void clearDirty();
bool compare(const MemRefType& memref);
friend std::ostream& operator<<(std::ostream& os, const MemRefType& memRef);
std::string toString();
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp
index 6b754414922..454165172dc 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp
@@ -10,6 +10,7 @@
#endif
#include <level_zero/ze_api.h>
+#include <ze_command_queue_npu_ext.h>
#include "ze_graph_ext.h"
@@ -72,7 +73,8 @@ extern "C" {
typedef enum _npu_vm_runtime_version_t {
NPU_VM_RUNTIME_VERSION_1_0 = ZE_MAKE_VERSION(1, 0), ///< version 1.0
NPU_VM_RUNTIME_VERSION_1_1 = ZE_MAKE_VERSION(1, 1), ///< version 1.1
- NPU_VM_RUNTIME_VERSION_CURRENT = NPU_VM_RUNTIME_VERSION_1_1, ///< latest known version
+ NPU_VM_RUNTIME_VERSION_2_0 = ZE_MAKE_VERSION(2, 0), ///< version 2.0
+ NPU_VM_RUNTIME_VERSION_CURRENT = NPU_VM_RUNTIME_VERSION_2_0, ///< latest known version
NPU_VM_RUNTIME_VERSION_FORCE_UINT32 = 0x7fffffff,
} npu_vm_runtime_version_t;
@@ -259,6 +261,136 @@ NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRun
npu_vm_runtime_predict_output_shape_params_t2* pParams ///< [in] pointer to predict output shape parameters
);
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Version 2.0
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Runtime configuration descriptor type.
+typedef uint64_t npu_vm_runtime_config_type_t;
+
+/// @brief Runtime configuration descriptor value.
+typedef uint64_t npu_vm_runtime_config_value_t;
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Runtime configuration descriptor.
+/// @details Each descriptor carries one typed uint64 value. pNext links additional
+/// descriptors and is only valid for the duration of the API call. Descriptor
+/// chains must be ordered by increasing type value during pNext traversal.
+/// Unknown and invalid descriptor types must be ignored, but still participate
+/// in numeric ordering. Runtime implementations may stop scanning once the
+/// current descriptor type is greater than the requested type. Descriptor
+/// types should be unique. If the same type appears more than once, the first
+/// descriptor reached by pNext traversal takes precedence.
+typedef struct _npu_vm_runtime_config_desc_t {
+ npu_vm_runtime_config_type_t type;
+ npu_vm_runtime_config_value_t value;
+ const struct _npu_vm_runtime_config_desc_t* pNext;
+} npu_vm_runtime_config_desc_t;
+
+#define NPU_VM_RUNTIME_CONFIG_TYPE_INVALID 0ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY 2ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE 3ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS 4ULL
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Init VM runtime instance with initial runtime configuration and return handle (v2.0)
+/// @details Use this instead of npuVMRuntimeCreate when the VM runtime API version is 2.0 or later.
+/// Runtime configuration descriptors provide initial runtime configuration for graph creation.
+/// Shared command queue usage is selected by passing a non-null commandQueue handle
+/// in v2 execution-context creation and execute parameters, not by a config descriptor.
+/// Updated queue configuration can still be provided per call through npuVMRuntimeExecute2::pConfig.
+NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreate2(
+ const npu_vm_runtime_blob_desc_t* desc, ///< [in] pointer to graph descriptor
+ const npu_vm_runtime_config_desc_t*
+ pConfig, ///< [in][optional] pointer to initial runtime configuration descriptors
+ npu_vm_runtime_handle_t* phRuntime, ///< [out] pointer to handle of VM runtime object created
+ npu_vm_runtime_properties_t* pProperties ///< [out] pointer to properties of the runtime
+);
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Init VM runtime execution context with Level Zero handles (v2.0)
+typedef struct _npu_vm_runtime_create_execution_context_params_t {
+ /// @brief Level Zero context. Used by interpreter to create internal CLs.
+ ze_context_handle_t ctx;
+
+ /// @brief Level Zero device. Used by interpreter to create internal CLs.
+ ze_device_handle_t device;
+
+ /// @brief Initial Level Zero command queue. Used by interpreter to create a fence for host synchronization.
+ /// Later npuVMRuntimeExecute2 calls may provide a different commandQueue.
+ ze_command_queue_handle_t commandQueue;
+
+ /// @brief Graph DDI table extension pointer.
+ ze_graph_dditable_ext_t* graphDdiTableExt;
+
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt;
+} npu_vm_runtime_create_execution_context_params_t;
+
+NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreateExecutionContext2(
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_create_execution_context_params_t*
+ pParams, ///< [in] pointer to execution context creation parameters
+ npu_vm_runtime_execution_context_handle_t*
+ phExecutionHandle ///< [out] pointer to handle of VM runtime execution context created
+);
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Execute parameters for npuVMRuntimeExecute2
+/// @details Plugin provides Level Zero context handles and a commandQueue.
+/// The interpreter creates and owns all internal command lists
+/// based on current pConfig descriptors, storing them inside executionContext.
+/// pConfig provides current per-execute runtime configuration and is valid
+/// only for this call. A non-null commandQueue provides the plugin-selected
+/// shared command queue; a null commandQueue lets the runtime manage queue usage.
+/// If commandQueue differs from the one currently stored in executionContext,
+/// runtime updates queue-dependent internal objects as needed.
+/// Plugin never creates or manages command lists directly in this path.
+typedef struct _npu_vm_runtime_execute_params2_t {
+ /// @brief Command queue for submitting command lists or configuring internal command lists.
+ ze_command_queue_handle_t commandQueue;
+
+ /// @brief Runtime configuration descriptor chain.
+ const npu_vm_runtime_config_desc_t* pConfig;
+
+ /// @brief Input tensor MemRef handles.
+ npu_vm_runtime_mem_ref_handle_t* pInputs;
+ uint32_t numOfInputs;
+
+ /// @brief Output tensor MemRef handles.
+ npu_vm_runtime_mem_ref_handle_t* pOutputs;
+ uint32_t numOfOutputs;
+
+ /// @brief Execution context. Interpreter stores its internal CLs here
+ /// and reuses them across Execute2 calls.
+ npu_vm_runtime_execution_context_handle_t executionContext;
+} npu_vm_runtime_execute_params2_t;
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Execute VM runtime (v2.0)
+/// @details Replaces npuVMRuntimeExecute + npuVMRuntimeUpdateMutableCommandList.
+/// On the first call per executionContext, interpreter lazily creates
+/// its internal command list based on pConfig descriptors and stores it in
+/// executionContext.
+///
+/// In both paths, call npuVMRuntimeHostSync(hRuntime, pParams) to block
+/// until the inference completes. The interpreter uses pParams->executionContext
+/// to access the underlying synchronization primitive.
+NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeExecute2(
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
+);
+
+///////////////////////////////////////////////////////////////////////////////
+/// @brief Block host until the inference associated with pParams completes (v2.0)
+/// @details The interpreter internally calls zeEventHostSynchronize or
+/// zeFenceHostSynchronize depending on which primitive is stored in
+/// pParams->executionContext. Other pParams fields are ignored by this call.
+/// Output buffers are safe to read after this returns.
+NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeHostSync(
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
+);
+
#if defined(__cplusplus)
} // extern "C"
#endif
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
index 64f9a131b99..8f4659849b7 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
@@ -32,8 +32,12 @@ namespace intel_npu {
nvm_symbol_statement(npuVMRuntimeUpdateMutableCommandList)
// symbols that may not be supported in older versions
-#define nvm_weak_symbols_list() \
- nvm_symbol_statement(npuVMRuntimePredictOutputShape2)
+#define nvm_weak_symbols_list() \
+ nvm_symbol_statement(npuVMRuntimePredictOutputShape2) \
+ nvm_symbol_statement(npuVMRuntimeCreate2) \
+ nvm_symbol_statement(npuVMRuntimeCreateExecutionContext2) \
+ nvm_symbol_statement(npuVMRuntimeExecute2) \
+ nvm_symbol_statement(npuVMRuntimeHostSync)
// clang-format on
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp
new file mode 100644
index 00000000000..48967e4c1ef
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <array>
+#include <cstddef>
+
+#include "intel_npu/utils/vm/npu_vm_runtime.hpp"
+#include "openvino/core/except.hpp"
+
+namespace intel_npu {
+
+inline bool use_npu_vm_runtime_v2_api(npu_vm_runtime_version_t apiVersion) {
+ return apiVersion >= NPU_VM_RUNTIME_VERSION_2_0;
+}
+
+class NpuVMRuntimeConfigChain final {
+public:
+ NpuVMRuntimeConfigChain() = default;
+ NpuVMRuntimeConfigChain(const NpuVMRuntimeConfigChain&) = delete;
+ NpuVMRuntimeConfigChain& operator=(const NpuVMRuntimeConfigChain&) = delete;
+
+ void clear() {
+ _size = 0;
+ }
+
+ void append(npu_vm_runtime_config_type_t type, npu_vm_runtime_config_value_t value) {
+ OPENVINO_ASSERT(_size < _descs.size(), "VM runtime config descriptor chain capacity exceeded");
+ OPENVINO_ASSERT(_size == 0 || _descs[_size - 1].type < type,
+ "VM runtime config descriptor chain must be ordered by increasing type");
+ _descs[_size] = npu_vm_runtime_config_desc_t{type, value, nullptr};
+ if (_size > 0) {
+ _descs[_size - 1].pNext = &_descs[_size];
+ }
+ ++_size;
+ }
+
+ const npu_vm_runtime_config_desc_t* head() const {
+ return _size == 0 ? nullptr : &_descs[0];
+ }
+
+private:
+ static constexpr size_t MAX_RUNTIME_CONFIG_DESCS = 3;
+
+ std::array<npu_vm_runtime_config_desc_t, MAX_RUNTIME_CONFIG_DESCS> _descs = {};
+ size_t _size = 0;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
index fed548d6dd9..408921c57ff 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_types.hpp
@@ -271,6 +271,10 @@ public:
throwWhenUnsupported("pfnSetWorkloadType", ZE_COMMAND_QUEUE_NPU_EXT_VERSION_1_0);
return _impl->pfnSetWorkloadType(hCommandQueue, workloadType);
}
+
+ ze_command_queue_npu_dditable_ext_t* getImpl() {
+ return _impl;
+ }
};
/**
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
index 622f49478a0..c0aacb5b112 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_wrappers.hpp
@@ -56,19 +56,20 @@ public:
bool operator==(const CommandQueueDesc& other) const;
-private:
- bool owner_tag_required() const;
- void update_key();
+ bool shared_common_queue() const {
+ return _shared_common_queue;
+ }
uint32_t options() const {
return _options;
}
+
+private:
+ bool owner_tag_required() const;
+ void update_key();
const void* owner_tag() const {
return _owner_tag;
}
- bool shared_common_queue() const {
- return _shared_common_queue;
- }
ze_command_queue_priority_t _priority = ZE_COMMAND_QUEUE_PRIORITY_NORMAL;
std::optional<ze_command_queue_workload_type_t> _workload = std::nullopt;
diff --git a/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cpp b/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cpp
index 991a78502d7..f1d81261fbe 100644
--- a/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cpp
+++ b/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cpp
@@ -12,13 +12,26 @@
namespace intel_npu {
void MemRefType::setArg(const void* arg) {
+ if (_basePtr != arg || _data != arg) {
+ markDirty(PTR_DIRTY);
+ }
_basePtr = _data = arg;
}
+void MemRefType::setOffset(int64_t offset) {
+ if (_offset != offset) {
+ markDirty(PTR_DIRTY);
+ }
+ _offset = offset;
+}
+
void MemRefType::setSize(const ov::Shape& shape) {
// Note: check difference between shape from compiler and shape from IR.
if (_dimsCount == 0) {
- _dimsCount = static_cast<uint32_t>(shape.size());
+ if (!_sizes.empty() || !_strides.empty() || _dimsCount != static_cast<int64_t>(shape.size())) {
+ markDirty(SHAPE_DIRTY);
+ }
+ _dimsCount = static_cast<int64_t>(shape.size());
_sizes.resize(shape.size());
_strides.resize(shape.size());
} else if (_dimsCount != static_cast<int64_t>(shape.size())) {
@@ -28,13 +41,17 @@ void MemRefType::setSize(const ov::Shape& shape) {
shape.size());
}
- for (int64_t i = 0; i < _dimsCount; ++i) {
- _sizes[i] = static_cast<int64_t>(shape[i]);
+ for (int64_t dimIndex = 0; dimIndex < _dimsCount; ++dimIndex) {
+ const auto size = static_cast<int64_t>(shape[dimIndex]);
+ if (_sizes[dimIndex] != size) {
+ markDirty(SHAPE_DIRTY);
+ }
+ _sizes[dimIndex] = size;
}
}
void MemRefType::setStrides(const ov::Strides& strides, int32_t elementSize) {
- if (_dimsCount == 0) {
+ if (_dimsCount == 0 && !strides.empty()) {
OPENVINO_THROW("Dimension count is zero, shall call setSize before setStrides");
} else if (_dimsCount != static_cast<int64_t>(strides.size())) {
OPENVINO_THROW("Dimension count mismatch. Current dimension count: ",
@@ -43,45 +60,51 @@ void MemRefType::setStrides(const ov::Strides& strides, int32_t elementSize) {
strides.size());
}
- for (int64_t i = 0; i < _dimsCount; ++i) {
- _strides[i] = static_cast<int64_t>(strides[i] / elementSize);
+ for (int64_t dimIndex = 0; dimIndex < _dimsCount; ++dimIndex) {
+ const auto stride = static_cast<int64_t>(strides[dimIndex] / elementSize);
+ if (_strides[dimIndex] != stride) {
+ markDirty(STRIDE_DIRTY);
+ }
+ _strides[dimIndex] = stride;
}
}
void MemRefType::set(const void* arg, int64_t offset, std::shared_ptr<ov::ITensor> tensor) {
- _basePtr = _data = arg;
- _offset = offset;
- if (_dimsCount == 0) {
- _dimsCount = static_cast<uint32_t>(tensor->get_shape().size());
- _sizes.resize(_dimsCount);
- _strides.resize(_dimsCount);
- } else if (_dimsCount != static_cast<int64_t>(tensor->get_shape().size())) {
- OPENVINO_THROW("Dimension count mismatch. Current dimension count: ",
- _dimsCount,
- ", new dimension count: ",
- tensor->get_shape().size());
- }
-
- auto& shape = tensor->get_shape();
- for (int64_t j = 0; j < _dimsCount; j++) {
- _sizes[j] = static_cast<int64_t>(shape[j]);
- }
- auto& strides = tensor->get_strides();
+ setArg(arg);
+ setOffset(offset);
+ setSize(tensor->get_shape());
size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- for (int64_t j = 0; j < _dimsCount; j++) {
- _strides[j] = static_cast<int64_t>(strides[j] / elementSize);
- }
+ setStrides(tensor->get_strides(), static_cast<int32_t>(elementSize));
}
void MemRefType::updateStride() {
// Note: NCHW layout style
uint64_t stride = 1;
- for (int64_t i = _dimsCount - 1; i >= 0; --i) {
- _strides[i] = stride;
- stride *= _sizes[i];
+ for (int64_t dimIndex = _dimsCount - 1; dimIndex >= 0; --dimIndex) {
+ if (_strides[dimIndex] != static_cast<int64_t>(stride)) {
+ markDirty(STRIDE_DIRTY);
+ }
+ _strides[dimIndex] = stride;
+ stride *= _sizes[dimIndex];
}
}
+bool MemRefType::isDirty() const {
+ return _dirtyFlag != 0;
+}
+
+uint32_t MemRefType::getDirtyFlag() const {
+ return _dirtyFlag;
+}
+
+void MemRefType::markDirty(uint32_t dirtyFlag) {
+ _dirtyFlag |= dirtyFlag;
+}
+
+void MemRefType::clearDirty() {
+ _dirtyFlag = 0;
+}
+
// The comparision only checks shape and strides now
bool MemRefType::compare(const MemRefType& memref) {
if (memref._dimsCount != _dimsCount || _sizes.size() != memref._sizes.size() ||
diff --git a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
index cfa1d5286e1..1cbc07c9996 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
@@ -33,11 +33,11 @@ inline std::shared_ptr<ov::Model> createMaxPoolModel(bool dynamicBatch = false,
std::shared_ptr<ov::op::v0::Parameter> input;
if (dynamicBatch) {
input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
- ov::PartialShape{ov::Dimension(1, 10), 16, 720, 1280});
+ ov::PartialShape{ov::Dimension(1, 10), 16, 1280, 1280});
} else {
input = std::make_shared<ov::op::v0::Parameter>(
ov::element::f16,
- ov::PartialShape{1, 16, ov::Dimension(10, 720), ov::Dimension(10, 1280)});
+ ov::PartialShape{1, 16, ov::Dimension(10, 1280), ov::Dimension(10, 1280)});
}
std::string inputName = "input1";
@@ -79,7 +79,7 @@ inline std::shared_ptr<ov::Model> createMaxPoolModel(bool dynamicBatch = false,
inline std::shared_ptr<ov::Model> createCustomNetModel(bool dynamicBatch = false) {
const ov::Dimension batchDimension = dynamicBatch ? ov::Dimension(1, 10) : ov::Dimension(1);
- const ov::PartialShape inputShape{batchDimension, 16, ov::Dimension(1, 1080), ov::Dimension(10, 1920)};
+ const ov::PartialShape inputShape{batchDimension, 16, ov::Dimension(1, 1280), ov::Dimension(10, 1920)};
auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, inputShape);
input->set_friendly_name("Parameter_59");
@@ -335,6 +335,11 @@ void InferWithHostCompileTests::setInputInferAndCompare(const std::shared_ptr<ov
}
bool InferWithHostCompileTests::logContains(const ScopedLogCapture& logCapture, const std::string& expectedEntry) {
+ const auto logs = logCapture.str();
+ if (logs.find("execute_vm_runtime_v2 - started") != std::string::npos) {
+ // VM runtime v2 manages command lists internally, so plugin-side legacy command list logs are not required
+ return true;
+ }
return logCapture.str().find(expectedEntry) != std::string::npos;
}
@@ -442,7 +447,13 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithDecreasedSize) {
auto& testContext = setupResult.context;
// Start with the largest shape in the dynamic range.
- ov::Shape shape = {1, 720, 1280, 16};
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+
ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
setInputInferAndCompare(model,
testContext.reqDynamic,
@@ -469,7 +480,14 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithDecreasedSize) {
"CompileAndInferWithDecreasedSize_third");
logCapture.clear();
- ov::Shape shape2 = {1, 720, 720, 16};
+
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 720, 720};
+ } else {
+ shape2 = {1, 720, 720, 16};
+ }
+
ov::Tensor inTensor3 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 0);
setInputInferAndCompare(model,
testContext.reqDynamic,
@@ -507,7 +525,13 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithIncreasedSize) {
auto& testContext = setupResult.context;
// Start with a smaller valid dynamic shape.
- ov::Shape shape = {1, 720, 720, 16};
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 1280, 720};
+ } else {
+ shape = {1, 1280, 720, 16};
+ }
+
ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
setInputInferAndCompare(model,
testContext.reqDynamic,
@@ -534,7 +558,13 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithIncreasedSize) {
"CompileAndInferWithIncreasedSize_third");
logCapture.clear();
- ov::Shape shape2 = {1, 720, 1280, 16};
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 1280, 1280};
+ } else {
+ shape2 = {1, 1280, 1280, 16};
+ }
+
ov::Tensor inTensor3 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 0);
setInputInferAndCompare(model,
testContext.reqDynamic,
@@ -570,7 +600,12 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithZeroTensor) {
auto& testContext = setupResult.context;
// Start from a regular host tensor.
- ov::Shape shape = {1, 720, 1280, 16};
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
setInputInferAndCompare(model,
testContext.reqDynamic,
@@ -742,6 +777,945 @@ TEST_P(InferWithHostCompileTests, DynamicBatchUsesOneVMExecution) {
ASSERT_EQ(countVMExecutions(logCapture.str()), 1u) << logCapture.str();
}
+// ── V2: NPU_SHARED_COMMON_QUEUE=YES and =NO baseline ─────────────────────────
+//
+// shared=YES → DynamicPipeline::DynamicPipeline() calls ensureV2(..., queue->handle(), ...)
+// shared=NO → ensureV2(..., nullptr, ...) (vm_runtime owns the internal queue)
+// Verifies first-infer, reuse (same ptr), new-ptr, and shape-change for both modes.
+TEST_P(InferWithHostCompileTests, SharedCommonQueue_BasicInferAndReuse) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << "shared=" << sharedQueue << ": " << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+ const std::string tag = sharedQueue ? "shared" : "nonshared";
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor t0 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t0, tag + "_first"));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_reuse"));
+
+ ov::Tensor t1 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 200, 0);
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t1, tag + "_new_ptr"));
+
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 360, 640};
+ } else {
+ shape2 = {1, 360, 640, 16};
+ }
+ ov::Tensor t2 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 50, 0);
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t2, tag + "_shape_change"));
+ }
+}
+
+TEST_P(InferWithHostCompileTests, SharedCommonQueue_ZeroTensorInputOutputSet) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << "shared=" << sharedQueue << ": " << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+ const std::string tag = sharedQueue ? "shared" : "nonshared";
+
+ auto zeroContext = core->get_default_context(target_device);
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor hostInput =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, hostInput, tag + "_host_input_baseline"));
+
+ auto zeroInput = zeroContext.create_host_tensor(model->input().get_element_type(), shape);
+ auto zeroInputSource =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 1);
+ ASSERT_EQ(zeroInputSource.get_byte_size(), zeroInput.get_byte_size());
+ std::memcpy(zeroInput.data(), zeroInputSource.data(), zeroInputSource.get_byte_size());
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, zeroInput, tag + "_zero_input"));
+
+ const auto outputShape = ctx.reqDynamic.get_tensor(model->output()).get_shape();
+ auto zeroOutput = zeroContext.create_host_tensor(model->output().get_element_type(), outputShape);
+ OV_ASSERT_NO_THROW(ctx.reqDynamic.set_tensor(model->output(), zeroOutput));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_zero_output"));
+
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 360, 640};
+ } else {
+ shape2 = {1, 360, 640, 16};
+ }
+ auto zeroInput2 = zeroContext.create_host_tensor(model->input().get_element_type(), shape2);
+ auto zeroInputSource2 =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 2);
+ ASSERT_EQ(zeroInputSource2.get_byte_size(), zeroInput2.get_byte_size());
+ std::memcpy(zeroInput2.data(), zeroInputSource2.data(), zeroInputSource2.get_byte_size());
+ auto zeroOutput2 = zeroContext.create_host_tensor(model->output().get_element_type(), shape2);
+ OV_ASSERT_NO_THROW(ctx.reqDynamic.set_tensor(model->output(), zeroOutput2));
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model,
+ ctx.reqDynamic,
+ ctx.reqReference,
+ zeroInput2,
+ tag + "_zero_input_output_shape_change"));
+ }
+}
+
+TEST_P(InferWithHostCompileTests, CompileTimeConfig_ModelPriority) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ for (auto priority : {ov::hint::Priority::LOW, ov::hint::Priority::MEDIUM, ov::hint::Priority::HIGH}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+ cfg[ov::hint::model_priority.name()] = priority;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model,
+ setupResult.context.reqDynamic,
+ setupResult.context.reqReference,
+ inTensor,
+ "CompileTimePriority"));
+ }
+ }
+}
+
+TEST_P(InferWithHostCompileTests, CompileTimeConfig_WorkloadType) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ for (auto workloadType : {ov::WorkloadType::DEFAULT, ov::WorkloadType::EFFICIENT}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+ cfg[ov::workload_type.name()] = workloadType;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "workload_type compile-time config not supported: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqRef = refModel.create_infer_request();
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqDynamic, reqRef, inTensor, "CompileTimeWorkload"));
+ }
+ }
+}
+
+TEST_P(InferWithHostCompileTests, CompileTimeConfig_Turbo) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ for (bool turbo : {false, true}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+ cfg[ov::intel_npu::turbo.name()] = turbo;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "turbo compile-time config not supported: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqRef = refModel.create_infer_request();
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+ OV_ASSERT_NO_THROW(reqDynamic.set_input_tensor(0, inTensor));
+ OV_ASSERT_NO_THROW(reqRef.set_input_tensor(0, inTensor));
+ try {
+ reqDynamic.infer();
+ OV_ASSERT_NO_THROW(reqRef.infer());
+ OV_ASSERT_NO_THROW(compareInferenceResult(model, reqDynamic, reqRef));
+ } catch (const ov::Exception& e) {
+ if (!turbo) {
+ FAIL() << "Unexpected turbo=false compile-time failure: " << e.what();
+ }
+ const std::string errorMsg = e.what();
+ const bool gotExpectedRuntimeError = errorMsg.find("QUEUE_OPTIONS") != std::string::npos ||
+ errorMsg.find("configCmdQueue") != std::string::npos ||
+ errorMsg.find("vm_runtime") != std::string::npos;
+ ASSERT_TRUE(gotExpectedRuntimeError) << "Unexpected turbo compile-time failure reason: " << errorMsg;
+ }
+ }
+ }
+}
+
+TEST_P(InferWithHostCompileTests, SetProperty_CombinedPriorityAndWorkload) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+ cfg[ov::workload_type.name()] = ov::WorkloadType::DEFAULT;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "compile_model failed: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ try {
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::EFFICIENT}});
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::DEFAULT}});
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "workload_type not supported: " << e.what();
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqRef = refModel.create_infer_request();
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqDynamic, reqRef, inTensor, "CombinedConfig_baseline"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH},
+ {ov::workload_type.name(), ov::WorkloadType::EFFICIENT}}));
+ OV_ASSERT_NO_THROW(
+ inferAndCompare(model, reqDynamic, reqRef, "CombinedConfig_priority_high_workload_efficient"));
+
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 360, 640};
+ } else {
+ shape2 = {1, 360, 640, 16};
+ }
+ ov::Tensor inTensor2 =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 1);
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, reqDynamic, reqRef, inTensor2, "CombinedConfig_shape_change"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW},
+ {ov::workload_type.name(), ov::WorkloadType::DEFAULT}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "CombinedConfig_restored"));
+ }
+}
+
+// ── V2: compiledModel.set_property(model_priority) → priority change ──────────
+//
+// This is the primary missing scenario: a user calls set_property() on a single
+// already-compiled model to change priority at runtime, then infers.
+//
+// Call chain:
+// compiledModel.set_property({model_priority, HIGH})
+// → DynamicGraph::set_model_priority(HIGH)
+// → _commandQueueDesc.set_priority(HIGH) → new key
+// reqDynamic.infer() → DynamicPipeline::push()
+// → command_queue_desc.key() != _command_queue->desc().key() (changed)
+// → [shared=YES] _command_queue = ZeroCmdQueuePool::getCommandQueue(new_desc)
+// → update_runtime_config(prev_desc, curr_desc) → QUEUE_PRIORITY diff → pConfig
+// → execute_vm_runtime_v2(..., pConfig) → npuVMRuntimeExecute2 with pConfig
+//
+// Transitions: LOW → HIGH → MEDIUM → LOW; also verifies a new InferRequest created
+// after set_property picks up the updated CommandQueueDesc.
+TEST_P(InferWithHostCompileTests, SetProperty_ModelPriority_SingleCompiledModel) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+ cfg[ov::intel_npu::shared_common_queue.name()] = true;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ // Baseline at LOW: command_queue_version_changed=false on first push().
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, inTensor, "Priority_low_baseline"));
+
+ // LOW → HIGH: _commandQueueDesc.key() changes; push() detects it and replaces queue.
+ // update_runtime_config produces QUEUE_PRIORITY diff in pConfig.
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_LOW_to_HIGH"));
+
+ // Reuse at HIGH: same shape, same ptr → no re-record, queue is now HIGH-priority.
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_HIGH_reuse"));
+
+ // HIGH → MEDIUM.
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::MEDIUM}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_HIGH_to_MEDIUM"));
+
+ // MEDIUM → LOW: exercises roundtrip back to LOW-priority queue entry in pool.
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_MEDIUM_to_LOW"));
+
+ // New InferRequest after set_property: must use the updated CommandQueueDesc.
+ ov::InferRequest reqNew = ctx.compiledModel.create_infer_request();
+ ov::InferRequest reqRefNew = ctx.referenceCompiledModel.create_infer_request();
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqNew, reqRefNew, inTensor, "Priority_new_request_after_set"));
+}
+
+// ── V2: compiledModel.set_property(workload_type) → workload change ───────────
+//
+// Call chain (shared=YES):
+// set_property(workload_type, EFFICIENT)
+// → DynamicGraph::set_workload_type()
+// → [_commandQueue not set yet] _commandQueueDesc.set_workload() → key changes
+// push(): command_queue_desc.key() changed → replace _command_queue from pool
+// update_runtime_config → WORKLOAD_TYPE diff → pConfig → configCmdQueue
+//
+// Skipped gracefully when the driver does not support workload_type.
+TEST_P(InferWithHostCompileTests, SetProperty_WorkloadType_SingleCompiledModel) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = true;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "compile_model failed: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ // Probe support before the actual test.
+ try {
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::EFFICIENT}});
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::DEFAULT}});
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "workload_type not supported: " << e.what();
+ }
+
+ ov::InferRequest reqDynamic = compiledModel.create_infer_request();
+ ov::InferRequest reqRef = refModel.create_infer_request();
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqDynamic, reqRef, inTensor, "Workload_default_baseline"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::EFFICIENT}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_DEFAULT_to_EFFICIENT"));
+
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_EFFICIENT_reuse"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::DEFAULT}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_EFFICIENT_to_DEFAULT"));
+}
+
+// TURBO is a compile-time command queue option. Verify both compile-time values
+// for the shared common queue configuration.
+TEST_P(InferWithHostCompileTests, CompileTimeConfig_Turbo_SharedCommonQueue) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ for (bool turbo : {false, true}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = true;
+ cfg[ov::intel_npu::turbo.name()] = turbo;
+
+ ov::CompiledModel compiledModel;
+ try {
+ compiledModel = core->compile_model(model, target_device, cfg);
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "turbo compile-time config not supported: " << e.what();
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqRef = refModel.create_infer_request();
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model,
+ reqDynamic,
+ reqRef,
+ inTensor,
+ turbo ? "Turbo_ON_compile_time" : "Turbo_OFF_compile_time"));
+ }
+}
+
+// ── V2: set_property between two InferRequests from the same CompiledModel ────
+//
+// Both InferRequests call _graph->get_command_queue_desc() on every push(), so
+// after set_property() changes the priority, each request's next push() sees
+// command_queue_version_changed=true and independently replaces its _command_queue.
+//
+// Sequence:
+// reqA.infer() at LOW → establishes LOW queue in reqA's DynamicPipeline
+// reqB.infer() at LOW → establishes LOW queue in reqB's DynamicPipeline
+// set_property(HIGH) → _commandQueueDesc.key() changes for both pipelines
+// reqA.infer() at HIGH → push() detects change; QUEUE_PRIORITY diff in pConfig
+// reqB.infer() at HIGH → same
+// set_property(LOW) → back to LOW
+// reqA.infer() at LOW → second transition
+// reqB.infer() at LOW → second transition
+TEST_P(InferWithHostCompileTests, SetProperty_Priority_BetweenTwoRequests) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+ cfg[ov::intel_npu::shared_common_queue.name()] = true;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "compile_model failed: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ ov::InferRequest reqA = compiledModel.create_infer_request();
+ ov::InferRequest reqB = compiledModel.create_infer_request();
+ ov::InferRequest reqRef = refModel.create_infer_request();
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ // Warmup both at LOW.
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqA, reqRef, inTensor, "TwoReq_A_LOW"));
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqB, reqRef, inTensor, "TwoReq_B_LOW"));
+
+ // Change to HIGH: both DynamicPipelines will see new CommandQueueDesc on next push().
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqA, reqRef, "TwoReq_A_LOW_to_HIGH"));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqB, reqRef, "TwoReq_B_LOW_to_HIGH"));
+
+ // Back to LOW: second transition for both.
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqA, reqRef, "TwoReq_A_HIGH_to_LOW"));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqB, reqRef, "TwoReq_B_HIGH_to_LOW"));
+}
+
+TEST_P(InferWithHostCompileTests, SetProperty_ModelPriority_SingleCompiledModel_NonSharedCommonQueue) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+ cfg[ov::intel_npu::shared_common_queue.name()] = false;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, inTensor, "Priority_nonshared_low_baseline"));
+
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_nonshared_LOW_to_HIGH"));
+
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_nonshared_HIGH_reuse"));
+
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::MEDIUM}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_nonshared_HIGH_to_MEDIUM"));
+
+ OV_ASSERT_NO_THROW(ctx.compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, "Priority_nonshared_MEDIUM_to_LOW"));
+
+ ov::InferRequest reqNew = ctx.compiledModel.create_infer_request();
+ ov::InferRequest reqRefNew = ctx.referenceCompiledModel.create_infer_request();
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, reqNew, reqRefNew, inTensor, "Priority_nonshared_new_request_after_set"));
+}
+
+TEST_P(InferWithHostCompileTests, SetProperty_WorkloadType_SingleCompiledModel_NonSharedCommonQueue) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = false;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "compile_model failed: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ try {
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::EFFICIENT}});
+ compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::DEFAULT}});
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "workload_type not supported in nonshared queue mode: " << e.what();
+ }
+
+ ov::InferRequest reqDynamic = compiledModel.create_infer_request();
+ ov::InferRequest reqRef = refModel.create_infer_request();
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, reqDynamic, reqRef, inTensor, "Workload_nonshared_default_baseline"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::EFFICIENT}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_nonshared_DEFAULT_to_EFFICIENT"));
+
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_nonshared_EFFICIENT_reuse"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::workload_type.name(), ov::WorkloadType::DEFAULT}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqDynamic, reqRef, "Workload_nonshared_EFFICIENT_to_DEFAULT"));
+}
+
+TEST_P(InferWithHostCompileTests, CompileTimeConfig_Turbo_NonSharedCommonQueue) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ for (bool turbo : {false, true}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = false;
+ cfg[ov::intel_npu::turbo.name()] = turbo;
+
+ ov::CompiledModel compiledModel;
+ try {
+ compiledModel = core->compile_model(model, target_device, cfg);
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "turbo compile-time config not supported in nonshared queue mode: " << e.what();
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqRef = refModel.create_infer_request();
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model,
+ reqDynamic,
+ reqRef,
+ inTensor,
+ turbo ? "Turbo_nonshared_ON_compile_time" : "Turbo_nonshared_OFF_compile_time"));
+ }
+}
+
+TEST_P(InferWithHostCompileTests, SetProperty_Priority_BetweenTwoRequests_NonSharedCommonQueue) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ ov::AnyMap cfg = configuration;
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+ cfg[ov::intel_npu::shared_common_queue.name()] = false;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ compiledModel = core->compile_model(model, target_device, configuration);
+ configuration = savedCfg;
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "compile_model failed: " << e.what();
+ }
+ ov::CompiledModel refModel;
+ try {
+ refModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ ov::InferRequest reqA = compiledModel.create_infer_request();
+ ov::InferRequest reqB = compiledModel.create_infer_request();
+ ov::InferRequest reqRef = refModel.create_infer_request();
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqA, reqRef, inTensor, "TwoReq_nonshared_A_LOW"));
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, reqB, reqRef, inTensor, "TwoReq_nonshared_B_LOW"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqA, reqRef, "TwoReq_nonshared_A_LOW_to_HIGH"));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqB, reqRef, "TwoReq_nonshared_B_LOW_to_HIGH"));
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW}}));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqA, reqRef, "TwoReq_nonshared_A_HIGH_to_LOW"));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, reqB, reqRef, "TwoReq_nonshared_B_HIGH_to_LOW"));
+}
+
+// ── V2 MemRef reuse: same-pointer / same-shape input ──────────────────────────
+//
+// Exercises the v2 execution path across repeated inferences with:
+// - same tensor pointer / same shape
+// - different tensor pointer / same shape
+// - different shape
+// Validates output correctness for all cases (this test does not assert on specific log messages).
+// The test is skipped when the v2 code path is not active (i.e., when
+// "execute_vm_runtime_v2 - started" is absent from the first-inference logs).
+TEST_P(InferWithHostCompileTests, MemRefReuse_SamePtrSameShape) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << "shared=" << sharedQueue << ": " << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+ const std::string tag = sharedQueue ? "shared" : "nonshared";
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor t0 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ // 1st inference: recording expected
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t0, tag + "_v2_first"));
+
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_v2_same_reuse"));
+
+ // 3rd inference: new tensor (different pointer, same shape) → recording
+ ov::Tensor t1 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 200, 0);
+
+ OV_ASSERT_NO_THROW(setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t1, tag + "_v2_new_ptr"));
+
+ // 4th inference: same new tensor again → reuse
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_v2_new_ptr_reuse"));
+
+ // 5th inference: different shape → recording
+ ov::Shape shape2;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape2 = {1, 16, 360, 640};
+ } else {
+ shape2 = {1, 360, 640, 16};
+ }
+ ov::Tensor t2 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 50, 0);
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, t2, tag + "_v2_shape_change"));
+ }
+}
+
+// ── V2 MemRef reuse: output pointer change ─────────────────────────────────────
+//
+// Verifies that changing the output tensor triggers re-recording (not reuse)
+// even when the input tensor is unchanged. This also exercises the code path
+// where vm_runtime must correctly reset output dirty bits (as opposed to the
+// known bug where it used pInputs instead of pOutputs for output dirty-bit
+// reset — if that bug were present every inference would incorrectly re-record).
+TEST_P(InferWithHostCompileTests, MemRefReuse_OutputPtrChange) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ ov::AnyMap cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+
+ auto model = createModelByName(selectedModelName);
+ RuntimeCompareSetupResult setupResult;
+ {
+ auto savedCfg = configuration;
+ configuration = cfg;
+ setupResult = prepareRuntimeCompareContext(model);
+ configuration = savedCfg;
+ }
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << "shared=" << sharedQueue << ": " << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& ctx = setupResult.context;
+ const std::string tag = sharedQueue ? "shared" : "nonshared";
+
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);
+
+ // 1st inference: recording expected
+ OV_ASSERT_NO_THROW(
+ setInputInferAndCompare(model, ctx.reqDynamic, ctx.reqReference, inTensor, tag + "_v2out_first"));
+
+ // 2nd inference: same input, no output change → reuse
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_v2out_input_reuse"));
+
+ // 3rd inference: set a new output tensor (different pointer, same shape) → recording
+ const auto outputShape = ctx.reqDynamic.get_tensor(model->output()).get_shape();
+ auto zeroCtx = core->get_default_context(target_device);
+ auto newOutputTensor = zeroCtx.create_host_tensor(model->output().get_element_type(), outputShape);
+ OV_ASSERT_NO_THROW(ctx.reqDynamic.set_tensor(model->output(), newOutputTensor));
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_v2out_output_ptr_change"));
+
+ // 4th inference: same output tensor again → reuse (validates output dirty bits are cleared)
+ OV_ASSERT_NO_THROW(inferAndCompare(model, ctx.reqDynamic, ctx.reqReference, tag + "_v2out_output_ptr_reuse"));
+ }
+}
+
using InferWithDefaultHostCompileTests = InferWithHostCompileTests;
inline bool isByteCodeBlob(const std::string& blob) {
@@ -828,7 +1802,7 @@ const std::vector<ov::AnyMap> configs = {
// Ensure the added test model's input and output shapes are identical and accept concrete NHWC shapes for reuse shape
// in tests.
-const std::vector<std::string> modelNames = {"CustomNet", "CustomNet_DynBatch", "MaxPool"};
+const std::vector<std::string> modelNames = {/*"CustomNet", "CustomNet_DynBatch", "MaxPool", */ "MaxPool_NCHW"};
INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,
InferWithHostCompileTests,
diff --git a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile_multithread.cpp b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile_multithread.cpp
new file mode 100644
index 00000000000..d7eae196012
--- /dev/null
+++ b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile_multithread.cpp
@@ -0,0 +1,1015 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <algorithm>
+#include <atomic>
+#include <common_test_utils/ov_tensor_utils.hpp>
+#include <condition_variable>
+#include <cstring>
+#include <functional>
+#include <future>
+#include <mutex>
+#include <sstream>
+#include <stdexcept>
+#include <string>
+#include <thread>
+#include <tuple>
+#include <vector>
+
+#include "common/utils.hpp"
+#include "intel_npu/npu_private_properties.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/opsets/opset6.hpp"
+#include "openvino/runtime/intel_npu/properties.hpp"
+#include "shared_test_classes/base/ov_behavior_test_utils.hpp"
+
+namespace ov {
+namespace test {
+namespace behavior {
+
+inline std::shared_ptr<ov::Model> createMaxPoolModelMT(bool dynamicBatch = false, bool nhwcLayout = true) {
+ std::shared_ptr<ov::op::v0::Parameter> input;
+ if (dynamicBatch) {
+ input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::PartialShape{ov::Dimension(1, 10), 16, 1280, 1280});
+ } else {
+ input = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f16,
+ ov::PartialShape{1, 16, ov::Dimension(10, 1280), ov::Dimension(10, 1280)});
+ }
+
+ std::string inputName = "input1";
+ input->set_friendly_name(inputName);
+ input->get_output_tensor(0).set_names({inputName});
+ if (!nhwcLayout)
+ input->set_layout("NCHW");
+ auto maxpool = std::make_shared<ov::op::v1::MaxPool>(input,
+ Strides{1, 1},
+ Shape{0, 0},
+ Shape{0, 0},
+ Shape{1, 1},
+ op::RoundingType::FLOOR,
+ op::PadType::EXPLICIT);
+ maxpool->set_friendly_name("MaxPool_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(maxpool);
+ std::string outputName = "output";
+ if (!nhwcLayout)
+ result->set_layout("NCHW");
+ result->set_friendly_name(outputName);
+ result->get_output_tensor(0).set_names({outputName});
+
+ auto model = std::make_shared<Model>(ResultVector{result}, ParameterVector{input}, "MaxPool");
+
+ if (nhwcLayout) {
+ auto preProc = ov::preprocess::PrePostProcessor(model);
+ preProc.input(0).tensor().set_layout("NHWC");
+ preProc.input(0).model().set_layout("NCHW");
+ preProc.output(0).tensor().set_layout("NHWC");
+ preProc.output(0).model().set_layout("NCHW");
+ model = preProc.build();
+ }
+
+ return model;
+}
+
+inline std::shared_ptr<ov::Model> createCustomNetModelMT() {
+ auto input = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f16,
+ ov::PartialShape{1, 16, ov::Dimension(1, 1280), ov::Dimension(10, 1920)});
+ input->set_friendly_name("Parameter_59");
+
+ auto make_conv_add = [](const ov::Output<ov::Node>& data,
+ const std::string& convName,
+ const std::string& addName,
+ float weightValue,
+ float biasValue) -> ov::Output<ov::Node> {
+ const std::vector<float> weightValues(16 * 16, weightValue);
+ const std::vector<float> biasValues(16, biasValue);
+
+ auto weights = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{16, 16, 1, 1}, weightValues);
+ auto conv = std::make_shared<ov::op::v1::Convolution>(data,
+ weights,
+ ov::Strides{1, 1},
+ ov::CoordinateDiff{0, 0},
+ ov::CoordinateDiff{0, 0},
+ ov::Strides{1, 1},
+ ov::op::PadType::EXPLICIT);
+ conv->set_friendly_name(convName);
+
+ auto bias = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 16, 1, 1}, biasValues);
+ auto add = std::make_shared<ov::op::v1::Add>(conv, bias);
+ add->set_friendly_name(addName);
+ return add;
+ };
+
+ auto x = make_conv_add(input, "Convolution_61", "Add_63", 0.01f, 0.001f);
+ x = make_conv_add(x, "Convolution_65", "Add_67", 0.011f, 0.001f);
+
+ auto relu68 = std::make_shared<ov::op::v0::Relu>(x);
+ relu68->set_friendly_name("Relu_68");
+ x = relu68;
+
+ x = make_conv_add(x, "Convolution_70", "Add_72", 0.012f, 0.001f);
+ auto relu73 = std::make_shared<ov::op::v0::Relu>(x);
+ relu73->set_friendly_name("Relu_73");
+ x = relu73;
+
+ x = make_conv_add(x, "Convolution_75", "Add_77", 0.013f, 0.001f);
+ auto relu78 = std::make_shared<ov::op::v0::Relu>(x);
+ relu78->set_friendly_name("Relu_78");
+ x = relu78;
+
+ x = make_conv_add(x, "Convolution_82", "Add_84", 0.014f, 0.001f);
+ auto relu85 = std::make_shared<ov::op::v0::Relu>(x);
+ relu85->set_friendly_name("Relu_85");
+ x = relu85;
+
+ x = make_conv_add(x, "Convolution_87", "Add_89", 0.015f, 0.001f);
+ auto relu90 = std::make_shared<ov::op::v0::Relu>(x);
+ relu90->set_friendly_name("Relu_90");
+ x = relu90;
+
+ x = make_conv_add(x, "Convolution_92", "Add_94", 0.016f, 0.001f);
+ auto relu95 = std::make_shared<ov::op::v0::Relu>(x);
+ relu95->set_friendly_name("Relu_95");
+ x = relu95;
+
+ auto multiplyScale = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{1, 16, 1, 1}, {0.5f});
+ auto multiply97 = std::make_shared<ov::op::v1::Multiply>(x, multiplyScale);
+ multiply97->set_friendly_name("Multiply_97");
+
+ auto add98 = std::make_shared<ov::op::v1::Add>(multiply97, multiply97);
+ add98->set_friendly_name("Add_98");
+
+ x = make_conv_add(add98, "Convolution_100", "Add_102", 0.017f, 0.001f);
+
+ auto result = std::make_shared<ov::op::v0::Result>(x);
+ result->set_friendly_name("Result_104");
+
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input}, "CustomNet");
+
+ auto preProc = ov::preprocess::PrePostProcessor(model);
+ preProc.input(0).tensor().set_layout("NHWC");
+ preProc.input(0).model().set_layout("NCHW");
+ preProc.output(0).tensor().set_layout("NHWC");
+ preProc.output(0).model().set_layout("NCHW");
+ model = preProc.build();
+
+ return model;
+}
+
+using InferWithHostCompileMTParams = std::tuple<std::string, ov::AnyMap, std::string>;
+
+class InferWithHostCompileMultithreadTests : public testing::WithParamInterface<InferWithHostCompileMTParams>,
+ public OVInferRequestTestBase {
+public:
+ static std::string getTestCaseName(testing::TestParamInfo<InferWithHostCompileMTParams> obj) {
+ std::string targetDevice;
+ ov::AnyMap cfg;
+ std::string modelName;
+ std::tie(targetDevice, cfg, modelName) = obj.param;
+ std::replace(targetDevice.begin(), targetDevice.end(), ':', '.');
+ std::ostringstream result;
+ result << "targetDevice=" << targetDevice << "_";
+ if (!cfg.empty()) {
+ for (auto& configItem : cfg) {
+ result << "configItem=" << configItem.first << "_";
+ configItem.second.print(result);
+ result << "_";
+ }
+ }
+ result << "model=" << modelName;
+ return result.str();
+ }
+
+ void SetUp() override {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ std::tie(target_device, configuration, selectedModelName) = this->GetParam();
+ if (selectedModelName == "CustomNet") {
+ GTEST_SKIP() << "CustomNet is currently skipped for multithread host compile tests";
+ }
+ configuration[ov::intel_npu::compile_log_level.name()] = ov::log::Level::ERR;
+
+ std::vector<std::string> deviceNames =
+ core->get_property("NPU", ov::available_devices.name()).as<std::vector<std::string>>();
+ for (const auto& name : deviceNames) {
+ if (target_device.find(name) != std::string::npos) {
+ isTargetDevice = true;
+ break;
+ }
+ }
+
+ APIBaseTest::SetUp();
+ }
+
+ static std::shared_ptr<ov::Model> createModelByName(const std::string& modelName) {
+ if (modelName == "CustomNet") {
+ return createCustomNetModelMT();
+ }
+ if (modelName == "MaxPool") {
+ return createMaxPoolModelMT();
+ }
+ if (modelName == "MaxPool_NCHW") {
+ return createMaxPoolModelMT(false, false);
+ }
+ OPENVINO_THROW("Unknown model name for InferWithHostCompileMultithreadTests: ", modelName);
+ }
+
+ static void runConcurrently(size_t threadCount,
+ const std::function<void(size_t)>& worker,
+ const std::function<void(const std::shared_future<void>&)>& beforeStart) {
+ std::promise<void> startSignal;
+ auto start = startSignal.get_future().share();
+ std::vector<std::future<void>> futures;
+ futures.reserve(threadCount);
+
+ for (size_t i = 0; i < threadCount; ++i) {
+ futures.emplace_back(std::async(std::launch::async, [i, &worker, start]() {
+ start.wait();
+ worker(i);
+ }));
+ }
+
+ beforeStart(start);
+ startSignal.set_value();
+
+ std::vector<std::string> failures;
+ for (size_t i = 0; i < futures.size(); ++i) {
+ try {
+ futures[i].get();
+ } catch (const std::exception& e) {
+ failures.push_back("thread " + std::to_string(i) + ": " + e.what());
+ }
+ }
+
+ if (!failures.empty()) {
+ std::ostringstream os;
+ os << "Parallel execution failures (" << failures.size() << "):";
+ for (const auto& message : failures) {
+ os << "\n" << message;
+ }
+ FAIL() << os.str();
+ }
+ }
+
+ static void runConcurrently(size_t threadCount, const std::function<void(size_t)>& worker) {
+ runConcurrently(threadCount, worker, [](const std::shared_future<void>&) {});
+ }
+
+ static void runConcurrentlyAsync(size_t threadCount,
+ const std::function<void(size_t)>& prepareInference,
+ const std::function<void(size_t)>& startInference,
+ const std::function<void(size_t)>& waitInference) {
+ std::mutex mutex;
+ std::condition_variable condition;
+ size_t readyCount = 0;
+ bool start = false;
+ bool aborted = false;
+ std::vector<std::future<void>> futures;
+ futures.reserve(threadCount);
+
+ for (size_t i = 0; i < threadCount; ++i) {
+ futures.emplace_back(std::async(std::launch::async,
+ [i,
+ &prepareInference,
+ &startInference,
+ &waitInference,
+ &mutex,
+ &condition,
+ &readyCount,
+ &start,
+ &aborted]() {
+ try {
+ prepareInference(i);
+ } catch (...) {
+ std::lock_guard<std::mutex> lock(mutex);
+ aborted = true;
+ condition.notify_all();
+ throw;
+ }
+ {
+ std::unique_lock<std::mutex> lock(mutex);
+ ++readyCount;
+ condition.notify_all();
+ condition.wait(lock, [&start, &aborted]() {
+ return start || aborted;
+ });
+ if (aborted) {
+ return;
+ }
+ }
+ startInference(i);
+ waitInference(i);
+ }));
+ }
+
+ {
+ std::unique_lock<std::mutex> lock(mutex);
+ condition.wait(lock, [&readyCount, threadCount, &aborted]() {
+ return readyCount == threadCount || aborted;
+ });
+ start = true;
+ }
+ condition.notify_all();
+
+ std::vector<std::string> failures;
+ for (size_t i = 0; i < futures.size(); ++i) {
+ try {
+ futures[i].get();
+ } catch (const std::exception& e) {
+ failures.push_back("thread " + std::to_string(i) + ": " + e.what());
+ }
+ }
+
+ if (!failures.empty()) {
+ std::ostringstream os;
+ os << "Parallel async execution failures (" << failures.size() << "):";
+ for (const auto& message : failures) {
+ os << "\n" << message;
+ }
+ FAIL() << os.str();
+ }
+ }
+
+ static void runConcurrentlyAsync(size_t threadCount,
+ const std::function<void(size_t)>& startInference,
+ const std::function<void(size_t)>& waitInference) {
+ runConcurrentlyAsync(threadCount, [](size_t) {}, startInference, waitInference);
+ }
+
+ static ov::Tensor makeInputTensor(const std::shared_ptr<ov::Model>& model,
+ const ov::Shape& shape,
+ const int startFrom) {
+ return ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, startFrom);
+ }
+
+ static void inferAndCompare(ov::InferRequest& reqDynamic, ov::InferRequest& reqReference) {
+ reqDynamic.infer();
+ reqReference.infer();
+
+ const auto npuOutputTensor = reqDynamic.get_output_tensor(0);
+ const auto referenceOutputTensor = reqReference.get_output_tensor(0);
+ ov::test::utils::compare(referenceOutputTensor, npuOutputTensor, npuOutputTensor.get_element_type());
+ }
+
+ static void waitAndCompare(ov::InferRequest& reqDynamic, ov::InferRequest& reqReference) {
+ reqDynamic.wait();
+ reqReference.infer();
+
+ const auto npuOutputTensor = reqDynamic.get_output_tensor(0);
+ const auto referenceOutputTensor = reqReference.get_output_tensor(0);
+ ov::test::utils::compare(referenceOutputTensor, npuOutputTensor, npuOutputTensor.get_element_type());
+ }
+
+ static void setInputInferAndCompare(ov::InferRequest& reqDynamic,
+ ov::InferRequest& reqReference,
+ const ov::Tensor& inputTensor) {
+ reqDynamic.set_input_tensor(0, inputTensor);
+ reqReference.set_input_tensor(0, inputTensor);
+ inferAndCompare(reqDynamic, reqReference);
+ }
+
+ static ov::Tensor makeZeroInputTensor(ov::RemoteContext& zeroContext,
+ const std::shared_ptr<ov::Model>& model,
+ const ov::Shape& shape,
+ const int startFrom) {
+ auto zeroInput = zeroContext.create_host_tensor(model->input().get_element_type(), shape);
+ auto inputSource = makeInputTensor(model, shape, startFrom);
+ if (inputSource.get_byte_size() != zeroInput.get_byte_size()) {
+ OPENVINO_THROW("Source and zero input tensors have different byte sizes");
+ }
+ std::memcpy(zeroInput.data(), inputSource.data(), inputSource.get_byte_size());
+ return zeroInput;
+ }
+
+protected:
+ ov::AnyMap makeConfig(bool sharedQueue) const {
+ auto cfg = configuration;
+ cfg[ov::intel_npu::shared_common_queue.name()] = sharedQueue;
+ return cfg;
+ }
+
+ std::shared_ptr<ov::Core> core = utils::PluginCache::get().core();
+ ov::AnyMap configuration;
+ std::string selectedModelName;
+ std::string target_device;
+ bool isTargetDevice = false;
+};
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_PerThreadCompileCreateInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 4;
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ std::vector<std::shared_ptr<ov::InferRequest>> requests(kThreadCount);
+ std::vector<std::shared_ptr<ov::InferRequest>> referenceRequests(kThreadCount);
+ std::vector<ov::Tensor> inputs(kThreadCount);
+ runConcurrentlyAsync(
+ kThreadCount,
+ [this, &cfg, &shape, &referenceCompiledModel, &requests, &referenceRequests, &inputs](size_t threadIdx) {
+ auto model = createModelByName(selectedModelName);
+ auto compiledModel = core->compile_model(model, target_device, cfg);
+ requests[threadIdx] = std::make_shared<ov::InferRequest>(compiledModel.create_infer_request());
+ referenceRequests[threadIdx] =
+ std::make_shared<ov::InferRequest>(referenceCompiledModel.create_infer_request());
+ inputs[threadIdx] = makeInputTensor(model, shape, static_cast<int>(100 + threadIdx));
+ requests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ referenceRequests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ },
+ [&requests](size_t threadIdx) {
+ requests[threadIdx]->start_async();
+ },
+ [&requests, &referenceRequests](size_t threadIdx) {
+ waitAndCompare(*requests[threadIdx], *referenceRequests[threadIdx]);
+ });
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_SingleCompileParallelCreateRequestAndInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 8;
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ OV_ASSERT_NO_THROW(compiledModel = core->compile_model(model, target_device, cfg));
+
+ std::vector<std::shared_ptr<ov::InferRequest>> requests(kThreadCount);
+ std::vector<std::shared_ptr<ov::InferRequest>> referenceRequests(kThreadCount);
+ std::vector<ov::Tensor> inputs(kThreadCount);
+ runConcurrentlyAsync(
+ kThreadCount,
+ [model, &compiledModel, &referenceCompiledModel, &shape, &requests, &referenceRequests, &inputs](
+ size_t threadIdx) {
+ requests[threadIdx] = std::make_shared<ov::InferRequest>(compiledModel.create_infer_request());
+ referenceRequests[threadIdx] =
+ std::make_shared<ov::InferRequest>(referenceCompiledModel.create_infer_request());
+ inputs[threadIdx] = makeInputTensor(model, shape, static_cast<int>(100 + threadIdx));
+ requests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ referenceRequests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ },
+ [&requests](size_t threadIdx) {
+ requests[threadIdx]->start_async();
+ },
+ [&requests, &referenceRequests](size_t threadIdx) {
+ waitAndCompare(*requests[threadIdx], *referenceRequests[threadIdx]);
+ });
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_ConcurrentInferThenSetPriorityAndInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 8;
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ auto cfg = makeConfig(sharedQueue);
+ cfg[ov::hint::model_priority.name()] = ov::hint::Priority::LOW;
+
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ try {
+ compiledModel = core->compile_model(model, target_device, cfg);
+ } catch (const ov::Exception& e) {
+ GTEST_SKIP() << "model priority is not supported: " << e.what();
+ }
+
+ std::vector<ov::InferRequest> requests;
+ std::vector<ov::InferRequest> referenceRequests;
+ requests.reserve(kThreadCount);
+ referenceRequests.reserve(kThreadCount);
+ for (size_t i = 0; i < kThreadCount; ++i) {
+ requests.emplace_back(compiledModel.create_infer_request());
+ referenceRequests.emplace_back(referenceCompiledModel.create_infer_request());
+ }
+
+ std::vector<ov::Tensor> firstInputs;
+ firstInputs.reserve(kThreadCount);
+ for (size_t i = 0; i < kThreadCount; ++i) {
+ firstInputs.emplace_back(makeInputTensor(model, shape, static_cast<int>(100 + i)));
+ requests[i].set_input_tensor(0, firstInputs.back());
+ referenceRequests[i].set_input_tensor(0, firstInputs.back());
+ }
+ runConcurrentlyAsync(
+ kThreadCount,
+ [&requests](size_t threadIdx) {
+ requests[threadIdx].start_async();
+ },
+ [&requests, &referenceRequests](size_t threadIdx) {
+ waitAndCompare(requests[threadIdx], referenceRequests[threadIdx]);
+ });
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::HIGH}}));
+
+ std::vector<ov::Tensor> secondInputs;
+ secondInputs.reserve(kThreadCount);
+ for (size_t i = 0; i < kThreadCount; ++i) {
+ secondInputs.emplace_back(makeInputTensor(model, shape, static_cast<int>(200 + i)));
+ requests[i].set_input_tensor(0, secondInputs.back());
+ referenceRequests[i].set_input_tensor(0, secondInputs.back());
+ }
+ runConcurrentlyAsync(
+ kThreadCount,
+ [&requests](size_t threadIdx) {
+ requests[threadIdx].start_async();
+ },
+ [&requests, &referenceRequests](size_t threadIdx) {
+ waitAndCompare(requests[threadIdx], referenceRequests[threadIdx]);
+ });
+
+ OV_ASSERT_NO_THROW(compiledModel.set_property({{ov::hint::model_priority.name(), ov::hint::Priority::LOW}}));
+
+ std::vector<ov::Tensor> thirdInputs;
+ thirdInputs.reserve(kThreadCount);
+ for (size_t i = 0; i < kThreadCount; ++i) {
+ thirdInputs.emplace_back(makeInputTensor(model, shape, static_cast<int>(300 + i)));
+ requests[i].set_input_tensor(0, thirdInputs.back());
+ referenceRequests[i].set_input_tensor(0, thirdInputs.back());
+ }
+ runConcurrentlyAsync(
+ kThreadCount,
+ [&requests](size_t threadIdx) {
+ requests[threadIdx].start_async();
+ },
+ [&requests, &referenceRequests](size_t threadIdx) {
+ waitAndCompare(requests[threadIdx], referenceRequests[threadIdx]);
+ });
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_MultiCompiledModelsMultiRequestsMultiInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 4;
+ constexpr size_t kModelCount = 3;
+ constexpr size_t kRequestsPerModel = 2;
+ constexpr size_t kInferLoops = 3;
+ ov::Shape shapeLarge;
+ ov::Shape shapeSmall;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shapeLarge = {1, 16, 720, 1280};
+ shapeSmall = {1, 16, 360, 640};
+ } else {
+ shapeLarge = {1, 720, 1280, 16};
+ shapeSmall = {1, 360, 640, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ auto model = createModelByName(selectedModelName);
+
+ std::vector<ov::CompiledModel> compiledModels;
+ compiledModels.reserve(kModelCount);
+ auto producer = std::async(std::launch::async, [this, &compiledModels, &model, &cfg, kModelCount]() {
+ for (size_t i = 0; i < kModelCount; ++i) {
+ compiledModels.emplace_back(core->compile_model(model, target_device, cfg));
+ }
+ });
+ producer.get();
+
+ ASSERT_EQ(compiledModels.size(), kModelCount);
+
+ std::atomic<size_t> successInferCount{0};
+ std::vector<std::vector<ov::InferRequest>> requests(kThreadCount);
+ std::vector<std::vector<ov::InferRequest>> referenceRequests(kThreadCount);
+ std::vector<std::vector<ov::Tensor>> inputs(kThreadCount);
+ for (size_t inferIdx = 0; inferIdx < kInferLoops; ++inferIdx) {
+ const bool useAltShape = (inferIdx % 2U) == 1U;
+ const auto& shape = useAltShape ? shapeSmall : shapeLarge;
+ runConcurrentlyAsync(
+ kThreadCount,
+ [model,
+ &compiledModels,
+ &referenceCompiledModel,
+ &requests,
+ &referenceRequests,
+ &inputs,
+ &shape,
+ kRequestsPerModel,
+ inferIdx](size_t threadIdx) {
+ if (requests[threadIdx].empty()) {
+ requests[threadIdx].reserve(compiledModels.size() * kRequestsPerModel);
+ referenceRequests[threadIdx].reserve(compiledModels.size() * kRequestsPerModel);
+ }
+ inputs[threadIdx].clear();
+ inputs[threadIdx].reserve(compiledModels.size() * kRequestsPerModel);
+ for (size_t modelIdx = 0; modelIdx < compiledModels.size(); ++modelIdx) {
+ for (size_t reqIdx = 0; reqIdx < kRequestsPerModel; ++reqIdx) {
+ if (inferIdx == 0) {
+ requests[threadIdx].emplace_back(compiledModels[modelIdx].create_infer_request());
+ referenceRequests[threadIdx].emplace_back(
+ referenceCompiledModel.create_infer_request());
+ }
+ const int startFrom =
+ static_cast<int>(100 + threadIdx * 17 + modelIdx * 7 + reqIdx * 3 + inferIdx);
+ inputs[threadIdx].emplace_back(makeInputTensor(model, shape, startFrom));
+ const size_t requestIdx = modelIdx * kRequestsPerModel + reqIdx;
+ requests[threadIdx][requestIdx].set_input_tensor(0, inputs[threadIdx].back());
+ referenceRequests[threadIdx][requestIdx].set_input_tensor(0, inputs[threadIdx].back());
+ }
+ }
+ },
+ [&requests](size_t threadIdx) {
+ for (auto& request : requests[threadIdx]) {
+ request.start_async();
+ }
+ },
+ [&requests, &referenceRequests, &successInferCount](size_t threadIdx) {
+ for (size_t requestIdx = 0; requestIdx < requests[threadIdx].size(); ++requestIdx) {
+ waitAndCompare(requests[threadIdx][requestIdx], referenceRequests[threadIdx][requestIdx]);
+ successInferCount.fetch_add(1, std::memory_order_relaxed);
+ }
+ });
+ }
+
+ const size_t expectedInferCount = kThreadCount * kModelCount * kRequestsPerModel * kInferLoops;
+ ASSERT_EQ(successInferCount.load(std::memory_order_relaxed), expectedInferCount)
+ << "Unexpected total successful infer count";
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_SingleCompileParallelZeroInputOutputTensorInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 4;
+ constexpr size_t kInferLoops = 3;
+ ov::Shape shapeLarge;
+ ov::Shape shapeSmall;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shapeLarge = {1, 16, 720, 1280};
+ shapeSmall = {1, 16, 360, 640};
+ } else {
+ shapeLarge = {1, 720, 1280, 16};
+ shapeSmall = {1, 360, 640, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ auto model = createModelByName(selectedModelName);
+ ov::CompiledModel compiledModel;
+ OV_ASSERT_NO_THROW(compiledModel = core->compile_model(model, target_device, cfg));
+
+ std::atomic<size_t> successInferCount{0};
+ std::vector<std::shared_ptr<ov::InferRequest>> requests(kThreadCount);
+ std::vector<std::shared_ptr<ov::InferRequest>> referenceRequests(kThreadCount);
+ std::vector<ov::Tensor> inputs(kThreadCount);
+ std::vector<ov::Tensor> outputs(kThreadCount);
+ for (size_t inferIdx = 0; inferIdx < kInferLoops; ++inferIdx) {
+ const bool useAltShape = (inferIdx % 2U) == 1U;
+ const auto& shape = useAltShape ? shapeSmall : shapeLarge;
+ runConcurrentlyAsync(
+ kThreadCount,
+ [this,
+ model,
+ &compiledModel,
+ &referenceCompiledModel,
+ &requests,
+ &referenceRequests,
+ &inputs,
+ &outputs,
+ &shape,
+ inferIdx](size_t threadIdx) {
+ if (!requests[threadIdx]) {
+ requests[threadIdx] = std::make_shared<ov::InferRequest>(compiledModel.create_infer_request());
+ referenceRequests[threadIdx] =
+ std::make_shared<ov::InferRequest>(referenceCompiledModel.create_infer_request());
+ }
+ auto zeroContext = core->get_default_context(target_device);
+ const int startFrom = static_cast<int>(100 + threadIdx * 11 + inferIdx);
+ inputs[threadIdx] = makeZeroInputTensor(zeroContext, model, shape, startFrom);
+ outputs[threadIdx] = zeroContext.create_host_tensor(model->output().get_element_type(), shape);
+ requests[threadIdx]->set_tensor(model->input(), inputs[threadIdx]);
+ requests[threadIdx]->set_tensor(model->output(), outputs[threadIdx]);
+ referenceRequests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ },
+ [&requests](size_t threadIdx) {
+ requests[threadIdx]->start_async();
+ },
+ [&requests, &referenceRequests, &successInferCount](size_t threadIdx) {
+ waitAndCompare(*requests[threadIdx], *referenceRequests[threadIdx]);
+ successInferCount.fetch_add(1, std::memory_order_relaxed);
+ });
+ }
+
+ ASSERT_EQ(successInferCount.load(std::memory_order_relaxed), kThreadCount * kInferLoops)
+ << "Unexpected successful zero tensor infer count";
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_PerThreadCompileZeroInputOutputTensorInfer) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kThreadCount = 4;
+ constexpr size_t kInferLoops = 3;
+ ov::Shape shapeLarge;
+ ov::Shape shapeSmall;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shapeLarge = {1, 16, 720, 1280};
+ shapeSmall = {1, 16, 360, 640};
+ } else {
+ shapeLarge = {1, 720, 1280, 16};
+ shapeSmall = {1, 360, 640, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ std::atomic<size_t> successInferCount{0};
+ std::vector<std::shared_ptr<ov::Model>> models(kThreadCount);
+ std::vector<std::shared_ptr<ov::CompiledModel>> compiledModels(kThreadCount);
+ std::vector<std::shared_ptr<ov::InferRequest>> requests(kThreadCount);
+ std::vector<std::shared_ptr<ov::InferRequest>> referenceRequests(kThreadCount);
+ std::vector<ov::Tensor> inputs(kThreadCount);
+ std::vector<ov::Tensor> outputs(kThreadCount);
+ for (size_t inferIdx = 0; inferIdx < kInferLoops; ++inferIdx) {
+ const bool useAltShape = (inferIdx % 2U) == 1U;
+ const auto& shape = useAltShape ? shapeSmall : shapeLarge;
+ runConcurrentlyAsync(
+ kThreadCount,
+ [this,
+ &cfg,
+ &referenceCompiledModel,
+ &models,
+ &compiledModels,
+ &requests,
+ &referenceRequests,
+ &inputs,
+ &outputs,
+ &shape,
+ inferIdx](size_t threadIdx) {
+ if (!models[threadIdx]) {
+ models[threadIdx] = createModelByName(selectedModelName);
+ compiledModels[threadIdx] = std::make_shared<ov::CompiledModel>(
+ core->compile_model(models[threadIdx], target_device, cfg));
+ requests[threadIdx] =
+ std::make_shared<ov::InferRequest>(compiledModels[threadIdx]->create_infer_request());
+ referenceRequests[threadIdx] =
+ std::make_shared<ov::InferRequest>(referenceCompiledModel.create_infer_request());
+ }
+ auto zeroContext = core->get_default_context(target_device);
+ const int startFrom = static_cast<int>(100 + threadIdx * 11 + inferIdx);
+ inputs[threadIdx] = makeZeroInputTensor(zeroContext, models[threadIdx], shape, startFrom);
+ outputs[threadIdx] =
+ zeroContext.create_host_tensor(models[threadIdx]->output().get_element_type(), shape);
+ requests[threadIdx]->set_tensor(models[threadIdx]->input(), inputs[threadIdx]);
+ requests[threadIdx]->set_tensor(models[threadIdx]->output(), outputs[threadIdx]);
+ referenceRequests[threadIdx]->set_input_tensor(0, inputs[threadIdx]);
+ },
+ [&requests](size_t threadIdx) {
+ requests[threadIdx]->start_async();
+ },
+ [&requests, &referenceRequests, &successInferCount](size_t threadIdx) {
+ waitAndCompare(*requests[threadIdx], *referenceRequests[threadIdx]);
+ successInferCount.fetch_add(1, std::memory_order_relaxed);
+ });
+ }
+
+ ASSERT_EQ(successInferCount.load(std::memory_order_relaxed), kThreadCount * kInferLoops)
+ << "Unexpected successful per-thread zero tensor infer count";
+ }
+}
+
+TEST_P(InferWithHostCompileMultithreadTests, MT_CompileAndInferOverlap) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ constexpr size_t kModelCount = 4;
+ constexpr size_t kThreadCount = 4;
+ ov::Shape shape;
+ if (selectedModelName == "MaxPool_NCHW") {
+ shape = {1, 16, 720, 1280};
+ } else {
+ shape = {1, 720, 1280, 16};
+ }
+
+ auto referenceModel = createModelByName(selectedModelName);
+ ov::CompiledModel referenceCompiledModel;
+ try {
+ referenceCompiledModel = core->compile_model(referenceModel, ov::test::utils::DEVICE_TEMPLATE);
+ } catch (const ov::Exception&) {
+ GTEST_SKIP() << "TEMPLATE plugin unavailable";
+ }
+
+ for (bool sharedQueue : {true, false}) {
+ const auto cfg = makeConfig(sharedQueue);
+ auto model = createModelByName(selectedModelName);
+
+ std::vector<ov::CompiledModel> compiledModels;
+ compiledModels.reserve(kModelCount);
+ std::mutex mutex;
+ std::condition_variable cv;
+ bool producerDone = false;
+ std::exception_ptr producerException;
+
+ std::atomic<size_t> nextModelIdx{0};
+ std::atomic<size_t> successInferCount{0};
+ std::future<void> producer;
+ runConcurrently(
+ kThreadCount,
+ [model,
+ &referenceCompiledModel,
+ &shape,
+ &compiledModels,
+ &mutex,
+ &cv,
+ &producerDone,
+ &producerException,
+ &nextModelIdx,
+ &successInferCount](size_t threadIdx) {
+ while (true) {
+ ov::CompiledModel compiledModel;
+ {
+ std::unique_lock<std::mutex> lock(mutex);
+ cv.wait(lock, [&compiledModels, &producerDone, &nextModelIdx]() {
+ return nextModelIdx.load(std::memory_order_relaxed) < compiledModels.size() || producerDone;
+ });
+ if (producerException) {
+ std::rethrow_exception(producerException);
+ }
+ const size_t idx = nextModelIdx.fetch_add(1, std::memory_order_relaxed);
+ if (idx >= compiledModels.size()) {
+ break;
+ }
+ compiledModel = compiledModels[idx];
+ }
+
+ auto reqDynamic = compiledModel.create_infer_request();
+ auto reqReference = referenceCompiledModel.create_infer_request();
+ auto input = makeInputTensor(model, shape, static_cast<int>(100 + threadIdx));
+ reqDynamic.set_input_tensor(0, input);
+ reqReference.set_input_tensor(0, input);
+ reqDynamic.start_async();
+ waitAndCompare(reqDynamic, reqReference);
+ successInferCount.fetch_add(1, std::memory_order_relaxed);
+ }
+ },
+ [this,
+ &cfg,
+ &model,
+ &compiledModels,
+ &mutex,
+ &cv,
+ &producerDone,
+ &producerException,
+ kModelCount,
+ &producer](const std::shared_future<void>& start) {
+ producer = std::async(std::launch::async,
+ [this,
+ &cfg,
+ &model,
+ &compiledModels,
+ &mutex,
+ &cv,
+ &producerDone,
+ &producerException,
+ start,
+ kModelCount]() {
+ start.wait();
+ try {
+ for (size_t i = 0; i < kModelCount; ++i) {
+ auto compiledModel = core->compile_model(model, target_device, cfg);
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ compiledModels.push_back(compiledModel);
+ }
+ cv.notify_all();
+ }
+ } catch (...) {
+ std::lock_guard<std::mutex> lock(mutex);
+ producerException = std::current_exception();
+ producerDone = true;
+ cv.notify_all();
+ return;
+ }
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ producerDone = true;
+ }
+ cv.notify_all();
+ });
+ });
+ producer.get();
+
+ ASSERT_EQ(successInferCount.load(std::memory_order_relaxed), kModelCount)
+ << "Each compiled model should be consumed by one overlapping infer worker";
+ }
+}
+
+const std::vector<std::string> mtDevices = {"NPU.4000", "NPU.5010"};
+
+const std::vector<ov::AnyMap> mtConfigs = {
+ {
+ {"NPU_COMPILER_TYPE", "PLUGIN"},
+ {"NPU_COMPILATION_MODE", "HostCompile_Interpreter"},
+ {"NPU_CREATE_EXECUTOR", "0"},
+ },
+ {
+ {"NPU_COMPILER_TYPE", "PLUGIN"},
+ {"NPU_COMPILATION_MODE", "HostCompile_Interpreter"},
+ },
+};
+
+const std::vector<std::string> mtModelNames = {"MaxPool_NCHW" /*, "CustomNet"*/};
+
+INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,
+ InferWithHostCompileMultithreadTests,
+ ::testing::Combine(::testing::ValuesIn(mtDevices),
+ ::testing::ValuesIn(mtConfigs),
+ ::testing::ValuesIn(mtModelNames)),
+ InferWithHostCompileMultithreadTests::getTestCaseName);
+
+} // namespace behavior
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
index 0a172683990..86dabedb20f 100644
--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
@@ -433,4 +433,16 @@ Example:
</filters>
</skip_config>
+ <skip_config>
+ <message>Random accuracy issue for multithread test.</message>
+ <enable_rules>
+ <device>4000</device>
+ <device>5010</device>
+ <device>6010</device>
+ </enable_rules>
+ <filters>
+ <filter>.*InferWithHostCompileMultithreadTests.MT_ConcurrentInferThenSetPriorityAndInfer.*</filter>
+ </filters>
+ </skip_config>
+
</skip_configs>