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]Move part DynamicGraph func toDynamicPipeline and refactor dynamic graph (#36099)
Dan Liuea75747a0253
diff --git a/src/plugins/intel_npu/src/CMakeLists.txt b/src/plugins/intel_npu/src/CMakeLists.txtindex f8e6e648589..29aebb0bac6 100644--- a/src/plugins/intel_npu/src/CMakeLists.txt+++ b/src/plugins/intel_npu/src/CMakeLists.txt@@ -13,7 +13,6 @@ add_subdirectory(ops)if (ENABLE_NPU_PLUGIN_ENGINE)add_subdirectory(common)- add_subdirectory(vm)add_subdirectory(compiler_adapter)add_subdirectory(backend)add_subdirectory(plugin)diff --git a/src/plugins/intel_npu/src/backend/CMakeLists.txt b/src/plugins/intel_npu/src/backend/CMakeLists.txtindex bf5a73759dd..da19deb17ec 100644--- a/src/plugins/intel_npu/src/backend/CMakeLists.txt+++ b/src/plugins/intel_npu/src/backend/CMakeLists.txt@@ -8,7 +8,7 @@ file(GLOB_RECURSE SOURCES *.cpp *.hpp *.h)source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})-add_library(${TARGET_NAME} STATIC ${SOURCES})+add_library(${TARGET_NAME} STATIC ${SOURCES} $<TARGET_OBJECTS:openvino_npu_vm_utils>)set_target_properties(${TARGET_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEASE ${ENABLE_LTO})ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})@@ -20,13 +20,14 @@ target_compile_definitions(${TARGET_NAME}target_include_directories(${TARGET_NAME}PUBLIC$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>+ PRIVATE+ $<TARGET_PROPERTY:openvino_npu_vm_utils,INTERFACE_INCLUDE_DIRECTORIES>)target_link_libraries(${TARGET_NAME}PRIVATEopenvino_npu_commonopenvino::npu_al- openvino::npu_vm_runtime_api)## targets installdiff --git a/src/plugins/intel_npu/src/backend/include/zero_dynamic_infer_request.hpp b/src/plugins/intel_npu/src/backend/include/zero_dynamic_infer_request.hppindex e47a8e04ae3..6eb9bc3e919 100644--- a/src/plugins/intel_npu/src/backend/include/zero_dynamic_infer_request.hpp+++ b/src/plugins/intel_npu/src/backend/include/zero_dynamic_infer_request.hpp@@ -32,15 +32,19 @@ protected:const std::vector<ov::SoPtr<ov::ITensor>>& tensors,const std::optional<size_t>& batchSize = std::nullopt) override;- void predict_shapes(std::vector<IDynamicGraph::MemRefType>& outputProps);- void check_tensor_and_predicted_shapes(const std::vector<IDynamicGraph::MemRefType>& outputProps);+ // Overrides the base allocation-only implementation to also resize Level Zero output buffers to the+ // predicted shapes (merging the former update_tensor step) and refresh the graph arguments in one pass.+ void prepare_outputs() override;- void update_tensor(const std::vector<IDynamicGraph::MemRefType>& outputProps);+ void predict_output_shapes(std::vector<ov::Shape>& predictedShapes);+ void check_tensor_and_predicted_shapes(const std::vector<ov::Shape>& predictedShapes);bool _isTensorChanged = false;private:- std::shared_ptr<IDynamicGraph::GraphArguments> _binding;+ // Predicted output shapes for the current inference. Filled by predict_output_shapes(), consumed by+ // check_tensor_and_predicted_shapes() and prepare_outputs().+ std::vector<ov::Shape> _predictedShapes;};} // namespace intel_npudiff --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 14daf8a2761..33ee5bca308 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@@ -4,22 +4,58 @@#pragma once-#include "intel_npu/common/idynamic_graph.hpp"+#include "intel_npu/common/network_metadata.hpp"+#include "intel_npu/utils/vm/mem_ref_type.hpp"#include "zero_pipeline.hpp"namespace intel_npu {+// VM runtime execution context owner. The handle is created lazily and shared between+// shape prediction (infer request) and execution (pipeline) so the same context is reused.+struct VMExecutionContext {+ npu_vm_runtime_execution_context_handle_t _handle = nullptr;++ VMExecutionContext() = default;+ VMExecutionContext(const VMExecutionContext&) = delete;+ VMExecutionContext& operator=(const VMExecutionContext&) = delete;+ VMExecutionContext(VMExecutionContext&&) = delete;+ 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);+};++struct DynamicArguments {+ std::vector<MemRefType> _inputsMemRef;+ std::vector<MemRefType> _outputsMemRef;++ // 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).+ bool _commandListsRecorded = false;++ DynamicArguments() = default;+ DynamicArguments(const DynamicArguments&) = delete;+ DynamicArguments& operator=(const DynamicArguments&) = delete;+ DynamicArguments(DynamicArguments&&) = delete;+ DynamicArguments& operator=(DynamicArguments&&) = delete;+ ~DynamicArguments() = default;++ void setArgumentProperties(uint32_t argi,+ const void* argv,+ const ov::Shape& shapes,+ const std::vector<size_t>& strides);+};+class DynamicPipeline final : public IPipeline {struct PipelinedCommandLists {- mutable std::shared_ptr<IDynamicGraph::GraphArguments> _binding;+ std::shared_ptr<DynamicArguments> _arguments;std::vector<std::unique_ptr<CommandList>> _commandLists;// Store command list handles to pass it to ExecutionEnginestd::vector<ze_command_list_handle_t> _commandListHandles;- PipelinedCommandLists(size_t numCommandLists,- const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- std::shared_ptr<IDynamicGraph::GraphArguments> requestBinding) {+ 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));@@ -28,9 +64,8 @@ class DynamicPipeline final : public IPipeline {for (size_t i = 0; i < numCommandLists; i++) {_commandListHandles.push_back(_commandLists[i]->handle());}- if (requestBinding != nullptr) {- _binding = requestBinding;- }++ _arguments = std::make_shared<DynamicArguments>();}size_t size() const {@@ -41,10 +76,28 @@ class DynamicPipeline final : public IPipeline {return _commandListHandles.data();}- void bind(IDynamicGraph* graph) {- if (_binding == nullptr) {- _binding = std::make_shared<IDynamicGraph::GraphArguments>();- graph->getBinding(*_binding);+ // Use metadata to initialize, which will later be updated again by setArgumentProperties+ void initArguments(const NetworkMetadata& metadata) {+ _arguments->_inputsMemRef.resize(metadata.inputs.size());+ auto& inputs = _arguments->_inputsMemRef;+ for (size_t i = 0; i < inputs.size(); ++i) {+ // 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].updateStride();+ }++ _arguments->_outputsMemRef.resize(metadata.outputs.size());+ 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].updateStride();}}@@ -52,8 +105,8 @@ class DynamicPipeline final : public IPipeline {return _commandListHandles;}- IDynamicGraph::GraphArguments& getBinding() {- return *_binding;+ DynamicArguments& getArguments() {+ return *_arguments;}void updateMutableCommandList(uint32_t arg_index,@@ -61,25 +114,19 @@ class DynamicPipeline final : public IPipeline {const ov::Strides& strides,const ov::Shape& shapes) {// The strides are already divided by element size- if (arg_index < _binding->_inputs.size()) {- _binding->_inputs[arg_index].setArg(arg_value);- _binding->_inputs[arg_index].setSize(shapes);- _binding->_inputs[arg_index].setStrides(strides);+ if (arg_index < _arguments->_inputsMemRef.size()) {+ _arguments->_inputsMemRef[arg_index].setArg(arg_value);+ _arguments->_inputsMemRef[arg_index].setSize(shapes);+ _arguments->_inputsMemRef[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);- _binding->_outputs[output_index].setSize(shapes);- _binding->_outputs[output_index].setStrides(strides);+ size_t output_index = static_cast<size_t>(arg_index) - _arguments->_inputsMemRef.size();+ if (output_index < _arguments->_outputsMemRef.size()) {+ _arguments->_outputsMemRef[output_index].setArg(arg_value);+ _arguments->_outputsMemRef[output_index].setSize(shapes);+ _arguments->_outputsMemRef[output_index].setStrides(strides);}}}-- void resetCommandList() {- for (auto& cmd_list : _commandLists) {- cmd_list->reset();- }- }};public:@@ -88,7 +135,6 @@ public:const Config& config,const std::vector<std::vector<std::shared_ptr<ZeroTensor>>>& input_tensors,const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors,- std::shared_ptr<IDynamicGraph::GraphArguments> requestBinding,size_t batch_size = 1);DynamicPipeline(const DynamicPipeline&) = delete;@@ -106,7 +152,22 @@ public:size_t batch_index,const std::shared_ptr<ov::ITensor>& userTensor = nullptr) override;+ // Predicts VM runtime output shapes for the given input/output tensors. A nullptr tensor entry falls+ // back to the graph metadata max shape. Uses the pipeline's own graph handle and VM execution context,+ // which is the same context reused by execute_vm_runtime.+ std::vector<ov::Shape> predict_output_shapes(const std::vector<std::shared_ptr<ov::ITensor>>& inputTensors,+ const std::vector<std::shared_ptr<ov::ITensor>>& outputTensors);+private:+ void execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,+ DynamicArguments& args,+ std::vector<ze_command_list_handle_t>& commandLists,+ ze_command_queue_handle_t commandQueue,+ ze_fence_handle_t fence,+ ze_event_handle_t event);++ // VM execution context owned by this pipeline; shared between shape prediction and execution.+ VMExecutionContext _executionContext;std::vector<std::unique_ptr<PipelinedCommandLists>> _command_lists;};diff --git a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hppindex c088ee3fb55..f63bae15a79 100644--- a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp+++ b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp@@ -4,6 +4,8 @@#pragma once+#include <vector>+#include "intel_npu/common/igraph.hpp"#include "intel_npu/utils/zero/zero_tensor.hpp"#include "intel_npu/utils/zero/zero_wrappers.hpp"@@ -43,6 +45,12 @@ public:protected:void enable_profiling();+ // Helper function handling strides for Zero Pipeline and ZeroDynamicPipeline. Stateless regarding pipeline+ // instances, hence static+ static std::vector<size_t> get_strides(const std::vector<size_t>& strides_in_bytes,+ size_t element_size,+ bool reverse_order = false);+std::shared_ptr<ZeroInitStructsHolder> _init_structs;std::shared_ptr<IGraph> _graph;const Config _config;diff --git a/src/plugins/intel_npu/src/backend/src/zero_device.cpp b/src/plugins/intel_npu/src/backend/src/zero_device.cppindex 606c3fcfd6f..e99805120c4 100644--- a/src/plugins/intel_npu/src/backend/src/zero_device.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_device.cpp@@ -4,6 +4,7 @@#include "zero_device.hpp"+#include "intel_npu/common/igraph.hpp"#include "intel_npu/common/itt.hpp"#include "intel_npu/utils/zero/zero_api.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"@@ -185,7 +186,7 @@ ov::device::Type ZeroDevice::getDeviceType() const {std::shared_ptr<InferRequest> ZeroDevice::createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,const Config& config) {- if (dynamic_cast<IDynamicGraph*>(compiledModel->get_graph().get())) {+ if (compiledModel->get_graph()->is_dynamic()) {return std::make_shared<ZeroDynamicInferRequest>(_initStructs, compiledModel, config);}return std::make_shared<ZeroInferRequest>(_initStructs, compiledModel, config);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 14634f1fe31..d628fbb54c9 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@@ -21,14 +21,13 @@ ZeroDynamicInferRequest::ZeroDynamicInferRequest(const std::shared_ptr<ZeroInitSvoid ZeroDynamicInferRequest::create_pipeline_impl() {_logger.debug("create_pipeline_impl - constructing pipeline");auto batchSize = _graph->get_batch_size();- // Construct pipeline+ // Construct pipeline. The pipeline owns the VM execution context shared by shape prediction and execution._pipeline =std::make_unique<DynamicPipeline>(_initStructs,_graph,_config,_levelZeroInputTensors,_levelZeroOutputTensors,- _binding,batchSize.has_value() ? batchSize.value() : utils::DEFAULT_BATCH_SIZE);_logger.debug("create_pipeline_impl - completed");@@ -202,101 +201,67 @@ std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(void ZeroDynamicInferRequest::infer_async() {_logger.debug("infer_async - started");OV_ITT_TASK_CHAIN(ZERO_INFER, itt::domains::LevelZeroBackend, "infer_async", "start");- // Store the predicted output shapes- std::vector<IDynamicGraph::MemRefType> outputPros;- predict_shapes(outputPros);- check_tensor_and_predicted_shapes(outputPros);+ // Create (or reuse) the dynamic pipeline first. Shape prediction now runs through the pipeline instance and+ // shares the pipeline-owned VM execution context with execution.prepare_inputs();++ // Predict output shapes and validate user output tensors; prepare_outputs() then allocates and resizes the+ // Level Zero output buffers to the predicted shapes.+ predict_output_shapes(_predictedShapes);+ check_tensor_and_predicted_shapes(_predictedShapes);prepare_outputs();- update_tensor(outputPros);OV_ITT_TASK_NEXT(ZERO_INFER, "push");_pipeline->push();}-void ZeroDynamicInferRequest::predict_shapes(std::vector<IDynamicGraph::MemRefType>& outputProps) {+void ZeroDynamicInferRequest::predict_output_shapes(std::vector<ov::Shape>& predictedShapes) {// TODO: If current output tensor is not large enough to be compatible with input tensor, need recreate pipeline// But reshape ZeroTensor can be used to avoid recreate pipeline now- // bool reCreatePipeline = false;- // Predict output shapes based on current inputs- intel_npu::IDynamicGraph* dynamicGraph = dynamic_cast<intel_npu::IDynamicGraph*>(_graph.get());- if (dynamicGraph == nullptr) {- OPENVINO_THROW("Failed to cast IGraph to IDynamicGraph, please check if the graph is created successfully and "- "supports dynamic shape.");- }- if (_binding == nullptr) {- _binding = std::make_shared<IDynamicGraph::GraphArguments>();- dynamicGraph->getBinding(*_binding);- }- if (_isTensorChanged) {- IDynamicGraph::GraphArguments& binding = *_binding;- // Use copy instead of reference to not pollute current graph arguments- std::vector<IDynamicGraph::MemRefType> inputPros = binding._inputs;- outputProps = binding._outputs;+ // Predict output shapes based on current inputs. The infer request only deals with tensors/OV shapes;+ // MemRef packing is done inside the pipeline layer.+ predictedShapes.clear();++ if (_graph->get_handle() != nullptr && _isTensorChanged) {+ std::vector<std::shared_ptr<ov::ITensor>> inputTensors(_metadata.inputs.size());+ std::vector<std::shared_ptr<ov::ITensor>> outputTensors(_metadata.outputs.size());// TODO: Support Batch later// Update input Info- // TENTATIVE CODE TO ALLOCATE a memref handle- for (size_t i = 0; i < inputPros.size(); ++i) {- auto& levelZeroTensor = get_level_zero_input(i);- auto& userTensor = get_user_input(i);+ // A null entry lets the pipeline fall back to the graph metadata max shape.+ for (size_t i = 0; i < inputTensors.size(); ++i) {+ const auto& userTensor = get_user_input(i);if (userTensor != nullptr) {- // If userTensor is set, use userTensor to update memref handle- const auto userTensorPtr = userTensor._ptr;- OPENVINO_ASSERT(userTensorPtr != nullptr, "Input user tensor pointer is null");- inputPros[i].set(get_tensor_data_ptr(userTensorPtr), 0, userTensorPtr);- } else if (levelZeroTensor != nullptr) {- // If userTensor is not set, use levelZeroTensor to update memref handle- inputPros[i].set(get_tensor_data_ptr(levelZeroTensor), 0, levelZeroTensor);+ // If userTensor is set, use userTensor to update memref handle in prediction+ inputTensors[i] = userTensor._ptr;} else {- // If all tensors are not set, use metadata- inputPros[i].setArg(nullptr);- inputPros[i]._offset = 0;- // TODO : BatchSize not checked here- inputPros[i].setSize(_metadata.inputs.at(i).shapeFromCompiler.get_max_shape());- inputPros[i].updateStride();+ // If userTensor is not set, use levelZeroTensor+ inputTensors[i] = get_level_zero_input(i);}}-// Update output Info- for (size_t i = 0; i < outputProps.size(); ++i) {- auto& levelZeroTensor = _levelZeroOutputTensors.at(i);- auto& userTensor = _userOutputTensors.at(i);+ for (size_t i = 0; i < outputTensors.size(); ++i) {+ const auto& userTensor = _userOutputTensors.at(i);if (userTensor != nullptr) {- // If userTensor is set, use userTensor to update memref handle- const auto userTensorPtr = userTensor._ptr;- OPENVINO_ASSERT(userTensorPtr != nullptr, "Output user tensor pointer is null");- outputProps[i].set(get_tensor_data_ptr(userTensorPtr), 0, userTensorPtr);- } else if (levelZeroTensor != nullptr) {- // If userTensor is not set, use levelZeroTensor to update memref handle- outputProps[i].set(get_tensor_data_ptr(levelZeroTensor), 0, levelZeroTensor);+ // If userTensor is set, use userTensor to update memref handle in prediction+ outputTensors[i] = userTensor._ptr;} else {- // If all tensors are not set, use metadata- outputProps[i].setArg(nullptr);- outputProps[i]._offset = 0;- // TODO : BatchSize not checked here- outputProps[i].setSize(_metadata.outputs.at(i).shapeFromCompiler.get_max_shape());- outputProps[i].updateStride();+ // If userTensor is not set, use levelZeroTensor+ outputTensors[i] = _levelZeroOutputTensors.at(i);}}- auto originalOutputProps = outputProps;-- dynamicGraph->predict_output_shape(binding, inputPros, outputProps);-- for (size_t i = 0; i < outputProps.size(); i++) {- if (!originalOutputProps[i].compare(outputProps[i])) {- _logger.debug("predict_shapes - output shape change detected");- break;- }- }+ OPENVINO_ASSERT(_pipeline != nullptr, "Dynamic pipeline must be created before predicting output shapes");+ // ZeroDynamicInferRequest always constructs a DynamicPipeline in create_pipeline_impl,+ // so this downcast is safe.+ predictedShapes =+ static_cast<DynamicPipeline*>(_pipeline.get())->predict_output_shapes(inputTensors, outputTensors);}}-void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(- const std::vector<IDynamicGraph::MemRefType>& outputProps) {- if (outputProps.empty()) {+void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(const std::vector<ov::Shape>& predictedShapes) {+ if (predictedShapes.empty()) {_logger.debug("check_tensor_and_predicted_shapes - no output props to check, skip check");return;}@@ -314,10 +279,7 @@ void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(continue;}- ov::Shape predictedShape;- for (int64_t j = 0; j < outputProps[i]._dimsCount; j++) {- predictedShape.push_back(outputProps[i]._sizes[j]);- }+ const ov::Shape& predictedShape = predictedShapes[i];if (userTensor != nullptr) {// User set output tensor, need check size and throw exception if not large enoughif (shape_size(userTensor->get_shape()) < shape_size(predictedShape)) {@@ -343,28 +305,41 @@ void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(}}-void ZeroDynamicInferRequest::update_tensor(const std::vector<IDynamicGraph::MemRefType>& outputProps) {- // Update local level zero buffer shape with predicted shape to prepare for comparasion- if (outputProps.size() > 0 && _isTensorChanged) {- for (size_t i = 0; i < _levelZeroOutputTensors.size(); i++) {- auto& levelZeroTensor = _levelZeroOutputTensors.at(i);- if (levelZeroTensor == nullptr) {- // Do not need to update user output tensor- continue;- }- ov::Shape predictedShape;- for (int64_t j = 0; j < outputProps[i]._dimsCount; j++) {- predictedShape.push_back(outputProps[i]._sizes[j]);- }+void ZeroDynamicInferRequest::prepare_outputs() {+ OV_ITT_TASK_CHAIN(ZERO_INFER, itt::domains::LevelZeroBackend, "infer_async", "prepare_outputs");+ // Resize outputs to the predicted shapes only when a tensor change triggered a fresh prediction.+ const bool reshapeToPredicted = !_predictedShapes.empty() && _isTensorChanged;++ for (size_t outputIndex = 0; outputIndex < _levelZeroOutputTensors.size(); ++outputIndex) {+ auto& levelZeroTensor = _levelZeroOutputTensors.at(outputIndex);+ OPENVINO_ASSERT(levelZeroTensor, "Output zero tensor is not allocated.");++ bool graphArgsNeedUpdate = false;++ // Ensure the output buffer is allocated (former base prepare_outputs behavior).+ if (levelZeroTensor->data() == nullptr) {+ levelZeroTensor->allocate_data();+ graphArgsNeedUpdate = true;+ }++ // Resize the output buffer to the predicted shape (former update_tensor behavior). set_shape may+ // reallocate the buffer, so the single graph-argument refresh below must run after it.+ if (reshapeToPredicted) {+ const ov::Shape& predictedShape = _predictedShapes[outputIndex];if (levelZeroTensor->get_shape() != predictedShape) {- _logger.info("update_tensor - reshape output tensor %d from %s to predicted shape %s",- i,+ _logger.info("prepare_outputs - reshape output tensor %zu from %s to predicted shape %s",+ outputIndex,levelZeroTensor->get_shape().to_string().c_str(),predictedShape.to_string().c_str());levelZeroTensor->set_shape(predictedShape);- _pipeline->update_graph_arguments(_metadata.outputs.at(i).indexUsedByDriver, levelZeroTensor);+ graphArgsNeedUpdate = true;}}++ if (graphArgsNeedUpdate) {+ _pipeline->update_graph_arguments(_metadata.outputs.at(outputIndex).indexUsedByDriver, levelZeroTensor);+ }}+_isTensorChanged = false;}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 e4e97142cd9..6d630904641 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@@ -13,40 +13,167 @@#include "intel_npu/config/options.hpp"#include "intel_npu/prefix.hpp"#include "intel_npu/utils/logger/logger.hpp"+#include "intel_npu/utils/vm/mem_ref_type.hpp"+#include "intel_npu/utils/vm/npu_vm_runtime_api.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_remote_tensor.hpp"#include "intel_npu/utils/zero/zero_types.hpp"+#include "zero_infer_request.hpp"-namespace {-std::vector<size_t> get_strides(const std::vector<size_t>& strides_in_bytes, size_t element_size) {- std::vector<size_t> element_strides(strides_in_bytes.size());- std::transform(strides_in_bytes.begin(),- strides_in_bytes.end(),- element_strides.begin(),- [element_size](size_t byte_stride) {- OPENVINO_ASSERT(byte_stride % element_size == 0,- "Stride ",- byte_stride,- " bytes is not aligned to element size ",- element_size,- " bytes. Strides must be multiples of element size.");-- return byte_stride / element_size;- });-- return element_strides;+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) {}++ ~MemRefTypeImpl() {+ destroyMemRef();+ }++ void alignWithHandle(MemRefType& memref) {+ if (_memRef == nullptr) {+ return;+ }++ if (npuVMRuntimeParseMemRef(_memRef,+ &memref._basePtr,+ &memref._data,+ &memref._offset,+ memref._sizes.data(),+ memref._strides.data(),+ &memref._dimsCount) != NPU_VM_RUNTIME_RESULT_SUCCESS) {+ OPENVINO_THROW("Failed to parse MemRef handle");+ }+ }++ void UpdateMemRefHandleStatus(MemRefType& memref) {+ // Update current MemRef handle to use latest metadata+ 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;+ }+ }+ 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");+ }+ }++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");+ }+ }+ }++ void destroyMemRef() {+ if (_memRef != nullptr) {+ npuVMRuntimeDestroyMemRef(_memRef);+ _memRef = nullptr;+ }+ }};-} // namespace+VMExecutionContext::~VMExecutionContext() {+ if (_handle != nullptr) {+ npuVMRuntimeDestroyExecutionContext(_handle);+ _handle = nullptr;+ }+}++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");+ }+ }+ return _handle;+}++// Init _inputsMemRef and _outputsMemRef vectors+void DynamicArguments::setArgumentProperties(uint32_t argi,+ const void* argv,+ 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]);+ }+ };++ if (argi < _inputsMemRef.size()) {+ assign_slot(_inputsMemRef[argi]);+ } else {+ auto idx = argi - _inputsMemRef.size();+ if (idx < _outputsMemRef.size()) {+ assign_slot(_outputsMemRef[idx]);+ }+ }+}-namespace intel_npu {DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,const std::shared_ptr<IGraph>& graph,const Config& config,const std::vector<std::vector<std::shared_ptr<ZeroTensor>>>& input_tensors,const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors,- std::shared_ptr<IDynamicGraph::GraphArguments> requestBinding,size_t batch_size): IPipeline(init_structs, graph, batch_size, config, "DynamicPipeline") {OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Zero_infer_request::DynamicPipeline::DynamicPipeline");@@ -55,9 +182,6 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& i_logger.debug("Initialization started, batch size: %zu", _batch_size);- intel_npu::IDynamicGraph* dynamicGraph = dynamic_cast<intel_npu::IDynamicGraph*>(graph.get());- OPENVINO_ASSERT(dynamicGraph != nullptr, "Failed to cast graph to IDynamicGraph");-if (!_sync_output_with_fences) {_event_pool = std::make_shared<EventPool>(_init_structs, _batch_size ? static_cast<uint32_t>(_batch_size) : 1);@@ -68,18 +192,14 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& i}_logger.debug("Event pool and command queue setup completed");- uint64_t num_of_subgraphs = dynamicGraph->get_num_subgraphs();+ const uint64_t num_of_subgraphs = _graph->get_metadata().numberOfSubgraphs;+_command_lists.reserve(_batch_size);- if (batch_size > 1) {- _logger.debug("Batch size %zu greater than 1, use new graph arguments for each batch", batch_size);+ if (batch_size >= 1) {+ _logger.debug("Initializing %zu command list group(s) (batch size %zu)", batch_size, batch_size);for (size_t i = 0; i < _batch_size; i++) {- _command_lists.emplace_back(- std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs, nullptr));+ _command_lists.emplace_back(std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs));}- } else if (batch_size == 1) {- _logger.debug("Batch size is 1, use the same graph arguments for all command lists");- _command_lists.emplace_back(- std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs, requestBinding));} else {OPENVINO_THROW("Batch size must be greater than 0, but got ", batch_size);}@@ -94,33 +214,25 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& ifor (size_t i = 0; i < _batch_size; i++) {_logger.debug("Set args for command list number: %zu", i);- _command_lists.at(i)->bind(dynamicGraph);- auto& graphArguments = _command_lists.at(i)->getBinding();+ _command_lists.at(i)->initArguments(_graph->get_metadata());+ auto& dynamicArguments = _command_lists.at(i)->getArguments();size_t io_index = 0;for (const auto& desc : _graph->get_metadata().inputs) {- if (desc.isMainInputWeights) {- // These values were set while running the "WeightlessGraph::init" method- continue;- }+ // DynamicPipeline does not currently support weightless model, just thrown exception.+ OPENVINO_ASSERT(!desc.isMainInputWeights,+ "DynamicPipeline does not support weightless graphs (input '",+ desc.nameFromCompiler,+ "' is a main-input weight)");if (input_tensors.at(io_index).size() > 1) {_logger.debug("Set args for input index: %zu", io_index);const auto& tensor = input_tensors.at(io_index).at(i);- if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() ||- tensor->get_strides().empty()) {- dynamicGraph->set_argument_value(desc.indexUsedByDriver, tensor->data());- } else {- dynamicGraph->set_argument_value_with_strides(- desc.indexUsedByDriver,- tensor->data(),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));- }size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();- graphArguments.setArgumentProperties(desc.indexUsedByDriver,- tensor->data(),- tensor->get_shape(),- get_strides(tensor->get_strides(), elementSize));+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,+ tensor->data(),+ tensor->get_shape(),+ get_strides(tensor->get_strides(), elementSize));++io_index;continue;}@@ -129,20 +241,13 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& iconst auto& tensor = input_tensors.at(io_index).at(0);size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() || tensor->get_strides().empty()) {- dynamicGraph->set_argument_value(- desc.indexUsedByDriver,- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size);- graphArguments.setArgumentProperties(+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size,tensor->get_shape(),get_strides(tensor->get_strides(), elementSize));} else {- dynamicGraph->set_argument_value_with_strides(- desc.indexUsedByDriver,- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));- graphArguments.setArgumentProperties(+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),tensor->get_shape(),@@ -157,21 +262,13 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& iconst auto& tensor = output_tensors.at(io_index);size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() || tensor->get_strides().empty()) {- dynamicGraph->set_argument_value(- desc.indexUsedByDriver,- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size);- graphArguments.setArgumentProperties(+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size,tensor->get_shape(),get_strides(tensor->get_strides(), elementSize));} else {- dynamicGraph->set_argument_value_with_strides(- desc.indexUsedByDriver,- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),- get_strides(tensor->get_strides(), elementSize));-- graphArguments.setArgumentProperties(+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),tensor->get_shape(),@@ -186,8 +283,8 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& ivoid DynamicPipeline::push() {_logger.debug("push - started");- auto* dynamicGraph = dynamic_cast<IDynamicGraph*>(_graph.get());- OPENVINO_ASSERT(dynamicGraph != nullptr, "Failed to cast graph to IDynamicGraph");+ 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());@@ -212,30 +309,244 @@ void DynamicPipeline::push() {}auto& command_lists = _command_lists.at(i);- auto& graphArguments = command_lists->getBinding();+ auto& dynamicArguments = command_lists->getArguments();if (_logger.level() >= ov::log::Level::DEBUG) {_logger.debug("push - inputs info for dynamic graph:");- for (auto& memType : graphArguments._inputs) {+ for (auto& memType : dynamicArguments._inputsMemRef) {_logger.debug("push - input: %s", memType.toString().c_str());}_logger.debug("push - outputs info for dynamic graph:");- for (auto& memType : graphArguments._outputs) {+ for (auto& memType : dynamicArguments._outputsMemRef) {_logger.debug("push - output: %s", memType.toString().c_str());}}- dynamicGraph->execute(_init_structs,- graphArguments,- command_lists->getHandles(),- commandQueueHandle,- fence,- event,- nullptr);+ execute_vm_runtime(vmRuntime, dynamicArguments, command_lists->getHandles(), commandQueueHandle, fence, event);}_logger.debug("push - completed");}+void DynamicPipeline::execute_vm_runtime(npu_vm_runtime_handle_t vmRuntime,+ DynamicArguments& args,+ std::vector<ze_command_list_handle_t>& commandLists,+ ze_command_queue_handle_t commandQueue,+ ze_fence_handle_t fence,+ ze_event_handle_t event) {+ _logger.debug("Start to execute graph with runtime engine");++ const bool firstInference = !args._commandListsRecorded;+ bool noTensorChange = true;++ // These vectors only stage the memref handle pointers for the npuVMRuntimeExecute call below. The handle objects+ // themselves are owned by the persistent DynamicArguments (args._inputsMemRef[i]._impl), so keeping these vectors+ // local is safe even though device execution is async.+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputMemRefHandles, outputMemRefHandles;++ auto processMemRefs = [&](auto& memRefs, auto& targetMemRefHandles) {+ targetMemRefHandles.clear();+ targetMemRefHandles.reserve(memRefs.size());++ for (auto& memref : memRefs) {+ std::shared_ptr<MemRefTypeImpl> impl = std::static_pointer_cast<MemRefTypeImpl>(memref._impl);+ if (impl == nullptr) {+ impl = std::make_shared<MemRefTypeImpl>();+ memref._impl = impl;+ }+ impl->UpdateMemRefHandleStatus(memref);++ // VM runtime execute path always needs current memref handles.+ targetMemRefHandles.push_back(impl->_memRef);++ if (impl->_ptrUpdated || impl->_shapeUpdated || impl->_strideUpdated) {+ noTensorChange = false;+ }+ }+ };++ processMemRefs(args._inputsMemRef, inputMemRefHandles);+ processMemRefs(args._outputsMemRef, outputMemRefHandles);++ if (!firstInference && noTensorChange) {+ _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;+ }++ _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) {+ const auto result = zeCommandListReset(cmdList);+ if (result != ZE_RESULT_SUCCESS) {+ OPENVINO_THROW("Failed to reset command list");+ }+ }++ npu_vm_runtime_execute_params_t params = {};+ params.executionContext = _executionContext.ensure(vmRuntime);+ params.pInputs = inputMemRefHandles.data();+ params.numOfInputs = static_cast<uint32_t>(inputMemRefHandles.size());+ params.pOutputs = outputMemRefHandles.data();+ params.numOfOutputs = static_cast<uint32_t>(outputMemRefHandles.size());+ params.ctx = _init_structs->getContext();+ params.device = _init_structs->getDevice();+ params.graphDdiTableExt = _init_structs->getGraphDdiTable().getImpl();+ params.commandLists = commandLists.data();+ params.numCommandLists = static_cast<uint64_t>(commandLists.size());+ params.commandQueue = commandQueue;+ params.inferenceFence = fence;+ params.event = event;++ _logger.debug("Execute graph with runtime engine");+ if (npuVMRuntimeExecute(vmRuntime, ¶ms) != NPU_VM_RUNTIME_RESULT_SUCCESS) {+ OPENVINO_THROW("Failed to execute VM runtime engine");+ }+ _logger.debug("Execution runtime engine is created successfully.");++ args._commandListsRecorded = true;+ _logger.debug("Completed to execute graph with runtime engine");+}++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) {+ _logger.debug("predict_output_shapes - started");++ const npu_vm_runtime_handle_t vmRuntime = static_cast<npu_vm_runtime_handle_t>(_graph->get_handle());+ OPENVINO_ASSERT(vmRuntime != nullptr, "predict_output_shapes requires a valid VM runtime engine");++ // Convert OV tensors/metadata into MemRef descriptors. A nullptr tensor falls back to the graph metadata+ // max shape. This keeps MemRef/DynamicArguments knowledge confined to the pipeline layer.+ const auto& metadata = _graph->get_metadata();+ auto buildMemRefs = [](const std::vector<std::shared_ptr<ov::ITensor>>& tensors,+ const std::vector<IODescriptor>& descriptors) {+ OPENVINO_ASSERT(tensors.size() == descriptors.size(),+ "Tensor count does not match descriptor count: ",+ tensors.size(),+ " vs ",+ descriptors.size());+ std::vector<MemRefType> memRefs(descriptors.size());+ for (size_t i = 0; i < memRefs.size(); ++i) {+ const auto& tensor = tensors.at(i);+ if (tensor != nullptr) {+ // Use userTensor or levelzero Tensor to update memref handle+ memRefs[i].set(get_tensor_data_ptr(tensor), 0, tensor);+ } else {+ // If all tensors are not set, use metadata+ memRefs[i].setArg(nullptr);+ memRefs[i]._offset = 0;+ // TODO : BatchSize not checked here+ memRefs[i].setSize(descriptors.at(i).shapeFromCompiler.get_max_shape());+ memRefs[i].updateStride();+ }+ }+ return memRefs;+ };++ std::vector<MemRefType> inputsMemRefs = buildMemRefs(inputTensors, metadata.inputs);+ std::vector<MemRefType> outputsMemRefs = buildMemRefs(outputTensors, metadata.outputs);++ // Snapshot the pre-prediction (input-derived) output shapes to detect shape changes after prediction.+ const std::vector<MemRefType> originalOutputMemRefs(outputsMemRefs);++ std::vector<npu_vm_runtime_mem_ref_handle_t> inputMemRefHandles, outputMemRefHandles;++ auto processMemRefs = [&](auto& memRefs, auto& destMemRefHandles) {+ destMemRefHandles.clear();+ destMemRefHandles.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);+ destMemRefHandles.push_back(impl->_memRef);+ }+ };++ processMemRefs(inputsMemRefs, inputMemRefHandles);+ 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));++ if (version == 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());+ params.pOutputs = outputMemRefHandles.data();+ params.numOfOutputs = static_cast<uint32_t>(outputMemRefHandles.size());++ result = npuVMRuntimePredictOutputShape(vmRuntime, ¶ms);+ } else {+ npu_vm_runtime_predict_output_shape_params_t2 params{};+ params.pInputs = inputMemRefHandles.data();+ 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);++ result = npuVMRuntimePredictOutputShape2(vmRuntime, ¶ms);+ }++ if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {+ OPENVINO_THROW("Failed to predict output shape with VM runtime engine, error code: ", result);+ } else {+ 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.");+ }+ outImpl->alignWithHandle(out);+ }+ _logger.debug("Output shape prediction is done successfully.");+ }++ // Build predicted output shapes (OV shapes) and detect whether prediction changed any+ // output shape vs the pre-prediction (input-derived) shapes. MemRef stays internal to the pipeline layer.+ std::vector<ov::Shape> predictedShapes(outputsMemRefs.size());+ bool outputShapeChanged = false;+ for (size_t i = 0; i < outputsMemRefs.size(); ++i) {+ ov::Shape shape;+ shape.reserve(static_cast<size_t>(outputsMemRefs[i]._dimsCount));+ for (int64_t j = 0; j < outputsMemRefs[i]._dimsCount; ++j) {+ shape.push_back(static_cast<size_t>(outputsMemRefs[i]._sizes[j]));+ }+ predictedShapes[i] = std::move(shape);++ if (!outputShapeChanged && !outputsMemRefs[i].compare(originalOutputMemRefs[i])) {+ outputShapeChanged = true;+ }+ }+ if (outputShapeChanged) {+ _logger.debug("predict_output_shapes - output shape change detected");+ }++ if (_logger.level() >= ov::log::Level::DEBUG) {+ for (size_t i = 0; i < predictedShapes.size(); ++i) {+ _logger.debug("predict_output_shapes - output %zu predicted shape: %s",+ i,+ predictedShapes[i].to_string().c_str());+ }+ }+ return predictedShapes;+}+void DynamicPipeline::pull() {_logger.debug("pull - started");OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PULL, itt::domains::LevelZeroBackend, "DynamicPipeline", "pull");diff --git a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cppindex 710bfde2b0f..cb96f2a8a0b 100644--- a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp@@ -7,6 +7,8 @@#include <level_zero/ze_api.h>#include <ze_graph_ext.h>+#include <algorithm>+#include "intel_npu/common/itt.hpp"#include "intel_npu/config/options.hpp"#include "intel_npu/utils/logger/logger.hpp"@@ -15,25 +17,6 @@namespace {-std::vector<size_t> get_strides(const std::vector<size_t>& strides_in_bytes, size_t element_size) {- std::vector<size_t> element_strides(strides_in_bytes.size());- std::transform(strides_in_bytes.rbegin(),- strides_in_bytes.rend(),- element_strides.begin(),- [element_size](size_t byte_stride) {- OPENVINO_ASSERT(byte_stride % element_size == 0,- "Stride ",- byte_stride,- " bytes is not aligned to element size ",- element_size,- " bytes. Strides must be multiples of element size.");-- return byte_stride / element_size;- });-- return element_strides;-};-uint32_t get_graph_unique_id_or_throw(const std::shared_ptr<intel_npu::IGraph>& graph) {OPENVINO_ASSERT(graph != nullptr, "Failed to create pipeline: graph is null");return graph->get_unique_id();@@ -43,6 +26,38 @@ uint32_t get_graph_unique_id_or_throw(const std::shared_ptr<intel_npu::IGraph>&namespace intel_npu {+std::vector<size_t> IPipeline::get_strides(const std::vector<size_t>& strides_in_bytes,+ size_t element_size,+ bool reverse_order) {+ OPENVINO_ASSERT(element_size != 0, "Element size must be greater than 0");++ std::vector<size_t> element_strides(strides_in_bytes.size());+ const auto convert_to_element_stride = [element_size](size_t byte_stride) {+ OPENVINO_ASSERT(byte_stride % element_size == 0,+ "Stride ",+ byte_stride,+ " bytes is not aligned to element size ",+ element_size,+ " bytes. Strides must be multiples of element size.");++ return byte_stride / element_size;+ };++ if (reverse_order) {+ std::transform(strides_in_bytes.rbegin(),+ strides_in_bytes.rend(),+ element_strides.begin(),+ convert_to_element_stride);+ } else {+ std::transform(strides_in_bytes.begin(),+ strides_in_bytes.end(),+ element_strides.begin(),+ convert_to_element_stride);+ }++ return element_strides;+}+IPipeline::IPipeline(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,const std::shared_ptr<IGraph>& graph,size_t batch_size,@@ -130,6 +145,8 @@ void IPipeline::enable_profiling() {if (profiling_pool->create()) {_profiling_query->create(profiling_pool);+ } else {+ _logger.warning("enable_profiling - failed to create profiling pool, profiling will not be available");}}@@ -192,7 +209,7 @@ Pipeline::Pipeline(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,_graph->set_argument_value_with_strides(desc.indexUsedByDriver,tensor->data(),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));+ get_strides(tensor->get_strides(), tensor->get_element_type().size(), true));}++io_index;continue;@@ -207,7 +224,7 @@ Pipeline::Pipeline(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,_graph->set_argument_value_with_strides(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));+ get_strides(tensor->get_strides(), tensor->get_element_type().size(), true));}++io_index;@@ -224,7 +241,7 @@ Pipeline::Pipeline(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,_graph->set_argument_value_with_strides(desc.indexUsedByDriver,static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));+ get_strides(tensor->get_strides(), tensor->get_element_type().size(), true));}++io_index;}@@ -370,7 +387,7 @@ void Pipeline::update_graph_arguments(uint32_t index,_command_lists.at(i)->updateMutableCommandListWithStrides(index,static_cast<const unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));+ get_strides(tensor->get_strides(), tensor->get_element_type().size(), true));}}};@@ -395,7 +412,7 @@ void Pipeline::update_graph_arguments(uint32_t index,->updateMutableCommandListWithStrides(index,tensor->data(),- get_strides(tensor->get_strides(), tensor->get_element_type().size()));+ get_strides(tensor->get_strides(), tensor->get_element_type().size(), true));}};diff --git a/src/plugins/intel_npu/src/backend/src/zero_profiling.cpp b/src/plugins/intel_npu/src/backend/src/zero_profiling.cppindex c7cd61f4f86..27433adfde9 100644--- a/src/plugins/intel_npu/src/backend/src/zero_profiling.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_profiling.cpp@@ -35,8 +35,16 @@ struct ZeProfilingTypeId<uint8_t> {};bool ProfilingPool::create() {- auto ret =- _init_structs->getProfilingDdiTable().pfnProfilingPoolCreate(_graph->get_handle(), _profiling_count, &_handle);+ // To avoid dynamic infer flow + perf_count_enabled calling static_cast<ze_graph_handle_t> which is not supported+ // in dynamic graph+ if (_graph->is_dynamic()) {+ return false;+ }++ auto ret = _init_structs->getProfilingDdiTable().pfnProfilingPoolCreate(+ static_cast<ze_graph_handle_t>(_graph->get_handle()),+ _profiling_count,+ &_handle);return ((ZE_RESULT_SUCCESS == ret) && (_handle != nullptr));}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.hppdeleted file mode 100644index cd179c2b9f5..00000000000--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/idynamic_graph.hpp+++ /dev/null@@ -1,80 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "intel_npu/common/igraph.hpp"-#include "intel_npu/utils/zero/zero_init.hpp"--namespace intel_npu {--class IDynamicGraph : public IGraph {-public:- struct MemRefType {- const void* _basePtr;- const void* _data;- int64_t _offset;- std::vector<int64_t> _sizes;- std::vector<int64_t> _strides;- int64_t _dimsCount;- std::shared_ptr<void> _impl;-- MemRefType() : _basePtr(nullptr), _data(nullptr), _offset(0), _sizes(), _strides(), _dimsCount(0) {}-- MemRefType(const void* basePtr,- const void* data,- int64_t offset,- const std::vector<int64_t>& sizes,- const std::vector<int64_t>& strides,- int64_t dimsCount)- : _basePtr(basePtr),- _data(data),- _offset(offset),- _sizes(sizes),- _strides(strides),- _dimsCount(dimsCount) {}-- 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);- friend std::ostream& operator<<(std::ostream& os, const IDynamicGraph::MemRefType& memRef);- std::string toString();- };-- struct GraphArguments {- std::vector<MemRefType> _inputs;- std::vector<MemRefType> _outputs;- std::shared_ptr<void> _impl;-- void setArgumentValue(uint32_t argi, const void* argv);- void setArgumentProperties(uint32_t argi,- const void* argv,- const ov::Shape& shapes,- const std::vector<size_t>& strides);- };-- IDynamicGraph() = default;- ~IDynamicGraph() override = default;-- virtual void execute(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- ze_fence_handle_t inferenceFence,- ze_event_handle_t event,- ze_graph_profiling_pool_handle_t profiling);-- virtual void getBinding(GraphArguments& args);-- virtual uint64_t get_num_subgraphs() const;-- virtual void predict_output_shape(GraphArguments& args,- std::vector<MemRefType>& inputDescriptors,- std::vector<MemRefType>& outputDescriptors);-};--} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hppindex d4c87a38a5e..92b58d6f22e 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp@@ -44,7 +44,14 @@ public:virtual ~IGraph() = default;virtual const NetworkMetadata& get_metadata() const;- virtual ze_graph_handle_t get_handle() const;+ // Returns the underlying native handle. Concrete graphs return different handle types:+ // Graph -> ze_graph_handle_t+ // DynamicGraph -> npu_vm_runtime_handle_t+ // Callers must static_cast the result to the type matching the concrete graph implementation.+ virtual void* get_handle() const;++ // Returns true if the graph is executed through the VM runtime (dynamic graph), false otherwise.+ virtual bool is_dynamic() const;virtual void update_network_name(std::string_view name);diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/network_metadata.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/network_metadata.hppindex e64fe319d5a..a9dce3f279b 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/network_metadata.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/network_metadata.hpp@@ -146,6 +146,12 @@ struct NetworkMetadata final {size_t numStreams = 1;+ /**+ * @brief The number of subgraphs the compiled network is split into.+ * @note The value is 1 for static graphs; dynamic graphs may be split into multiple subgraphs.+ */+ uint64_t numberOfSubgraphs = 1;+/*** @brief Binds the (state input, state output) and (dynamic tensor, shape tensor) pairs using the* "relatedDescriptorIndex" attribute.diff --git a/src/plugins/intel_npu/src/common/src/igraph.cpp b/src/plugins/intel_npu/src/common/src/igraph.cppindex 513890005df..fd1e0b463e5 100644--- a/src/plugins/intel_npu/src/common/src/igraph.cpp+++ b/src/plugins/intel_npu/src/common/src/igraph.cpp@@ -46,10 +46,14 @@ const NetworkMetadata& IGraph::get_metadata() const {OPENVINO_THROW("get_metadata not implemented");}-ze_graph_handle_t IGraph::get_handle() const {+void* IGraph::get_handle() const {OPENVINO_THROW("get_handle not implemented");}+bool IGraph::is_dynamic() const {+ return false;+}+void IGraph::update_network_name(std::string_view) {OPENVINO_THROW("update_network_name not implemented");}diff --git a/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt b/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txtindex 08161856f57..a27d50d0415 100644--- a/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt+++ b/src/plugins/intel_npu/src/compiler_adapter/CMakeLists.txt@@ -8,7 +8,7 @@ file(GLOB_RECURSE SOURCES *.cpp *.hpp *.h)source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})-add_library(${TARGET_NAME} STATIC ${SOURCES} $<TARGET_OBJECTS:openvino_npu_vcl_utils> $<TARGET_OBJECTS:openvino_npu_vm_utils>)+add_library(${TARGET_NAME} STATIC ${SOURCES} $<TARGET_OBJECTS:openvino_npu_vcl_utils>)ov_build_target_faster(${TARGET_NAME}PCH_HEADER "src/precomp.hpp"@@ -20,6 +20,8 @@ ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})target_include_directories(${TARGET_NAME}PUBLIC$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>+ PRIVATE+ $<TARGET_PROPERTY:openvino_npu_vm_utils,INTERFACE_INCLUDE_DIRECTORIES>)target_link_libraries(${TARGET_NAME}@@ -27,7 +29,6 @@ target_link_libraries(${TARGET_NAME}openvino_npu_commonopenvino::npu_alopenvino::xml_util- openvino::npu_vm_runtime_api)#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 8abf5caeecd..3dd2696df85 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@@ -8,7 +8,7 @@#include <mutex>-#include "intel_npu/common/idynamic_graph.hpp"+#include "intel_npu/common/igraph.hpp"#include "intel_npu/common/network_metadata.hpp"#include "intel_npu/utils/vm/npu_vm_runtime_api.hpp"#include "intel_npu/utils/zero/zero_init.hpp"@@ -16,152 +16,19 @@#include "openvino/runtime/so_ptr.hpp"namespace intel_npu {-class DynamicGraph final : public IDynamicGraph {+class DynamicGraph final : public IGraph {public:- struct MemRefTypeImpl {- npu_vm_runtime_mem_ref_handle_t _memRef;- bool _ptrUpdated = false;- bool _shapeUpdated = false;- bool _strideUpdated = false;-- MemRefTypeImpl() : _memRef(nullptr) {}-- ~MemRefTypeImpl() {- destroyMemRef();- }-- void UpdateMemRefHandleStatus(MemRefType& memref) {- // Update current MemRef handle to use latest metadata- 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;- }- }- 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) {- throw std::runtime_error("Failed to update MemRef handle");- }- }-- void alignWithHandle(MemRefType& memref) {- if (_memRef == nullptr) {- return;- }-- if (npuVMRuntimeParseMemRef(_memRef,- &memref._basePtr,- &memref._data,- &memref._offset,- memref._sizes.data(),- memref._strides.data(),- &memref._dimsCount) != NPU_VM_RUNTIME_RESULT_SUCCESS) {- throw std::runtime_error("Failed to parse MemRef handle");- }- }-- 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");- }- }- }-- void destroyMemRef() {- if (_memRef != nullptr) {- npuVMRuntimeDestroyMemRef(_memRef);- _memRef = nullptr;- }- }- };-- struct GraphArgumentsImpl {- std::vector<npu_vm_runtime_mem_ref_handle_t> _inputMemRefs;- std::vector<npu_vm_runtime_mem_ref_handle_t> _outputMemRefs;- npu_vm_runtime_execute_params_t _executeParams = {};-- ~GraphArgumentsImpl() {- if (_executeParams.executionContext != nullptr) {- npuVMRuntimeDestroyExecutionContext(_executeParams.executionContext);- _executeParams.executionContext = nullptr;- }- }- };-- class Impl {- using MemRefTypeImpl = DynamicGraph::MemRefTypeImpl;-- public:- virtual void initialize(std::optional<ov::Tensor>& blob, NetworkMetadata& metadata) = 0;- virtual void setArgumentValue(uint32_t argi, const void* argv) = 0;- virtual void setArgumentValueWithStrides(uint32_t argi,- const void* argv,- const std::vector<size_t>& strides) = 0;- virtual uint64_t getNumSubgraphs() = 0;- virtual void getBinding(GraphArguments& binding) = 0;- virtual void executeGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- ze_fence_handle_t fence,- ze_event_handle_t event,- ze_graph_profiling_pool_handle_t profiling) = 0;- virtual void predictOutputShape(GraphArguments& args,- std::vector<MemRefType>& inputDescriptors,- std::vector<MemRefType>& outputDescriptors) = 0;- virtual ~Impl() {};- };-DynamicGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,ov::Tensor blob,- bool blobAllocatedByPlugin,const FilteredConfig& config);std::pair<uint64_t, std::optional<std::vector<uint64_t>>> export_blob(std::ostream& stream) const override;- void set_argument_value(uint32_t argi, const void* argv) const override;-- void set_argument_value_with_strides(uint32_t id,- const void* data,- const std::vector<size_t>& strides) const override;+ void* get_handle() const override;- ze_graph_handle_t get_handle() const override;+ bool is_dynamic() const override {+ return true;+ }~DynamicGraph() override;@@ -181,22 +48,6 @@ public:void set_last_submitted_id(uint32_t id_index) override;uint32_t get_last_submitted_id() const override;- void execute(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- ze_fence_handle_t inferenceFence,- ze_event_handle_t event,- ze_graph_profiling_pool_handle_t profiling) override;-- void getBinding(GraphArguments& args) override;-- uint64_t get_num_subgraphs() const override;-- void predict_output_shape(GraphArguments& args,- std::vector<MemRefType>& inputDescriptors,- std::vector<MemRefType>& outputDescriptors) override;-std::optional<bool> is_profiling_blob() const override;std::optional<std::string_view> get_compatibility_descriptor() const override;@@ -207,6 +58,10 @@ private:bool release_blob(const FilteredConfig& config);std::optional<size_t> determine_batch_size();+ void initialize_engine();+ void create_execution_engine();+ void prepare_metadata();+std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;NetworkMetadata _metadata;@@ -216,12 +71,6 @@ private:std::optional<ov::WorkloadType> _workloadType = std::nullopt;std::shared_ptr<CommandQueue> _commandQueue = nullptr;- /**- * @brief Stores the number of subgraphs for dynamic models- * @note the number of subgraphs will be one for static models- */- uint64_t _num_of_subgraphs = 1;-mutable std::mutex _commandQueueDescMutex;CommandQueueDesc _commandQueueDesc;std::vector<std::shared_ptr<Event>> _lastSubmittedEvent;@@ -243,7 +92,9 @@ private:Logger _logger;- std::unique_ptr<Impl> _impl;+ npu_vm_runtime_handle_t _engine = nullptr;+ npu_vm_runtime_properties_t _engineProperties{};+ bool _engineInitialized = false;};} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hppindex 18ac0ccbae4..30ddae9752a 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp@@ -40,7 +40,7 @@ public:const std::vector<size_t>& strides) const override;const NetworkMetadata& get_metadata() const override;- ze_graph_handle_t get_handle() const override;+ void* get_handle() const override;void update_network_name(std::string_view name) override;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 27cd7972fca..e5a14d2ec95 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,6 +4,7 @@#include "dynamic_graph.hpp"+#include <array>#include <iostream>#include <iterator>@@ -19,106 +20,10 @@namespace intel_npu {-class DynamicGraphImpl : public DynamicGraph::Impl {-public:- using MemRefType = DynamicGraph::MemRefType;--public:- DynamicGraphImpl() : _engineProperties{}, _logger("DynamicGraphImpl", Logger::global().level()) {}- void initialize(std::optional<ov::Tensor>& blob, NetworkMetadata& metadata) override;- void createExecutionEngine(std::optional<ov::Tensor>& blob);- void prepareMetadata(NetworkMetadata& metadata);- void initializeDynamicGraphExecution(std::optional<ov::Tensor>& blob, NetworkMetadata& metadata);- void setArgumentValue(uint32_t argi, const void* argv) override;- void setArgumentValueWithStrides(uint32_t argi, const void* argv, const std::vector<size_t>& strides) override;- uint64_t getNumSubgraphs() override {- return _engineProperties.numOfSubGraphs;- }- void executeGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- DynamicGraph::GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- ze_fence_handle_t inferenceFence,- ze_event_handle_t event,- ze_graph_profiling_pool_handle_t profiling) override;- void getBinding(DynamicGraph::GraphArguments& binding) override;-- virtual ~DynamicGraphImpl() {- destroy();- }-- void destroy() {- if (_engine != nullptr) {- npuVMRuntimeDestroy(_engine);- _engine = nullptr;- }- }-- void predictOutputShape(DynamicGraph::GraphArguments& args,- std::vector<DynamicGraph::MemRefType>& inputDescriptors,- std::vector<DynamicGraph::MemRefType>& outputDescriptors) override;--public:- npu_vm_runtime_handle_t _engine = nullptr;- npu_vm_runtime_properties_t _engineProperties;- DynamicGraph::GraphArguments _binding;- bool _initialized = false;- Logger _logger;-};--void DynamicGraphImpl::initialize(std::optional<ov::Tensor>& blob, NetworkMetadata& metadata) {- if (!_initialized) {- initializeDynamicGraphExecution(blob, metadata);- _initialized = true;- }-- _binding._inputs.resize(metadata.inputs.size());-- 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;- for (size_t i = 0; i < inputs.size(); ++i) {- // Use size as placeholder of stride- const auto& shape = metadata.inputs[i].shapeFromCompiler.get_shape();- std::vector<int64_t> shapeVec(shape.begin(), shape.end());- inputs[i] = MemRefType(nullptr, nullptr, 0, shapeVec, shapeVec, shapeVec.size());- // Calc real stride- inputs[i].updateStride();- }-- _binding._outputs.resize(metadata.outputs.size());- auto& outputs = _binding._outputs;- for (size_t i = 0; i < outputs.size(); ++i) {- const auto& shape = metadata.outputs[i].shapeFromCompiler.get_shape();- std::vector<int64_t> shapeVec(shape.begin(), shape.end());- outputs[i] = MemRefType(nullptr, nullptr, 0, shapeVec, shapeVec, shapeVec.size());- outputs[i].updateStride();- }-}--void DynamicGraphImpl::createExecutionEngine(std::optional<ov::Tensor>& blob) {+void DynamicGraph::create_execution_engine() {npu_vm_runtime_blob_desc_t blobDesc;- blobDesc.pInput = reinterpret_cast<const uint8_t*>(blob.value().data());- blobDesc.inputSize = blob.value().get_byte_size();+ 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) {OPENVINO_THROW("Failed to create VM runtime engine");@@ -215,15 +120,14 @@ static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,metadata.has_value() ? std::optional(shapeFromIRModel) : std::nullopt};}-void DynamicGraphImpl::prepareMetadata(NetworkMetadata& metadata) {- metadata.inputs.clear();- metadata.outputs.clear();+void DynamicGraph::prepare_metadata() {+ _metadata.inputs.clear();+ _metadata.outputs.clear();for (uint32_t i = 0; i < _engineProperties.numOfGraphArgs; ++i) {// TODO: follow graph ext to support Optional metadata for weightless modelze_graph_argument_properties_3_t arg;ze_graph_argument_metadata_t meta;- std::vector<int64_t> upperBound;- upperBound.reserve(ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE);+ std::array<int64_t, ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE> upperBound = {};if (npuVMRuntimeGetMetadata(_engine, i, &arg, &meta, upperBound.data()) != NPU_VM_RUNTIME_RESULT_SUCCESS) {OPENVINO_THROW("Failed to get VM runtime metadata");}@@ -233,10 +137,10 @@ void DynamicGraphImpl::prepareMetadata(NetworkMetadata& metadata) {ioDesc.supportsStridedLayout = true;switch (arg.type) {case ZE_GRAPH_ARGUMENT_TYPE_INPUT: {- metadata.inputs.push_back(std::move(ioDesc));+ _metadata.inputs.push_back(std::move(ioDesc));} break;case ZE_GRAPH_ARGUMENT_TYPE_OUTPUT: {- metadata.outputs.push_back(std::move(ioDesc));+ _metadata.outputs.push_back(std::move(ioDesc));} break;default: {OPENVINO_THROW("Invalid ze_graph_argument_type_t found in ze_graph_argument_properties_3_t object: ",@@ -244,244 +148,45 @@ void DynamicGraphImpl::prepareMetadata(NetworkMetadata& metadata) {}}}- metadata.bindRelatedDescriptors();-}--void DynamicGraphImpl::getBinding(DynamicGraph::GraphArguments& binding) {- binding = _binding;-}--void DynamicGraphImpl::initializeDynamicGraphExecution(std::optional<ov::Tensor>& blob, NetworkMetadata& metadata) {- createExecutionEngine(blob);- prepareMetadata(metadata);-- _logger.debug("num of subgraphs: %d inputs: %d outputs: %d",- _engineProperties.numOfSubGraphs,- metadata.inputs.size(),- metadata.outputs.size());-}--void DynamicGraphImpl::setArgumentValue(uint32_t argi, const void* argv) {- auto& inputs = _binding._inputs;- if (argi < inputs.size()) {- _logger.debug("setArgumentValue for index %d (input %d)", argi, argi);- inputs[argi].setArg(argv);- } else {- auto& outputs = _binding._outputs;- auto idx = argi - inputs.size();- _logger.debug("setArgumentValue for index %d (output %d)", argi, idx);- if (idx < outputs.size()) {- outputs[idx].setArg(argv);- }- }-}--void DynamicGraphImpl::setArgumentValueWithStrides(uint32_t argi,- const void* argv,- const std::vector<size_t>& strides) {- _logger.debug("setArgumentValueWithStrides for index %d", argi);- auto& inputs = _binding._inputs;- if (argi < inputs.size()) {- _logger.debug("setArgumentValueWithStrides for index %d (input %d)", argi, argi);- inputs[argi].setArg(argv);- // 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);- // The passed strides are based on elemnt- outputs[idx].setStrides(strides);- }- }+ _metadata.bindRelatedDescriptors();}-void DynamicGraphImpl::executeGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- IDynamicGraph::GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- 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 firstInference = argsImpl->_executeParams.graphDdiTableExt == nullptr;- 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);- if (inImpl == nullptr) {- inImpl = std::make_shared<DynamicGraph::MemRefTypeImpl>();- in._impl = inImpl;- }- inImpl->UpdateMemRefHandleStatus(in);- if (firstInference) {- argsImpl->_inputMemRefs.push_back(inImpl->_memRef);- } else if (inImpl->_ptrUpdated || inImpl->_shapeUpdated || inImpl->_strideUpdated) {- noTensorChange = false;- }- }- for (auto& out : args._outputs) {- std::shared_ptr<DynamicGraph::MemRefTypeImpl> outImpl =- std::static_pointer_cast<DynamicGraph::MemRefTypeImpl>(out._impl);- if (outImpl == nullptr) {- outImpl = std::make_shared<DynamicGraph::MemRefTypeImpl>();- out._impl = outImpl;- }- outImpl->UpdateMemRefHandleStatus(out);- if (firstInference) {- argsImpl->_outputMemRefs.push_back(outImpl->_memRef);- } else if (outImpl->_ptrUpdated || outImpl->_shapeUpdated || outImpl->_strideUpdated) {- noTensorChange = false;- }- }-- if (firstInference || !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 arguments- if (params->executionContext == nullptr) {- if (npuVMRuntimeCreateExecutionContext(_engine, ¶ms->executionContext) != NPU_VM_RUNTIME_RESULT_SUCCESS) {- OPENVINO_THROW("Failed to create a VM execution context");- } else {- _logger.debug("Execution context is created successfully.");- }- }-- params->pInputs = argsImpl->_inputMemRefs.data();- params->numOfInputs = static_cast<uint32_t>(argsImpl->_inputMemRefs.size());- params->pOutputs = argsImpl->_outputMemRefs.data();- params->numOfOutputs = static_cast<uint32_t>(argsImpl->_outputMemRefs.size());- params->ctx = zeroInitStruct->getContext();- params->device = zeroInitStruct->getDevice();- params->graphDdiTableExt = zeroInitStruct->getGraphDdiTable().getImpl();- params->commandLists = commandLists.data();- params->numCommandLists = static_cast<uint64_t>(commandLists.size());- params->commandQueue = commandQueue;- params->inferenceFence = fence;- params->event = event;+void DynamicGraph::initialize_engine() {+ if (!_engineInitialized) {+ create_execution_engine();+ prepare_metadata();+ _engineInitialized = true;+ _metadata.numberOfSubgraphs = _engineProperties.numOfSubGraphs;- _logger.debug("Execute graph with runtime engine");- if (npuVMRuntimeExecute(_engine, params) != NPU_VM_RUNTIME_RESULT_SUCCESS) {- OPENVINO_THROW("Failed to execute VM runtime engine");+ _logger.debug("num of subgraphs: %d inputs: %d outputs: %d",+ _engineProperties.numOfSubGraphs,+ _metadata.inputs.size(),+ _metadata.outputs.size());}- if (args._impl == nullptr) {- args._impl = argsImpl;- }-}--void DynamicGraphImpl::predictOutputShape(DynamicGraph::GraphArguments& args,- std::vector<DynamicGraph::MemRefType>& inputDescriptors,- std::vector<DynamicGraph::MemRefType>& outputDescriptors) {- std::shared_ptr<DynamicGraph::GraphArgumentsImpl> argsImpl =- args._impl ? std::static_pointer_cast<DynamicGraph::GraphArgumentsImpl>(args._impl)- : std::make_shared<DynamicGraph::GraphArgumentsImpl>();-- std::vector<std::shared_ptr<DynamicGraph::MemRefTypeImpl>> inputMemRefImpls;- inputMemRefImpls.reserve(inputDescriptors.size());- std::vector<npu_vm_runtime_mem_ref_handle_t> inputHandles;- inputHandles.reserve(inputDescriptors.size());- for (auto& in : inputDescriptors) {- std::shared_ptr<DynamicGraph::MemRefTypeImpl> inImpl = std::make_shared<DynamicGraph::MemRefTypeImpl>();- inImpl->UpdateMemRefHandleStatus(in);- inputMemRefImpls.push_back(inImpl);- inputHandles.push_back(inImpl->_memRef);- }- std::vector<std::shared_ptr<DynamicGraph::MemRefTypeImpl>> outputMemRefImpls;- outputMemRefImpls.reserve(outputDescriptors.size());- std::vector<npu_vm_runtime_mem_ref_handle_t> outputHandles;- outputHandles.reserve(outputDescriptors.size());- for (auto& out : outputDescriptors) {- std::shared_ptr<DynamicGraph::MemRefTypeImpl> outImpl = std::make_shared<DynamicGraph::MemRefTypeImpl>();- outImpl->UpdateMemRefHandleStatus(out);- outputMemRefImpls.push_back(outImpl);- outputHandles.push_back(outImpl->_memRef);- }-- 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));-- if (version == NPU_VM_RUNTIME_VERSION_1_0) {- npu_vm_runtime_predict_output_shape_params_t params;- params.pInputs = inputHandles.data();- params.numOfInputs = static_cast<uint32_t>(inputHandles.size());- params.pOutputs = outputHandles.data();- params.numOfOutputs = static_cast<uint32_t>(outputHandles.size());-- result = npuVMRuntimePredictOutputShape(_engine, ¶ms);- } else {- npu_vm_runtime_execute_params_t* executeParams = &argsImpl->_executeParams;-- // Prepare execution context for each graph arguments- if (executeParams->executionContext == nullptr) {- if (npuVMRuntimeCreateExecutionContext(_engine, &executeParams->executionContext) !=- NPU_VM_RUNTIME_RESULT_SUCCESS) {- OPENVINO_THROW("Failed to create a VM execution context");- } else {- _logger.debug("Execution context is created successfully.");- }+ if (_logger.level() >= ov::log::Level::DEBUG) {+ _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");}-- npu_vm_runtime_predict_output_shape_params_t2 params;- params.pInputs = inputHandles.data();- params.numOfInputs = static_cast<uint32_t>(inputHandles.size());- params.pOutputs = outputHandles.data();- params.numOfOutputs = static_cast<uint32_t>(outputHandles.size());- params.executionContext = executeParams->executionContext;-- result = npuVMRuntimePredictOutputShape2(_engine, ¶ms);- }-- if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {- OPENVINO_THROW("Failed to predict output shape with VM runtime engine, error code: ", result);- } else {- for (size_t i = 0; i < outputDescriptors.size(); ++i) {- auto& out = outputDescriptors[i];- std::shared_ptr<DynamicGraph::MemRefTypeImpl> outImpl = outputMemRefImpls[i];- if (outImpl == nullptr) {- OPENVINO_THROW("MemRefType implementation is broken, unknown error happens in shape prediction.");- }- outImpl->alignWithHandle(out);+ _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");}- _logger.debug("Output shape prediction is done successfully.");- }-- if (args._impl == nullptr) {- args._impl = argsImpl;}}DynamicGraph::DynamicGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,ov::Tensor blob,- bool blobAllocatedByPlugin,const FilteredConfig& config): _zeroInitStruct(zeroInitStruct),_blob(std::move(blob)),@@ -492,14 +197,10 @@ DynamicGraph::DynamicGraph(const std::shared_ptr<ZeroInitStructsHolder>& zeroInireturn;}- _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// descriptors- _impl->initialize(_blob, _metadata);-- _num_of_subgraphs = _impl->getNumSubgraphs();+ initialize_engine();initialize(config);}@@ -617,39 +318,16 @@ void DynamicGraph::set_model_priority(const ov::hint::Priority modelPriority) {}}-void DynamicGraph::set_argument_value(uint32_t argi, const void* argv) const {- if (_impl == nullptr) {- _logger.warning("Graph handle is null, dynamic pipeline to handle set_argument_value");- return;- }-- _impl->setArgumentValue(argi, argv);-}--void DynamicGraph::set_argument_value_with_strides(uint32_t id,- const void* data,- const std::vector<size_t>& strides) const {- if (_impl == nullptr) {- _logger.warning("Graph handle is null, dynamic pipeline to handle set_argument_value");- return;- }-- _impl->setArgumentValueWithStrides(id, data, strides);-}--ze_graph_handle_t DynamicGraph::get_handle() const {- _logger.warning("DynamicGraph does not support get_handle() method.");- return nullptr;+void* DynamicGraph::get_handle() const {+ return _engine;}void DynamicGraph::initialize_impl(const FilteredConfig& config) {_logger.debug("Graph initialize start");- if (!_impl) {- _impl = std::make_unique<DynamicGraphImpl>();+ if (!_engineInitialized) {// initialize VM execution engine, metadata, input&output descriptors- _impl->initialize(_blob, _metadata);- _num_of_subgraphs = _impl->getNumSubgraphs();+ initialize_engine();}if (!_zeroInitStruct) {@@ -777,45 +455,10 @@ DynamicGraph::~DynamicGraph() {if (!_lastSubmittedEvent.empty()) {_lastSubmittedEvent.clear();}-}--void DynamicGraph::execute(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- DynamicGraph::GraphArguments& args,- std::vector<ze_command_list_handle_t>& commandLists,- ze_command_queue_handle_t commandQueue,- ze_fence_handle_t inferenceFence,- ze_event_handle_t event,- ze_graph_profiling_pool_handle_t profiling) {- auto impl = reinterpret_cast<DynamicGraphImpl*>(_impl.get());-- if (impl == nullptr)- return;-- impl->executeGraph(zeroInitStruct, args, commandLists, commandQueue, inferenceFence, event, profiling);-}--void DynamicGraph::getBinding(GraphArguments& args) {- auto impl = reinterpret_cast<DynamicGraphImpl*>(_impl.get());-- if (impl == nullptr)- return;-- impl->getBinding(args);-}--uint64_t DynamicGraph::get_num_subgraphs() const {- return _num_of_subgraphs;-}--void DynamicGraph::predict_output_shape(GraphArguments& args,- std::vector<MemRefType>& inputDescriptors,- std::vector<MemRefType>& outputDescriptors) {- auto impl = reinterpret_cast<DynamicGraphImpl*>(_impl.get());-- if (impl == nullptr)- return;-- impl->predictOutputShape(args, inputDescriptors, outputDescriptors);+ if (_engine != nullptr) {+ npuVMRuntimeDestroy(_engine);+ _engine = nullptr;+ }}std::optional<bool> DynamicGraph::is_profiling_blob() const {diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cppindex 1fe9c0d31f9..03528249e5c 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp@@ -107,7 +107,7 @@ void Graph::set_model_priority(const ov::hint::Priority modelPriority) {}}-ze_graph_handle_t Graph::get_handle() const {+void* Graph::get_handle() const {return _graphDesc._handle;}@@ -309,7 +309,8 @@ std::optional<bool> Graph::is_profiling_blob() const {ze_graph_properties_3_t graphProperties = {};graphProperties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES_3;- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties3(get_handle(), &graphProperties);+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties3(static_cast<ze_graph_handle_t>(get_handle()),+ &graphProperties);THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());return graphProperties.flags & ZE_GRAPH_PROPERTIES_FLAG_PROFILING_ENABLED;diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cppindex 4a5e5cc90c0..76c10d46ac6 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp@@ -44,7 +44,7 @@ std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,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!");NPUVMRuntimeApi::initializeFromBlob(data, size);- return std::make_shared<DynamicGraph>(_zeroInitStruct, mainBlob, true, config);+ return std::make_shared<DynamicGraph>(_zeroInitStruct, mainBlob, config);}GraphDescriptor mainGraphDesc;diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cppindex d7d5b16be08..402d9e41525 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp@@ -107,7 +107,7 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<con// metadata will be obtained in initialze() of DynamicGraph_logger.debug("Use dynamicGraph to hold blob for HostCompile mode!");- return std::make_shared<DynamicGraph>(_zeroInitStruct, std::move(tensor), true, config);+ return std::make_shared<DynamicGraph>(_zeroInitStruct, std::move(tensor), config);}GraphDescriptor graphDesc;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.hppnew file mode 100644index 00000000000..fee89ab1707--- /dev/null+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp@@ -0,0 +1,79 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <iosfwd>+#include <memory>+#include <string>+#include <vector>++#include "intel_npu/utils/vm/npu_vm_runtime.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/shape.hpp"+#include "openvino/runtime/itensor.hpp"++namespace intel_npu {++struct MemRefType {+ const void* _basePtr;+ const void* _data;+ int64_t _offset;+ std::vector<int64_t> _sizes;+ std::vector<int64_t> _strides;+ int64_t _dimsCount;+ std::shared_ptr<void> _impl;++ MemRefType() : _basePtr(nullptr), _data(nullptr), _offset(0), _sizes(), _strides(), _dimsCount(0) {}++ MemRefType(const void* basePtr,+ const void* data,+ int64_t offset,+ const std::vector<int64_t>& sizes,+ const std::vector<int64_t>& strides,+ int64_t dimsCount)+ : _basePtr(basePtr),+ _data(data),+ _offset(offset),+ _sizes(sizes),+ _strides(strides),+ _dimsCount(dimsCount) {}++ // Copy intentionally drops the runtime impl: VM MemRef handles must not be aliased+ // across copies (would cause double-destroy / shared device state).+ MemRefType(const MemRefType& other)+ : _basePtr(other._basePtr),+ _data(other._data),+ _offset(other._offset),+ _sizes(other._sizes),+ _strides(other._strides),+ _dimsCount(other._dimsCount) {}+ MemRefType& operator=(const MemRefType& other) {+ if (this != &other) {+ _basePtr = other._basePtr;+ _data = other._data;+ _offset = other._offset;+ _sizes = other._sizes;+ _strides = other._strides;+ _dimsCount = other._dimsCount;+ _impl.reset();+ }+ return *this;+ }+ MemRefType(MemRefType&&) noexcept = default;+ MemRefType& operator=(MemRefType&&) noexcept = default;+ ~MemRefType() = default;++ 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);+ friend std::ostream& operator<<(std::ostream& os, const MemRefType& memRef);+ std::string toString();+};++} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/vm/runtime/include/intel_npu/runtime/npu_vm_runtime.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hppsimilarity index 99%rename from src/plugins/intel_npu/src/vm/runtime/include/intel_npu/runtime/npu_vm_runtime.hpprename to src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hppindex b0078dd8efa..6b754414922 100644--- a/src/plugins/intel_npu/src/vm/runtime/include/intel_npu/runtime/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_graph_ext.h"#if defined(__cplusplus)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.hppindex 6ec9fdc386b..4fba6717b02 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@@ -10,7 +10,7 @@#include <type_traits>#include <utility>-#include "intel_npu/runtime/npu_vm_runtime.hpp"+#include "npu_vm_runtime.hpp"#include "openvino/core/except.hpp"namespace intel_npu {diff --git a/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txtindex 6264da970c6..95a6f78696a 100644--- a/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt+++ b/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt@@ -21,8 +21,11 @@ target_include_directories(${TARGET_NAME}$<TARGET_PROPERTY:openvino::util,INTERFACE_INCLUDE_DIRECTORIES>$<TARGET_PROPERTY:openvino::core::dev,INTERFACE_INCLUDE_DIRECTORIES>$<TARGET_PROPERTY:openvino::runtime::dev,INTERFACE_INCLUDE_DIRECTORIES>- $<TARGET_PROPERTY:npu_vm_runtime_api,INTERFACE_INCLUDE_DIRECTORIES>- $<TARGET_PROPERTY:openvino_npu_zero_utils,INTERFACE_INCLUDE_DIRECTORIES>+)++target_link_libraries(${TARGET_NAME} PUBLIC+ LevelZero::NPUExt # contain ze_graph_ext.h for npu_vm_runtime.hpp+ openvino::zero_loader # contain level_zero/ze_api.h> for npu_vm_runtime.hpp)if(NOT BUILD_SHARED_LIBS)diff --git a/src/plugins/intel_npu/src/common/src/idynamic_graph.cpp b/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cppsimilarity index 54%rename from src/plugins/intel_npu/src/common/src/idynamic_graph.cpprename to src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cppindex 61952d2f435..991a78502d7 100644--- a/src/plugins/intel_npu/src/common/src/idynamic_graph.cpp+++ b/src/plugins/intel_npu/src/utils/src/vm/mem_ref_type.cpp@@ -1,19 +1,21 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//-//-#include "intel_npu/common/idynamic_graph.hpp"+#include "intel_npu/utils/vm/mem_ref_type.hpp"++#include <sstream>+#include "intel_npu/utils/vm/npu_vm_runtime_api.hpp"#include "openvino/core/except.hpp"namespace intel_npu {-void IDynamicGraph::MemRefType::setArg(const void* arg) {+void MemRefType::setArg(const void* arg) {_basePtr = _data = arg;}-void IDynamicGraph::MemRefType::setSize(const ov::Shape& shape) {+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());@@ -31,7 +33,7 @@ void IDynamicGraph::MemRefType::setSize(const ov::Shape& shape) {}}-void IDynamicGraph::MemRefType::setStrides(const ov::Strides& strides, int32_t elementSize) {+void 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())) {@@ -46,7 +48,7 @@ void IDynamicGraph::MemRefType::setStrides(const ov::Strides& strides, int32_t e}}-void IDynamicGraph::MemRefType::set(const void* arg, int64_t offset, std::shared_ptr<ov::ITensor> tensor) {+void MemRefType::set(const void* arg, int64_t offset, std::shared_ptr<ov::ITensor> tensor) {_basePtr = _data = arg;_offset = offset;if (_dimsCount == 0) {@@ -71,7 +73,7 @@ void IDynamicGraph::MemRefType::set(const void* arg, int64_t offset, std::shared}}-void IDynamicGraph::MemRefType::updateStride() {+void MemRefType::updateStride() {// Note: NCHW layout styleuint64_t stride = 1;for (int64_t i = _dimsCount - 1; i >= 0; --i) {@@ -81,7 +83,7 @@ void IDynamicGraph::MemRefType::updateStride() {}// The comparision only checks shape and strides now-bool IDynamicGraph::MemRefType::compare(const IDynamicGraph::MemRefType& memref) {+bool MemRefType::compare(const MemRefType& memref) {if (memref._dimsCount != _dimsCount || _sizes.size() != memref._sizes.size() ||_strides.size() != memref._strides.size())return false;@@ -96,7 +98,7 @@ bool IDynamicGraph::MemRefType::compare(const IDynamicGraph::MemRefType& memref)return true;}-std::ostream& operator<<(std::ostream& os, const IDynamicGraph::MemRefType& memRef) {+std::ostream& operator<<(std::ostream& os, const MemRefType& memRef) {os << "BasePtr: " << memRef._basePtr << ", Data: " << memRef._data << ", Offset: " << memRef._offset<< ", Sizes: [";for (int64_t size : memRef._sizes) {@@ -111,65 +113,10 @@ std::ostream& operator<<(std::ostream& os, const IDynamicGraph::MemRefType& memRreturn os;}-std::string IDynamicGraph::MemRefType::toString() {+std::string MemRefType::toString() {std::stringstream stream;stream << *this;return stream.str();}-void IDynamicGraph::GraphArguments::setArgumentValue(uint32_t argi, const void* argv) {- if (argi < _inputs.size()) {- _inputs[argi]._basePtr = _inputs[argi]._data = const_cast<void*>(argv);- } else {- auto idx = argi - _inputs.size();- if (idx < _outputs.size()) {- _outputs[idx]._basePtr = _outputs[idx]._data = const_cast<void*>(argv);- }- }-}--void IDynamicGraph::GraphArguments::setArgumentProperties(uint32_t argi,- const void* argv,- const ov::Shape& sizes,- const std::vector<size_t>& strides) {- if (argi < _inputs.size()) {- _inputs[argi]._basePtr = _inputs[argi]._data = const_cast<void*>(argv);- for (int64_t i = 0; i < _inputs[argi]._dimsCount; i++) {- _inputs[argi]._sizes[i] = sizes[i];- _inputs[argi]._strides[i] = strides[i];- }- } else {- auto idx = argi - _inputs.size();- if (idx < _outputs.size()) {- _outputs[idx]._basePtr = _outputs[idx]._data = const_cast<void*>(argv);- for (int64_t i = 0; i < _outputs[idx]._dimsCount; i++) {- _outputs[idx]._sizes[i] = sizes[i];- _outputs[idx]._strides[i] = strides[i];- }- }- }-}--void IDynamicGraph::execute(const std::shared_ptr<ZeroInitStructsHolder>&,- GraphArguments&,- std::vector<ze_command_list_handle_t>&,- ze_command_queue_handle_t,- ze_fence_handle_t,- ze_event_handle_t,- ze_graph_profiling_pool_handle_t) {- OPENVINO_THROW("execute not implemented");-}--void IDynamicGraph::getBinding(GraphArguments&) {- OPENVINO_THROW("getBinding not implemented");-}--uint64_t IDynamicGraph::get_num_subgraphs() const {- OPENVINO_THROW("get_num_subgraphs not implemented");-}--void IDynamicGraph::predict_output_shape(GraphArguments&, std::vector<MemRefType>&, std::vector<MemRefType>&) {- OPENVINO_THROW("predict_output_shape not implemented");-}-} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/vm/CMakeLists.txt b/src/plugins/intel_npu/src/vm/CMakeLists.txtdeleted file mode 100644index 339c85a8bd8..00000000000--- a/src/plugins/intel_npu/src/vm/CMakeLists.txt+++ /dev/null@@ -1,6 +0,0 @@-#-# Copyright (C) 2026 Intel Corporation-# SPDX-License-Identifier: Apache-2.0-#--add_subdirectory(runtime)diff --git a/src/plugins/intel_npu/src/vm/runtime/CMakeLists.txt b/src/plugins/intel_npu/src/vm/runtime/CMakeLists.txtdeleted file mode 100644index 44393bc50fa..00000000000--- a/src/plugins/intel_npu/src/vm/runtime/CMakeLists.txt+++ /dev/null@@ -1,21 +0,0 @@-#-# Copyright (C) 2026 Intel Corporation-# SPDX-License-Identifier: Apache-2.0-#--set(TARGET_NAME npu_vm_runtime_api)--add_library(${TARGET_NAME} INTERFACE)-add_library(openvino::npu_vm_runtime_api ALIAS ${TARGET_NAME})--target_include_directories(${TARGET_NAME} INTERFACE- $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>- $<INSTALL_INTERFACE:include>-)--ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})--ov_developer_package_export_targets(TARGET openvino::npu_vm_runtime_api- INSTALL_INCLUDE_DIRECTORIES- ${CMAKE_CURRENT_SOURCE_DIR}/include/)-ov_install_static_lib(npu_vm_runtime_api ${NPU_PLUGIN_COMPONENT})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 f4a97d9d7c2..ae3e696b0fa 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@@ -733,4 +733,4 @@ TEST_P(InferWithDefaultHostCompileTests, CompileDynamicModelWithNoHostCompileMod} // namespace behavior} // namespace test-} // namespace ov+} // namespace ov\ No newline at end of filediff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 0051f70b285..5a3e55febc9 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -15,6 +15,7 @@ set(MANDATORY_UNIT_TESTS_LIBS"openvino::npu_logger_utils""openvino_npu_common""openvino::npu_ops"+ "openvino_npu_vm_utils")ov_add_test_target(