OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPU] Execute command list without change if no tensor change detected (#35399)
Xin Wang3eddda303ece
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.hppindex 8f712fcef58..1890e43ba93 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@@ -52,39 +52,17 @@ class DynamicPipeline final : public IPipeline {const void* arg_value,const ov::Strides& strides,const ov::Shape& shapes) {+ // The strides are already divided by element sizeif (arg_index < _binding._inputs.size()) {_binding._inputs[arg_index].setArg(arg_value);- // Only store the valid shape dimensions- for (int64_t i = 0; i < _binding._inputs[arg_index]._dimsCount; i++) {- _binding._inputs[arg_index]._sizes[i] = shapes[i];- }-- if (!strides.empty()) {- for (int64_t i = 0; i < _binding._inputs[arg_index]._dimsCount; i++) {- _binding._inputs[arg_index]._strides[i] = strides[i];- }- } else {- // Need stride based on element but not byte, calc from shape- _binding._inputs[arg_index].updateStride();- }+ _binding._inputs[arg_index].setSize(shapes);+ _binding._inputs[arg_index].setStrides(strides);} else {size_t output_index = static_cast<size_t>(arg_index) - _binding._inputs.size();if (output_index < _binding._outputs.size()) {_binding._outputs[output_index].setArg(arg_value);-- // Only store the valid shape dimensions- for (int64_t i = 0; i < _binding._outputs[output_index]._dimsCount; i++) {- _binding._outputs[output_index]._sizes[i] = shapes[i];- }-- if (!strides.empty()) {- for (int64_t i = 0; i < _binding._outputs[output_index]._dimsCount; i++) {- _binding._outputs[output_index]._strides[i] = strides[i];- }- } else {- // Need stride based on element but not byte, calc from shape- _binding._outputs[output_index].updateStride();- }+ _binding._outputs[output_index].setSize(shapes);+ _binding._outputs[output_index].setStrides(strides);}}}diff --git a/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cppindex de73337f907..1ef94a1432b 100644--- a/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp@@ -43,6 +43,8 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequestauto& levelZeroTensor =foundPort.is_input() ? get_level_zero_input(foundPort.idx) : _levelZeroOutputTensors.at(foundPort.idx);+ auto originallevelZeroTensor = levelZeroTensor;+try {_logger.debug("sync_zero_tensor_with_graph - create zero tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "create zero tensor");@@ -70,12 +72,14 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest}if (_pipelineIsCreated && !_dynamicBatchValueChanged) {- _logger.debug("sync_zero_tensor_with_graph - update command list");+ _logger.debug("sync_zero_tensor_with_graph - update graph arguments");OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "update_graph_arguments");- if (levelZeroTensor->get_byte_size() != tensor->get_byte_size()) {+ if (originallevelZeroTensor != nullptr && originallevelZeroTensor->get_shape() != tensor->get_shape()) {+ _logger.debug("sync_zero_tensor_with_graph - update graph arguments with user tensor pointer since "+ "shape is changed");_pipeline->update_graph_arguments(foundPort.is_input()? _metadata.inputs.at(foundPort.idx).indexUsedByDriver: _metadata.outputs.at(foundPort.idx).indexUsedByDriver,@@ -84,6 +88,8 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest_isTensorChanged = true;} else {// This L0 tensor shall have same info with user tensor+ _logger.debug("sync_zero_tensor_with_graph - update graph arguments without user tensor pointer since "+ "shape is not changed");_pipeline->update_graph_arguments(foundPort.is_input()? _metadata.inputs.at(foundPort.idx).indexUsedByDriver: _metadata.outputs.at(foundPort.idx).indexUsedByDriver,@@ -109,6 +115,7 @@ void ZeroDynamicInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequesget_level_zero_inputs(foundPort.idx).resize(tensors.size());for (size_t i = 0; i < tensors.size(); i++) {+ auto originalLevelZeroTensor = get_level_zero_input(foundPort.idx, i);try {_logger.debug("sync_zero_tensors_with_graph - create zero tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create_zero_tensor");@@ -126,11 +133,22 @@ void ZeroDynamicInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequesif (_pipelineIsCreated && !_dynamicBatchValueChanged) {OPENVINO_ASSERT(get_level_zero_input(foundPort.idx, i)->data(), "Empty buffer");OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");- _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,- get_level_zero_input(foundPort.idx, i),- i,- tensors.at(i)._ptr);- _isTensorChanged = true;+ if (originalLevelZeroTensor != nullptr &&+ originalLevelZeroTensor->get_shape() != tensors.at(i)->get_shape()) {+ _logger.debug(+ "set_tensors - update graph arguments with user tensor pointer since shape is changed");+ _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,+ get_level_zero_input(foundPort.idx, i),+ i,+ tensors.at(i)._ptr);+ _isTensorChanged = true;+ } else {+ _logger.debug(+ "set_tensors - update graph arguments without user tensor pointer since shape is not changed");+ _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,+ get_level_zero_input(foundPort.idx, i),+ i);+ }}}}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.cppindex a924ce3dad1..45ec77c2e9e 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@@ -214,9 +214,6 @@ void DynamicPipeline::push() {}}- // L0 wrapper handle closed command list- command_lists->resetCommandList();-dynamicGraph->execute(_init_structs,graphArguments,command_lists->getHandles(),@@ -257,7 +254,6 @@ void DynamicPipeline::reset() const {_events.at(i)->reset();}}-_logger.debug("reset - completed");}@@ -265,7 +261,7 @@ void DynamicPipeline::update_graph_arguments(uint32_t index,const std::shared_ptr<ZeroTensor>& zeroTensor,const std::shared_ptr<ov::ITensor>& userTensor) {OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_IP_UMCL, itt::domains::LevelZeroBackend, "DynamicPipeline", "updateCommandList");- _logger.debug("update_graph_arguments - update command list");+ _logger.debug("update_graph_arguments - started");// This is the tensor with right shape and strides// The required check is alredy done in inferRequestconst std::shared_ptr<ov::ITensor>& tensor = userTensor ? userTensor : zeroTensor;@@ -287,6 +283,7 @@ void DynamicPipeline::update_graph_arguments(uint32_t index,tensor->get_shape());}}+ _logger.debug("update_graph_arguments - completed");}void DynamicPipeline::update_graph_arguments(uint32_t index,diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/idynamic_graph.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/idynamic_graph.hppindex cd9bf9e1e9b..89eb0b4a6bc 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/idynamic_graph.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/idynamic_graph.hpp@@ -37,6 +37,7 @@ public:void setArg(const void* arg);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 compare(const MemRefType& memref);diff --git a/src/plugins/intel_npu/src/common/src/idynamic_graph.cpp b/src/plugins/intel_npu/src/common/src/idynamic_graph.cppindex fcc82b80469..0777edd04fb 100644--- a/src/plugins/intel_npu/src/common/src/idynamic_graph.cpp+++ b/src/plugins/intel_npu/src/common/src/idynamic_graph.cpp@@ -15,28 +15,60 @@ void IDynamicGraph::MemRefType::setArg(const void* arg) {void IDynamicGraph::MemRefType::setSize(const ov::Shape& shape) {// Note: check difference between shape from compiler and shape from IR.- _sizes.resize(shape.size());- _strides.resize(shape.size());- _dimsCount = static_cast<uint32_t>(shape.size());- for (size_t i = 0; i < shape.size(); ++i) {- _sizes[i] = shape[i];- _strides[i] = 0; // Strides are not set yet, will be updated+ if (_dimsCount == 0) {+ _dimsCount = static_cast<uint32_t>(shape.size());+ _sizes.resize(shape.size());+ _strides.resize(shape.size());+ } else if (_dimsCount != static_cast<int64_t>(shape.size())) {+ OPENVINO_THROW("Dimension count mismatch. Current dimension count: ",+ _dimsCount,+ ", new dimension count: ",+ shape.size());+ }++ for (int64_t i = 0; i < _dimsCount; ++i) {+ _sizes[i] = static_cast<int64_t>(shape[i]);+ }+}++void IDynamicGraph::MemRefType::setStrides(const ov::Strides& strides, int32_t elementSize) {+ if (_dimsCount == 0) {+ 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: ",+ _dimsCount,+ ", new dimension count: ",+ strides.size());+ }++ for (int64_t i = 0; i < _dimsCount; ++i) {+ _strides[i] = static_cast<int64_t>(strides[i] / elementSize);}}void IDynamicGraph::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 (size_t j = 0; j < shape.size(); j++) {- _sizes[j] = shape[j];+ for (int64_t j = 0; j < _dimsCount; j++) {+ _sizes[j] = static_cast<int64_t>(shape[j]);}auto& strides = tensor->get_strides();size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();- for (size_t j = 0; j < strides.size(); j++) {- _strides[j] = strides[j] / elementSize;+ for (int64_t j = 0; j < _dimsCount; j++) {+ _strides[j] = static_cast<int64_t>(strides[j] / elementSize);}- _dimsCount = shape.size();}void IDynamicGraph::MemRefType::updateStride() {@@ -75,6 +107,7 @@ std::ostream& operator<<(std::ostream& os, const IDynamicGraph::MemRefType& memRos << stride << " ";}os << "]";+return os;}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.hppindex 2c3c6d7a3f0..b827d196810 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@@ -19,6 +19,9 @@ class DynamicGraph final : public IDynamicGraph {public:struct MemRefTypeImpl {npu_vm_runtime_mem_ref_handle_t _memRef;+ bool _ptrUpdated = false;+ bool _shapeUpdated = false;+ bool _strideUpdated = false;MemRefTypeImpl() : _memRef(nullptr) {}@@ -30,6 +33,36 @@ public:// Update current MemRef handle to use latest metadataif (_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;+ }}auto result = npuVMRuntimeSetMemRef(_memRef,memref._basePtr,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.cppindex 0e7ed6e518d..04f67116e6f 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@@ -73,23 +73,25 @@ void DynamicGraphImpl::initialize(std::optional<ov::Tensor>& blob, NetworkMetada_binding._inputs.resize(metadata.inputs.size());- // dump output of _metadata- _logger.debug("Dump metadata info from blob");- _logger.debug("Metadata inputs: %d", metadata.inputs.size());- for (const auto& input : metadata.inputs) {- _logger.debug("Input compiler name: %s input node name: %s shapeFromCompiler: %s shapeFromIRModel: %s",- input.nameFromCompiler.c_str(),- input.nodeFriendlyName.c_str(),- input.shapeFromCompiler.to_string().c_str(),- input.shapeFromIRModel.has_value() ? input.shapeFromIRModel->to_string().c_str() : "N/A");- }- _logger.debug("Metadata outputs: %d", metadata.outputs.size());- for (const auto& output : metadata.outputs) {- _logger.debug("Output compiler name: %s output node name: %s shapeFromCompiler: %s shapeFromIRModel: %s",- output.nameFromCompiler.c_str(),- output.nodeFriendlyName.c_str(),- output.shapeFromCompiler.to_string().c_str(),- output.shapeFromIRModel.has_value() ? output.shapeFromIRModel->to_string().c_str() : "N/A");+ if (_logger.level() >= ov::log::Level::DEBUG) {+ // dump output of _metadata+ _logger.debug("Dump metadata info from blob");+ _logger.debug("Metadata inputs: %d", metadata.inputs.size());+ for (const auto& input : metadata.inputs) {+ _logger.debug("Input compiler name: %s input node name: %s shapeFromCompiler: %s shapeFromIRModel: %s",+ input.nameFromCompiler.c_str(),+ input.nodeFriendlyName.c_str(),+ input.shapeFromCompiler.to_string().c_str(),+ input.shapeFromIRModel.has_value() ? input.shapeFromIRModel->to_string().c_str() : "N/A");+ }+ _logger.debug("Metadata outputs: %d", metadata.outputs.size());+ for (const auto& output : metadata.outputs) {+ _logger.debug("Output compiler name: %s output node name: %s shapeFromCompiler: %s shapeFromIRModel: %s",+ output.nameFromCompiler.c_str(),+ output.nodeFriendlyName.c_str(),+ output.shapeFromCompiler.to_string().c_str(),+ output.shapeFromIRModel.has_value() ? output.shapeFromIRModel->to_string().c_str() : "N/A");+ }}auto& inputs = _binding._inputs;@@ -281,20 +283,16 @@ void DynamicGraphImpl::setArgumentValueWithStrides(uint32_t argi,if (argi < inputs.size()) {_logger.debug("setArgumentValueWithStrides for index %d (input %d)", argi, argi);inputs[argi].setArg(argv);-- for (int64_t i = 0; i < inputs[argi]._dimsCount; i++) {- inputs[argi]._strides[i] = strides[i];- }+ // The passed strides are based on element+ inputs[argi].setStrides(strides);} else {auto& outputs = _binding._outputs;auto idx = argi - inputs.size();_logger.debug("setArgumentValueWithStrides for index %d (output %d)", argi, idx);if (idx < outputs.size()) {outputs[idx].setArg(argv);-- for (int64_t i = 0; i < outputs[idx]._dimsCount; i++) {- outputs[idx]._strides[i] = strides[i];- }+ // The passed strides are based on elemnt+ outputs[idx].setStrides(strides);}}}@@ -306,12 +304,13 @@ void DynamicGraphImpl::executeGraph(const std::shared_ptr<ZeroInitStructsHolder>ze_fence_handle_t fence,ze_event_handle_t event,ze_graph_profiling_pool_handle_t profiling) {+ _logger.debug("Start to execute graph with runtime engine");std::shared_ptr<DynamicGraph::GraphArgumentsImpl> argsImpl =args._impl ? std::static_pointer_cast<DynamicGraph::GraphArgumentsImpl>(args._impl): std::make_shared<DynamicGraph::GraphArgumentsImpl>();+ bool noTensorChange = true;npu_vm_runtime_execute_params_t* params = &argsImpl->_executeParams;-for (auto& in : args._inputs) {std::shared_ptr<DynamicGraph::MemRefTypeImpl> inImpl =std::static_pointer_cast<DynamicGraph::MemRefTypeImpl>(in._impl);@@ -322,6 +321,8 @@ void DynamicGraphImpl::executeGraph(const std::shared_ptr<ZeroInitStructsHolder>inImpl->UpdateMemRefHandleStatus(in);if (args._impl == nullptr) {argsImpl->_inputMemRefs.push_back(inImpl->_memRef);+ } else if (inImpl->_ptrUpdated || inImpl->_shapeUpdated || inImpl->_strideUpdated) {+ noTensorChange = false;}}for (auto& out : args._outputs) {@@ -334,9 +335,31 @@ void DynamicGraphImpl::executeGraph(const std::shared_ptr<ZeroInitStructsHolder>outImpl->UpdateMemRefHandleStatus(out);if (args._impl == nullptr) {argsImpl->_outputMemRefs.push_back(outImpl->_memRef);+ } else if (outImpl->_ptrUpdated || outImpl->_shapeUpdated || outImpl->_strideUpdated) {+ noTensorChange = false;}}+ if (args._impl == nullptr || !noTensorChange) {+ _logger.debug("Reset command list to run with runtime");+ // Reset commandLists since there are tensor with new shapes or it is the first execution, can not reuse command+ // list with update+ for (auto& cmdList : commandLists) {+ zeCommandListReset(cmdList);+ }+ } else {+ _logger.debug("Reuse command list without update since no tensor change detected");++ auto result = zeCommandQueueExecuteCommandLists(commandQueue,+ static_cast<uint32_t>(commandLists.size()),+ commandLists.data(),+ fence);+ if (result != ZE_RESULT_SUCCESS) {+ OPENVINO_THROW("Failed to submit command lists");+ }+ return;+ }+// Prepare execution context for each graph argumentsif (params->executionContext == nullptr) {if (npuVMRuntimeCreateExecutionContext(_engine, ¶ms->executionContext) != NPU_VM_RUNTIME_RESULT_SUCCESS) {@@ -359,6 +382,7 @@ void DynamicGraphImpl::executeGraph(const std::shared_ptr<ZeroInitStructsHolder>params->inferenceFence = fence;params->event = event;+ _logger.debug("Execute graph with runtime engine");if (npuVMRuntimeExecute(_engine, params) != NPU_VM_RUNTIME_RESULT_SUCCESS) {OPENVINO_THROW("Failed to execute VM runtime engine");}@@ -428,6 +452,7 @@ DynamicGraph::DynamicGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroIni}_impl = std::make_unique<DynamicGraphImpl>();+// TODO: metadata needs to be parsed even when CREATE_EXECUTOR is 0 or DEFER_WEIGHTS_LOAD is YES, keep here to// support pure compilation without vm runtime initialize VM execution engine, metadata, input&output// descriptorsdiff --git a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cppindex c1f221367d7..2493cdd3f52 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp@@ -38,8 +38,8 @@ std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,} else {header.assign(static_cast<const char*>(data), size);}- if (header.find("llvm") != std::string::npos) {- _logger.debug("Create graph for LLVM IR, use internal function to get metadata!");+ if (header.find("llvm") != std::string::npos || header.find("NPUByte\x00") != std::string::npos) {+ _logger.debug("Create graph for dynamic blob, use internal function to get metadata!");return std::make_shared<DynamicGraph>(_zeroInitStruct, mainBlob, true, config);}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.cppindex 238d7f54685..37269776cdd 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@@ -9,17 +9,12 @@#include "intel_npu/config/options.hpp"#include "intel_npu/npu_private_properties.hpp"-const std::vector<ov::AnyMap> configs = {{{"NPU_COMPILER_TYPE", "PLUGIN"},- {"NPU_PLATFORM", "NPU4000"},- {"NPU_COMPILATION_MODE", "HostCompile"},- {"NPU_CREATE_EXECUTOR", "0"}},- {{"NPU_COMPILER_TYPE", "PLUGIN"},- {"NPU_PLATFORM", "NPU5010"},- {"NPU_COMPILATION_MODE", "HostCompile"},- {"NPU_CREATE_EXECUTOR", "0"}}};+const std::vector<std::string> devices = {"NPU.4000", "NPU.5010"};++const std::vector<ov::AnyMap> configs = {+ {{"NPU_COMPILER_TYPE", "PLUGIN"}, {"NPU_COMPILATION_MODE", "HostCompile"}, {"NPU_CREATE_EXECUTOR", "0"}}};INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,InferWithHostCompileTests,- ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),- ::testing::ValuesIn(configs)),+ ::testing::Combine(::testing::ValuesIn(devices), ::testing::ValuesIn(configs)),ov::test::utils::appendPlatformTypeTestName<InferWithHostCompileTests>);diff --git a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.hpp b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.hppindex e3d40de92f5..9a8c879b59a 100644--- a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.hpp@@ -14,14 +14,16 @@#include "openvino/opsets/opset6.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/make_tensor.hpp"#include "shared_test_classes/base/ov_behavior_test_utils.hpp"+namespace ov {namespace test {namespace behavior {inline std::shared_ptr<ov::Model> createMaxPoolModel() {- auto input =- std::make_shared<ov::op::v0::Parameter>(element::f16, PartialShape{1, 16, 720, ov::Dimension(10, 1280)});+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32,+ ov::PartialShape{1, 16, 720, ov::Dimension(10, 1280)});input->set_friendly_name("input1");auto maxpool = std::make_shared<ov::op::v1::MaxPool>(input,@@ -48,6 +50,40 @@ using InferWithHostCompileParams = std::tuple<std::string, // Device nameclass InferWithHostCompileTests : public testing::WithParamInterface<InferWithHostCompileParams>,public OVInferRequestTestBase {public:+ enum class RuntimeCompareStatus {+ ready,+ skip,+ fail,+ };++ struct ScopedLogCapture {+ ScopedLogCapture();+ ~ScopedLogCapture();++ void clear();+ std::string str() const;++ private:+ std::stringstream stream;+ std::function<void(std::string_view)> callback;++ friend class InferWithHostCompileTests;+ };++ struct RuntimeCompareContext {+ std::shared_ptr<ov::Model> model;+ ov::CompiledModel compiledModel;+ ov::CompiledModel referenceCompiledModel;+ ov::InferRequest reqDynamic;+ ov::InferRequest reqReference;+ };++ struct RuntimeCompareSetupResult {+ RuntimeCompareStatus status = RuntimeCompareStatus::ready;+ std::string message;+ RuntimeCompareContext context;+ };+static std::string getTestCaseName(testing::TestParamInfo<InferWithHostCompileParams> obj) {std::string target_device;ov::AnyMap configuration;@@ -79,67 +115,136 @@ public:break;}}+ originalLogLevel = core->get_property("NPU", ov::log::level.name()).as<ov::log::Level>();APIBaseTest::SetUp();}void TearDown() {- core->set_property("NPU", ov::log::level(ov::log::Level::ERR));+ core->set_property("NPU", ov::log::level(originalLogLevel));}+ static void compareInferenceResult(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference);++ static void inferAndCompare(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference,+ const std::string& dumpPrefix);++ static void setInputInferAndCompare(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference,+ const ov::Tensor& inputTensor,+ const std::string& dumpPrefix);++ static bool logContains(const ScopedLogCapture& logCapture, const std::string& expectedEntry);++ RuntimeCompareSetupResult prepareRuntimeCompareContext(const std::shared_ptr<ov::Model>& model);+protected:std::shared_ptr<ov::Core> core = utils::PluginCache::get().core();ov::AnyMap configuration;bool isTargetDevice = false;+ ov::log::Level originalLogLevel = ov::log::Level::ERR;};-TEST_P(InferWithHostCompileTests, Compile) {- // Skip test according to plugin specific disabledTestPatterns() (if any)- SKIP_IF_CURRENT_TEST_IS_DISABLED()- auto model = createMaxPoolModel();+InferWithHostCompileTests::ScopedLogCapture::ScopedLogCapture()+ : callback([this](std::string_view s) {+ stream << s << std::endl;+ }) {+ ov::util::set_log_callback(callback);+}- ov::CompiledModel compiledModel;- // Compilation shall pass since load of npu_mlir_runtime is deffered with NPU_CREATE_EXECUTOR=0- OV_ASSERT_NO_THROW(compiledModel = core->compile_model(model, target_device, configuration));+InferWithHostCompileTests::ScopedLogCapture::~ScopedLogCapture() {+ ov::util::reset_log_callback();+}- std::stringstream modelStream;- OV_ASSERT_NO_THROW(compiledModel.export_model(modelStream));+void InferWithHostCompileTests::ScopedLogCapture::clear() {+ stream.str("");+ stream.clear();+}- ov::InferRequest reqDynamic;+std::string InferWithHostCompileTests::ScopedLogCapture::str() const {+ return stream.str();+}+void InferWithHostCompileTests::compareInferenceResult(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference) {+ const auto inputTensor = reqDynamic.get_input_tensor(0);+ const auto npuOutputTensor = reqDynamic.get_tensor(model->output());+ const auto referenceOutputTensor = reqReference.get_tensor(model->output());++ ov::test::utils::compare(referenceOutputTensor, npuOutputTensor, npuOutputTensor.get_element_type());+}++void InferWithHostCompileTests::inferAndCompare(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference,+ const std::string& stage) {+ OV_ASSERT_NO_THROW(reqDynamic.infer());+ OV_ASSERT_NO_THROW(reqReference.infer());try {- reqDynamic = compiledModel.create_infer_request();+ compareInferenceResult(model, reqDynamic, reqReference);} catch (const ov::Exception& e) {- if (std::string(e.what()).find("Cannot load library") == std::string::npos) {- FAIL() << "Expected exception message to contain 'Cannot load library', but got: " << e.what();- }+ FAIL() << "Inference result comparison failed at stage " << stage << ": " << e.what();}}-TEST_P(InferWithHostCompileTests, CompileAndImport) {- // Skip test according to plugin specific disabledTestPatterns() (if any)- SKIP_IF_CURRENT_TEST_IS_DISABLED()- auto model = createMaxPoolModel();+void InferWithHostCompileTests::setInputInferAndCompare(const std::shared_ptr<ov::Model>& model,+ ov::InferRequest& reqDynamic,+ ov::InferRequest& reqReference,+ const ov::Tensor& inputTensor,+ const std::string& stage) {+ OV_ASSERT_NO_THROW(reqDynamic.set_input_tensor(0, inputTensor));+ OV_ASSERT_NO_THROW(reqReference.set_input_tensor(0, inputTensor));+ inferAndCompare(model, reqDynamic, reqReference, stage);+}- ov::CompiledModel compiledModel;- // Compilation shall pass since load of npu_mlir_runtime is deffered with NPU_CREATE_EXECUTOR=0- OV_ASSERT_NO_THROW(compiledModel = core->compile_model(model, target_device, configuration));+bool InferWithHostCompileTests::logContains(const ScopedLogCapture& logCapture, const std::string& expectedEntry) {+ return logCapture.str().find(expectedEntry) != std::string::npos;+}- std::stringstream modelStream;- OV_ASSERT_NO_THROW(compiledModel.export_model(modelStream));+InferWithHostCompileTests::RuntimeCompareSetupResult InferWithHostCompileTests::prepareRuntimeCompareContext(+ const std::shared_ptr<ov::Model>& model) {+ RuntimeCompareSetupResult result;+ result.context.model = model;- ov::CompiledModel importedModel;- OV_ASSERT_NO_THROW(core->import_model(modelStream, target_device, configuration));+ try {+ result.context.compiledModel = core->compile_model(model, target_device, configuration);+ } catch (const ov::Exception& e) {+ result.status = RuntimeCompareStatus::fail;+ result.message = std::string("Failed to compile model for target device: ") + e.what();+ return result;+ }- ov::InferRequest reqDynamic;+ try {+ result.context.referenceCompiledModel = core->compile_model(model, ov::test::utils::DEVICE_TEMPLATE);+ } catch (const ov::Exception& e) {+ result.status = RuntimeCompareStatus::skip;+ result.message = std::string("CPU plugin is not available for reference comparison: ") + e.what();+ return result;+ }try {- reqDynamic = compiledModel.create_infer_request();+ result.context.reqDynamic = result.context.compiledModel.create_infer_request();} catch (const ov::Exception& e) {if (std::string(e.what()).find("Cannot load library") == std::string::npos) {- FAIL() << "Expected exception message to contain 'Cannot load library', but got: " << e.what();+ result.status = RuntimeCompareStatus::fail;+ result.message =+ std::string("Expected exception message to contain 'Cannot load library', but got: ") + e.what();+ return result;}++ result.status = RuntimeCompareStatus::skip;+ result.message = "Cannot load library, skip test.";+ return result;}++ result.context.reqReference = result.context.referenceCompiledModel.create_infer_request();+ return result;}TEST_P(InferWithHostCompileTests, CompileAndImportAndInfer) {@@ -157,13 +262,10 @@ TEST_P(InferWithHostCompileTests, CompileAndImportAndInfer) {std::stringstream modelStream;OV_ASSERT_NO_THROW(compiledModel.export_model(modelStream));- ov::CompiledModel importedModel;- OV_ASSERT_NO_THROW(core->import_model(modelStream, target_device, configuration));-ov::InferRequest reqDynamic;-try {- reqDynamic = compiledModel.create_infer_request();+ ov::CompiledModel importedModel = core->import_model(modelStream, target_device);+ reqDynamic = importedModel.create_infer_request();} catch (const ov::Exception& e) {if (std::string(e.what()).find("Cannot load library") == std::string::npos) {FAIL() << "Expected exception message to contain 'Cannot load library', but got: " << e.what();@@ -175,6 +277,271 @@ TEST_P(InferWithHostCompileTests, CompileAndImportAndInfer) {OV_ASSERT_NO_THROW(reqDynamic.infer());}+// Compile, infer with a large shape, then shrink the input shape and verify both output correctness and command-list+// reuse behavior.+TEST_P(InferWithHostCompileTests, CompileAndInferWithDecreasedSize) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+ if (!isTargetDevice) {+ GTEST_SKIP() << "Skip test for current device";+ }++ auto model = createMaxPoolModel();+ ScopedLogCapture logCapture;++ core->set_property("NPU", ov::log::level(ov::log::Level::DEBUG));+ auto setupResult = prepareRuntimeCompareContext(model);+ if (setupResult.status == RuntimeCompareStatus::fail) {+ FAIL() << setupResult.message;+ }+ if (setupResult.status == RuntimeCompareStatus::skip) {+ GTEST_SKIP() << setupResult.message;+ }+ auto& testContext = setupResult.context;++ // Start with the largest shape in the dynamic range.+ ov::Shape shape = {1, 16, 720, 1280};+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor,+ "CompileAndInferWithDecreasedSize_first");+ // The first run materializes runtime state for the initial shape.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime', but got: " << logCapture.str();++ logCapture.clear();+ inferAndCompare(model, testContext.reqDynamic, testContext.reqReference, "CompileAndInferWithDecreasedSize_second");+ // Reusing the same input should keep the existing command list intact.+ ASSERT_TRUE(logContains(logCapture, "Reuse command list without update since no tensor change detected"))+ << "Expected log to contain 'Reuse command list without update since no tensor change detected' for second "+ "inference, but got: "+ << logCapture.str();++ logCapture.clear();+ ov::Tensor inTensor1 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor1,+ "CompileAndInferWithDecreasedSize_third");+ // A new host tensor with the same shape should still reuse the command list.+ ASSERT_TRUE(logContains(logCapture, "Reuse command list without update since no tensor change detected"))+ << "Expected log to contain 'Reuse command list without update since no tensor change detected' for third "+ "inference, but got: "+ << logCapture.str();++ logCapture.clear();+ ov::Shape shape2 = {1, 16, 720, 720};+ ov::Tensor inTensor3 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor3,+ "CompileAndInferWithDecreasedSize_fourth");+ // Shrinking the shape should force runtime reconfiguration for the new tensor layout.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for fourth inference with new shape, but "+ "got: "+ << logCapture.str();+}++// Compile, infer with a small shape, then grow the input shape and verify both output correctness and command-list+// reuse behavior.+TEST_P(InferWithHostCompileTests, CompileAndInferWithIncreasedSize) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+ if (!isTargetDevice) {+ GTEST_SKIP() << "Skip test for current device";+ }++ auto model = createMaxPoolModel();+ ScopedLogCapture logCapture;++ core->set_property("NPU", ov::log::level(ov::log::Level::DEBUG));+ auto setupResult = prepareRuntimeCompareContext(model);+ if (setupResult.status == RuntimeCompareStatus::fail) {+ FAIL() << setupResult.message;+ }+ if (setupResult.status == RuntimeCompareStatus::skip) {+ GTEST_SKIP() << setupResult.message;+ }++ auto& testContext = setupResult.context;++ // Start with a smaller valid dynamic shape.+ ov::Shape shape = {1, 16, 720, 720};+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor,+ "CompileAndInferWithIncreasedSize_first");+ // The first run materializes runtime state for the initial shape.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime', but got: " << logCapture.str();++ logCapture.clear();+ inferAndCompare(model, testContext.reqDynamic, testContext.reqReference, "CompileAndInferWithIncreasedSize_second");+ // Reusing the same input should keep the existing command list intact.+ ASSERT_TRUE(logContains(logCapture, "Reuse command list without update since no tensor change detected"))+ << "Expected log to contain 'Reuse command list without update since no tensor change detected' for second "+ "inference, but got: "+ << logCapture.str();++ logCapture.clear();+ ov::Tensor inTensor1 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor1,+ "CompileAndInferWithIncreasedSize_third");+ // A new host tensor with the same shape should still reuse the command list.+ ASSERT_TRUE(logContains(logCapture, "Reuse command list without update since no tensor change detected"))+ << "Expected log to contain 'Reuse command list without update since no tensor change detected' for third "+ "inference, but got: "+ << logCapture.str();++ logCapture.clear();+ ov::Shape shape2 = {1, 16, 720, 1280};+ ov::Tensor inTensor3 = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape2, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor3,+ "CompileAndInferWithIncreasedSize_fourth");+ // Growing the shape should force runtime reconfiguration for the new tensor layout.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for fourth inference with new shape, but "+ "got: "+ << logCapture.str();+}++// Exercise imported Level Zero tensors and verify both output correctness and command-list pointer updates.+TEST_P(InferWithHostCompileTests, CompileAndInferWithZeroTensor) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+ if (!isTargetDevice) {+ GTEST_SKIP() << "Skip test for current device";+ }++ auto model = createMaxPoolModel();+ ScopedLogCapture logCapture;++ core->set_property("NPU", ov::log::level(ov::log::Level::DEBUG));+ auto setupResult = prepareRuntimeCompareContext(model);+ if (setupResult.status == RuntimeCompareStatus::fail) {+ FAIL() << setupResult.message;+ }+ if (setupResult.status == RuntimeCompareStatus::skip) {+ GTEST_SKIP() << setupResult.message;+ }+ auto& testContext = setupResult.context;++ // Start from a regular host tensor.+ ov::Shape shape = {1, 16, 720, 1280};+ ov::Tensor inTensor = ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ setInputInferAndCompare(model,+ testContext.reqDynamic,+ testContext.reqReference,+ inTensor,+ "CompileAndInferWithZeroTensor_first");++ // The first run materializes runtime state for the initial shape.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime', but got: " << logCapture.str();++ logCapture.clear();+ ov::InferRequest reqDynamic1 = testContext.compiledModel.create_infer_request();+ ov::InferRequest reqReference1 = testContext.referenceCompiledModel.create_infer_request();+ setInputInferAndCompare(model, reqDynamic1, reqReference1, inTensor, "CompileAndInferWithZeroTensor_second");+ // A fresh infer request rebuilds runtime state on its first execution.+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime', but got: " << logCapture.str();++ logCapture.clear();+ auto outputTensorFromReq = testContext.reqDynamic.get_tensor(model->output());+ setInputInferAndCompare(model,+ reqDynamic1,+ reqReference1,+ outputTensorFromReq,+ "CompileAndInferWithZeroTensor_third");+ // Feeding an imported output tensor, ptr change detected and rebuild runtime+ // TODO: Update commandlist once dynamic stride supported+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for third inference, but got: "+ << logCapture.str();++ logCapture.clear();+ auto zeroContext = core->get_default_context(target_device);+ auto inputHostTensorForForthInfer = zeroContext.create_host_tensor(model->input().get_element_type(), shape);+ auto hostTensorSourceForForthInfer =+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), shape, 100, 0);+ ASSERT_EQ(hostTensorSourceForForthInfer.get_byte_size(), inputHostTensorForForthInfer.get_byte_size())+ << "Source and destination tensors must have identical byte sizes for copy";+ std::memcpy(inputHostTensorForForthInfer.data(),+ hostTensorSourceForForthInfer.data(),+ hostTensorSourceForForthInfer.get_byte_size());+ setInputInferAndCompare(model,+ reqDynamic1,+ reqReference1,+ inputHostTensorForForthInfer,+ "CompileAndInferWithZeroTensor_fourth");+ // Feeding a context-allocated host tensor, ptr change detected and rebuild runtime+ // TODO: Update commandlist once dynamic stride supported+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for fourth inference, but got: "+ << logCapture.str();++ logCapture.clear();+ auto outputShape = reqDynamic1.get_tensor(model->output()).get_shape();+ auto zeroOutputTensorForFifthInfer = zeroContext.create_host_tensor(model->input().get_element_type(), outputShape);+ auto hostTensorSourceForOutputForFifthInfer =+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), outputShape, 100, 0);+ ASSERT_EQ(hostTensorSourceForOutputForFifthInfer.get_byte_size(), zeroOutputTensorForFifthInfer.get_byte_size())+ << "Source and destination tensors must have identical byte sizes for copy";+ std::memcpy(zeroOutputTensorForFifthInfer.data(),+ hostTensorSourceForOutputForFifthInfer.data(),+ hostTensorSourceForOutputForFifthInfer.get_byte_size());+ OV_ASSERT_NO_THROW(reqDynamic1.set_tensor(model->output(), zeroOutputTensorForFifthInfer));+ inferAndCompare(model, reqDynamic1, reqReference1, "CompileAndInferWithZeroTensor_fifth");+ // Feeding a context-allocated host tensor as output, ptr change detected and rebuild runtime+ // TODO: Update commandlist once dynamic stride supported+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for fifth inference, but got: "+ << logCapture.str();++ logCapture.clear();+ auto inputTensorForSixthInfer =+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(),+ reqDynamic1.get_tensor(model->input()).get_shape(),+ 100,+ 0);++ auto outputShapeForSixthInfer = reqDynamic1.get_tensor(model->output()).get_shape();+ auto zeroOutputTensorForSixthInfer =+ zeroContext.create_host_tensor(model->input().get_element_type(), outputShapeForSixthInfer);+ auto hostTensorSourceForOutputForSixthInfer =+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), outputShapeForSixthInfer, 100, 0);+ ASSERT_EQ(hostTensorSourceForOutputForSixthInfer.get_byte_size(), zeroOutputTensorForSixthInfer.get_byte_size())+ << "Source and destination tensors must have identical byte sizes for copy";+ std::memcpy(zeroOutputTensorForSixthInfer.data(),+ hostTensorSourceForOutputForSixthInfer.data(),+ hostTensorSourceForOutputForSixthInfer.get_byte_size());+ OV_ASSERT_NO_THROW(reqDynamic1.set_tensor(model->output(), zeroOutputTensorForSixthInfer));+ setInputInferAndCompare(model,+ reqDynamic1,+ reqReference1,+ inputTensorForSixthInfer,+ "CompileAndInferWithZeroTensor_sixth");+ // Feeding a context-allocated host tensor, ptr change detected and rebuild runtime+ // TODO: Update commandlist once dynamic stride supported+ ASSERT_TRUE(logContains(logCapture, "Reset command list to run with runtime"))+ << "Expected log to contain 'Reset command list to run with runtime' for sixth inference, but got: "+ << logCapture.str();+}+} // namespace behavior} // namespace test} // namespace ov