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] Refactor zero infer request (#34763)
Bogdan Pereanu85f3186df862
diff --git a/src/plugins/intel_npu/src/backend/include/zero_device.hpp b/src/plugins/intel_npu/src/backend/include/zero_device.hppindex ca4787274bd..50aeadca345 100644--- a/src/plugins/intel_npu/src/backend/include/zero_device.hpp+++ b/src/plugins/intel_npu/src/backend/include/zero_device.hpp@@ -32,8 +32,8 @@ public:std::map<ov::element::Type, float> getGops() const override;ov::device::Type getDeviceType() const override;- std::shared_ptr<SyncInferRequest> createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,- const Config& config) override;+ std::shared_ptr<InferRequest> createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,+ const Config& config) override;void updateInfo(const ov::AnyMap& properties) override;diff --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 5b4e0147787..36b3f35ce99 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@@ -19,27 +19,20 @@ public:void infer_async() override;protected:- void construct_pipeline() override;-- /**- * @brief Allocates a tensor on host and stores the reference inside multiple attributes.- * @param index The index which the allocated tensor shall use.- * @param isInput Determines the containers in which the newly allocated tensors will be stored.- * @param batchSize If provided, the value of the shape on the 0th axis is overriden with this value.- * @return Pointer towards the allocated tensor- */- std::shared_ptr<ZeroTensor> allocate_tensor(const size_t index,- const bool isInput,- const std::optional<std::size_t> batchSize = std::nullopt) const;-- void update_command_list_for_tensor(SyncInferRequest::FoundPort& foundPort,- const ov::SoPtr<ov::ITensor>& tensor) override;-- void update_command_list_for_tensors(SyncInferRequest::FoundPort& foundPort,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- std::optional<size_t> batchSizeCandidate = std::nullopt) override;- void predict_shapes(std::vector<IDynamicGraph::MemRefType>& outputProps);+ void create_pipeline_impl() override;++ std::shared_ptr<ZeroTensor> allocate_tensor(+ const size_t index,+ const bool isInput,+ const std::optional<std::size_t>& batchSize = std::nullopt) const override;+ void sync_zero_tensor_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const ov::SoPtr<ov::ITensor>& tensor) override;+ void sync_zero_tensors_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ 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);void update_tensor(const std::vector<IDynamicGraph::MemRefType>& outputProps);diff --git a/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp b/src/plugins/intel_npu/src/backend/include/zero_infer_request.hppindex 861dbf89b2a..d21aed69607 100644--- a/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp+++ b/src/plugins/intel_npu/src/backend/include/zero_infer_request.hpp@@ -4,15 +4,12 @@#pragma once-#include <ze_api.h>-#include <ze_graph_ext.h>-+#include "intel_npu/common/icompiled_model.hpp"+#include "intel_npu/common/igraph.hpp"#include "intel_npu/common/npu.hpp"-#include "intel_npu/common/sync_infer_request.hpp"+#include "intel_npu/network_metadata.hpp"#include "intel_npu/utils/logger/logger.hpp"-#include "intel_npu/utils/zero/zero_remote_tensor.hpp"#include "intel_npu/utils/zero/zero_tensor.hpp"-#include "intel_npu/utils/zero/zero_wrappers.hpp"#include "zero_pipeline.hpp"namespace intel_npu {@@ -28,31 +25,57 @@ std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,void* get_tensor_data_ptr(const std::shared_ptr<ov::ITensor>& tensor);-class ZeroInferRequest : public SyncInferRequest {+class ZeroInferRequest : public InferRequest {public:explicit ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>& initStructs,const std::shared_ptr<const ICompiledModel>& compiledModel,const Config& config);ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;+ std::vector<ov::SoPtr<ov::ITensor>> get_tensors(const ov::Output<const ov::Node>& port) const override;void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override;void set_tensors(const ov::Output<const ov::Node>& port,const std::vector<ov::SoPtr<ov::ITensor>>& tensors) override;void infer() override;- void infer_async() override;-+ virtual void infer_async() override;void get_result() override;+ const std::vector<ov::Output<const ov::Node>>& get_inputs() const override;+ const std::vector<ov::Output<const ov::Node>>& get_outputs() const override;++ const std::shared_ptr<const ov::ICompiledModel>& get_compiled_model() const override;++ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override;+protected:- std::vector<ov::ProfilingInfo> get_profiling_info() const override;+ /**+ * @see ov::ISyncInferRequest+ */+ struct FoundPort {+ size_t idx;+ enum class Type { NOT_FOUND = 0, INPUT, OUTPUT } type;++ bool found() const {+ return type != Type::NOT_FOUND;+ }+ bool is_input() const {+ return type == Type::INPUT;+ }+ bool is_output() const {+ return !is_input();+ }+ };- void check_network_precision(const ov::element::Type_t precision) const override;- void create_pipeline();- virtual void construct_pipeline();+ /**+ * @brief Finds input or output port+ * @return structure which contains index of Input/Output or report that port wasn't found+ * @see ov::ISyncInferRequest+ */+ ZeroInferRequest::FoundPort find_port(const ov::Output<const ov::Node>& port) const;- std::shared_ptr<ZeroTensor>& get_level_zero_input(size_t index, size_t tensorNo = 0) const;- std::vector<std::shared_ptr<ZeroTensor>>& get_level_zero_inputs(size_t index) const;+ void setup_pipeline();+ virtual void create_pipeline_impl();/*** @brief Allocates a tensor on host and stores the reference inside multiple attributes.@@ -61,29 +84,77 @@ protected:* @param batchSize If provided, the value of the shape on the 0th axis is overridden with this value.* @return Pointer towards the allocated tensor*/- std::shared_ptr<ZeroTensor> allocate_tensor(const size_t index,- const bool isInput,- const std::optional<std::size_t>& batchSize = std::nullopt) const;+ virtual std::shared_ptr<ZeroTensor> allocate_tensor(+ const size_t index,+ const bool isInput,+ const std::optional<std::size_t>& batchSize = std::nullopt) const;+ void initialize_states();void add_state(const IODescriptor& descriptor, size_t tensorIndex) const;void update_pipeline_if_memory_changed();void update_states_if_memory_changed();- virtual void update_command_list_for_tensor(SyncInferRequest::FoundPort& foundPort,- const ov::SoPtr<ov::ITensor>& tensor);-- virtual void update_command_list_for_tensors(SyncInferRequest::FoundPort& foundPort,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- std::optional<size_t> batchSizeCandidate = std::nullopt);+ virtual void sync_zero_tensor_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const ov::SoPtr<ov::ITensor>& tensor);+ virtual void sync_zero_tensors_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const std::optional<size_t>& batchSize = std::nullopt);virtual void prepare_inputs();virtual void prepare_outputs();+ /**+ * @brief Basic checks for input/output tensor+ *+ * @param port Input/Output port+ * @param tensor Input/Output tensor+ */+ void check_tensor(const ov::Output<const ov::Node>& port,+ const ov::SoPtr<ov::ITensor>& tensor,+ const bool supportStrides) const;++ /**+ * @brief Basic checks for input tensors+ *+ * @param port Input port+ * @param tensors Input tensors+ */+ void check_batched_tensors(const ov::Output<const ov::Node>& port,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const bool supportStrides) const;++ bool is_batched_input(size_t idx) const;++ /**+ * @brief Check that all tensors are valid. Throws an exception if it's not.+ */+ void check_tensors() const override;++ ov::SoPtr<ov::ITensor>& get_user_input(size_t index) const;+ std::vector<ov::SoPtr<ov::ITensor>>& get_user_inputs(size_t index) const;++ std::shared_ptr<ZeroTensor>& get_level_zero_input(size_t index, size_t tensorNo = 0) const;+ std::vector<std::shared_ptr<ZeroTensor>>& get_level_zero_inputs(size_t index) const;++ void check_network_precision(const ov::element::Type_t precision) const;+ std::vector<ov::ProfilingInfo> get_profiling_info() const override;+const std::shared_ptr<ZeroInitStructsHolder> _initStructs;++ // This is intel_npu::ICompiledModel pointer, but need to use OV base class because+ // ov::IInferRequest::get_compiled_model returns a reference to shared_ptr!+ std::shared_ptr<const ov::ICompiledModel> _compiledModel;+const std::shared_ptr<IGraph> _graph;+ NetworkMetadata _metadata;const Config _config;- Logger _logger;++ // In case set_tensors is called, we receive a vector with N tensors otherwise only 1 tensor is needed+ mutable std::vector<std::vector<ov::SoPtr<ov::ITensor>>> _userInputTensors;+ mutable std::vector<ov::SoPtr<ov::ITensor>> _userOutputTensors;++ mutable std::vector<ov::SoPtr<ov::IVariableState>> _variableStates;// A copy of each tensor is needed to maintain the original L0 memory allocation in case the user provides another// memory area for the tensor.@@ -91,9 +162,20 @@ protected:mutable std::vector<std::shared_ptr<ZeroTensor>> _levelZeroOutputTensors;std::unique_ptr<IPipeline> _pipeline;-bool _pipelineIsCreated = false;bool _dynamicBatchValueChanged = false;++ Logger _logger;++ /**+ * @see ov::ISyncInferRequest+ */+ mutable std::unordered_map<size_t, ZeroInferRequest::FoundPort> _cachedPorts;++ /**+ * @see ov::ISyncInferRequest+ */+ mutable std::mutex _cacheMutex;};} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/backend/src/zero_device.cpp b/src/plugins/intel_npu/src/backend/src/zero_device.cppindex 227e7e001ca..fcbc2d21536 100644--- a/src/plugins/intel_npu/src/backend/src/zero_device.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_device.cpp@@ -183,9 +183,8 @@ ov::device::Type ZeroDevice::getDeviceType() const {return ov::device::Type::INTEGRATED;}-std::shared_ptr<SyncInferRequest> ZeroDevice::createInferRequest(- const std::shared_ptr<const ICompiledModel>& compiledModel,- const Config& config) {+std::shared_ptr<InferRequest> ZeroDevice::createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,+ const Config& config) {if (dynamic_cast<IDynamicGraph*>(compiledModel->get_graph().get())) {return std::make_shared<ZeroDynamicInferRequest>(_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 47916a54716..1c809482e6f 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@@ -18,8 +18,8 @@ ZeroDynamicInferRequest::ZeroDynamicInferRequest(const std::shared_ptr<ZeroInitS_logger.setName("ZeroDynamicInferRequest");}-void ZeroDynamicInferRequest::construct_pipeline() {- _logger.debug("create_pipeline - constructing pipeline");+void ZeroDynamicInferRequest::create_pipeline_impl() {+ _logger.debug("create_pipeline_impl - constructing pipeline");auto batchSize = _graph->get_batch_size();// Construct pipeline_pipeline =@@ -30,24 +30,27 @@ void ZeroDynamicInferRequest::construct_pipeline() {_levelZeroOutputTensors,batchSize.has_value() ? batchSize.value() : utils::DEFAULT_BATCH_SIZE);- _logger.debug("create_pipeline - completed");+ _logger.debug("create_pipeline_impl - completed");}-void ZeroDynamicInferRequest::update_command_list_for_tensor(SyncInferRequest::FoundPort& foundPort,- const ov::SoPtr<ov::ITensor>& tensor) {- OV_ITT_TASK_CHAIN(ZERO_SET_TENSOR, itt::domains::LevelZeroBackend, "set_tensor", "update_command_list_for_tensor");+void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const ov::SoPtr<ov::ITensor>& tensor) {+ OV_ITT_TASK_CHAIN(ZERO_SET_TENSOR,+ itt::domains::LevelZeroBackend,+ "ZeroDynamicInferRequest",+ "sync_zero_tensor_with_graph");if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {auto& levelZeroTensor =foundPort.is_input() ? get_level_zero_input(foundPort.idx) : _levelZeroOutputTensors.at(foundPort.idx);try {- _logger.debug("set_tensor - create zero tensor");+ _logger.debug("sync_zero_tensor_with_graph - create zero tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "create zero tensor");// Try to use the user tensor directly if its underlying data is already allocated in the same Level Zero// context.levelZeroTensor = std::make_shared<ZeroTensor>(_initStructs, tensor);} catch (const ZeroMemException& exception) {- _logger.debug("set_tensor - exception caught while trying to create a Level Zero tensor "+ _logger.debug("sync_zero_tensor_with_graph - exception caught while trying to create a Level Zero tensor ""from the user tensor: %s",exception.what());@@ -55,19 +58,19 @@ void ZeroDynamicInferRequest::update_command_list_for_tensor(SyncInferRequest::F// allocate a new tensor to back up the user tensor (which cannot be imported or used directly).if (_dynamicBatchValueChanged || levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused() ||(levelZeroTensor != nullptr && (levelZeroTensor->get_byte_size() < tensor->get_byte_size()))) {- _logger.debug("set_tensor - allocate locally L0 tensor");+ _logger.debug("sync_zero_tensor_with_graph - allocate locally L0 tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "allocate tensor");auto batch = _graph->get_batch_size();levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), batch);} else {- _logger.debug("set_tensor - reusing the level zero tensor since it is not shared "- "with the user, and old L0 tensor is large enough");+ _logger.debug("sync_zero_tensor_with_graph - reusing the level zero tensor since it is not shared with "+ "the user, and old L0 tensor is large enough");}}if (_pipelineIsCreated && !_dynamicBatchValueChanged) {- _logger.debug("infer_async - update command list");+ _logger.debug("sync_zero_tensor_with_graph - update command list");OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");@@ -95,35 +98,34 @@ void ZeroDynamicInferRequest::update_command_list_for_tensor(SyncInferRequest::F// If command list updates are not supported, fallback to copying tensors every time.}-void ZeroDynamicInferRequest::update_command_list_for_tensors(SyncInferRequest::FoundPort& foundPort,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- std::optional<size_t> batchSizeCandidate) {+void ZeroDynamicInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const std::optional<size_t>& batchSize) {OV_ITT_TASK_CHAIN(ZERO_SET_TENSORS,itt::domains::LevelZeroBackend,- "set_tensors",- "update_command_list_for_tensors");- if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) && batchSizeCandidate.has_value()) {+ "ZeroDynamicInferRequest",+ "sync_zero_tensors_with_graph");+ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) && batchSize.has_value()) {get_level_zero_inputs(foundPort.idx).resize(tensors.size());for (size_t i = 0; i < tensors.size(); i++) {try {- _logger.debug("set_tensors - create zero tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create zero tensor");+ _logger.debug("sync_zero_tensors_with_graph - create zero tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create_zero_tensor");get_level_zero_input(foundPort.idx, i) = std::make_shared<ZeroTensor>(_initStructs, tensors.at(i));} catch (const ZeroMemException& exception) {- _logger.debug("set_tensors - exception caught while trying to create a Level "- "Zero tensor "- "from the user tensor: %s",+ _logger.debug("sync_zero_tensors_with_graph - exception caught while trying to create a Level Zero "+ "tensor from the user tensor: %s",exception.what());- _logger.debug("set_tensors - allocate locally L0 tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate tensor");- get_level_zero_input(foundPort.idx, i) = allocate_tensor(foundPort.idx, INPUT, batchSizeCandidate);+ _logger.debug("sync_zero_tensors_with_graph - allocate locally L0 tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate_tensor");+ get_level_zero_input(foundPort.idx, i) = allocate_tensor(foundPort.idx, INPUT, batchSize);}if (_pipelineIsCreated && !_dynamicBatchValueChanged) {OPENVINO_ASSERT(get_level_zero_input(foundPort.idx, i)->data(), "Empty buffer");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "updateCommandList");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");_pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,get_level_zero_input(foundPort.idx, i),i,@@ -139,18 +141,19 @@ void ZeroDynamicInferRequest::update_command_list_for_tensors(SyncInferRequest::// If command list updates are not supported, fallback to copying tensors every time.}-std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(const size_t index,- const bool isInput,- const std::optional<std::size_t> batchSize) const {+std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(+ const size_t index,+ const bool isInput,+ const std::optional<std::size_t>& batchSize) const {IODescriptor descriptor = isInput ? _metadata.inputs.at(index) : _metadata.outputs.at(index);// Create new IODescriptor based on user input|output and descriptorif (isInput && get_user_input(index) != nullptr) {- _logger.debug("Update input descriptor with shape from user input : %s instead of %s",+ _logger.debug("allocate_tensor - update input descriptor with shape from user input: %s instead of %s",get_user_input(index)->get_shape().to_string().c_str(),descriptor.shapeFromCompiler.to_string().c_str());descriptor.shapeFromCompiler = get_user_input(index)->get_shape();} else if (!isInput && _userOutputTensors.at(index) != nullptr) {- _logger.debug("Update output descriptor with shape from user output : %s instead of %s",+ _logger.debug("allocate_tensor - update output descriptor with shape from user output: %s instead of %s",_userOutputTensors.at(index)->get_shape().to_string().c_str(),descriptor.shapeFromCompiler.to_string().c_str());descriptor.shapeFromCompiler = _userOutputTensors.at(index)->get_shape();@@ -178,7 +181,7 @@ std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(const size_}void ZeroDynamicInferRequest::infer_async() {- _logger.debug("infer_async started");+ _logger.debug("infer_async - started");OV_ITT_TASK_CHAIN(ZERO_INFER, itt::domains::LevelZeroBackend, "infer_async", "start");// Store the predicted output shapesstd::vector<IDynamicGraph::MemRefType> outputPros;@@ -257,7 +260,7 @@ void ZeroDynamicInferRequest::predict_shapes(std::vector<IDynamicGraph::MemRefTyfor (size_t i = 0; i < outputProps.size(); i++) {if (!originalOutputProps[i].compare(outputProps[i])) {- _logger.debug("Output shape change detected");+ _logger.debug("predict_shapes - output shape change detected");break;}}@@ -276,7 +279,7 @@ void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(if (levelZeroTensor != nullptr && zeroTensor != nullptr && zeroTensor == levelZeroTensor) {// If user output tensor is ZeroTensor, no need check size here// These tensors are allocated by plugin and reshape will used later to resize tensor- _logger.debug("Output tensor %zu is ZeroTensor, skip size check", i);+ _logger.debug("check_tensor_and_predicted_shapes - output tensor %zu is ZeroTensor, skip size check", i);continue;}@@ -287,8 +290,8 @@ void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(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)) {- _logger.error("User output tensor %zu shape %s is different from predicted shape %s, can not "- "run inference",+ _logger.error("check_tensor_and_predicted_shapes - user output tensor %zu shape %s is different from "+ "predicted shape %s, can not run inference",i,userTensor->get_shape().to_string().c_str(),predictedShape.to_string().c_str());@@ -299,8 +302,8 @@ void ZeroDynamicInferRequest::check_tensor_and_predicted_shapes(if (levelZeroTensor != nullptr) {if (shape_size(levelZeroTensor->get_shape()) < shape_size(predictedShape)) {// Local levelZero output tensor is not large enough, reshape will solve issue- _logger.debug("LevelZero output tensor %zu shape %s is smaller than predicted shape %s, need "- "recreate pipeline",+ _logger.debug("check_tensor_and_predicted_shapes - LevelZero output tensor %zu shape %s is smaller "+ "than predicted shape %s, need recreate pipeline",i,levelZeroTensor->get_shape().to_string().c_str(),predictedShape.to_string().c_str());@@ -323,7 +326,7 @@ void ZeroDynamicInferRequest::update_tensor(const std::vector<IDynamicGraph::MempredictedShape.push_back(outputProps[i]._sizes[j]);}if (levelZeroTensor->get_shape() != predictedShape) {- _logger.info("Reshape output tensor %d from %s to predicted shape %s",+ _logger.info("update_tensor - reshape output tensor %d from %s to predicted shape %s",i,levelZeroTensor->get_shape().to_string().c_str(),predictedShape.to_string().c_str());diff --git a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cppindex 9683e0057e3..572bd6821ee 100644--- a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp@@ -9,13 +9,28 @@#include "intel_npu/prefix.hpp"#include "intel_npu/utils/utils.hpp"#include "intel_npu/utils/zero/zero_api.hpp"+#include "intel_npu/utils/zero/zero_remote_tensor.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/runtime/intel_npu/remote_properties.hpp"#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/plugin_itt.hpp"+#include "openvino/util/common_util.hpp"+#include "transformations/utils/utils.hpp"#include "zero_variable_state.hpp"+namespace intel_npu {+namespace {++std::shared_ptr<const ov::ICompiledModel> validate_compiled_model(+ const std::shared_ptr<const ov::ICompiledModel>& compiledModel) {+ OPENVINO_ASSERT(compiledModel, "Inference request creation: compiled model is not available");+ return compiledModel;+}++} // namespace+std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,const ov::PartialShape& ioShape,const std::shared_ptr<ov::ITensor>& tensor,@@ -67,15 +82,32 @@ void* get_tensor_data_ptr(const std::shared_ptr<ov::ITensor>& tensor) {ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>& initStructs,const std::shared_ptr<const ICompiledModel>& compiledModel,const Config& config)- : SyncInferRequest(compiledModel, config),- _initStructs(initStructs),+ : _initStructs(initStructs),+ _compiledModel(validate_compiled_model(compiledModel)),_graph(compiledModel->get_graph()),+ _metadata(_graph->get_metadata()),_config(config),- _logger("ZeroInferRequest", _config.get<LOG_LEVEL>()),+ _userInputTensors(_metadata.inputs.size(), std::vector<ov::SoPtr<ov::ITensor>>(1, {nullptr})),+ _userOutputTensors(_metadata.outputs.size(), {nullptr}),_levelZeroInputTensors(_metadata.inputs.size(), std::vector<std::shared_ptr<ZeroTensor>>(1, nullptr)),- _levelZeroOutputTensors(_metadata.outputs.size(), nullptr) {- _logger.debug("ZeroInferRequest::ZeroInferRequest - checking level zero attributes and allocating tensors");+ _levelZeroOutputTensors(_metadata.outputs.size(), nullptr),+ _logger("ZeroInferRequest", _config.get<LOG_LEVEL>()) {+ OPENVINO_ASSERT(!get_outputs().empty(), "Inference request creation: no output found for network ", _metadata.name);++ // Create map of empty tensors and cache ports from the compiled model+ // See the ov::ISyncInferRequest constructor+ auto portType = ZeroInferRequest::FoundPort::Type::INPUT;+ for (const auto& ports : {get_inputs(), get_outputs()}) {+ for (size_t i = 0; i < ports.size(); i++) {+ const auto& port = ports[i];+ size_t portHash = ov::util::hash_combine(+ {std::hash<const ov::Node*>()(port.get_node()), std::hash<size_t>()(port.get_index())});+ _cachedPorts[portHash] = {i, portType};+ }+ portType = ZeroInferRequest::FoundPort::Type::OUTPUT;+ }+ _logger.debug("ZeroInferRequest - checking level zero attributes and allocating tensors");size_t ioIndex = 0;for (const IODescriptor& inputDescriptor : _metadata.inputs) {// Tensors for regular inputs will be allocated later, only for ports that were not set by the user.@@ -122,11 +154,97 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&++ioIndex;}- _logger.debug("ZeroInferRequest::ZeroInferRequest - SyncInferRequest completed");+ initialize_states();++ _logger.debug("ZeroInferRequest - completed");+}++ZeroInferRequest::FoundPort ZeroInferRequest::find_port(const ov::Output<const ov::Node>& port) const {+ // check if the tensor names of target port is a subset of source port's tensor names+ auto check_tensor_names = [](const std::unordered_set<std::string>& source,+ const std::unordered_set<std::string>& target) {+ for (const auto& name : target) {+ if (source.find(name) == source.end()) {+ return false;+ }+ }+ return true;+ };++ // This function is hotspot, need optimization.+ auto check_nodes = [](const ov::Node* node1, const ov::Node* node2) {+ return node1 == node2 ||+ (node1->outputs().size() == node2->outputs().size() &&+ node1->inputs().size() == node2->inputs().size() && node1->get_type_info() == node2->get_type_info() &&+ node1->get_friendly_name() == node2->get_friendly_name());+ };+ // Find port without caching work slow because we need each time iterate over all ports and compare different+ // strings So use WA with caching in order to make 2+ calls for the same ports faster.+ // Calculate hash for the port+ size_t port_hash =+ ov::util::hash_combine({std::hash<const ov::Node*>()(port.get_node()), std::hash<size_t>()(port.get_index())});+ {+ std::lock_guard<std::mutex> lock(_cacheMutex);+ if (_cachedPorts.find(port_hash) != _cachedPorts.end()) {+ // Cached port for the hash was found+ return _cachedPorts[port_hash];+ }+ }+ ZeroInferRequest::FoundPort::Type type = ZeroInferRequest::FoundPort::Type::INPUT;+ for (const auto& ports : {get_inputs(), get_outputs()}) {+ for (size_t i = 0; i < ports.size(); i++) {+ // The order of the arguments might matter for the "check_tensor_names" call. If the "CompiledModel" object+ // was obtained via "import_model", then the number of tensor names could be cut to 32 due to limitations+ // inside the NPU stack. For this particular scenario, we are checking if all tensor names corresponding to+ // the "CompiledModel" are found in the provided port instead of doing the opposite.+ if (ports[i].get_index() == port.get_index() && check_nodes(ports[i].get_node(), port.get_node()) &&+ check_tensor_names(port.get_names(), ports[i].get_names())) {+ std::lock_guard<std::mutex> lock(_cacheMutex);+ _cachedPorts[port_hash] = {i, type};+ return _cachedPorts[port_hash];+ }+ }+ type = ZeroInferRequest::FoundPort::Type::OUTPUT;+ }+ return {0, ZeroInferRequest::FoundPort::Type::NOT_FOUND};+}++const std::vector<ov::Output<const ov::Node>>& ZeroInferRequest::get_inputs() const {+ return _compiledModel->inputs();+}++const std::vector<ov::Output<const ov::Node>>& ZeroInferRequest::get_outputs() const {+ return _compiledModel->outputs();+}++const std::shared_ptr<const ov::ICompiledModel>& ZeroInferRequest::get_compiled_model() const {+ return _compiledModel;+}++void ZeroInferRequest::initialize_states() {+ for (const ov::SoPtr<ov::IVariableState>& variableState : _variableStates) {+ variableState->reset();+ }+}++void ZeroInferRequest::add_state(const IODescriptor& descriptor, size_t tensorIndex) const {+ OPENVINO_ASSERT(descriptor.relatedDescriptorIndex.has_value(),+ "The link between state descriptors is missing, state name: ",+ descriptor.nameFromCompiler);++ _variableStates.push_back(std::make_shared<ZeroVariableState>(_initStructs,+ descriptor.nameFromCompiler,+ get_level_zero_input(tensorIndex),+ tensorIndex,+ descriptor.relatedDescriptorIndex.value()));+}++std::vector<ov::SoPtr<ov::IVariableState>> ZeroInferRequest::query_state() const {+ return _variableStates;}-void ZeroInferRequest::create_pipeline() {- _logger.debug("ZeroInferRequest::create_pipeline");+void ZeroInferRequest::setup_pipeline() {+ _logger.debug("setup_pipeline - started");auto batchSize = _graph->get_batch_size();for (size_t inputIndex = 0; inputIndex < _metadata.inputs.size(); ++inputIndex) {@@ -137,7 +255,7 @@ void ZeroInferRequest::create_pipeline() {if (is_batched_input(inputIndex) && batchSize.has_value()) {if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {- _logger.debug("ZeroInferRequest::create_pipeline - tensors %s were already allocated",+ _logger.debug("setup_pipeline - tensors %s were already allocated",_metadata.inputs.at(inputIndex).nodeFriendlyName.c_str());} else {if (get_level_zero_input(inputIndex) == nullptr) {@@ -156,7 +274,7 @@ void ZeroInferRequest::create_pipeline() {" has different batch size than other tensors.");}- _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated and has size: %zu",+ _logger.debug("setup_pipeline - tensor %s was already allocated and has size: %zu",_metadata.inputs.at(inputIndex).nodeFriendlyName.c_str(),get_level_zero_input(inputIndex)->get_byte_size());@@ -164,7 +282,7 @@ void ZeroInferRequest::create_pipeline() {}get_level_zero_input(inputIndex) = allocate_tensor(inputIndex, INPUT, batchSize);- _logger.debug("ZeroInferRequest::create_pipeline - new input tensor %s allocated, size: %zu",+ _logger.debug("setup_pipeline - new input tensor %s allocated, size: %zu",_metadata.inputs.at(inputIndex).nodeFriendlyName.c_str(),get_level_zero_input(inputIndex)->get_byte_size());}@@ -174,17 +292,17 @@ void ZeroInferRequest::create_pipeline() {if (_dynamicBatchValueChanged) {if (batchSize.has_value() &&_levelZeroOutputTensors.at(outputIndex)->get_shape()[utils::BATCH_AXIS] == batchSize.value()) {- _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated",+ _logger.debug("setup_pipeline - tensor %s was already allocated",_metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());continue;}} else {- _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated",+ _logger.debug("setup_pipeline - tensor %s was already allocated",_metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());continue;}}- _logger.debug("ZeroInferRequest::create_pipeline - allocate new output tensor %s",+ _logger.debug("setup_pipeline - allocate new output tensor %s",_metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());_levelZeroOutputTensors.at(outputIndex) = allocate_tensor(outputIndex, OUTPUT, batchSize);@@ -201,28 +319,28 @@ void ZeroInferRequest::create_pipeline() {_userOutputTensors.at(outputIndex) = _levelZeroOutputTensors.at(outputIndex);}- _logger.debug("ZeroInferRequest::create_pipeline - new output tensor %s allocated, size: %zu",+ _logger.debug("setup_pipeline - new output tensor %s allocated, size: %zu",_metadata.outputs.at(outputIndex).nodeFriendlyName.c_str(),_levelZeroOutputTensors.at(outputIndex)->get_byte_size());}- _logger.debug("ZeroInferRequest::create_pipeline - init completed");+ _logger.debug("setup_pipeline - initialization completed");// Set new tensors and reset variable state flag if memory updated before creating the pipeline- _logger.debug("ZeroInferRequest::create_pipeline - set new tensors and reset variable state flag if memory updated "+ _logger.debug("setup_pipeline - set new tensors and reset variable state flag if memory updated ""before creating the pipeline");for (const auto& variableState : _variableStates) {auto zeroState = std::dynamic_pointer_cast<ZeroVariableState>(variableState._ptr);OPENVINO_ASSERT(zeroState != nullptr, "State is not compatible with NPU plugin");if (zeroState->state_update_pending()) {- _logger.debug("ZeroInferRequest::create_pipeline - user state tensor should be updated");+ _logger.debug("setup_pipeline - user state tensor should be updated");get_user_input(zeroState->get_tensor_index()) = zeroState->get_user_state();_userOutputTensors.at(zeroState->get_related_tensor_index()) = zeroState->get_user_state();zeroState->clear_state_update_pending();if (zeroState->zero_state_update_pending()) {- _logger.debug("ZeroInferRequest::create_pipeline - level zero state tensor should be updated");+ _logger.debug("setup_pipeline - level zero state tensor should be updated");get_level_zero_input(zeroState->get_tensor_index()) = zeroState->get_zero_state();_levelZeroOutputTensors.at(zeroState->get_related_tensor_index()) = zeroState->get_zero_state();@@ -231,11 +349,11 @@ void ZeroInferRequest::create_pipeline() {}}- construct_pipeline();+ create_pipeline_impl();}-void ZeroInferRequest::construct_pipeline() {- _logger.debug("ZeroInferRequest::create_pipeline - constructing pipeline");+void ZeroInferRequest::create_pipeline_impl() {+ _logger.debug("create_pipeline_impl - constructing pipeline");auto batchSize = _graph->get_batch_size();// Construct pipeline_pipeline = std::make_unique<Pipeline>(_initStructs,@@ -245,7 +363,7 @@ void ZeroInferRequest::construct_pipeline() {_levelZeroOutputTensors,batchSize.has_value() ? batchSize.value() : utils::DEFAULT_BATCH_SIZE);- _logger.debug("ZeroInferRequest::create_pipeline - SyncInferRequest completed");+ _logger.debug("create_pipeline_impl - completed");}void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) {@@ -265,7 +383,7 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, constif (foundPort.is_input()) {if (get_user_input(foundPort.idx)._ptr == tensor._ptr) {// set_tensor called with the same tensor object; no action needed- _logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");+ _logger.debug("set_tensor - got the same input tensor, do nothing");return;}@@ -310,7 +428,7 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const} else {if (_userOutputTensors.at(foundPort.idx)._ptr == tensor._ptr) {// set_tensor called with the same tensor object; no action needed- _logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");+ _logger.debug("set_tensor - got the same output tensor, do nothing");return;}@@ -340,55 +458,55 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const_userOutputTensors.at(foundPort.idx) = tensor;}- update_command_list_for_tensor(foundPort, tensor);+ sync_zero_tensor_with_graph(foundPort, tensor);}-void ZeroInferRequest::update_command_list_for_tensor(SyncInferRequest::FoundPort& foundPort,- const ov::SoPtr<ov::ITensor>& tensor) {- OV_ITT_TASK_CHAIN(ZERO_SET_TENSOR, itt::domains::LevelZeroBackend, "set_tensor", "update_command_list_for_tensor");- const bool isMutableCommandListSupported = _initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0);+void ZeroInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const ov::SoPtr<ov::ITensor>& tensor) {+ OV_ITT_TASK_CHAIN(ZERO_SET_TENSOR,+ itt::domains::LevelZeroBackend,+ "ZeroInferRequest",+ "sync_zero_tensor_with_graph");auto& levelZeroTensor =foundPort.is_input() ? get_level_zero_input(foundPort.idx) : _levelZeroOutputTensors.at(foundPort.idx);- if (isMutableCommandListSupported || levelZeroTensor == nullptr) {+ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {bool updateCommandListArg = false;-try {- _logger.debug("ZeroInferRequest::set_tensor - create zero tensor");+ _logger.debug("sync_zero_tensor_with_graph - create zero tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "create zero tensor");- if (!isMutableCommandListSupported) {- // Forbid memory import when tensor reallocation is not supported- // Copies into level zero tensor will cause altering the initial user tensor- throw ZeroMemException{"Importing standard allocation is forbidden with this driver version"};- }-// Try to use the user tensor directly if its underlying data is already allocated in the same Level Zero// context.levelZeroTensor = std::make_shared<ZeroTensor>(_initStructs, tensor);updateCommandListArg = true;} catch (const ZeroMemException& exception) {- _logger.debug("ZeroInferRequest::set_tensor - exception caught while trying to create a Level Zero tensor "- "from the user tensor: %s",+ _logger.debug("sync_zero_tensor_with_graph - exception caught while trying to create a "+ "Level Zero tensor from the user tensor: %s",exception.what());// Check if the current Level Zero tensor was previously shared with the user. If so, it cannot be reused;// allocate a new tensor to back up the user tensor (which cannot be imported or used directly).if (_dynamicBatchValueChanged || levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused()) {- _logger.debug("ZeroInferRequest::set_tensor - allocate locally L0 tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "allocate tensor");+ _logger.debug("sync_zero_tensor_with_graph - allocate locally L0 tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "allocate_tensor");- auto batch = _graph->get_batch_size();- levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), batch);+ levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), _graph->get_batch_size());updateCommandListArg = true;} else {- _logger.debug("ZeroInferRequest::set_tensor - reusing the level zero tensor since it is not shared "- "with the user");+ _logger.debug("sync_zero_tensor_with_graph - reusing the level zero tensor since it "+ "is not shared with the user");+ }++ const auto& userTensorElementType = tensor->get_element_type();+ if (userTensorElementType == ov::element::boolean &&+ levelZeroTensor->get_element_type() == ov::element::u8) {+ levelZeroTensor->set_element_type(userTensorElementType);}}- if (isMutableCommandListSupported && _pipelineIsCreated && updateCommandListArg && !_dynamicBatchValueChanged) {- _logger.debug("ZeroInferRequest::infer_async - update command list");+ if (_pipelineIsCreated && updateCommandListArg && !_dynamicBatchValueChanged) {+ _logger.debug("sync_zero_tensor_with_graph - update command list");OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");@@ -398,15 +516,17 @@ void ZeroInferRequest::update_command_list_for_tensor(SyncInferRequest::FoundPor: _metadata.outputs.at(foundPort.idx).indexUsedByDriver,levelZeroTensor);}- }+ } else {+ // If command list updates are not supported, fallback to copying tensors every time.+ if (levelZeroTensor == nullptr) {+ levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), _graph->get_batch_size());+ }- OPENVINO_ASSERT(levelZeroTensor, "Zero tensor is not allocated.");- // corner case for boolean inputs as compiler maps them to u8- const auto& userTensorElementType = tensor->get_element_type();- if (userTensorElementType == ov::element::boolean && levelZeroTensor->get_element_type() == ov::element::u8) {- levelZeroTensor->set_element_type(userTensorElementType);+ const auto& userTensorElementType = tensor->get_element_type();+ if (userTensorElementType == ov::element::boolean && levelZeroTensor->get_element_type() == ov::element::u8) {+ levelZeroTensor->set_element_type(userTensorElementType);+ }}- // If command list updates are not supported, fallback to copying tensors every time.}void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,@@ -425,7 +545,7 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,check_batched_tensors(port, tensors, _metadata.inputs.at(foundPort.idx).supportsStridedLayout);- _logger.debug("ZeroInferRequest::set_tensors: %zu", tensors.size());+ _logger.debug("set_tensors - tensor count: %zu", tensors.size());const auto& ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();auto batchSizeCandidate =@@ -455,83 +575,90 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,get_user_inputs(foundPort.idx).resize(tensors.size());get_user_inputs(foundPort.idx) = tensors;- update_command_list_for_tensors(foundPort, tensors, batchSizeCandidate);+ sync_zero_tensors_with_graph(foundPort, tensors, batchSizeCandidate);}-void ZeroInferRequest::update_command_list_for_tensors(SyncInferRequest::FoundPort& foundPort,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- std::optional<size_t> batchSizeCandidate) {+void ZeroInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequest::FoundPort& foundPort,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const std::optional<size_t>& batchSize) {OV_ITT_TASK_CHAIN(ZERO_SET_TENSORS,itt::domains::LevelZeroBackend,- "set_tensors",- "update_command_list_for_tensors");-- const bool isMutableCommandListSupported = _initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0);- if (isMutableCommandListSupported && batchSizeCandidate.has_value()) {- get_level_zero_inputs(foundPort.idx).resize(tensors.size());-- for (size_t i = 0; i < tensors.size(); i++) {- try {- _logger.debug("ZeroInferRequest::set_tensors - create zero tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create zero tensor");- get_level_zero_input(foundPort.idx, i) = std::make_shared<ZeroTensor>(_initStructs, tensors.at(i));- } catch (const ZeroMemException& exception) {- _logger.debug(- "ZeroInferRequest::set_tensors - exception caught while trying to create a Level Zero tensor "- "from the user tensor: %s",- exception.what());+ "ZeroInferRequest",+ "sync_zero_tensors_with_graph");++ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {+ if (batchSize.has_value()) {+ get_level_zero_inputs(foundPort.idx).resize(tensors.size());+ for (size_t i = 0; i < tensors.size(); i++) {+ try {+ _logger.debug("sync_zero_tensors_with_graph - create zero tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create zero tensor");+ get_level_zero_input(foundPort.idx, i) = std::make_shared<ZeroTensor>(_initStructs, tensors.at(i));+ } catch (const ZeroMemException& exception) {+ _logger.debug(+ "sync_zero_tensors_with_graph - exception caught while trying to create a Level Zero tensor "+ "from the user tensor: %s",+ exception.what());++ _logger.debug("sync_zero_tensors_with_graph - allocate locally L0 tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate_tensor");+ auto& levelZeroTensor = get_level_zero_input(foundPort.idx, i);+ levelZeroTensor = allocate_tensor(foundPort.idx, INPUT);++ // corner case for boolean inputs as compiler maps them to u8+ const auto& userTensorElementType = tensors.at(i)->get_element_type();+ if (userTensorElementType == ov::element::boolean &&+ levelZeroTensor->get_element_type() == ov::element::u8) {+ levelZeroTensor->set_element_type(userTensorElementType);+ }+ }- _logger.debug("ZeroInferRequest::set_tensors - allocate locally L0 tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate tensor");- get_level_zero_input(foundPort.idx, i) = allocate_tensor(foundPort.idx, INPUT, batchSizeCandidate);+ if (_pipelineIsCreated && !_dynamicBatchValueChanged) {+ OPENVINO_ASSERT(get_level_zero_input(foundPort.idx, i)->data(), "Empty buffer");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");+ _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,+ get_level_zero_input(foundPort.idx, i),+ i);+ }}-- if (_pipelineIsCreated && !_dynamicBatchValueChanged) {- OPENVINO_ASSERT(get_level_zero_input(foundPort.idx, i)->data(), "Empty buffer");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "updateCommandList");- _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,- get_level_zero_input(foundPort.idx, i),- i);+ } else {+ auto& levelZeroTensor = get_level_zero_input(foundPort.idx);+ // Check if the current Level Zero tensor was previously shared with the user. If so, it cannot be reused;+ // allocate a new tensor to back up the user tensor (which cannot be imported or used directly).+ if (levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused()) {+ _logger.debug("sync_zero_tensors_with_graph - allocate locally L0 tensor");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate_tensor");+ levelZeroTensor = allocate_tensor(foundPort.idx, INPUT, tensors.size());++ if (_pipelineIsCreated && !_dynamicBatchValueChanged) {+ OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");+ _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,+ levelZeroTensor);+ }+ } else {+ _logger.debug("sync_zero_tensors_with_graph - reusing the level zero tensor since it is "+ "not shared with the user");}- auto& levelZeroTensor = get_level_zero_input(foundPort.idx, i);- OPENVINO_ASSERT(levelZeroTensor, "Zero tensor is not allocated.");- // corner case for boolean inputs as compiler maps them to u8- const auto& userTensorElementType = tensors.at(i)->get_element_type();+ const auto& userTensorElementType = tensors.at(SINGLE_TENSOR)->get_element_type();if (userTensorElementType == ov::element::boolean &&levelZeroTensor->get_element_type() == ov::element::u8) {levelZeroTensor->set_element_type(userTensorElementType);}}} else {+ // If command list updates are not supported, fallback to copying tensors every time.auto& levelZeroTensor = get_level_zero_input(foundPort.idx);- // Check if the current Level Zero tensor was previously shared with the user. If so, it cannot be reused;- // allocate a new tensor to back up the user tensor (which cannot be imported or used directly).- if (levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused()) {- _logger.debug("ZeroInferRequest::set_tensors - allocate locally L0 tensor");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate tensor");-- levelZeroTensor = allocate_tensor(foundPort.idx, INPUT, tensors.size());-- if (isMutableCommandListSupported && _pipelineIsCreated && !_dynamicBatchValueChanged) {- OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "updateCommandList");- _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,- levelZeroTensor);- }- } else {- _logger.debug("ZeroInferRequest::set_tensors - reusing the level zero tensor since it is not shared "- "with the user");+ if (levelZeroTensor == nullptr) {+ levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), tensors.size());}- OPENVINO_ASSERT(levelZeroTensor, "Zero tensor is not allocated.");- // corner case for boolean inputs as compiler maps them to u8const auto& userTensorElementType = tensors.at(SINGLE_TENSOR)->get_element_type();if (userTensorElementType == ov::element::boolean && levelZeroTensor->get_element_type() == ov::element::u8) {levelZeroTensor->set_element_type(userTensorElementType);}}- // If command list updates are not supported, fallback to copying tensors every time.}ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {@@ -560,7 +687,7 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::Nif (userTensor) {if (!_dynamicBatchValueChanged) {- _logger.debug("ZeroInferRequest::get_tensor - tensor allocated, get the tensor by index: %zu", ioIndex);+ _logger.debug("get_tensor - tensor allocated, get tensor by index: %zu", ioIndex);auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(userTensor._ptr);if (zeroTensor != nullptr) {@@ -570,7 +697,7 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::Nreturn userTensor;} else {if (batchSize.has_value() && userTensor->get_shape()[utils::BATCH_AXIS] == batchSize.value()) {- _logger.debug("ZeroInferRequest::get_tensor - tensor by index: %zu is already allocated", ioIndex);+ _logger.debug("get_tensor - tensor by index: %zu is already allocated", ioIndex);auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(userTensor._ptr);if (zeroTensor != nullptr) {@@ -584,7 +711,7 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::N}auto& metadata = isInput ? _metadata.inputs.at(ioIndex) : _metadata.outputs.at(ioIndex);- _logger.debug("ZeroInferRequest::get_tensor - tensor by index: %zu is not allocated.New tensor %s will be created",+ _logger.debug("get_tensor - tensor by index: %zu is not allocated, new tensor %s will be created",ioIndex,metadata.nodeFriendlyName.c_str());@@ -600,6 +727,19 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::Nreturn levelZeroTensor;}+std::vector<ov::SoPtr<ov::ITensor>> ZeroInferRequest::get_tensors(const ov::Output<const ov::Node>& port) const {+ OV_ITT_SCOPED_TASK(ov::itt::domains::Plugin, "get_tensors");++ auto foundPort = find_port(port);+ OPENVINO_ASSERT(foundPort.found(), "Cannot find input tensors for port ", port);++ if (foundPort.is_input() && is_batched_input(foundPort.idx)) {+ return get_user_inputs(foundPort.idx);+ }++ return {};+}+std::shared_ptr<ZeroTensor> ZeroInferRequest::allocate_tensor(const size_t index,const bool isInput,const std::optional<std::size_t>& batchSize) const {@@ -644,7 +784,7 @@ void ZeroInferRequest::update_pipeline_if_memory_changed() {OPENVINO_THROW("Reallocation of zero memory is not supported with this driver.");}- _logger.debug("Update input graph descriptor with the new tensor");+ _logger.debug("update_pipeline_if_memory_changed - update input graph descriptor with the new tensor");OPENVINO_ASSERT(levelZeroTensor.at(SINGLE_TENSOR)->data(), "Empty buffer");_pipeline->update_graph_arguments(_metadata.inputs.at(ioIndex).indexUsedByDriver,levelZeroTensor.at(SINGLE_TENSOR));@@ -674,7 +814,7 @@ void ZeroInferRequest::update_pipeline_if_memory_changed() {OPENVINO_THROW("Reallocation of zero memory is not supported with this driver.");}- _logger.debug("Update output graph descriptor with the new tensor");+ _logger.debug("update_pipeline_if_memory_changed - update output graph descriptor with the new tensor");OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");_pipeline->update_graph_arguments(_metadata.outputs.at(ioIndex).indexUsedByDriver, levelZeroTensor);@@ -727,7 +867,7 @@ void ZeroInferRequest::infer() {}void ZeroInferRequest::infer_async() {- _logger.debug("InferRequest::infer_async started");+ _logger.debug("infer_async - started");// TASK_BASE marker is always on by defaultOV_ITT_SCOPED_TASK_BASE(itt::domains::InferenceNPU, "Inference::start");// This task chain marker will only be available when ENABLE_PROFILING_ITT=FULL@@ -746,7 +886,7 @@ void ZeroInferRequest::prepare_inputs() {if (!_pipelineIsCreated || _dynamicBatchValueChanged) {OV_ITT_TASK_NEXT(ZERO_INFER, "create_pipeline");- create_pipeline(); // Reallocate pipeline if necessary+ setup_pipeline(); // Reallocate pipeline if necessary_pipelineIsCreated = true;_dynamicBatchValueChanged = false; // Reset reallocation flag} else {@@ -802,7 +942,7 @@ void ZeroInferRequest::prepare_inputs() {OPENVINO_ASSERT(userBuffer != nullptr && levelZeroBuffer != nullptr, "Empty buffer");_logger.debug(- "Batched Tensors - Tensor by index: %zu is not allocated in the current Level Zero "+ "prepare_inputs - batched tensor by index: %zu is not allocated in the current Level Zero ""context, copy bytes from user tensor: %zu, into L0 with expected size: %zu",inputIndex,userTensorPtr->get_byte_size(),@@ -815,10 +955,11 @@ void ZeroInferRequest::prepare_inputs() {const auto& levelZeroTensor = get_level_zero_input(inputIndex);OPENVINO_ASSERT(levelZeroTensor, "Input zero tensor is not allocated.");- _logger.debug("Batched Tensors - Tensor by index: %zu is not allocated in the current Level Zero "- "context or must be in a continued memory space, copy into L0 with size: %zu",- inputIndex,- levelZeroTensor->get_byte_size());+ _logger.debug(+ "prepare_inputs - batched tensor by index: %zu is not allocated in the current Level Zero "+ "context or must be in a continued memory space, copy into L0 with size: %zu",+ inputIndex,+ levelZeroTensor->get_byte_size());size_t copied_bytes_from_user = 0;for (size_t i = 0; i < userTensor.size(); i++) {auto viewTensor = ov::make_tensor(@@ -857,7 +998,7 @@ void ZeroInferRequest::prepare_inputs() {if (userBuffer != levelZeroBuffer) {OPENVINO_ASSERT(userBuffer != nullptr && levelZeroBuffer != nullptr, "Empty buffer");- _logger.info("Tensor is not allocated in the current Level Zero context");+ _logger.info("prepare_inputs - tensor is not allocated in the current Level Zero context");OV_ITT_TASK_NEXT(ZERO_INFER, "memcpy");userTensor.at(SINGLE_TENSOR)->copy_to(levelZeroTensor);}@@ -882,7 +1023,7 @@ void ZeroInferRequest::prepare_outputs() {void ZeroInferRequest::get_result() {OV_ITT_SCOPED_TASK_BASE(itt::domains::InferenceNPU, "Inference::get_result");OV_ITT_TASK_CHAIN(ZERO_RESULT, itt::domains::LevelZeroBackend, "get_result", "pull");- _logger.debug("InferRequest::get_result start");+ _logger.debug("get_result - started");_pipeline->pull();size_t outputIndex = 0;@@ -913,7 +1054,8 @@ void ZeroInferRequest::get_result() {}if (userBuffer != levelZeroBuffer) {- _logger.info("Output tensor by index: %zu is not allocated in the current Level Zero context", outputIndex);+ _logger.info("get_result - output tensor by index: %zu is not allocated in the current Level Zero context",+ outputIndex);OV_ITT_TASK_NEXT(ZERO_RESULT, "memcpy");levelZeroTensor->copy_to(userTensor._ptr);}@@ -933,7 +1075,210 @@ void ZeroInferRequest::get_result() {OV_ITT_TASK_NEXT(ZERO_RESULT, "reset");_pipeline->reset();- _logger.debug("InferRequest::get_result finished");+ _logger.debug("get_result - finished");+}++void ZeroInferRequest::check_tensor(const ov::Output<const ov::Node>& port,+ const ov::SoPtr<ov::ITensor>& tensor,+ const bool supportStrides) const {+ if (tensor == nullptr)+ OPENVINO_THROW("The tensor is not initialized!");++ bool is_input = ov::op::util::is_parameter(port.get_node());+ const std::string_view tensor_type = is_input ? "input" : "output";++ if (!supportStrides) {+ OPENVINO_ASSERT(+ tensor->is_continuous(),+ "The tensor has a non-contiguous memory layout (custom strides), which is not supported by the "+ "current driver/compiler version. To use strided tensors, either:\n"+ " 1. Upgrade to a driver version that supports strides, or\n"+ " 2. Enable stride support using the 'enable_strides_for' configuration property if this is supported.");+ }++ const auto& port_element_type = port.get_element_type();+ const auto& tensor_element_type = tensor->get_element_type();++ if ((port_element_type == ov::element::Type_t::boolean || tensor_element_type == ov::element::Type_t::boolean) &&+ port_element_type != tensor_element_type) {+ // Exception case for boolean treated as u8 in the NPU driver+ OPENVINO_ASSERT(port_element_type == ov::element::Type_t::u8 || tensor_element_type == ov::element::Type_t::u8,+ "The tensor element type is not corresponding with output element type (",+ tensor_element_type,+ " != ",+ port_element_type);+ } else {+ OPENVINO_ASSERT(port_element_type == tensor_element_type,+ "The tensor element type is not corresponding with output element type (",+ tensor_element_type,+ " != ",+ port_element_type);+ }++ const auto& port_partial_shape = port.get_partial_shape();+ const auto& tensor_shape = tensor->get_shape();++ bool is_dynamic = port_partial_shape.is_dynamic();++ if (is_dynamic) {+ auto port_length = port_partial_shape.rank().get_length();+ OPENVINO_ASSERT(ov::PartialShape(tensor_shape).rank().get_length() == port_length,+ "The tensor shape size is not equal to the model input/output rank: got ",+ tensor_shape.size(),+ " expecting ",+ port_length);++ if (port_length > 0) {+ const auto& port_max_shape = port_partial_shape.get_max_shape();+ for (auto i = 0; i < port_length; ++i) {+ if (tensor_shape[i] > port_max_shape[i]) {+ OPENVINO_THROW("The tensor shape is not compatible with the model input/output max shape: got ",+ tensor_shape,+ " expecting max shape ",+ port_max_shape);+ }+ }+ }+ }++ OPENVINO_ASSERT(is_dynamic || port_partial_shape == tensor_shape,+ "The ",+ tensor_type,+ " tensor size is not equal to the model ",+ tensor_type,+ " type: got ",+ tensor_shape,+ " expecting ",+ port_partial_shape,+ ".");+ OPENVINO_ASSERT(+ std::dynamic_pointer_cast<ov::IRemoteTensor>(tensor._ptr) || tensor->data() != nullptr || is_dynamic,+ "Tensor data equal nullptr!");+}++void ZeroInferRequest::check_batched_tensors(const ov::Output<const ov::Node>& port,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const bool supportStrides) const {+ OPENVINO_ASSERT(!tensors.empty(), "set_input_tensors/set_tensors can't be called with empty tensors");+ OPENVINO_ASSERT(+ tensors.size() != 1,+ "Internal error (plugin): check_batched_tensors is not allowed to have only one tensor inside batch");++ auto layout = ov::layout::get_layout(port);++ int64_t batch_idx;++ if (layout.empty()) {+ _logger.warning("check_batched_tensors - set_input_tensors/set_tensors layout is not set, assuming batch "+ "dimension is found on 0 axis");+ batch_idx = utils::BATCH_AXIS;+ } else {+ OPENVINO_ASSERT(ov::layout::has_batch(layout),+ "set_input_tensors/set_tensors can be used only for inputs with N(batch) dimension"+ " 'layout' defined. Current layout is ",+ layout.to_string());+ batch_idx = ov::layout::batch_idx(layout);+ }++ if (batch_idx < 0) {+ batch_idx += static_cast<int64_t>(tensors[utils::BATCH_AXIS]->get_shape().size());+ }+ OPENVINO_ASSERT(batch_idx == utils::BATCH_AXIS,+ "set_input_tensors/set_tensors is not currently supported for batch dimension index ",+ batch_idx,+ " != 0");+ std::for_each(tensors.begin(), tensors.end(), [&batch_idx](const ov::SoPtr<ov::ITensor>& item) {+ OPENVINO_ASSERT(item, "Uninitialized tensor is provided!");+ OPENVINO_ASSERT(item->get_shape()[batch_idx] == 1,+ "set_input_tensors/set_tensors. Tensors shall represent one item in a batch, ",+ item->get_shape()[batch_idx],+ " provided");+ });+ auto tensors_size = static_cast<int>(tensors.size());+ if (port.get_partial_shape().rank().is_static()) {+ OPENVINO_ASSERT(batch_idx >= 0 && batch_idx < port.get_partial_shape().rank().get_length(),+ "set_input_tensors/set_tensors error. Layout ",+ layout.to_string(),+ " is incorrect for operation with shape ",+ port.get_partial_shape());+ auto batch = port.get_partial_shape()[batch_idx];++ OPENVINO_ASSERT(batch.is_dynamic() || batch.get_length() == tensors_size,+ "set_input_tensors/set_tensors error. Input shape ",+ port.get_partial_shape(),+ "batch ",+ batch,+ "doesn't match with total blobs count: ",+ tensors_size);+ }++ auto batched_shape = tensors[utils::BATCH_AXIS]->get_shape();+ auto element_type = tensors[utils::BATCH_AXIS]->get_element_type();+ batched_shape[batch_idx] = tensors_size;+ for (const auto& item : tensors) {+ OPENVINO_ASSERT(item, "Uninitialized tensor is provided!");+ auto item_shape = item->get_shape();+ item_shape[batch_idx] = batched_shape[batch_idx];+ OPENVINO_ASSERT(item_shape == batched_shape && item->get_element_type() == element_type,+ "set_input_tensors/set_tensors error. Tensor with element type ",+ item->get_element_type(),+ " and shape ",+ item_shape,+ " is not compatible with batched tensor with element type ",+ element_type,+ " and shape ",+ batched_shape);++ if (!supportStrides) {+ OPENVINO_ASSERT(+ item->is_continuous(),+ "The tensor has a non-contiguous memory layout (custom strides), which is not supported by the "+ "current driver/compiler version. To use strided tensors, either:\n"+ " 1. Upgrade to a driver version that supports strides, or\n"+ " 2. Enable stride support using the 'NPU_ENABLE_STRIDES_FOR' configuration property if this is "+ "supported.");+ }+ }+}++void ZeroInferRequest::check_tensors() const {+ const auto& inputs = _compiledModel->inputs();+ for (size_t i = 0; i < inputs.size(); i++) {+ if (is_batched_input(i)) {+ check_batched_tensors(inputs[i], get_user_inputs(i), _metadata.inputs.at(i).supportsStridedLayout);+ continue;+ }+ if (get_user_input(i)) {+ check_tensor(inputs[i], get_user_input(i), _metadata.inputs.at(i).supportsStridedLayout);+ }+ }++ const auto& outputs = _compiledModel->outputs();+ for (size_t i = 0; i < outputs.size(); i++) {+ if (_userOutputTensors.at(i)) {+ check_tensor(outputs[i], _userOutputTensors.at(i), _metadata.outputs.at(i).supportsStridedLayout);+ }+ }+}++bool ZeroInferRequest::is_batched_input(size_t idx) const {+ return _userInputTensors.at(idx).size() > 1;+}++ov::SoPtr<ov::ITensor>& ZeroInferRequest::get_user_input(size_t index) const {+ return _userInputTensors.at(index).at(0);+}++std::vector<ov::SoPtr<ov::ITensor>>& ZeroInferRequest::get_user_inputs(size_t index) const {+ return _userInputTensors.at(index);+}++std::shared_ptr<ZeroTensor>& ZeroInferRequest::get_level_zero_input(size_t index, size_t tensorNo) const {+ return _levelZeroInputTensors.at(index).at(tensorNo);+}++std::vector<std::shared_ptr<ZeroTensor>>& ZeroInferRequest::get_level_zero_inputs(size_t index) const {+ return _levelZeroInputTensors.at(index);}void ZeroInferRequest::check_network_precision(const ov::element::Type_t precision) const {@@ -992,24 +1337,4 @@ std::vector<ov::ProfilingInfo> ZeroInferRequest::get_profiling_info() const {return _pipeline->get_profiling_info();}-void ZeroInferRequest::add_state(const IODescriptor& descriptor, size_t tensorIndex) const {- OPENVINO_ASSERT(descriptor.relatedDescriptorIndex.has_value(),- "The link between state descriptors is missing, state name: ",- descriptor.nameFromCompiler);-- _variableStates.push_back(std::make_shared<ZeroVariableState>(_initStructs,- descriptor.nameFromCompiler,- get_level_zero_input(tensorIndex),- tensorIndex,- descriptor.relatedDescriptorIndex.value()));-}--std::shared_ptr<ZeroTensor>& ZeroInferRequest::get_level_zero_input(size_t index, size_t tensorNo) const {- return _levelZeroInputTensors.at(index).at(tensorNo);-}--std::vector<std::shared_ptr<ZeroTensor>>& ZeroInferRequest::get_level_zero_inputs(size_t index) const {- return _levelZeroInputTensors.at(index);-}-} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hppindex d09b9a5d362..739cab5170e 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/npu.hpp@@ -8,9 +8,9 @@#include "intel_npu/common/icompiled_model.hpp"#include "intel_npu/common/igraph.hpp"-#include "intel_npu/common/sync_infer_request.hpp"#include "intel_npu/config/config.hpp"#include "intel_npu/utils/zero/zero_init.hpp"+#include "openvino/runtime/iinfer_request.hpp"#include "openvino/runtime/properties.hpp"namespace intel_npu {@@ -55,6 +55,14 @@ protected://------------------------------------------------------------------------------+class InferRequest : public ov::IInferRequest {+public:+ virtual void infer_async() = 0;+ virtual void get_result() = 0;++ virtual ~InferRequest() = default;+};+//------------------------------------------------------------------------------class IDevice : public std::enable_shared_from_this<IDevice> {@@ -73,9 +81,8 @@ public:virtual ov::device::Type getDeviceType() const;virtual std::map<ov::element::Type, float> getGops() const;- virtual std::shared_ptr<SyncInferRequest> createInferRequest(- const std::shared_ptr<const ICompiledModel>& compiledModel,- const Config& config) = 0;+ virtual std::shared_ptr<InferRequest> createInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel,+ const Config& config) = 0;virtual void updateInfo(const ov::AnyMap& properties) = 0;diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hppdeleted file mode 100644index 7f325dfbb7b..00000000000--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/sync_infer_request.hpp+++ /dev/null@@ -1,183 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include "intel_npu/common/icompiled_model.hpp"-#include "intel_npu/common/igraph.hpp"-#include "intel_npu/network_metadata.hpp"-#include "openvino/runtime/iinfer_request.hpp"-#include "openvino/runtime/iplugin.hpp"--namespace intel_npu {--/**- * @brief Acts as an interface for the inference request structures implemented by all backends.- * @details The operations common for all backends can be found implemented here, these include tensors' extraction,- * state variables handling and and a few helper functions.- * @note Regarding the code design, the "ov::ISyncInferRequest" would normally be the better option for- * inheritance. However, the interface exposed by that class forces some additional latency in several unfavorable- * scenarios, thus a reimplementation was required.- */-class SyncInferRequest : public ov::IInferRequest {-public:- explicit SyncInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel, const Config& config);-- /**- * @brief Gets an input/output tensor for inference.- * @note If the tensor with the specified @p port is not found, an exception is thrown.- * @param port Port of the tensor to get.- * @return Tensor for the port @p port.- */- virtual ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override;-- /**- * @brief Sets an input/output tensor to infer.- * @param port Port of the input or output tensor.- * @param tensor Reference to a tensor. The element_type and shape of a tensor must match- * the model's input/output element_type and size.- */- virtual void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override;-- /**- * @brief Currently there is no support implemented for batches of tensors, thus this call is a simple redirection- * to the "get_tensor" one.- */- std::vector<ov::SoPtr<ov::ITensor>> get_tensors(const ov::Output<const ov::Node>& port) const override;-- /**- * @brief Currently there is no support implemented for batches of tensors, thus this call is a simple redirection- * to the "set_tensor" one.- */- virtual void set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) override;-- /**- * @brief Gets inputs for infer request- *- * @return vector of input ports- */- const std::vector<ov::Output<const ov::Node>>& get_inputs() const override;-- /**- * @brief Gets outputs for infer request- *- * @return vector of output ports- */- const std::vector<ov::Output<const ov::Node>>& get_outputs() const override;-- /**- * @brief Gets pointer to compiled model (usually synchronous request holds the compiled model)- *- * @return Pointer to the compiled model- */- const std::shared_ptr<const ov::ICompiledModel>& get_compiled_model() const override;-- /**- * @brief Used for executing the inference.- */- virtual void infer_async() = 0;-- /**- * @brief Used for retrieving the prediction's result.- */- virtual void get_result() = 0;-- std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override;-- /**- * @brief Initializes the tensor values corresponding to the state variables.- * @details The inital values are usually all 0s.- */- void initialize_states();--protected:- /**- * @see ov::ISyncInferRequest- */- struct FoundPort {- size_t idx;- enum class Type { NOT_FOUND = 0, INPUT, OUTPUT } type;-- bool found() {- return type != Type::NOT_FOUND;- }- bool is_input() {- return type == Type::INPUT;- }- bool is_output() {- return !is_input();- }- };-- /**- * @brief Finds input or output port- * @return structure which contains index of Input/Output or report that port wasn't found- * @see ov::ISyncInferRequest- */- FoundPort find_port(const ov::Output<const ov::Node>& port) const;-- /**- * @brief Basic checks for input/output tensor- *- * @param port Input/Output port- * @param tensor Input/Output tensor- */- void check_tensor(const ov::Output<const ov::Node>& port,- const ov::SoPtr<ov::ITensor>& tensor,- const bool support_strides) const;-- /**- * @brief Basic checks for input tensors- *- * @param port Input port- * @param tensors Input tensors- */- void check_batched_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- const bool support_strides) const;-- /**- * @brief Check that all tensors are valid. Throws an exception if it's not.- */- void check_tensors() const override;-- /**- * @brief Checks if the provided precision value is supported by the current backend, should throw an error- * otherwise.- * @param precision The precision value to be checked.- */- virtual void check_network_precision(const ov::element::Type_t precision) const = 0;-- bool is_batched_input(size_t idx) const;-- ov::SoPtr<ov::ITensor>& get_user_input(size_t index) const;- std::vector<ov::SoPtr<ov::ITensor>>& get_user_inputs(size_t index) const;-- // This is intel_npu::ICompiledModel pointer, but need to use OV base class because- // ov::IInferRequest::get_compiled_model returns a refernce to shared_ptr!- std::shared_ptr<const ov::ICompiledModel> _compiledModel;-- NetworkMetadata _metadata;-- Logger _logger;-- // In case set_tensors is called, we receive a vector with N tensors otherwise only 1 tensor is needed- mutable std::vector<std::vector<ov::SoPtr<ov::ITensor>>> _userInputTensors;- mutable std::vector<ov::SoPtr<ov::ITensor>> _userOutputTensors;-- mutable std::vector<ov::SoPtr<ov::IVariableState>> _variableStates;-- /**- * @see ov::ISyncInferRequest- */- mutable std::unordered_map<size_t, FoundPort> _cachedPorts;-- /**- * @see ov::ISyncInferRequest- */- mutable std::mutex _cacheMutex;-};--} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp b/src/plugins/intel_npu/src/common/src/sync_infer_request.cppdeleted file mode 100644index 3fa52ff76fa..00000000000--- a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp+++ /dev/null@@ -1,364 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "intel_npu/common/sync_infer_request.hpp"--#include "intel_npu/prefix.hpp"-#include "intel_npu/utils/utils.hpp"-#include "openvino/op/util/op_types.hpp"-#include "openvino/runtime/make_tensor.hpp"-#include "openvino/runtime/plugin_itt.hpp"-#include "openvino/util/common_util.hpp"-#include "transformations/utils/utils.hpp"--namespace intel_npu {--SyncInferRequest::SyncInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel, const Config& config)- : _compiledModel(compiledModel),- _metadata(compiledModel->get_graph()->get_metadata()),- _logger("SyncInferRequest", config.get<LOG_LEVEL>()),- _userInputTensors(_metadata.inputs.size(), std::vector<ov::SoPtr<ov::ITensor>>(1, {nullptr})),- _userOutputTensors(_metadata.outputs.size(), {nullptr}) {- OPENVINO_ASSERT(_compiledModel);-- if (get_outputs().empty()) {- OPENVINO_THROW("Inference request creation: no output found for network " + _metadata.name);- }-- // Create map of empty tensors and cache ports from the compiled model- // See the ov::ISyncInferRequest constructor- auto portType = SyncInferRequest::FoundPort::Type::INPUT;- for (const auto& ports : {get_inputs(), get_outputs()}) {- for (size_t i = 0; i < ports.size(); i++) {- const auto& port = ports[i];- size_t portHash = ov::util::hash_combine(std::vector<size_t>{std::hash<const ov::Node*>()(port.get_node()),- std::hash<size_t>()(port.get_index())});- _cachedPorts[portHash] = {i, portType};- }- portType = SyncInferRequest::FoundPort::Type::OUTPUT;- }-}--SyncInferRequest::FoundPort SyncInferRequest::find_port(const ov::Output<const ov::Node>& port) const {- // check if the tensor names of target port is a subset of source port's tensor names- auto check_tensor_names = [](const std::unordered_set<std::string>& source,- const std::unordered_set<std::string>& target) {- for (const auto& name : target) {- if (source.find(name) == source.end()) {- return false;- }- }- return true;- };-- // This function is hotspot, need optimization.- auto check_nodes = [](const ov::Node* node1, const ov::Node* node2) {- return node1 == node2 ||- (node1->outputs().size() == node2->outputs().size() &&- node1->inputs().size() == node2->inputs().size() && node1->get_type_info() == node2->get_type_info() &&- node1->get_friendly_name() == node2->get_friendly_name());- };- // Find port without caching work slow because we need each time iterate over all ports and compare different- // strings So use WA with caching in order to make 2+ calls for the same ports faster.- // Calculate hash for the port- size_t port_hash =- ov::util::hash_combine({std::hash<const ov::Node*>()(port.get_node()), std::hash<size_t>()(port.get_index())});- {- std::lock_guard<std::mutex> lock(_cacheMutex);- if (_cachedPorts.find(port_hash) != _cachedPorts.end()) {- // Cached port for the hash was found- return _cachedPorts[port_hash];- }- }- SyncInferRequest::FoundPort::Type type = SyncInferRequest::FoundPort::Type::INPUT;- for (const auto& ports : {get_inputs(), get_outputs()}) {- for (size_t i = 0; i < ports.size(); i++) {- // The order of the arguments might matter for the "check_tensor_names" call. If the "CompiledModel" object- // was obtained via "import_model", then the number of tensor names could be cut to 32 due to limitations- // inside the NPU stack. For this particular scenario, we are checking if all tensor names corresponding to- // the "CompiledModel" are found in the provided port instead of doing the opposite.- if (ports[i].get_index() == port.get_index() && check_nodes(ports[i].get_node(), port.get_node()) &&- check_tensor_names(port.get_names(), ports[i].get_names())) {- std::lock_guard<std::mutex> lock(_cacheMutex);- _cachedPorts[port_hash] = {i, type};- return _cachedPorts[port_hash];- }- }- type = SyncInferRequest::FoundPort::Type::OUTPUT;- }- return {0, SyncInferRequest::FoundPort::Type::NOT_FOUND};-}--const std::vector<ov::Output<const ov::Node>>& SyncInferRequest::get_inputs() const {- return _compiledModel->inputs();-}--const std::vector<ov::Output<const ov::Node>>& SyncInferRequest::get_outputs() const {- return _compiledModel->outputs();-}--const std::shared_ptr<const ov::ICompiledModel>& SyncInferRequest::get_compiled_model() const {- return _compiledModel;-}--void SyncInferRequest::initialize_states() {- for (const ov::SoPtr<ov::IVariableState>& variableState : _variableStates) {- variableState->reset();- }-}--std::vector<ov::SoPtr<ov::IVariableState>> SyncInferRequest::query_state() const {- return _variableStates;-}--ov::SoPtr<ov::ITensor> SyncInferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {- auto foundPort = find_port(port);- OPENVINO_ASSERT(foundPort.found(), "Cannot find tensor for port ", port);-- if (foundPort.is_input()) {- return get_user_input(foundPort.idx);- }- return _userOutputTensors.at(foundPort.idx);-}--void SyncInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) {- OV_ITT_SCOPED_TASK(ov::itt::domains::Plugin, "set_tensor");-- auto foundPort = find_port(port);- OPENVINO_ASSERT(foundPort.found(), "Cannot find tensor for port ", port);- try {- check_tensor(port,- tensor,- foundPort.is_input() ? _metadata.inputs.at(foundPort.idx).supportsStridedLayout- : _metadata.outputs.at(foundPort.idx).supportsStridedLayout);- } catch (const ov::Exception& ex) {- OPENVINO_THROW("Failed to set tensor. ", ex.what());- }-- if (foundPort.is_input()) {- get_user_input(foundPort.idx) = tensor;- } else {- _userOutputTensors.at(foundPort.idx) = tensor;- }-}--std::vector<ov::SoPtr<ov::ITensor>> SyncInferRequest::get_tensors(const ov::Output<const ov::Node>& port) const {- OV_ITT_SCOPED_TASK(ov::itt::domains::Plugin, "get_tensors");-- auto foundPort = find_port(port);- OPENVINO_ASSERT(foundPort.found(), "Cannot find input tensors for port ", port);-- if (foundPort.is_input() && is_batched_input(foundPort.idx)) {- return get_user_inputs(foundPort.idx);- }-- return {};-}--void SyncInferRequest::set_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors) {- OV_ITT_SCOPED_TASK(ov::itt::domains::Plugin, "set_tensors");- if (tensors.size() == 1) {- set_tensor(port, tensors[0]);- return;- }-- OPENVINO_THROW_NOT_IMPLEMENTED("set_input_tensors/set_tensors are not supported by this plugin");-}--void SyncInferRequest::check_tensor(const ov::Output<const ov::Node>& port,- const ov::SoPtr<ov::ITensor>& tensor,- const bool support_strides) const {- if (tensor == nullptr)- OPENVINO_THROW("The tensor is not initialized!");-- bool is_input = ov::op::util::is_parameter(port.get_node());- const std::string_view tensor_type = is_input ? "input" : "output";-- if (!support_strides) {- OPENVINO_ASSERT(- tensor->is_continuous(),- "The tensor has a non-contiguous memory layout (custom strides), which is not supported by the "- "current driver/compiler version. To use strided tensors, either:\n"- " 1. Upgrade to a driver version that supports strides, or\n"- " 2. Enable stride support using the 'enable_strides_for' configuration property if this is supported.");- }-- const auto& port_element_type = port.get_element_type();- const auto& tensor_element_type = tensor->get_element_type();-- if ((port_element_type == ov::element::Type_t::boolean || tensor_element_type == ov::element::Type_t::boolean) &&- port_element_type != tensor_element_type) {- // Exception case for boolean treated as u8 in the NPU driver- OPENVINO_ASSERT(port_element_type == ov::element::Type_t::u8 || tensor_element_type == ov::element::Type_t::u8,- "The tensor element type is not corresponding with output element type (",- tensor_element_type,- " != ",- port_element_type);- } else {- OPENVINO_ASSERT(port_element_type == tensor_element_type,- "The tensor element type is not corresponding with output element type (",- tensor_element_type,- " != ",- port_element_type);- }-- const auto& port_partial_shape = port.get_partial_shape();- const auto& tensor_shape = tensor->get_shape();-- bool is_dynamic = port_partial_shape.is_dynamic();-- if (is_dynamic) {- auto port_length = port_partial_shape.rank().get_length();- OPENVINO_ASSERT(ov::PartialShape(tensor_shape).rank().get_length() == port_length,- "The tensor shape size is not equal to the model input/output rank: got ",- tensor_shape.size(),- " expecting ",- port_length);-- if (port_length > 0) {- const auto& port_max_shape = port_partial_shape.get_max_shape();- for (auto i = 0; i < port_length; ++i) {- if (tensor_shape[i] > port_max_shape[i]) {- OPENVINO_THROW("The tensor shape is not compatible with the model input/output max shape: got ",- tensor_shape,- " expecting max shape ",- port_max_shape);- }- }- }- }-- OPENVINO_ASSERT(is_dynamic || port_partial_shape == tensor_shape,- "The ",- tensor_type,- " tensor size is not equal to the model ",- tensor_type,- " type: got ",- tensor_shape,- " expecting ",- port_partial_shape,- ".");- OPENVINO_ASSERT(- std::dynamic_pointer_cast<ov::IRemoteTensor>(tensor._ptr) || tensor->data() != nullptr || is_dynamic,- "Tensor data equal nullptr!");-}--void SyncInferRequest::check_batched_tensors(const ov::Output<const ov::Node>& port,- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,- const bool support_strides) const {- OPENVINO_ASSERT(!tensors.empty(), "set_input_tensors/set_tensors can't be called with empty tensors");- OPENVINO_ASSERT(- tensors.size() != 1,- "Internal error (plugin): check_batched_tensors is not allowed to have only one tensor inside batch");-- auto layout = ov::layout::get_layout(port);-- int64_t batch_idx;-- if (layout.empty()) {- _logger.warning("set_input_tensors/set_tensors layout is not set, assuming batch dimension is found on 0 axis");- batch_idx = utils::BATCH_AXIS;- } else {- OPENVINO_ASSERT(ov::layout::has_batch(layout),- "set_input_tensors/set_tensors can be used only for inputs with N(batch) dimension"- " 'layout' defined. Current layout is ",- layout.to_string());- batch_idx = ov::layout::batch_idx(layout);- }-- if (batch_idx < 0) {- batch_idx += static_cast<int64_t>(tensors[utils::BATCH_AXIS]->get_shape().size());- }- OPENVINO_ASSERT(batch_idx == utils::BATCH_AXIS,- "set_input_tensors/set_tensors is not currently supported for batch dimension index ",- batch_idx,- " != 0");- std::for_each(tensors.begin(), tensors.end(), [&batch_idx](const ov::SoPtr<ov::ITensor>& item) {- OPENVINO_ASSERT(item, "Unintialized tensor is provided!");- OPENVINO_ASSERT(item->get_shape()[batch_idx] == 1,- "set_input_tensors/set_tensors. Tensors shall represent one item in a batch, ",- item->get_shape()[batch_idx],- " provided");- });- auto tensors_size = static_cast<int>(tensors.size());- if (port.get_partial_shape().rank().is_static()) {- OPENVINO_ASSERT(batch_idx >= 0 && batch_idx < port.get_partial_shape().rank().get_length(),- "set_input_tensors/set_tensors error. Layout ",- layout.to_string(),- " is incorrect for operation with shape ",- port.get_partial_shape());- auto batch = port.get_partial_shape()[batch_idx];-- OPENVINO_ASSERT(batch.is_dynamic() || batch.get_length() == tensors_size,- "set_input_tensors/set_tensors error. Input shape ",- port.get_partial_shape(),- "batch ",- batch,- "doesn't match with total blobs count: ",- tensors_size);- }-- auto batched_shape = tensors[utils::BATCH_AXIS]->get_shape();- auto element_type = tensors[utils::BATCH_AXIS]->get_element_type();- batched_shape[batch_idx] = tensors_size;- for (const auto& item : tensors) {- OPENVINO_ASSERT(item, "Unintialized tensor is provided!");- auto item_shape = item->get_shape();- item_shape[batch_idx] = batched_shape[batch_idx];- OPENVINO_ASSERT(item_shape == batched_shape && item->get_element_type() == element_type &&- "set_input_tensors/set_tensors error. Tensor with element type ",- item->get_element_type(),- " and shape ",- item_shape,- " is not compatible with batched tensor with element type ",- element_type,- " and shape ",- batched_shape);-- if (!support_strides) {- OPENVINO_ASSERT(- item->is_continuous(),- "The tensor has a non-contiguous memory layout (custom strides), which is not supported by the "- "current driver/compiler version. To use strided tensors, either:\n"- " 1. Upgrade to a driver version that supports strides, or\n"- " 2. Enable stride support using the 'NPU_ENABLE_STRIDES_FOR' configuration property if this is "- "supported.");- }- }-}--void SyncInferRequest::check_tensors() const {- const auto& inputs = _compiledModel->inputs();- for (size_t i = 0; i < inputs.size(); i++) {- if (is_batched_input(i)) {- check_batched_tensors(inputs[i], get_user_inputs(i), _metadata.inputs.at(i).supportsStridedLayout);- continue;- }- if (get_user_input(i)) {- check_tensor(inputs[i], get_user_input(i), _metadata.inputs.at(i).supportsStridedLayout);- }- }-- const auto& outputs = _compiledModel->outputs();- for (size_t i = 0; i < outputs.size(); i++) {- if (_userOutputTensors.at(i)) {- check_tensor(outputs[i], _userOutputTensors.at(i), _metadata.outputs.at(i).supportsStridedLayout);- }- }-}--bool SyncInferRequest::is_batched_input(size_t idx) const {- return _userInputTensors.at(idx).size() > 1;-}--ov::SoPtr<ov::ITensor>& SyncInferRequest::get_user_input(size_t index) const {- return _userInputTensors.at(index).at(0);-}--std::vector<ov::SoPtr<ov::ITensor>>& SyncInferRequest::get_user_inputs(size_t index) const {- return _userInputTensors.at(index);-}--} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp b/src/plugins/intel_npu/src/plugin/include/async_infer_request.hppindex ea8a3f3ce33..c999c336e17 100644--- a/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp@@ -4,14 +4,17 @@#pragma once-#include "intel_npu/common/sync_infer_request.hpp"+#include <memory>+#include "openvino/runtime/iasync_infer_request.hpp"namespace intel_npu {+class InferRequest;+class AsyncInferRequest final : public ov::IAsyncInferRequest {public:- explicit AsyncInferRequest(const std::shared_ptr<SyncInferRequest>& inferRequest,+ explicit AsyncInferRequest(const std::shared_ptr<InferRequest>& inferRequest,const std::shared_ptr<ov::threading::ITaskExecutor>& requestExecutor,const std::shared_ptr<ov::threading::ITaskExecutor>& getResultExecutor,const std::shared_ptr<ov::threading::ITaskExecutor>& callbackExecutor);@@ -22,12 +25,12 @@ public:~AsyncInferRequest();- std::shared_ptr<SyncInferRequest> get_sync_infer_request() {+ std::shared_ptr<InferRequest> get_sync_infer_request() {return _syncInferRequest;}private:- std::shared_ptr<SyncInferRequest> _syncInferRequest;+ std::shared_ptr<InferRequest> _syncInferRequest;std::shared_ptr<ov::threading::ITaskExecutor> _getResultExecutor;};diff --git a/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp b/src/plugins/intel_npu/src/plugin/src/async_infer_request.cppindex ed457be8bef..622e5a51f1a 100644--- a/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp@@ -4,10 +4,12 @@#include "async_infer_request.hpp"+#include "intel_npu/common/npu.hpp"+namespace intel_npu {// clang-format off-AsyncInferRequest::AsyncInferRequest(const std::shared_ptr<SyncInferRequest>& syncInferRequest,+AsyncInferRequest::AsyncInferRequest(const std::shared_ptr<InferRequest>& syncInferRequest,const std::shared_ptr<ov::threading::ITaskExecutor>& requestExecutor,const std::shared_ptr<ov::threading::ITaskExecutor>& getResultExecutor,const std::shared_ptr<ov::threading::ITaskExecutor>& callbackExecutor)diff --git a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/src/compiled_model.cppindex f5355517532..54b2b42a65e 100644--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp@@ -69,9 +69,8 @@ std::shared_ptr<ov::IAsyncInferRequest> CompiledModel::create_infer_request() co"The driver is not applicable. The driver doesn't exist or is too old to run inference for this blob.");}- const std::shared_ptr<SyncInferRequest>& syncInferRequest =+ const std::shared_ptr<InferRequest>& syncInferRequest =_device->createInferRequest(shared_from_this(), _propertiesManager->getConfig());- syncInferRequest->initialize_states();return std::make_shared<AsyncInferRequest>(syncInferRequest,get_task_executor(),