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] Dynamic batching via BatchMode::PLUGIN (#30923)
Sergey Ivanova38cac5ccfa2
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 a5a433224d1..49456851173 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@@ -89,6 +89,7 @@ private:std::unique_ptr<Pipeline> _pipeline;bool _pipelineIsCreated = false;+ bool _pipelineNeedsReallocation = false;};} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hppindex c15ff778be1..8569ba4e003 100644--- a/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp+++ b/src/plugins/intel_npu/src/backend/include/zero_pipeline.hpp@@ -19,7 +19,8 @@ public:const std::shared_ptr<ZeroInitStructsHolder>& init_structs,const std::shared_ptr<IGraph>& graph,const std::vector<std::vector<std::shared_ptr<ov::ITensor>>>& input_tensors,- const std::vector<std::shared_ptr<ov::ITensor>>& output_tensors);+ const std::vector<std::shared_ptr<ov::ITensor>>& output_tensors,+ size_t batch_size = 1);Pipeline(const Pipeline&) = delete;Pipeline& operator=(const Pipeline&) = delete;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 1035018c2b4..fd25d60a020 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@@ -21,6 +21,8 @@ constexpr std::size_t SINGLE_TENSOR = 0;constexpr bool INPUT = true;constexpr bool OUTPUT = false;+constexpr std::size_t DEFAULT_BATCH_SIZE = 1;+/*** @brief Checks that the metadata of the provided descriptor corresponds to the values registered in the Level Zero* structure.@@ -60,7 +62,10 @@ void check_level_zero_attributes_match(const IODescriptor& ioDescriptor, const Afor (size_t index = 0; index < ovDimensions.size(); ++index) {OPENVINO_ASSERT(ovDimensions[index] == zeDescriptor.info.dims[index],- "Shape mismatch for input/output named " + ioDescriptor.nameFromCompiler);+ "Shape mismatch for input/output named \"" + ioDescriptor.nameFromCompiler ++ "\" by dimension index: " + std::to_string(index) ++ ". L0 has: " + std::to_string(zeDescriptor.info.dims[index]) ++ " but meta has: " + std::to_string(ovDimensions[index]));}for (size_t index = ovDimensions.size(); index < ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE; ++index) {OPENVINO_ASSERT(zeDescriptor.info.dims[index] == 0 || zeDescriptor.info.dims[index] == 1,@@ -92,6 +97,10 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&_logger.debug("ZeroInferRequest::ZeroInferRequest - checking level zero attributes and allocating tensors");size_t ioIndex = 0;+ auto batchSize = _graph->get_batch_size(_metadata, {}, {});+ if (!_userInputTensors.empty() && !_graphInputDescriptors.empty()) {+ batchSize = _graph->get_batch_size(_metadata, _userInputTensors.at(0), _graphInputDescriptors[0]);+ }for (const IODescriptor& inputDescriptor : _metadata.inputs) {check_level_zero_attributes_match(inputDescriptor, _graphInputDescriptors.at(ioIndex));@@ -100,8 +109,7 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&continue;}- get_level_zero_input(ioIndex) =- allocate_tensor(inputDescriptor, ioIndex, INPUT, *_inputAllocator, _graph->get_batch_size());+ get_level_zero_input(ioIndex) = allocate_tensor(inputDescriptor, ioIndex, INPUT, *_inputAllocator, batchSize);++ioIndex;}@@ -116,7 +124,7 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&}_levelZeroOutputTensors.at(ioIndex) =- allocate_tensor(outputDescriptor, ioIndex, OUTPUT, *_outputAllocator, _graph->get_batch_size());+ allocate_tensor(outputDescriptor, ioIndex, OUTPUT, *_outputAllocator, batchSize);++ioIndex;}@@ -125,8 +133,13 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&}void ZeroInferRequest::create_pipeline() {+ _logger.debug("ZeroInferRequest::create_pipeline");+ auto batchSize = _graph->get_batch_size(_metadata, {}, {});+ if (!_userInputTensors.empty() && !_graphInputDescriptors.empty()) {+ batchSize = _graph->get_batch_size(_metadata, _userInputTensors.at(0), _graphInputDescriptors[0]);+ }for (size_t inputIndex = 0; inputIndex < _metadata.inputs.size(); ++inputIndex) {- if (is_batched_input(inputIndex) && _graph->get_batch_size().has_value()) {+ 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",_metadata.inputs.at(inputIndex).nodeFriendlyName.c_str());@@ -134,29 +147,31 @@ void ZeroInferRequest::create_pipeline() {for (size_t i = 0; i < get_user_inputs(inputIndex).size(); i++) {get_level_zero_inputs(inputIndex).resize(get_user_inputs(inputIndex).size());- _logger.debug("ZeroInferRequest::create_pipeline - allocate new input tensor for batched input: %s",- _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str());+ _logger.debug("ZeroInferRequest::create_pipeline - allocate new input tensor for batched input: "+ "%s, batch_size: %zu",+ _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str(),+ batchSize.value());get_level_zero_input(inputIndex, i) =- allocate_tensor(_metadata.inputs.at(inputIndex), inputIndex, true, *_inputAllocator);+ allocate_tensor(_metadata.inputs.at(inputIndex), inputIndex, true, *_inputAllocator, batchSize);}}continue;}if (get_level_zero_input(inputIndex)) {- _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated",- _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str());+ _logger.debug("ZeroInferRequest::create_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());+continue;}- _logger.debug("ZeroInferRequest::create_pipeline - allocate new input tensor %s",- _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str());- get_level_zero_input(inputIndex) = allocate_tensor(_metadata.inputs.at(inputIndex),- inputIndex,- INPUT,- *_inputAllocator,- _graph->get_batch_size());+ get_level_zero_input(inputIndex) =+ allocate_tensor(_metadata.inputs.at(inputIndex), inputIndex, INPUT, *_inputAllocator, batchSize);+ _logger.debug("ZeroInferRequest::create_pipeline - new input tensor %s allocated, size: %zu",+ _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str(),+ get_level_zero_input(inputIndex)->get_byte_size());}for (size_t outputIndex = 0; outputIndex < _metadata.outputs.size(); ++outputIndex) {@@ -167,11 +182,11 @@ void ZeroInferRequest::create_pipeline() {}_logger.debug("ZeroInferRequest::create_pipeline - allocate new output tensor %s",_metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());- _levelZeroOutputTensors.at(outputIndex) = allocate_tensor(_metadata.outputs.at(outputIndex),- outputIndex,- OUTPUT,- *_outputAllocator,- _graph->get_batch_size());+ _levelZeroOutputTensors.at(outputIndex) =+ allocate_tensor(_metadata.outputs.at(outputIndex), outputIndex, OUTPUT, *_outputAllocator, batchSize);+ _logger.debug("ZeroInferRequest::create_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");@@ -201,8 +216,12 @@ void ZeroInferRequest::create_pipeline() {_logger.debug("ZeroInferRequest::create_pipeline - constructing pipeline");// Construct pipeline- _pipeline =- std::make_unique<Pipeline>(_config, _initStructs, _graph, _levelZeroInputTensors, _levelZeroOutputTensors);+ _pipeline = std::make_unique<Pipeline>(_config,+ _initStructs,+ _graph,+ _levelZeroInputTensors,+ _levelZeroOutputTensors,+ batchSize.has_value() ? batchSize.value() : DEFAULT_BATCH_SIZE);_logger.debug("ZeroInferRequest::create_pipeline - SyncInferRequest completed");}@@ -217,7 +236,8 @@ void ZeroInferRequest::set_tensor_data(const std::shared_ptr<ov::ITensor>& tensoOV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "check_data_allocation");if (zeroUtils::memory_was_allocated_in_the_same_l0_context(_initStructs->getContext(), tensor->data())) {- _logger.debug("ZeroInferRequest::set_tensor_data - tensor was created in the same L0 context");+ _logger.debug("ZeroInferRequest::set_tensor_data - tensor was created in the same L0 context, size: %zu",+ tensor->get_byte_size());levelZeroTensors = tensor;updateCommandListArg = true;} else {@@ -226,12 +246,20 @@ void ZeroInferRequest::set_tensor_data(const std::shared_ptr<ov::ITensor>& tenso_logger.debug("ZeroInferRequest::set_tensor_data - create locally L0 tensor");OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "allocate tensor");+ ov::SoPtr<ov::ITensor> soPtrTensor(tensor);+ std::vector<ov::SoPtr<ov::ITensor>> tensorVector = {soPtrTensor};+ auto batch =+ _graph->get_batch_size(_metadata,+ tensorVector,+ isInput ? _graphInputDescriptors.at(index) : _graphOutputDescriptors.at(index));+levelZeroTensors = allocate_tensor(isInput ? _metadata.inputs.at(index) : _metadata.outputs.at(index),index,isInput,isInput ? *_inputAllocator : *_outputAllocator,- _graph->get_batch_size());-+ batch);+ _logger.debug("ZeroInferRequest::set_tensor_data - tensor created locally, size: %zu",+ levelZeroTensors->get_byte_size());updateCommandListArg = true;}}@@ -293,12 +321,32 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const_logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");return;}- if (is_batched_input(foundPort.idx)) {+ // Check if batch has been changed+ if (get_user_input(foundPort.idx) != nullptr) {+ _logger.debug(+ "ZeroInferRequest::set_tensor - check if input tensors may have their sizes changed, existing: %zu and "+ "count: %zu, new: %zu - to determine whether we need for pipeline reallocation",+ get_user_input(foundPort.idx)->get_byte_size(),+ get_user_inputs(foundPort.idx).size(),+ tensor->get_byte_size());+ if (get_user_input(foundPort.idx)->get_byte_size() * get_user_inputs(foundPort.idx).size() !=+ tensor->get_byte_size()) {+ _pipelineNeedsReallocation = true;+ }+ }++ std::vector<ov::SoPtr<ov::ITensor>> tensorVector = {tensor};+ _graph->reset_last_batch_size();+ auto batchSizeCandidate =+ _graph->get_batch_size(_metadata, tensorVector, _graphInputDescriptors.at(foundPort.idx));+ if (is_batched_input(foundPort.idx) || batchSizeCandidate.has_value()) {// resize vector size to 1 if set_tensor is called after set_tensorsget_level_zero_inputs(foundPort.idx).resize(1);get_level_zero_inputs(foundPort.idx).shrink_to_fit();get_user_inputs(foundPort.idx).resize(1);get_user_inputs(foundPort.idx).shrink_to_fit();++ _graph->set_batch_size(batchSizeCandidate.has_value() ? batchSizeCandidate.value() : DEFAULT_BATCH_SIZE);}get_user_input(foundPort.idx) = tensor;@@ -308,6 +356,16 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const_logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");return;}+ // Check if batch has been changed+ if (_userOutputTensors.at(foundPort.idx) != nullptr) {+ _logger.debug("ZeroInferRequest::set_tensor - check if tensors have their sizes changed, existing: %zu, "+ "new: %zu - to determien whether we need for pipeline reallocation",+ _userOutputTensors.at(foundPort.idx)->get_byte_size(),+ tensor->get_byte_size());+ if (_userOutputTensors.at(foundPort.idx)->get_byte_size() != tensor->get_byte_size()) {+ _pipelineNeedsReallocation = true;+ }+ }_userOutputTensors.at(foundPort.idx) = tensor;}@@ -343,8 +401,23 @@ 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;+ _logger.debug("ZeroInferRequest::set_tensors: %zu", tensors.size());+ auto batch_size = _graph->get_batch_size(_metadata, tensors, _graphInputDescriptors.at(foundPort.idx));++ if (batch_size.has_value()) {+ _logger.debug("ZeroInferRequest::set_tensors: determined batch: %zu, preallocated L0 tensors: %zu ",+ batch_size.value(),+ _levelZeroInputTensors.at(foundPort.idx).size());+ if (tensors.size() != _levelZeroInputTensors.at(foundPort.idx).size() && batch_size.value() != tensors.size()) {+ batch_size = tensors.size();+ _logger.debug("ZeroInferRequest::set_tensors: batch sized has been changed to: %zu", batch_size.value());+ _graph->set_batch_size(tensors.size());+ _pipelineNeedsReallocation = true;+ }+ }+if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {- if (_graph->get_batch_size().has_value()) {+ if (batch_size) {for (size_t i = 0; i < tensors.size(); i++) {auto remoteTensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(tensors[i]._ptr);@@ -367,8 +440,11 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,_logger.debug("ZeroInferRequest::set_tensors - tensor wasn't created in the same L0 context, ""create a L0 tensor");- get_level_zero_input(foundPort.idx, i) =- allocate_tensor(_metadata.inputs.at(foundPort.idx), foundPort.idx, true, *_inputAllocator);+ get_level_zero_input(foundPort.idx, i) = allocate_tensor(_metadata.inputs.at(foundPort.idx),+ foundPort.idx,+ true,+ *_inputAllocator,+ batch_size);}data = get_level_zero_input(foundPort.idx, i)->data();@@ -380,7 +456,7 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,get_level_zero_input(foundPort.idx, i) = tensors.at(i)._ptr;}- if (_pipelineIsCreated) {+ if (_pipelineIsCreated && !_pipelineNeedsReallocation) {OPENVINO_ASSERT(data, "Empty buffer");OV_ITT_TASK_NEXT(SET_TENSORS, "updateCommandList");@@ -408,27 +484,62 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::Nauto& userTensors = isInput ? get_user_input(ioIndex) : _userOutputTensors.at(ioIndex);- if (userTensors) {+ if (userTensors && !_pipelineNeedsReallocation) {auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(userTensors._ptr);if (zeroTensor != nullptr) {zeroTensor->set_tensor_shared_with_user();}- _logger.debug("ZeroInferRequest::get_tensor - tensor allocated, get the tensor");+ _logger.debug("ZeroInferRequest::get_tensor - tensor allocated, get the tensor by index: %zu", ioIndex);return userTensors;}auto& metadata = isInput ? _metadata.inputs.at(ioIndex) : _metadata.outputs.at(ioIndex);- _logger.debug("ZeroInferRequest::get_tensor - tensor is not allocated, create tensor %s",+ _logger.debug("ZeroInferRequest::get_tensor - tensor by index: %zu is not allocated, or the existing pipeline "+ "needs reallocation: %s. New tensor %s will be created",+ ioIndex,+ _pipelineNeedsReallocation ? "true" : "false",metadata.nodeFriendlyName.c_str());auto& levelZeroTensors = isInput ? get_level_zero_input(ioIndex) : _levelZeroOutputTensors.at(ioIndex);- levelZeroTensors = allocate_tensor(metadata,- ioIndex,- isInput,- isInput ? *_inputAllocator : *_outputAllocator,- _graph->get_batch_size());+ // LIMITATION for the dynamic batch implementation:+ // We need to allocate output tensors having the same batch size as input tensors.+ // Which means that input tensor batch sizes must have been determined.+ // In other words, it means that someone MUST HAVE called set_tensor() BEFORE+ // asking get_tensor(). Otherwise we won't deduct the actual batch size+ // which we must return here.+ // If we may return wrong batch size here then we must have a mechanism notifying+ // user that that returned tensor is now obsolete, when someone had changed batch using set_tensor()+ // by holding already the old tensor from get_tensor() with the old batch size.+ // OR we must reallocate that tensor by callback+ std::vector<ov::SoPtr<ov::ITensor>> tensorVector;+ _logger.debug("ZeroInferRequest::get_tensor - try to get batch size from input tensors, if output is not created");+ if (isInput) {+ tensorVector.push_back(get_user_input(ioIndex));+ } else {+ tensorVector.push_back(get_user_input(0));+ }++ auto batch_size =+ _graph->get_batch_size(_metadata,+ tensorVector,+ isInput ? _graphInputDescriptors.at(ioIndex) : _graphOutputDescriptors.at(ioIndex));++ levelZeroTensors =+ allocate_tensor(metadata, ioIndex, isInput, isInput ? *_inputAllocator : *_outputAllocator, batch_size);++ _logger.debug("ZeroInferRequest::get_tensor - tensor by index: %zu is allocated: %s, size: %zu",+ ioIndex,+ metadata.nodeFriendlyName.c_str(),+ levelZeroTensors->get_byte_size());++ if (!isInput && _pipelineNeedsReallocation) {+ _logger.debug(+ "ZeroInferRequest::get_tensor - set new output tensor as pipeline reallocated required, batch size: %zu",+ batch_size.has_value() ? batch_size.value() : DEFAULT_BATCH_SIZE);+ userTensors = levelZeroTensors;+ }auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(levelZeroTensors);if (zeroTensor != nullptr) {@@ -543,11 +654,11 @@ void ZeroInferRequest::infer_async() {{std::lock_guard<std::mutex> lock(_graph->get_mutex());- if (!_pipelineIsCreated) {+ if (!_pipelineIsCreated || _pipelineNeedsReallocation) {OV_ITT_TASK_NEXT(ZERO_INFER, "create_pipeline");- create_pipeline();-+ create_pipeline(); // Reallocate pipeline if necessary_pipelineIsCreated = true;+ _pipelineNeedsReallocation = false; // Reset reallocation flag} else {if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {update_pipeline_if_memory_changed();@@ -575,8 +686,10 @@ void ZeroInferRequest::infer_async() {}}- if (is_batched_input(inputIndex)) {- if (_graph->get_batch_size().has_value()) {+ auto batch_size =+ _graph->get_batch_size(_metadata, _userInputTensors.at(inputIndex), _graphInputDescriptors.at(inputIndex));+ if (is_batched_input(inputIndex) || batch_size.has_value()) {+ if (batch_size.has_value()) {for (size_t i = 0; i < userTensor.size(); i++) {if (!is_remote_tensor(get_level_zero_input(inputIndex, i))) {void* levelZeroBuffer = get_level_zero_input(inputIndex, i)->data();@@ -591,7 +704,12 @@ void ZeroInferRequest::infer_async() {OPENVINO_THROW("Empty buffer");}- _logger.info("Batched Tensors - Tensor is not allocated in the current Level Zero context");+ _logger.info(+ "Batched Tensors - 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,+ userTensor.at(i)->get_byte_size(),+ get_level_zero_input(inputIndex, i)->get_byte_size());OV_ITT_TASK_NEXT(ZERO_INFER, "memcpy");std::memcpy(levelZeroBuffer, userBuffer, userTensor.at(i)->get_byte_size());}@@ -600,9 +718,12 @@ void ZeroInferRequest::infer_async() {} else {void* levelZeroBuffer = get_level_zero_input(inputIndex)->data();- _logger.info("Batched Tensors - Tensor is not allocated in the current Level Zero context or must be "- "in a continued memory space");-+ _logger.info("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,+ get_level_zero_input(inputIndex)->get_byte_size());+ size_t copied_bytes_from_user = 0;for (size_t i = 0; i < userTensor.size(); i++) {auto userBatchRemoteTensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(userTensor.at(i)._ptr);@@ -612,7 +733,14 @@ void ZeroInferRequest::infer_async() {std::memcpy(static_cast<unsigned char*>(levelZeroBuffer) + (i * userTensor.at(i)->get_byte_size()),userBuffer,userTensor.at(i)->get_byte_size());+ copied_bytes_from_user += userTensor.at(i)->get_byte_size();+ _logger.debug("Batched Tensors - Tensor by index: %zu copied bytes: [%zu/%zu]",+ inputIndex,+ copied_bytes_from_user,+ get_level_zero_input(inputIndex)->get_byte_size());}+ OPENVINO_ASSERT(get_level_zero_input(inputIndex)->get_byte_size() == copied_bytes_from_user,+ "Bytes copied must be equal");}++inputIndex;@@ -686,7 +814,8 @@ void ZeroInferRequest::get_result() {OPENVINO_THROW("Empty buffer");}- _logger.info("Tensor is not allocated in the current Level Zero context");+ _logger.info("Output tensor by index: %zu is not allocated in the current Level Zero context",+ outputIndex);OV_ITT_TASK_NEXT(ZERO_RESULT, "memcpy");std::memcpy(userBuffer, levelZeroBuffer, userTensor->get_byte_size());}diff --git a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cppindex af417821114..1a535aafc26 100644--- a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp@@ -16,20 +16,29 @@#include "intel_npu/utils/zero/zero_types.hpp"namespace intel_npu {-Pipeline::Pipeline(const Config& config,const std::shared_ptr<ZeroInitStructsHolder>& init_structs,const std::shared_ptr<IGraph>& graph,const std::vector<std::vector<std::shared_ptr<ov::ITensor>>>& input_tensors,- const std::vector<std::shared_ptr<ov::ITensor>>& output_tensors)+ const std::vector<std::shared_ptr<ov::ITensor>>& output_tensors,+ size_t batch_size): _init_structs(init_structs),_graph(graph),_config(config),_id(_graph->get_unique_id()),- _number_of_command_lists(_graph->get_batch_size().has_value() ? *_graph->get_batch_size() : 1),+ _number_of_command_lists(_graph->get_batch_size().has_value() ? *_graph->get_batch_size() : batch_size),_logger("Pipeline", _config.get<LOG_LEVEL>()) {OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Zero_infer_request::Pipeline::Pipeline");- _logger.debug("Pipeline - initialize started");+ auto batch = _graph->get_batch_size().has_value() ? *_graph->get_batch_size() : batch_size;++ if (_init_structs->getCommandQueueDdiTable().version() < ZE_MAKE_VERSION(1, 1) &&+ _config.get<RUN_INFERENCES_SEQUENTIALLY>()) {+ _graph->resize_last_submitted_event(_number_of_command_lists);+ }++ _logger.info("Pipeline - initialize started, batch %i, number_of_command_lists %i",+ batch,+ _number_of_command_lists);OPENVINO_ASSERT(_sync_output_with_fences || !_config.get<RUN_INFERENCES_SEQUENTIALLY>() ||_init_structs->getCommandQueueDdiTable().version() >= ZE_MAKE_VERSION(1, 1),@@ -79,6 +88,7 @@ Pipeline::Pipeline(const Config& config,}for (size_t i = 0; i < _number_of_command_lists; i++) {+ _logger.debug("Pipeline - set args for command list number: %zu", i);size_t io_index = 0;for (const auto& desc : graph->get_input_descriptors()) {if (isMainInputWeightsName(desc.info.name)) {@@ -86,7 +96,8 @@ Pipeline::Pipeline(const Config& config,continue;}- if (input_tensors.at(io_index).size() > 1) {+ if (io_index < input_tensors.size() && input_tensors.at(io_index).size() > 1) {+ _logger.debug("Pipeline - set args for input index: %zu", io_index);void* data = nullptr;auto remote_tensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(input_tensors.at(io_index).at(i));if (remote_tensor == nullptr) {diff --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 0d548ea015b..22ca65705dd 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@@ -11,10 +11,23 @@#include "intel_npu/network_metadata.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"#include "intel_npu/utils/zero/zero_wrappers.hpp"+#include "openvino/runtime/itensor.hpp"#include "openvino/runtime/profiling_info.hpp"+#include "openvino/runtime/so_ptr.hpp"namespace intel_npu {+struct IONodeMetadata {+ IONodeMetadata() = default;+ IONodeMetadata(const ArgumentDescriptor& d);+ std::optional<ArgumentDescriptor> descriptor;+ std::optional<size_t> extract_batch(const ov::Shape& shape) const;+ std::optional<size_t> extract_batch(const ov::Shape& shape, std::optional<ov::PartialShape> partial_shape) const;+ std::optional<size_t> extract_batch_impl(const ov::Shape& shape,+ std::optional<ov::PartialShape> partial_shape,+ size_t index) const;+};+class IGraph : public std::enable_shared_from_this<IGraph> {public:IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob);@@ -54,12 +67,22 @@ public:void set_last_submitted_event(const std::shared_ptr<Event>& event, size_t indexOfCommandList);const std::shared_ptr<Event>& get_last_submitted_event(size_t indexOfCommandList) const;+ void resize_last_submitted_event(size_t batch);+ void set_batch_size(std::size_t batch);+ void reset_last_batch_size();uint32_t get_unique_id();void set_last_submitted_id(uint32_t id_index);uint32_t get_last_submitted_id() const;const std::optional<std::size_t> get_batch_size() const;+ std::optional<size_t> determine_batch_size(const NetworkMetadata& metadata,+ const std::vector<ov::SoPtr<ov::ITensor>>& input_tensors,+ const IONodeMetadata& input_output_info) const;++ std::optional<size_t> get_batch_size(const NetworkMetadata& metadata,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const IONodeMetadata& input_output_info);protected:/**@@ -79,7 +102,6 @@ protected:* @returns The batch size deduced by the algorithm or the default value of 1 if batching cannot be performed inside* the plugin.*/- std::optional<size_t> get_batch_size(const NetworkMetadata& metadata);ze_graph_handle_t _handle = nullptr;NetworkMetadata _metadata;diff --git a/src/plugins/intel_npu/src/common/src/igraph.cpp b/src/plugins/intel_npu/src/common/src/igraph.cppindex 513cea7a81d..f6093c0b371 100644--- a/src/plugins/intel_npu/src/common/src/igraph.cpp+++ b/src/plugins/intel_npu/src/common/src/igraph.cpp@@ -13,6 +13,39 @@ constexpr std::size_t DEFAULT_BATCH_SIZE = 1;namespace intel_npu {+IONodeMetadata::IONodeMetadata(const ArgumentDescriptor& d) : descriptor(d) {}++std::optional<size_t> IONodeMetadata::extract_batch_impl(const ov::Shape& shape,+ std::optional<ov::PartialShape> partial_shape,+ size_t index) const {+ if (partial_shape.has_value()) {+ if (partial_shape.value()[index].is_dynamic()) {+ return shape[index];+ }+ return std::nullopt;+ }+ return shape[index];+}++std::optional<size_t> IONodeMetadata::extract_batch(const ov::Shape& shape) const {+ return extract_batch(shape, std::nullopt);+}++std::optional<size_t> IONodeMetadata::extract_batch(const ov::Shape& shape,+ std::optional<ov::PartialShape> partial_shape) const {+ if (descriptor.has_value()) {+ auto nLayout = descriptor.value().info.networkLayout;+ if (nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_NCHW || nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_NHWC ||+ nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_NCDHW || nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_NDHWC ||+ nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_NC) {+ return extract_batch_impl(shape, partial_shape.has_value() ? partial_shape : std::nullopt, 0);+ } else if (nLayout == ZE_GRAPH_ARGUMENT_LAYOUT_CN) {+ return extract_batch_impl(shape, partial_shape.has_value() ? partial_shape : std::nullopt, 1);+ }+ }+ return std::nullopt; // TODO get layout from shape+}+IGraph::IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob): _handle(handle),_metadata(std::move(metadata)),@@ -79,6 +112,18 @@ const std::shared_ptr<Event>& IGraph::get_last_submitted_event(size_t indexOfComreturn _last_submitted_event[indexOfCommandList];}+void IGraph::resize_last_submitted_event(size_t batch) {+ _last_submitted_event.resize(batch);+}++void IGraph::set_batch_size(std::size_t batch) {+ _batch_size = batch;+}++void IGraph::reset_last_batch_size() {+ _batch_size.reset();+}+uint32_t IGraph::get_unique_id() {return _unique_id++;}@@ -91,7 +136,79 @@ uint32_t IGraph::get_last_submitted_id() const {return _last_submitted_id;}-std::optional<size_t> IGraph::get_batch_size(const NetworkMetadata& metadata) {+std::optional<size_t> IGraph::determine_batch_size(const NetworkMetadata& metadata,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const IONodeMetadata& input_output_info) const {+ if (get_batch_size() > 1) {+ return get_batch_size();+ }++ if (tensors.empty()) {+ return std::nullopt; // Return std::nullopt if no input tensors are set+ }++ const auto& first_tensor = tensors.at(0);+ if (!first_tensor) {+ return std::nullopt; // Return std::nullopt if the first tensor is null+ }++ const auto& first_shape = first_tensor->get_shape();+ if (first_shape.empty()) {+ return std::nullopt; // Return std::nullopt if the shape is empty+ }++ if (!metadata.inputs.at(0).shapeFromIRModel.has_value()) {+ _logger.debug("Batching on the plugin is not used, batching is handled by the compiler");+ return std::nullopt;+ }++ // A first dimensionin shape may be appeared 'C' as well.+ // We need to get batch Idx and determine a true batch value here.+ // Let's use input_output_info as a helper.+ const ov::PartialShape& firstPartialShape = *metadata.inputs.at(0).shapeFromIRModel;+ auto candidateBatchSizeIfExist = input_output_info.extract_batch(first_shape, firstPartialShape);+ if (!candidateBatchSizeIfExist.has_value()) {+ return std::nullopt; // Return std::nullopt if there is no batch dimension+ }+ const size_t candidateBatchSize = candidateBatchSizeIfExist.value();+ _logger.debug("Candidate batch size: %zu, shape: %s", candidateBatchSize, first_shape.to_string().c_str());+ auto checkBatchSizeConsistency = [candidateBatchSize,+ &input_output_info](const std::vector<ov::SoPtr<ov::ITensor>>& tensors) {+ for (const auto& tensor : tensors) {+ if (!tensor) {+ return false; // Tensor is null+ }++ const auto& shape = tensor->get_shape();+ if (shape.empty()) {+ return false; // Inconsistent batch size+ }++ auto batchIfExist = input_output_info.extract_batch(shape);+ if (!batchIfExist.has_value()) {+ return false; // no batch size to check+ }++ if (batchIfExist.value() != candidateBatchSize) {+ return false;+ }+ }+ return true;+ };++ if (!checkBatchSizeConsistency(tensors)) {+ _logger.warning("Inconsistent batch sizes in input tensors");+ return std::nullopt; // Return std::nullopt if batch sizes are inconsistent+ }++ _logger.debug("Determined batch size: %zu", candidateBatchSize);++ return candidateBatchSize;+}++std::optional<size_t> IGraph::get_batch_size(const NetworkMetadata& metadata,+ const std::vector<ov::SoPtr<ov::ITensor>>& tensors,+ const IONodeMetadata& input_output_info) {if (!metadata.outputs.at(0).shapeFromIRModel.has_value()) {_logger.debug("Batching on the plugin is not used, batching is handled by the compiler");return std::nullopt;@@ -99,8 +216,10 @@ std::optional<size_t> IGraph::get_batch_size(const NetworkMetadata& metadata) {const ov::PartialShape& firstOutputShape = *metadata.outputs.at(0).shapeFromIRModel;if (firstOutputShape.is_dynamic()) {- _logger.warning("Networks using dynamic shapes are not supported when batching is handled by the plugin");- return std::nullopt;+ _logger.debug(+ "Networks using dynamic batch are handled by the plugin. Let's determine batch size over tensors: %zu",+ tensors.size());+ return !tensors.empty() ? determine_batch_size(metadata, tensors, input_output_info) : std::nullopt;}if (firstOutputShape.rank().get_length() == 0) {_logger.warning("Networks using rank 0 shapes for inputs/outputs are not supported when batching is "@@ -108,7 +227,7 @@ std::optional<size_t> IGraph::get_batch_size(const NetworkMetadata& metadata) {return std::nullopt;}- const size_t candidateBatchSize = firstOutputShape[BATCH_AXIS].get_length();+ const size_t candidateBatchSize = firstOutputShape[BATCH_AXIS].get_max_length();if (candidateBatchSize == 0 || candidateBatchSize == DEFAULT_BATCH_SIZE) {_logger.debug("Batching on the plugin is not used, batching is handled by the compiler");return std::nullopt;diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cppindex 5ba44dd5408..ca8cc2ffbcf 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp@@ -119,8 +119,11 @@ void Graph::initialize(const Config& config) {if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {_input_descriptors.push_back(ArgumentDescriptor{arg3, index});+ _logger.debug("got pfnGetArgumentProperties3 for input: %s", _input_descriptors.back().to_string().c_str());} else {_output_descriptors.push_back(ArgumentDescriptor{arg3, index});+ _logger.debug("got pfnGetArgumentProperties3 for output: %s",+ _output_descriptors.back().to_string().c_str());}}@@ -162,7 +165,8 @@ void Graph::initialize(const Config& config) {// _zeGraphExt->initializeGraph(). The driver will not access the original blob from this moment on, so we are// releasing it here to avoid unnecessary memory usage._blobIsReleased = release_blob(config);- _batch_size = get_batch_size(_metadata);++ _batch_size = get_batch_size(_metadata, {}, {});if (_zeroInitStruct->getCommandQueueDdiTable().version() < ZE_MAKE_VERSION(1, 1) &&config.get<RUN_INFERENCES_SEQUENTIALLY>()) {diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cppindex e155e29cc6f..7ddab1089b4 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp@@ -36,6 +36,11 @@#define UseCopyForNativeBinary(T) (T < ZE_GRAPH_EXT_VERSION_1_7)+namespace {+constexpr std::size_t BATCH_AXIS = 0;+constexpr std::size_t DEFAULT_BATCH_SIZE = 1;+} // namespace+namespace intel_npu {ZeGraphExtWrappers::ZeGraphExtWrappers(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)@@ -348,6 +353,7 @@ ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(const uint8_t& blobData, si*/static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,const std::optional<ze_graph_argument_metadata_t>& metadata) {+ auto logger = Logger::global().clone("getIODescriptor");ov::element::Type_t precision = zeroUtils::toOVElementType(arg.devicePrecision);ov::Shape shapeFromCompiler;ov::PartialShape shapeFromIRModel;@@ -369,7 +375,14 @@ static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,// lower bound is ignored, so we set it to 1 just to satisfy the Dimension constructor,// upper bound is set to the value from shapeFromCompiler as it is filled with upper bounds// in case of dynamic dimensions- shapeFromIRModel.push_back(ov::Dimension(1, shapeFromCompiler[id]));+ if (id == BATCH_AXIS && shapeFromCompiler[id] == DEFAULT_BATCH_SIZE) {+ logger.info("Ignore dynamic batch size upper limit, but keep the dimension dynamic as a metadata "+ "from compiler has been lost.");+ // We need to kepp batch dimension dynamic+ shapeFromIRModel.push_back(ov::Dimension(1, dynamicDim));+ } else {+ shapeFromIRModel.push_back(ov::Dimension(1, shapeFromCompiler[id]));+ }}}}diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hppindex ce53a7a9c39..5931761e1ea 100644--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_utils.hpp@@ -18,6 +18,17 @@ namespace intel_npu {struct ArgumentDescriptor {ze_graph_argument_properties_3_t info;uint32_t idx;+ std::string to_string() const {+ std::stringstream sstream;+ sstream << "dims_count: " << info.dims_count << " - [";+ for (uint32_t i = 0; i < std::min<uint32_t>(info.dims_count, ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE); i ++) {+ sstream << info.dims[i] << ",";+ }+ sstream << "]"+ << ", networkLayout: " << std::to_string(static_cast<size_t>(info.networkLayout))+ << ", deviceLayout: " << std::to_string(static_cast<size_t>(info.deviceLayout));+ return sstream.str();+ }};namespace zeroUtils {diff --git a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.cpp b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.cppindex 96645f479fd..977a5ff363a 100644--- a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.cpp@@ -19,3 +19,12 @@ INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest,::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),::testing::ValuesIn(batchedConfigs)),BatchedTensorsRunTests::getTestCaseName);++const std::vector<ov::AnyMap> DynamicBatchedConfigs = {+ {ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN)}};++INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest,+ DynamicBatchedTensorsRunTests,+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),+ ::testing::ValuesIn(DynamicBatchedConfigs)),+ BatchedTensorsRunTests::getTestCaseName);diff --git a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hppindex c3c8b8d3457..b5fd7b2af05 100644--- a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp@@ -8,7 +8,6 @@#include <gmock/gmock.h>#include <gtest/gtest.h>-#include "shared_test_classes/base/ov_behavior_test_utils.hpp"#include "common/npu_test_env_cfg.hpp"#include "common/utils.hpp"#include "functional_test_utils/ov_plugin_cache.hpp"@@ -22,6 +21,7 @@#include "openvino/runtime/core.hpp"#include "openvino/runtime/intel_npu/level_zero/level_zero.hpp"#include "overload/overload_test_utils_npu.hpp"+#include "shared_test_classes/base/ov_behavior_test_utils.hpp"using CompilationParams = std::tuple<std::string, // Device nameov::AnyMap // Config@@ -128,6 +128,19 @@ public:}};+// To avoid error: no previous declaration+void executeMutlipleTensorsBatchInfer(ov::InferRequest req,+ size_t batch_value,+ const Shape& non_batched_shape,+ ov::RemoteContext& context);+void executeContiguousTensorBatchInfer(ov::InferRequest req,+ size_t batch_value,+ const Shape& non_batched_shape,+ ov::RemoteContext& context);++// Second test group inheriting from the first+using DynamicBatchedTensorsRunTests = BatchedTensorsRunTests;+TEST_P(BatchedTensorsRunTests, SetInputRemoteTensorsMultipleInfer) {// Skip test according to plugin specific disabledTestPatterns() (if any)SKIP_IF_CURRENT_TEST_IS_DISABLED()@@ -420,6 +433,354 @@ TEST_P(BatchedTensorsRunTests, SetInputDifferentRemoteTensorsMultipleInferMCL) {}}+TEST_P(DynamicBatchedTensorsRunTests, DynamicSetInputRemoteTensorsMultipleInfer) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ auto one_shape_size = ov::shape_size(one_shape);+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);+ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ for (size_t i = 0; i < batch; ++i) {+ // non contiguous memory+ auto tensor = context.create_host_tensor(ov::element::f32, one_shape);+ tensors.push_back(std::move(tensor));+ }+ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ auto* actual = actual_tensor.data<float>();+ for (auto testNum = 0; testNum < 1; testNum++) {+ for (size_t i = 0; i < batch; ++i) {+ auto* f = tensors[i].data<float>();+ for (size_t j = 0; j < one_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20 * (i + 1));+ }+ }+ req.infer(); // Adds '1' to each element+ for (size_t i = 0; i < batch; i++) {+ for (size_t j = 0; j < one_shape_size; ++j) {+ auto expected = testNum + 20 * (i + 1) + 1;+ EXPECT_EQ(actual[i * one_shape_size + j], expected)+ << "Infer " << testNum << ": Expected=" << expected << ", actual=" << actual[j] << " for index "+ << j << ", batch: " << i;+ }+ }+ }+}++void executeMutlipleTensorsBatchInfer(ov::InferRequest req,+ size_t batch_value,+ const Shape& non_batched_shape,+ ov::RemoteContext& context) {+ auto non_batched_shape_size = ov::shape_size(non_batched_shape);+ std::vector<ov::Tensor> tensors;+ tensors.reserve(batch_value);+ ASSERT_TRUE(batch_value != 0);+ for (size_t i = 0; i < batch_value; ++i) {+ // non contiguous memory+ auto tensor = context.create_host_tensor(ov::element::f32, non_batched_shape);+ tensors.push_back(std::move(tensor));+ }+ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ ASSERT_EQ(actual_tensor.get_byte_size(), tensors.back().get_byte_size() * tensors.size())+ << "\"tensor_output0\" must have the same size as \"tensor_input0\" for batch_value value:" << batch_value;+ auto* actual = actual_tensor.data<float>();+ for (auto testNum = 0; testNum < 1; testNum++) {+ for (size_t i = 0; i < batch_value; ++i) {+ auto* f = tensors[i].data<float>();+ for (size_t j = 0; j < non_batched_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20 * (i + 1));+ }+ }+ req.infer();+ for (size_t i = 0; i < batch_value; i++) {+ for (size_t j = 0; j < non_batched_shape_size; ++j) {+ auto expected = testNum + 20 * (i + 1) + 1;+ EXPECT_EQ(actual[i * non_batched_shape_size + j], expected)+ << "Infer " << testNum << ": Expected=" << expected << ", actual=" << actual[j] << " for index "+ << j << ", batch: " << i;+ }+ }+ }+}++TEST_P(DynamicBatchedTensorsRunTests, DynamicSetInputRemoteTensorsDynamicBatchInflation) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ size_t model_batch_bottom_bound = 1;+ size_t model_batch_upper_bound = 10;+ auto modelShape = PartialShape{ov::Dimension(model_batch_bottom_bound, model_batch_upper_bound), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);+ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ for (size_t tensor_batch = model_batch_bottom_bound; tensor_batch <= model_batch_upper_bound; ++tensor_batch) {+ executeMutlipleTensorsBatchInfer(req, tensor_batch, one_shape, context);+ }+}++TEST_P(DynamicBatchedTensorsRunTests, DynamicSetInputRemoteTensorsDynamicBatchDeflation) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ size_t model_batch_bottom_bound = 1;+ size_t model_batch_upper_bound = 10;+ auto modelShape = PartialShape{ov::Dimension(model_batch_bottom_bound, model_batch_upper_bound), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);+ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ for (size_t tensor_batch = model_batch_upper_bound; tensor_batch >= model_batch_bottom_bound; tensor_batch--) {+ executeMutlipleTensorsBatchInfer(req, tensor_batch, one_shape, context);+ }+}++TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorSingleInfer) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ size_t tensor_batch = 3;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ auto one_shape_size = ov::shape_size(one_shape);+ auto tensor_shape = Shape{tensor_batch, 2, 2, 2};+ auto tensor_shape_size = ov::shape_size(tensor_shape);+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);+ // Create InferRequest++ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ // contiguous memory+ auto tensor = context.create_host_tensor(ov::element::f32, tensor_shape);+ tensors.push_back(std::move(tensor));++ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ auto* actual = actual_tensor.data<float>();+ for (auto testNum = 0; testNum < 5; testNum++) {+ auto* f = tensors[0].data<float>();+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20 * (j / one_shape_size + 1));+ }+ req.infer(); // Adds '1' to each element+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ auto expected = testNum + 20 * (j / one_shape_size + 1) + 1;+ EXPECT_EQ(actual[j], expected)+ << "Infer " << testNum << ": Expected=" << expected << ", actual=" << actual[j] << " for index " << j+ << ", batch: " << j / one_shape_size;+ }+ }+}++void executeContiguousTensorBatchInfer(ov::InferRequest req,+ size_t batch_value,+ const Shape& non_batched_shape,+ ov::RemoteContext& context) {+ auto non_batched_shape_size = ov::shape_size(non_batched_shape);+ auto tensor_shape = non_batched_shape;+ tensor_shape[0] = batch_value;+ auto tensor_shape_size = ov::shape_size(tensor_shape);+ auto tensor = context.create_host_tensor(ov::element::f32, tensor_shape);++ std::vector<ov::Tensor> tensors;+ tensors.push_back(std::move(tensor));++ req.set_tensors("tensor_input0", tensors);+ auto actual_tensor = req.get_tensor("tensor_output0");+ ASSERT_EQ(actual_tensor.get_byte_size(), tensors.back().get_byte_size())+ << "\"tensor_output0\" must have the same size as \"tensor_input0\" for batch_value value:" << batch_value;++ auto* actual = actual_tensor.data<float>();+ auto* f = tensors.back().data<float>();+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ f[j] = static_cast<float>(batch_value + 20 * (j / non_batched_shape_size + 1));+ }+ req.infer();+ // check that we got valid inference results on each lines of N+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ auto expected = batch_value + 20 * (j / non_batched_shape_size + 1) + 1;+ EXPECT_EQ(actual[j], expected) << "Infer " << batch_value << ": Expected=" << expected+ << ", actual=" << actual[j] << " for index " << j+ << ", batch: " << j / non_batched_shape_size;+ }+}++TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBatchInflation) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ size_t model_batch_bottom_bound = 1;+ size_t model_batch_upper_bound = 10;+ auto modelShape = PartialShape{ov::Dimension(model_batch_bottom_bound, model_batch_upper_bound), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);++ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ for (size_t tensor_batch = model_batch_bottom_bound; tensor_batch <= model_batch_upper_bound; tensor_batch++) {+ // dynamically change N of contiduous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]+ // and check that the output tensor kept modified accordingly+ executeContiguousTensorBatchInfer(req, tensor_batch, one_shape, context);+ }+}++TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBatchDeflation) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ size_t model_batch_bottom_bound = 1;+ size_t model_batch_upper_bound = 10;+ auto modelShape = PartialShape{ov::Dimension(model_batch_bottom_bound, model_batch_upper_bound), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);++ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;+ for (size_t tensor_batch = model_batch_upper_bound; tensor_batch >= model_batch_bottom_bound; tensor_batch--) {+ // dynamically change N of contiduous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]+ // and check that the output tensor kept modified accordingly+ executeContiguousTensorBatchInfer(req, tensor_batch, one_shape, context);+ }+}++TEST_P(DynamicBatchedTensorsRunTests, DynamicSetInputDifferentTensorsMultipleInfer) {+ // Skip test according to plugin specific disabledTestPatterns() (if any)+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ auto one_shape_size = ov::shape_size(one_shape);+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");+ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);+ auto execNet = core->compile_model(model, target_device, configuration);+ auto context = core->get_default_context(target_device);+ // Create InferRequest+ ov::InferRequest req;+ req = execNet.create_infer_request();+ std::vector<ov::Tensor> tensors;++ std::vector<float> buffer(one_shape_size * 2 * 2, 0);++ auto tensor0 = ov::Tensor(element::f32, one_shape, &buffer[(0 * 2) * one_shape_size]);+ auto tensor1 = context.create_host_tensor(ov::element::f32, one_shape);+ auto tensor2 = ov::Tensor(element::f32, one_shape, &buffer[(1 * 2) * one_shape_size]);+ auto tensor3 = context.create_host_tensor(ov::element::f32, one_shape);++ tensors.push_back(std::move(tensor0));+ tensors.push_back(std::move(tensor1));+ tensors.push_back(std::move(tensor2));+ tensors.push_back(std::move(tensor3));++ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ auto* actual = actual_tensor.data<float>();+ for (auto testNum = 0; testNum < 1; testNum++) {+ for (size_t i = 0; i < batch; ++i) {+ auto* f = tensors[i].data<float>();+ for (size_t j = 0; j < one_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20);+ }+ }+ req.infer(); // Adds '1' to each element+ for (size_t j = 0; j < one_shape_size * batch; ++j) {+ EXPECT_EQ(actual[j], testNum + 21) << "Infer " << testNum << ": Expected=" << testNum + 21+ << ", actual=" << actual[j] << " for index " << j;+ }+ }+}+} // namespace behavior} // namespace test} // namespace ovdiff --git a/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cpp b/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cppindex 0cf272fd7b3..84cdee6f28a 100644--- a/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cpp@@ -54,6 +54,15 @@ INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest,::testing::ValuesIn(batchingConfigs)),InferRequestRunTests::getTestCaseName);+const std::vector<ov::AnyMap> DynamicBatchedConfigs = {+ {ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN), ov::log::level(ov::log::Level::WARNING)}};++INSTANTIATE_TEST_SUITE_P(smoke_DynamicBatchingSeqTests,+ DynamicBatchingRunSeqTests,+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),+ ::testing::ValuesIn(DynamicBatchedConfigs)),+ InferRequestRunTests::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTest,ROITensorInference,::testing::Combine(::testing::Values(tensor_roi::roi_nchw()),diff --git a/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.hpp b/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.hppindex f3e4bdee869..110e43a0d6b 100644--- a/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.hpp@@ -1051,6 +1051,66 @@ TEST_P(BatchingRunSeqTests, CheckMultipleBatchingRunsSeq) {}}+using DynamicBatchingRunSeqTests = InferRequestRunTests;++TEST_P(DynamicBatchingRunSeqTests, DynamicCheckMultipleBatchingRunsSeq) {+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 64, 64};+ auto shape = Shape{4, 2, 64, 64};+ auto shape_size = ov::shape_size(shape);+ auto model = createModel(element::f32, modelShape, "N...");++ auto context = core->get_default_context(target_device);++ configuration[ov::intel_npu::run_inferences_sequentially.name()] = true;+ configuration[ov::intel_npu::tiles.name()] = 2;+ compiled_model = core->compile_model(model, target_device, configuration);++ const uint32_t inferences = 32;+ std::array<ov::InferRequest, inferences> inference_request;+ ov::Tensor input_tensor;+ std::array<ov::Tensor, inferences> output_tensor;++ input_tensor = context.create_host_tensor(ov::element::f32, shape);+ for (uint32_t i = 0; i < inferences; i++) {+ inference_request[i] = compiled_model.create_infer_request();+ output_tensor[i] = context.create_host_tensor(ov::element::f32, shape);+ }++ inference_request[0].set_input_tensor(input_tensor);+ inference_request[0].set_output_tensor(output_tensor[0]);++ const uint32_t runs = 10;+ for (uint32_t z = 0; z < runs; z++) {+ auto* input_data = reinterpret_cast<float*>(input_tensor.data());+ for (size_t i = 0; i < shape_size; ++i) {+ input_data[i] = static_cast<float>(z);+ }++ inference_request[0].start_async(); // Adds '1' to each element++ for (uint32_t i = 1; i < inferences; i++) {+ inference_request[i].set_input_tensor(output_tensor[i - 1]);+ inference_request[i].set_output_tensor(output_tensor[i]);++ inference_request[i].start_async(); // Adds '1' to each element+ }++ inference_request[inferences - 1].wait();++ float expected_result = static_cast<float>(z) + 1.f;++ for (uint32_t i = 0; i < inferences; i++) {+ auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());+ for (size_t j = 0; j < shape_size; ++j) {+ EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)+ << "Run=" << z << "Output=" << i << " Expected=" << expected_result+ << ", actual=" << output_tensor_data[j] << " for index " << j;+ }+ expected_result++;+ }+ }+}+using ROITensorInference = OVInferRequestInferenceTests;TEST_P(ROITensorInference, InferenceROITensor) {diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xmlindex a480db88e9a..3f117fa0905 100644--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml@@ -904,4 +904,13 @@ Example:</filters></skip_config>+ <!-- E#168772 -->+ <skip_config>+ <message>Tests currently skipped until dynamic batch is fully supported (need NPU compiler alignment/driver update)</message>+ <filters>+ <filter>.*DynamicBatchingRunSeqTests.*</filter>+ <filter>.*DynamicBatchedTensorsRunTests.*</filter>+ </filters>+ </skip_config>+</skip_configs>