Skip to content

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

[NPU] Refactor the igraph class (#31652)

Bogdan Pereanu6876e8c0f58d
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.hpp
index ef30ef8769c..ea56512dc8a 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,7 +89,7 @@ private:
std::unique_ptr<Pipeline> _pipeline;
bool _pipelineIsCreated = false;
- bool _pipelineNeedsReallocation = false;
+ bool _dynamicBatchValueChanged = false;
bool _externalMemoryStandardAllocationSupported = false;
};
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.cpp
index 5929c5e7a85..f73bc958f1a 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
@@ -24,8 +24,6 @@ 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.
@@ -76,6 +74,32 @@ void check_level_zero_attributes_match(const IODescriptor& ioDescriptor, const A
}
}
+std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,
+ const std::shared_ptr<ov::ITensor>& tensor,
+ const std::optional<size_t> batchSize) {
+ if (tensor == nullptr && !batchSize.has_value()) {
+ return std::nullopt;
+ }
+
+ if (!desc.shapeFromIRModel.has_value() || !desc.shapeFromIRModel.value().is_dynamic()) {
+ return std::nullopt;
+ }
+
+ if (batchSize.has_value()) {
+ return batchSize.value();
+ }
+
+ if (tensor->get_shape().empty() || *desc.shapeFromCompiler.begin() != intel_npu::utils::DEFAULT_BATCH_SIZE) {
+ return std::nullopt;
+ }
+
+ if ((*desc.shapeFromIRModel)[intel_npu::utils::BATCH_AXIS].is_dynamic()) {
+ return tensor->get_shape()[intel_npu::utils::BATCH_AXIS];
+ }
+
+ return std::nullopt;
+}
+
} // namespace
//------------------------------------------------------------------------------
@@ -109,10 +133,6 @@ 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));
@@ -121,7 +141,7 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&
continue;
}
- get_level_zero_input(ioIndex) = allocate_tensor(inputDescriptor, ioIndex, INPUT, *_inputAllocator, batchSize);
+ get_level_zero_input(ioIndex) = allocate_tensor(inputDescriptor, ioIndex, INPUT, *_inputAllocator);
++ioIndex;
}
@@ -135,8 +155,7 @@ ZeroInferRequest::ZeroInferRequest(const std::shared_ptr<ZeroInitStructsHolder>&
continue;
}
- _levelZeroOutputTensors.at(ioIndex) =
- allocate_tensor(outputDescriptor, ioIndex, OUTPUT, *_outputAllocator, batchSize);
+ _levelZeroOutputTensors.at(ioIndex) = allocate_tensor(outputDescriptor, ioIndex, OUTPUT, *_outputAllocator);
++ioIndex;
}
@@ -146,10 +165,8 @@ 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]);
- }
+ auto batchSize = _graph->get_batch_size();
+
for (size_t inputIndex = 0; inputIndex < _metadata.inputs.size(); ++inputIndex) {
if (_metadata.inputs.at(inputIndex).isMainInputWeights) {
// These values were set while running the "WeightlessGraph::init" method
@@ -177,6 +194,13 @@ void ZeroInferRequest::create_pipeline() {
}
if (get_level_zero_input(inputIndex)) {
+ if (_dynamicBatchValueChanged && batchSize.has_value() &&
+ get_level_zero_input(inputIndex)->get_shape()[utils::BATCH_AXIS] != batchSize.value()) {
+ OPENVINO_THROW("Input tensor ",
+ _metadata.inputs.at(inputIndex).nodeFriendlyName.c_str(),
+ " has different batch size than other tensors.");
+ }
+
_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());
@@ -193,14 +217,37 @@ void ZeroInferRequest::create_pipeline() {
for (size_t outputIndex = 0; outputIndex < _metadata.outputs.size(); ++outputIndex) {
if (_levelZeroOutputTensors.at(outputIndex)) {
- _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated",
- _metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());
- continue;
+ 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",
+ _metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());
+ continue;
+ }
+ } else {
+ _logger.debug("ZeroInferRequest::create_pipeline - tensor %s was already allocated",
+ _metadata.outputs.at(outputIndex).nodeFriendlyName.c_str());
+ continue;
+ }
}
_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, batchSize);
+
+ if (_dynamicBatchValueChanged && !_userOutputTensors.at(outputIndex)->get_shape().empty() &&
+ _userOutputTensors.at(outputIndex)->get_shape()[utils::BATCH_AXIS] !=
+ _levelZeroOutputTensors.at(outputIndex)->get_shape()[utils::BATCH_AXIS]) {
+ if (std::dynamic_pointer_cast<ZeroTensor>(_userOutputTensors.at(outputIndex)._ptr) == nullptr) {
+ OPENVINO_THROW("Output tensor ",
+ _metadata.outputs.at(outputIndex).nodeFriendlyName.c_str(),
+ " has different batch size than other tensors.");
+ }
+
+ _userOutputTensors.at(outputIndex) = _levelZeroOutputTensors.at(outputIndex);
+ }
+
_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());
@@ -260,7 +307,7 @@ void ZeroInferRequest::create_pipeline() {
_graph,
_levelZeroInputTensors,
_levelZeroOutputTensors,
- batchSize.has_value() ? batchSize.value() : DEFAULT_BATCH_SIZE);
+ batchSize.has_value() ? batchSize.value() : utils::DEFAULT_BATCH_SIZE);
_logger.debug("ZeroInferRequest::create_pipeline - SyncInferRequest completed");
}
@@ -305,17 +352,12 @@ void ZeroInferRequest::set_tensor_data(const std::shared_ptr<ov::ITensor>& tenso
} else {
auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(levelZeroTensors);
- if (zeroTensor == nullptr || (zeroTensor != nullptr && zeroTensor->tensor_was_shared_with_user())) {
+ if (_dynamicBatchValueChanged || zeroTensor == nullptr ||
+ (zeroTensor != nullptr && zeroTensor->tensor_was_shared_with_user())) {
_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));
+ auto batch = _graph->get_batch_size();
levelZeroTensors = allocate_tensor(isInput ? _metadata.inputs.at(index) : _metadata.outputs.at(index),
index,
@@ -386,26 +428,22 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
return;
}
- 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));
+ determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), tensor._ptr, std::nullopt);
// Check if batch has been changed
if (batchSizeCandidate.has_value()) {
- 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;
+ if (!_dynamicBatchValueChanged ||
+ (get_user_input(foundPort.idx)._ptr != nullptr &&
+ get_user_input(foundPort.idx)->get_byte_size() * get_user_inputs(foundPort.idx).size() !=
+ tensor->get_byte_size())) {
+ _dynamicBatchValueChanged = true;
+ _graph->set_batch_size(batchSizeCandidate.value());
+ } else {
+ if (batchSizeCandidate.value() != _graph->get_batch_size().value()) {
+ OPENVINO_THROW("Batching size is not matching all the tensors.");
}
}
- _graph->set_batch_size(batchSizeCandidate.has_value() ? batchSizeCandidate.value() : DEFAULT_BATCH_SIZE);
}
if (is_batched_input(foundPort.idx)) {
@@ -423,16 +461,24 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
_logger.debug("ZeroInferRequest::set_tensor - got the same tensor, do nothing");
return;
}
+
+ auto batchSizeCandidate =
+ determine_dynamic_batch_size(_metadata.outputs.at(foundPort.idx), tensor._ptr, std::nullopt);
+
// 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;
+ if (batchSizeCandidate.has_value()) {
+ if (!_dynamicBatchValueChanged ||
+ (_userOutputTensors.at(foundPort.idx)._ptr != nullptr &&
+ _userOutputTensors.at(foundPort.idx)->get_byte_size() != tensor->get_byte_size())) {
+ _dynamicBatchValueChanged = true;
+ _graph->set_batch_size(batchSizeCandidate.value());
+ } else {
+ if (batchSizeCandidate.value() != _graph->get_batch_size().value()) {
+ OPENVINO_THROW("Batching size is not matching all the tensors.");
+ }
}
}
+
_userOutputTensors.at(foundPort.idx) = tensor;
}
@@ -465,90 +511,91 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,
check_batched_tensors(port, tensors);
- 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;
+
+ auto batchSize = determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), nullptr, tensors.size());
+
+ // Check if batch has been changed
+ if (batchSize.has_value()) {
+ if (!_dynamicBatchValueChanged || get_user_inputs(foundPort.idx).size() != tensors.size()) {
+ _dynamicBatchValueChanged = true;
+ _graph->set_batch_size(batchSize.value());
+ } else {
+ if (batchSize.value() != _graph->get_batch_size().value()) {
+ OPENVINO_THROW("Batching size is not matching all the tensors.");
+ }
}
+ } else {
+ batchSize = _graph->get_batch_size();
}
- if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {
- if (batch_size) {
- for (size_t i = 0; i < tensors.size(); i++) {
- auto remoteTensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(tensors[i]._ptr);
+ get_user_inputs(foundPort.idx).resize(tensors.size());
+ get_user_inputs(foundPort.idx) = tensors;
- get_level_zero_inputs(foundPort.idx).resize(tensors.size());
- void* data = nullptr;
+ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) && batchSize.has_value()) {
+ for (size_t i = 0; i < tensors.size(); i++) {
+ auto remoteTensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(tensors[i]._ptr);
- if (remoteTensor == nullptr) {
- bool levelZeroTensorCreated = false;
+ get_level_zero_inputs(foundPort.idx).resize(tensors.size());
+ void* data = nullptr;
- OV_ITT_TASK_NEXT(SET_TENSORS, "check_data_allocation");
- if (zeroUtils::memory_was_allocated_in_the_same_l0_context(_initStructs->getContext(),
- tensors[i]->data())) {
- _logger.debug("ZeroInferRequest::set_tensors - tensor was created in the same L0 context");
+ if (remoteTensor == nullptr) {
+ bool levelZeroTensorCreated = false;
+
+ OV_ITT_TASK_NEXT(SET_TENSORS, "check_data_allocation");
+ if (zeroUtils::memory_was_allocated_in_the_same_l0_context(_initStructs->getContext(),
+ tensors[i]->data())) {
+ _logger.debug("ZeroInferRequest::set_tensors - tensor was created in the same L0 context");
+
+ get_level_zero_input(foundPort.idx, i) = tensors.at(i)._ptr;
+ levelZeroTensorCreated = true;
+ } else {
+ if (_externalMemoryStandardAllocationSupported &&
+ utils::memory_and_size_aligned_to_standard_page_size(tensors.at(i)->data(),
+ tensors.at(i)->get_byte_size())) {
+ _logger.debug("ZeroInferRequest::set_tensors - import memory from a system memory pointer");
+ auto hostMemSharedAllocator =
+ zeroMemory::HostMemSharedAllocator(_initStructs,
+ tensors.at(i)._ptr,
+ ZE_HOST_MEM_ALLOC_FLAG_BIAS_WRITE_COMBINED);
+ get_level_zero_input(foundPort.idx, i) =
+ std::make_shared<ZeroTensor>(_initStructs,
+ _config,
+ tensors.at(i)->get_element_type(),
+ tensors.at(i)->get_shape(),
+ hostMemSharedAllocator);
- get_level_zero_input(foundPort.idx, i) = tensors.at(i)._ptr;
levelZeroTensorCreated = true;
- } else {
- if (_externalMemoryStandardAllocationSupported &&
- utils::memory_and_size_aligned_to_standard_page_size(tensors.at(i)->data(),
- tensors.at(i)->get_byte_size())) {
- _logger.debug("ZeroInferRequest::set_tensors - import memory from a system memory pointer");
- auto hostMemSharedAllocator =
- zeroMemory::HostMemSharedAllocator(_initStructs,
- tensors.at(i)._ptr,
- ZE_HOST_MEM_ALLOC_FLAG_BIAS_WRITE_COMBINED);
- get_level_zero_input(foundPort.idx, i) =
- std::make_shared<ZeroTensor>(_initStructs,
- _config,
- tensors.at(i)->get_element_type(),
- tensors.at(i)->get_shape(),
- hostMemSharedAllocator);
-
- levelZeroTensorCreated = true;
- }
}
+ }
- if (!levelZeroTensorCreated) {
- _logger.debug("ZeroInferRequest::set_tensors - tensor wasn't created in the same L0 context, "
- "create a L0 tensor");
+ if (!levelZeroTensorCreated) {
+ _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,
- batch_size);
- }
+ get_level_zero_input(foundPort.idx, i) = allocate_tensor(_metadata.inputs.at(foundPort.idx),
+ foundPort.idx,
+ true,
+ *_inputAllocator,
+ batchSize);
+ }
- data = get_level_zero_input(foundPort.idx, i)->data();
- } else {
- _logger.debug("ZeroInferRequest::set_tensors - remote tensor is used");
+ data = get_level_zero_input(foundPort.idx, i)->data();
+ } else {
+ _logger.debug("ZeroInferRequest::set_tensors - remote tensor is used");
- data = remoteTensor->get_original_memory();
+ data = remoteTensor->get_original_memory();
- get_level_zero_input(foundPort.idx, i) = tensors.at(i)._ptr;
- }
+ get_level_zero_input(foundPort.idx, i) = tensors.at(i)._ptr;
+ }
- if (_pipelineIsCreated && !_pipelineNeedsReallocation) {
- OPENVINO_ASSERT(data, "Empty buffer");
- OV_ITT_TASK_NEXT(SET_TENSORS, "updateCommandList");
+ if (_pipelineIsCreated && !_dynamicBatchValueChanged) {
+ OPENVINO_ASSERT(data, "Empty buffer");
+ OV_ITT_TASK_NEXT(SET_TENSORS, "updateCommandList");
- _pipeline->update_graph_arguments_batching(_graph->get_input_descriptors().at(foundPort.idx).idx,
- data,
- i);
- }
+ _pipeline->update_graph_arguments_batching(_graph->get_input_descriptors().at(foundPort.idx).idx,
+ data,
+ i);
}
}
}
@@ -568,25 +615,7 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::N
}
auto& userTensors = isInput ? get_user_input(ioIndex) : _userOutputTensors.at(ioIndex);
-
- 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 by index: %zu", ioIndex);
- return userTensors;
- }
-
- auto& metadata = isInput ? _metadata.inputs.at(ioIndex) : _metadata.outputs.at(ioIndex);
- _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);
+ auto batchSize = _graph->get_batch_size();
// LIMITATION for the dynamic batch implementation:
// We need to allocate output tensors having the same batch size as input tensors.
@@ -598,40 +627,56 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::N
// 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));
+
+ if (userTensors) {
+ if (!_dynamicBatchValueChanged) {
+ 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 by index: %zu", ioIndex);
+ return userTensors;
+ } else {
+ if (batchSize.has_value() && userTensors->get_shape()[utils::BATCH_AXIS] == batchSize.value()) {
+ auto zeroTensor = std::dynamic_pointer_cast<ZeroTensor>(userTensors._ptr);
+ if (zeroTensor != nullptr) {
+ zeroTensor->set_tensor_shared_with_user();
+ }
+
+ _logger.debug("ZeroInferRequest::get_tensor - tensor by index: %zu is already allocated", ioIndex);
+ return userTensors;
+ }
+ }
}
- auto batch_size =
- _graph->get_batch_size(_metadata,
- tensorVector,
- isInput ? _graphInputDescriptors.at(ioIndex) : _graphOutputDescriptors.at(ioIndex));
+ auto& metadata = isInput ? _metadata.inputs.at(ioIndex) : _metadata.outputs.at(ioIndex);
+ _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,
+ _dynamicBatchValueChanged ? "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, batch_size);
+ allocate_tensor(metadata, ioIndex, isInput, isInput ? *_inputAllocator : *_outputAllocator, batchSize);
+
+ if (!_dynamicBatchValueChanged) {
+ userTensors = levelZeroTensors;
+ }
_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) {
zeroTensor->set_tensor_shared_with_user();
}
- return userTensors;
+ return levelZeroTensors;
}
void ZeroInferRequest::update_pipeline_if_memory_changed() {
@@ -791,11 +836,11 @@ void ZeroInferRequest::infer_async() {
{
std::lock_guard<std::mutex> lock(_graph->get_mutex());
- if (!_pipelineIsCreated || _pipelineNeedsReallocation) {
+ if (!_pipelineIsCreated || _dynamicBatchValueChanged) {
OV_ITT_TASK_NEXT(ZERO_INFER, "create_pipeline");
create_pipeline(); // Reallocate pipeline if necessary
_pipelineIsCreated = true;
- _pipelineNeedsReallocation = false; // Reset reallocation flag
+ _dynamicBatchValueChanged = false; // Reset reallocation flag
} else {
if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {
update_pipeline_if_memory_changed();
@@ -804,6 +849,7 @@ void ZeroInferRequest::infer_async() {
}
}
+ auto batch_size = _graph->get_batch_size();
size_t inputIndex = 0;
for (const auto& userTensor : _userInputTensors) {
const IODescriptor inputDescriptor = _metadata.inputs.at(inputIndex);
@@ -823,8 +869,6 @@ void ZeroInferRequest::infer_async() {
}
}
- 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++) {
diff --git a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
index 4ecdee49af9..1b4e718d41d 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp
@@ -26,20 +26,17 @@ Pipeline::Pipeline(const Config& config,
_graph(graph),
_config(config),
_id(_graph->get_unique_id()),
- _number_of_command_lists(_graph->get_batch_size().has_value() ? *_graph->get_batch_size() : batch_size),
+ _number_of_command_lists(batch_size),
_logger("Pipeline", _config.get<LOG_LEVEL>()) {
OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Zero_infer_request::Pipeline::Pipeline");
- auto batch = _graph->get_batch_size().has_value() ? *_graph->get_batch_size() : batch_size;
+
+ _logger.debug("Pipeline - initialize started, number_of_command_lists %i", _number_of_command_lists);
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.debug("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),
"In-order execution doesn't work in case synchronization of the inferences is done using events");
@@ -96,7 +93,7 @@ Pipeline::Pipeline(const Config& config,
continue;
}
- if (io_index < input_tensors.size() && input_tensors.at(io_index).size() > 1) {
+ if (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));
@@ -131,6 +128,7 @@ Pipeline::Pipeline(const Config& config,
io_index = 0;
for (const auto& desc : graph->get_output_descriptors()) {
void* data = nullptr;
+
auto remote_tensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(output_tensors.at(io_index));
if (remote_tensor == nullptr) {
data = output_tensors.at(io_index)->data();
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.hpp
index 3fdf2d983b1..b3128454db9 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
@@ -17,20 +17,9 @@
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(NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob);
+ IGraph() = default;
/**
* @brief Writes the compiled model along with some metadata to the provided stream. The content of the stream can
@@ -51,83 +40,37 @@ public:
virtual ~IGraph() = default;
- const NetworkMetadata& get_metadata() const;
+ virtual const NetworkMetadata& get_metadata() const = 0;
virtual ze_graph_handle_t get_handle() const = 0;
- void update_network_name(std::string_view name);
-
- const std::vector<ArgumentDescriptor>& get_input_descriptors() const;
- const std::vector<ArgumentDescriptor>& get_output_descriptors() const;
- const std::shared_ptr<CommandQueue>& get_command_queue() const;
- uint32_t get_command_queue_group_ordinal() const;
+ virtual void update_network_name(std::string_view name) = 0;
- void set_workload_type(const ov::WorkloadType workloadType) const;
+ virtual const std::vector<ArgumentDescriptor>& get_input_descriptors() const = 0;
+ virtual const std::vector<ArgumentDescriptor>& get_output_descriptors() const = 0;
+ virtual const std::shared_ptr<CommandQueue>& get_command_queue() const = 0;
+ virtual uint32_t get_command_queue_group_ordinal() const = 0;
- std::mutex& get_mutex();
+ virtual void set_workload_type(const ov::WorkloadType workloadType) const = 0;
- 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();
+ std::mutex& get_mutex() {
+ return _mutex;
+ }
- uint32_t get_unique_id();
- void set_last_submitted_id(uint32_t id_index);
- uint32_t get_last_submitted_id() const;
+ virtual void set_last_submitted_event(const std::shared_ptr<Event>& event, size_t indexOfCommandList) = 0;
+ virtual const std::shared_ptr<Event>& get_last_submitted_event(size_t indexOfCommandList) const = 0;
+ virtual void resize_last_submitted_event(size_t batch) = 0;
+ virtual void set_batch_size(std::size_t batch) = 0;
- 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;
+ virtual const std::optional<std::size_t> get_batch_size() const = 0;
- std::optional<size_t> get_batch_size(const NetworkMetadata& metadata,
- const std::vector<ov::SoPtr<ov::ITensor>>& tensors,
- const IONodeMetadata& input_output_info);
+ virtual uint32_t get_unique_id() = 0;
+ virtual void set_last_submitted_id(uint32_t id_index) = 0;
+ virtual uint32_t get_last_submitted_id() const = 0;
protected:
- /**
- * @brief Determines if batching can be addressed inside the plugin. In the positive case, the batch size used by
- * the model will also be deduced and returned.
- * @details Batching can be handled by the plugin only if:
- * - The batch axis is the first axis.
- * - The batch size received by the compiler takes the default value of 1.
- * - The batch size found in the IR model matches for all inputs/outputs and takes a value different than the
- * default one.
- *
- * If any of the previous conditions is not fulfilled, the functon will return the default batch size, thus no
- * custom algorithm will be applied inside the plugin in order to address batching.
- *
- * @param metadata Metadata containing the shape values as seen by both the compiler and IR model. These will
- * ultimately be used for determining the batch size.
- * @returns The batch size deduced by the algorithm or the default value of 1 if batching cannot be performed inside
- * the plugin.
- */
-
- NetworkMetadata _metadata;
-
- std::vector<ArgumentDescriptor> _input_descriptors;
- std::vector<ArgumentDescriptor> _output_descriptors;
-
- std::shared_ptr<CommandQueue> _command_queue;
- uint32_t _command_queue_group_ordinal = 0;
- std::vector<std::shared_ptr<Event>> _last_submitted_event;
-
// Used to protect zero pipeline creation in the graph. The pipeline should be created only once per graph when the
// first inference starts running
std::mutex _mutex;
-
- std::optional<ov::Tensor> _blob;
-
- uint32_t _unique_id = 0;
- uint32_t _last_submitted_id = 0;
-
- /**
- * @brief The batch size used by the corresponding model.
- * @details The attribute contains a value only if the plugin performs the batches splitting operation.
- */
- std::optional<std::size_t> _batch_size = std::nullopt;
-
- Logger _logger;
};
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/common/src/igraph.cpp b/src/plugins/intel_npu/src/common/src/igraph.cpp
deleted file mode 100644
index 9ef13b922b0..00000000000
--- a/src/plugins/intel_npu/src/common/src/igraph.cpp
+++ /dev/null
@@ -1,270 +0,0 @@
-// Copyright (C) 2018-2025 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-
-#include "intel_npu/common/igraph.hpp"
-
-#include "intel_npu/config/options.hpp"
-
-namespace {
-constexpr std::size_t BATCH_AXIS = 0;
-constexpr std::size_t DEFAULT_BATCH_SIZE = 1;
-} // namespace
-
-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(NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob)
- : _metadata(std::move(metadata)),
- _blob(std::move(blob)),
- _logger("IGraph", config.get<LOG_LEVEL>()) {}
-
-const NetworkMetadata& IGraph::get_metadata() const {
- return _metadata;
-}
-
-void IGraph::update_network_name(std::string_view name) {
- _metadata.name = name;
-}
-
-const std::vector<ArgumentDescriptor>& IGraph::get_input_descriptors() const {
- return _input_descriptors;
-}
-
-const std::vector<ArgumentDescriptor>& IGraph::get_output_descriptors() const {
- return _output_descriptors;
-}
-
-const std::shared_ptr<CommandQueue>& IGraph::get_command_queue() const {
- return _command_queue;
-}
-
-uint32_t IGraph::get_command_queue_group_ordinal() const {
- return _command_queue_group_ordinal;
-}
-
-void IGraph::set_workload_type(const ov::WorkloadType workloadType) const {
- if (_command_queue == nullptr) {
- return;
- }
-
- ze_command_queue_workload_type_t zeWorkloadType;
- switch (workloadType) {
- case ov::WorkloadType::DEFAULT:
- zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_DEFAULT;
- break;
- case ov::WorkloadType::EFFICIENT:
- zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_BACKGROUND;
- break;
- default:
- OPENVINO_THROW("Unknown value for WorkloadType!");
- }
-
- _command_queue->setWorkloadType(zeWorkloadType);
-}
-
-std::mutex& IGraph::get_mutex() {
- return _mutex;
-}
-
-void IGraph::set_last_submitted_event(const std::shared_ptr<Event>& event, size_t indexOfCommandList) {
- _last_submitted_event[indexOfCommandList] = event;
-}
-
-const std::shared_ptr<Event>& IGraph::get_last_submitted_event(size_t indexOfCommandList) const {
- return _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++;
-}
-
-void IGraph::set_last_submitted_id(uint32_t id_index) {
- _last_submitted_id = id_index;
-}
-
-uint32_t IGraph::get_last_submitted_id() const {
- return _last_submitted_id;
-}
-
-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;
- }
-
- const ov::PartialShape& firstOutputShape = *metadata.outputs.at(0).shapeFromIRModel;
- if (firstOutputShape.is_dynamic()) {
- _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 "
- "handled by the plugin");
- return std::nullopt;
- }
-
- 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;
- }
-
- auto checkDescriptorsUseCandidateBatchSize = [candidateBatchSize](const std::vector<IODescriptor>& descriptors) {
- for (const IODescriptor& descriptor : descriptors) {
- OPENVINO_ASSERT(descriptor.shapeFromIRModel.has_value(),
- "Missing value for the \"shapeFromIRModel\" attribute, I/O descriptor");
-
- const ov::PartialShape& shapeFromCompiler = descriptor.shapeFromCompiler;
- const ov::PartialShape& shapeFromIRModel = *descriptor.shapeFromIRModel;
-
- if (shapeFromCompiler.is_dynamic() || shapeFromCompiler.rank().get_length() == 0 ||
- *shapeFromCompiler.begin() != DEFAULT_BATCH_SIZE) {
- return false;
- }
-
- if (!descriptor.isStateInput && !descriptor.isStateOutput && !descriptor.isShapeTensor) {
- if (shapeFromIRModel.is_dynamic() || shapeFromIRModel.rank().get_length() == 0 ||
- *shapeFromIRModel.begin() != candidateBatchSize) {
- return false;
- }
- }
- }
-
- return true;
- };
-
- if (!checkDescriptorsUseCandidateBatchSize(metadata.inputs) ||
- !checkDescriptorsUseCandidateBatchSize(metadata.outputs)) {
- _logger.debug("Batching on the plugin is not used, batching is handled by the compiler");
- return std::nullopt;
- }
-
- _logger.debug("Batching is handled by the plugin");
-
- return candidateBatchSize;
-}
-
-const std::optional<std::size_t> IGraph::get_batch_size() const {
- return _batch_size;
-}
-
-} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp b/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
index e8e00fc2e1a..ce1576c31a2 100644
--- a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
+++ b/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp
@@ -5,18 +5,13 @@
#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 {
-
-constexpr size_t BATCH_AXIS = 0;
-
-}
-
namespace intel_npu {
SyncInferRequest::SyncInferRequest(const std::shared_ptr<const ICompiledModel>& compiledModel, const Config& config)
@@ -247,7 +242,7 @@ void SyncInferRequest::check_batched_tensors(const ov::Output<const ov::Node>& p
if (layout.empty()) {
_logger.warning("set_input_tensors/set_tensors layout is not set, assuming batch dimension is found on 0 axis");
- batch_idx = BATCH_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"
@@ -257,9 +252,9 @@ void SyncInferRequest::check_batched_tensors(const ov::Output<const ov::Node>& p
}
if (batch_idx < 0) {
- batch_idx += static_cast<int64_t>(tensors[BATCH_AXIS]->get_shape().size());
+ batch_idx += static_cast<int64_t>(tensors[utils::BATCH_AXIS]->get_shape().size());
}
- OPENVINO_ASSERT(batch_idx == BATCH_AXIS,
+ OPENVINO_ASSERT(batch_idx == utils::BATCH_AXIS,
"set_input_tensors/set_tensors is not currently supported for batch dimension index ",
batch_idx,
" != 0");
@@ -288,8 +283,8 @@ void SyncInferRequest::check_batched_tensors(const ov::Output<const ov::Node>& p
tensors_size);
}
- auto batched_shape = tensors[BATCH_AXIS]->get_shape();
- auto element_type = tensors[BATCH_AXIS]->get_element_type();
+ 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!");
@@ -339,7 +334,7 @@ std::shared_ptr<ov::ITensor> SyncInferRequest::allocate_tensor(const IODescripto
ov::Shape allocatedTensorShape = descriptor.shapeFromCompiler.get_max_shape();
if (batchSize.has_value()) {
- allocatedTensorShape[BATCH_AXIS] = *batchSize;
+ allocatedTensorShape[utils::BATCH_AXIS] = *batchSize;
}
if (descriptor.isStateOutput) {
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
index 29318a331c6..45de6b921e0 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
@@ -35,26 +35,67 @@ public:
void set_argument_value(uint32_t argi, const void* argv) const override;
+ void initialize(const Config& config) override;
+
+ const NetworkMetadata& get_metadata() const override;
ze_graph_handle_t get_handle() const override;
- void initialize(const Config& config) override;
+ void update_network_name(std::string_view name) override;
+
+ const std::vector<ArgumentDescriptor>& get_input_descriptors() const override;
+ const std::vector<ArgumentDescriptor>& get_output_descriptors() const override;
+ const std::shared_ptr<CommandQueue>& get_command_queue() const override;
+ uint32_t get_command_queue_group_ordinal() const override;
+
+ void set_workload_type(const ov::WorkloadType workloadType) const override;
+
+ void set_last_submitted_event(const std::shared_ptr<Event>& event, size_t indexOfCommandList) override;
+ const std::shared_ptr<Event>& get_last_submitted_event(size_t indexOfCommandList) const override;
+ void resize_last_submitted_event(size_t batch) override;
+ void set_batch_size(std::size_t batch) override;
+
+ const std::optional<std::size_t> get_batch_size() const override;
+
+ uint32_t get_unique_id() override;
+ void set_last_submitted_id(uint32_t id_index) override;
+ uint32_t get_last_submitted_id() const override;
~Graph() override;
protected:
bool release_blob(const Config& config);
+ std::optional<size_t> determine_batch_size();
std::shared_ptr<ZeGraphExtWrappers> _zeGraphExt;
std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
GraphDescriptor _graphDesc;
+ NetworkMetadata _metadata;
+
+ std::vector<ArgumentDescriptor> _inputDescriptors;
+ std::vector<ArgumentDescriptor> _outputDescriptors;
+
+ std::shared_ptr<CommandQueue> _commandQueue;
+ uint32_t _commandQueueGroupOrdinal = 0;
+ std::vector<std::shared_ptr<Event>> _lastSubmittedEvent;
+
+ std::optional<ov::Tensor> _blob;
// In the case of the import path, the blob is released after graph initialization so it can not be any longer
// exported
bool _blobIsReleased = false;
bool _blobIsPersistent = false;
+ uint32_t _uniqueId = 0;
+ uint32_t _lastSubmittedId = 0;
+
+ /**
+ * @brief The batch size used by the corresponding model.
+ * @details The attribute contains a value only if the plugin performs the batches splitting operation.
+ */
+ std::optional<std::size_t> _batchSize = std::nullopt;
+
const ov::SoPtr<ICompiler> _compiler;
Logger _logger;
};
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp
index fd7c713cacb..735c5ac6157 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp
@@ -72,7 +72,7 @@ private:
std::vector<IODescriptor>& inputs,
std::vector<IODescriptor>& outputs) const;
- void initialize_graph_through_command_list(ze_graph_handle_t graphHandle, uint32_t commandQueueGroupOrdinal) const;
+ void initializeGraphThroughCommandList(ze_graph_handle_t graphHandle, uint32_t commandQueueGroupOrdinal) const;
void* importCpuVa(void* data, size_t size, const uint32_t flags = 0) const;
bool releaseCpuVa(void* data);
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
index 6d8041744e4..2ca5df2649f 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
@@ -22,10 +22,12 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
const bool blobIsPersistent,
const ov::SoPtr<ICompiler>& compiler,
const bool calledFromWeightlessGraph)
- : IGraph(std::move(metadata), config, std::move(blob)),
+ : IGraph(),
_zeGraphExt(zeGraphExt),
_zeroInitStruct(zeroInitStruct),
_graphDesc(graphDesc),
+ _metadata(std::move(metadata)),
+ _blob(std::move(blob)),
_blobIsPersistent(blobIsPersistent),
_compiler(compiler),
_logger("Graph", config.get<LOG_LEVEL>()) {
@@ -40,6 +42,50 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
}
}
+const NetworkMetadata& Graph::get_metadata() const {
+ return _metadata;
+}
+
+void Graph::update_network_name(std::string_view name) {
+ _metadata.name = name;
+}
+
+const std::vector<ArgumentDescriptor>& Graph::get_input_descriptors() const {
+ return _inputDescriptors;
+}
+
+const std::vector<ArgumentDescriptor>& Graph::get_output_descriptors() const {
+ return _outputDescriptors;
+}
+
+const std::shared_ptr<CommandQueue>& Graph::get_command_queue() const {
+ return _commandQueue;
+}
+
+uint32_t Graph::get_command_queue_group_ordinal() const {
+ return _commandQueueGroupOrdinal;
+}
+
+void Graph::set_workload_type(const ov::WorkloadType workloadType) const {
+ if (_commandQueue == nullptr) {
+ return;
+ }
+
+ ze_command_queue_workload_type_t zeWorkloadType;
+ switch (workloadType) {
+ case ov::WorkloadType::DEFAULT:
+ zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_DEFAULT;
+ break;
+ case ov::WorkloadType::EFFICIENT:
+ zeWorkloadType = ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_BACKGROUND;
+ break;
+ default:
+ OPENVINO_THROW("Unknown value for WorkloadType!");
+ }
+
+ _commandQueue->setWorkloadType(zeWorkloadType);
+}
+
ze_graph_handle_t Graph::get_handle() const {
return _graphDesc._handle;
}
@@ -82,7 +128,7 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> Graph::export_blob(std
_logger.info(str.str().c_str());
}
- size_t size = utils::align_size_to_standarg_page_size(blobSize);
+ size_t size = utils::align_size_to_standard_page_size(blobSize);
size_t paddingSize = size - blobSize;
if (paddingSize > 0) {
std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
@@ -139,47 +185,46 @@ void Graph::initialize(const Config& config) {
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
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());
+ _inputDescriptors.push_back(ArgumentDescriptor{arg3, index});
+ _logger.debug("got pfnGetArgumentProperties3 for input: %s", _inputDescriptors.back().to_string().c_str());
} else {
- _output_descriptors.push_back(ArgumentDescriptor{arg3, index});
+ _outputDescriptors.push_back(ArgumentDescriptor{arg3, index});
_logger.debug("got pfnGetArgumentProperties3 for output: %s",
- _output_descriptors.back().to_string().c_str());
+ _outputDescriptors.back().to_string().c_str());
}
}
- _input_descriptors.shrink_to_fit();
- _output_descriptors.shrink_to_fit();
+ _inputDescriptors.shrink_to_fit();
+ _outputDescriptors.shrink_to_fit();
- _command_queue_group_ordinal =
- zeroUtils::findCommandQueueGroupOrdinal(_zeroInitStruct->getDevice(),
- ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);
+ _commandQueueGroupOrdinal = zeroUtils::findCommandQueueGroupOrdinal(_zeroInitStruct->getDevice(),
+ ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);
- uint32_t command_queue_options = 0;
+ uint32_t commandQueueOptions = 0;
if (config.has<TURBO>() && config.get<TURBO>()) {
if (_zeroInitStruct->getCommandQueueDdiTable().version() >= ZE_MAKE_VERSION(1, 0)) {
_logger.debug("Set ZE_NPU_COMMAND_QUEUE_OPTION_TURBO in command queue options");
- command_queue_options = command_queue_options | ZE_NPU_COMMAND_QUEUE_OPTION_TURBO;
+ commandQueueOptions = commandQueueOptions | ZE_NPU_COMMAND_QUEUE_OPTION_TURBO;
}
}
if (_zeroInitStruct->getCommandQueueDdiTable().version() >= ZE_MAKE_VERSION(1, 1) &&
config.has<RUN_INFERENCES_SEQUENTIALLY>() && config.get<RUN_INFERENCES_SEQUENTIALLY>()) {
_logger.debug("Set ZE_NPU_COMMAND_QUEUE_OPTION_DEVICE_SYNC in command queue options");
- command_queue_options = command_queue_options | ZE_NPU_COMMAND_QUEUE_OPTION_DEVICE_SYNC;
+ commandQueueOptions = commandQueueOptions | ZE_NPU_COMMAND_QUEUE_OPTION_DEVICE_SYNC;
}
- _command_queue = std::make_shared<CommandQueue>(_zeroInitStruct,
- zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>()),
- _command_queue_group_ordinal,
- command_queue_options);
+ _commandQueue = std::make_shared<CommandQueue>(_zeroInitStruct,
+ zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>()),
+ _commandQueueGroupOrdinal,
+ commandQueueOptions);
if (config.has<WORKLOAD_TYPE>()) {
set_workload_type(config.get<WORKLOAD_TYPE>());
}
- _zeGraphExt->initializeGraph(_graphDesc, _command_queue_group_ordinal);
+ _zeGraphExt->initializeGraph(_graphDesc, _commandQueueGroupOrdinal);
_logger.debug("Graph initialize finish");
// We are allowed to release the original blob because weights were loaded in NPU memory during
@@ -187,13 +232,13 @@ void Graph::initialize(const Config& config) {
// releasing it here to avoid unnecessary memory usage.
_blobIsReleased = release_blob(config);
- _batch_size = get_batch_size(_metadata, {}, {});
+ _batchSize = determine_batch_size();
if (_zeroInitStruct->getCommandQueueDdiTable().version() < ZE_MAKE_VERSION(1, 1) &&
config.get<RUN_INFERENCES_SEQUENTIALLY>()) {
- auto number_of_command_lists = _batch_size.has_value() ? *_batch_size : 1;
+ auto numberOfCommandLists = _batchSize.has_value() ? *_batchSize : 1;
- _last_submitted_event.resize(number_of_command_lists);
+ _lastSubmittedEvent.resize(numberOfCommandLists);
}
}
@@ -217,18 +262,102 @@ bool Graph::release_blob(const Config& config) {
return true;
};
+void Graph::set_last_submitted_event(const std::shared_ptr<Event>& event, size_t indexOfCommandList) {
+ _lastSubmittedEvent[indexOfCommandList] = event;
+}
+
+const std::shared_ptr<Event>& Graph::get_last_submitted_event(size_t indexOfCommandList) const {
+ return _lastSubmittedEvent[indexOfCommandList];
+}
+
+void Graph::resize_last_submitted_event(size_t batch) {
+ _lastSubmittedEvent.resize(batch);
+}
+
+void Graph::set_batch_size(std::size_t batch) {
+ _batchSize = batch;
+}
+
+uint32_t Graph::get_unique_id() {
+ return _uniqueId++;
+}
+
+void Graph::set_last_submitted_id(uint32_t id_index) {
+ _lastSubmittedId = id_index;
+}
+
+uint32_t Graph::get_last_submitted_id() const {
+ return _lastSubmittedId;
+}
+
+std::optional<size_t> Graph::determine_batch_size() {
+ 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;
+ }
+
+ const ov::PartialShape& firstShape = *_metadata.outputs.at(0).shapeFromIRModel;
+ if (firstShape.is_dynamic() || firstShape.rank().get_length() == 0) {
+ return std::nullopt;
+ }
+
+ const size_t candidateBatchSize = firstShape[utils::BATCH_AXIS].get_max_length();
+ if (candidateBatchSize == 0 || candidateBatchSize == utils::DEFAULT_BATCH_SIZE) {
+ _logger.debug("Batching on the plugin is not used, batching is handled by the compiler");
+ return std::nullopt;
+ }
+
+ auto checkDescriptorsUseCandidateBatchSize = [candidateBatchSize](const std::vector<IODescriptor>& descriptors) {
+ for (const IODescriptor& descriptor : descriptors) {
+ OPENVINO_ASSERT(descriptor.shapeFromIRModel.has_value(),
+ "Missing value for the \"shapeFromIRModel\" attribute, I/O descriptor");
+
+ const ov::PartialShape& shapeFromCompiler = descriptor.shapeFromCompiler;
+ const ov::PartialShape& shapeFromIRModel = *descriptor.shapeFromIRModel;
+
+ if (shapeFromCompiler.is_dynamic() || shapeFromCompiler.rank().get_length() == 0 ||
+ *shapeFromCompiler.begin() != utils::DEFAULT_BATCH_SIZE) {
+ return false;
+ }
+
+ if (!descriptor.isStateInput && !descriptor.isStateOutput && !descriptor.isShapeTensor) {
+ if (shapeFromIRModel.is_dynamic() || shapeFromIRModel.rank().get_length() == 0 ||
+ *shapeFromIRModel.begin() != candidateBatchSize) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ };
+
+ if (!checkDescriptorsUseCandidateBatchSize(_metadata.inputs) ||
+ !checkDescriptorsUseCandidateBatchSize(_metadata.outputs)) {
+ _logger.debug("Batching on the plugin is not used, batching is handled by the compiler");
+ return std::nullopt;
+ }
+
+ _logger.debug("Batching is handled by the plugin");
+
+ return candidateBatchSize;
+}
+
+const std::optional<std::size_t> Graph::get_batch_size() const {
+ return _batchSize;
+}
+
Graph::~Graph() {
// make sure all the context-dependent components are destroyed before the zero context is destroyed
if (_zeGraphExt != nullptr) {
_zeGraphExt->destroyGraph(_graphDesc);
}
- if (!_last_submitted_event.empty()) {
- _last_submitted_event.clear();
+ if (!_lastSubmittedEvent.empty()) {
+ _lastSubmittedEvent.clear();
}
- if (_command_queue != nullptr) {
- _command_queue.reset();
+ if (_commandQueue != nullptr) {
+ _commandQueue.reset();
}
}
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
index da2ddc138d2..91c9b99caaf 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
@@ -232,7 +232,7 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> WeightlessGraph::expor
_logger.info(str.str().c_str());
}
- size_t size = utils::align_size_to_standarg_page_size(blobSize);
+ size_t size = utils::align_size_to_standard_page_size(blobSize);
size_t paddingSize = size - blobSize;
if (paddingSize > 0) {
std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
@@ -581,7 +581,7 @@ void WeightlessGraph::run_pipeline(const size_t initIndex) {
}
void WeightlessGraph::set_weights_inputs() {
- for (const auto& desc : _input_descriptors) {
+ for (const auto& desc : _inputDescriptors) {
if (!isMainInputWeightsName(desc.info.name)) {
continue;
}
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.cpp
index 554bb5c9dbc..21e6396c752 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
@@ -39,11 +39,6 @@
#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 {
GraphDescriptor::GraphDescriptor(ze_graph_handle_t handle, void* data) : _handle(handle), _data(data) {}
@@ -156,8 +151,8 @@ void ZeGraphExtWrappers::setGraphArgumentValue(const GraphDescriptor& graphDescr
void ZeGraphExtWrappers::initializeGraph(const GraphDescriptor& graphDescriptor,
uint32_t commandQueueGroupOrdinal) const {
if (_zeroInitStruct->getGraphDdiTable().version() < ZE_GRAPH_EXT_VERSION_1_8) {
- _logger.debug("Use initialize_graph_through_command_list for ext version smaller than 1.8");
- initialize_graph_through_command_list(graphDescriptor._handle, commandQueueGroupOrdinal);
+ _logger.debug("Use initializeGraphThroughCommandList for ext version smaller than 1.8");
+ initializeGraphThroughCommandList(graphDescriptor._handle, commandQueueGroupOrdinal);
} else {
_logger.debug("Initialize graph based on graph properties for ext version larger than 1.8");
ze_graph_properties_2_t properties = {};
@@ -171,33 +166,33 @@ void ZeGraphExtWrappers::initializeGraph(const GraphDescriptor& graphDescriptor,
}
if (properties.initStageRequired & ZE_GRAPH_STAGE_COMMAND_LIST_INITIALIZE) {
- initialize_graph_through_command_list(graphDescriptor._handle, commandQueueGroupOrdinal);
+ initializeGraphThroughCommandList(graphDescriptor._handle, commandQueueGroupOrdinal);
}
}
}
-void ZeGraphExtWrappers::initialize_graph_through_command_list(ze_graph_handle_t graphHandle,
- uint32_t commandQueueGroupOrdinal) const {
- _logger.debug("initialize_graph_through_command_list init start - create graph_command_list");
- CommandList graph_command_list(_zeroInitStruct, commandQueueGroupOrdinal);
- _logger.debug("initialize_graph_through_command_list - create graph_command_queue");
- std::shared_ptr<CommandQueue> graph_command_queue = std::make_shared<CommandQueue>(_zeroInitStruct,
- ZE_COMMAND_QUEUE_PRIORITY_NORMAL,
- commandQueueGroupOrdinal,
- false);
- _logger.debug("initialize_graph_through_command_list - create fence");
- Fence fence(graph_command_queue);
-
- _logger.debug("initialize_graph_through_command_list - performing appendGraphInitialize");
- graph_command_list.appendGraphInitialize(graphHandle);
- _logger.debug("initialize_graph_through_command_list - closing graph command list");
- graph_command_list.close();
-
- _logger.debug("initialize_graph_through_command_list - performing executeCommandList");
- graph_command_queue->executeCommandList(graph_command_list, fence);
- _logger.debug("initialize_graph_through_command_list - performing hostSynchronize");
+void ZeGraphExtWrappers::initializeGraphThroughCommandList(ze_graph_handle_t graphHandle,
+ uint32_t commandQueueGroupOrdinal) const {
+ _logger.debug("initializeGraphThroughCommandList init start - create graphCommandList");
+ CommandList graphCommandList(_zeroInitStruct, commandQueueGroupOrdinal);
+ _logger.debug("initializeGraphThroughCommandList - create graphCommandQueue");
+ std::shared_ptr<CommandQueue> graphCommandQueue = std::make_shared<CommandQueue>(_zeroInitStruct,
+ ZE_COMMAND_QUEUE_PRIORITY_NORMAL,
+ commandQueueGroupOrdinal,
+ false);
+ _logger.debug("initializeGraphThroughCommandList - create fence");
+ Fence fence(graphCommandQueue);
+
+ _logger.debug("initializeGraphThroughCommandList - performing appendGraphInitialize");
+ graphCommandList.appendGraphInitialize(graphHandle);
+ _logger.debug("initializeGraphThroughCommandList - closing graph command list");
+ graphCommandList.close();
+
+ _logger.debug("initializeGraphThroughCommandList - performing executeCommandList");
+ graphCommandQueue->executeCommandList(graphCommandList, fence);
+ _logger.debug("initializeGraphThroughCommandList - performing hostSynchronize");
fence.hostSynchronize();
- _logger.debug("initialize_graph_through_command_list - hostSynchronize completed");
+ _logger.debug("initializeGraphThroughCommandList - hostSynchronize completed");
}
// Parse the result string of query from format <name_0><name_1><name_2> to unordered_set of string
@@ -462,7 +457,7 @@ 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
- if (id == BATCH_AXIS && shapeFromCompiler[id] == DEFAULT_BATCH_SIZE) {
+ if (id == utils::BATCH_AXIS && shapeFromCompiler[id] == utils::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
diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
index 40714d87ce3..67b3213ad6c 100644
--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
@@ -116,7 +116,7 @@ void Metadata<METADATA_VERSION_2_1>::read(const ov::Tensor& tensor) {
void MetadataBase::append_padding_blob_size_and_magic(std::ostream& stream) {
size_t metadataSize = get_metadata_size() + sizeof(_blobDataSize) + MAGIC_BYTES.size();
- size_t size = utils::align_size_to_standarg_page_size(metadataSize);
+ size_t size = utils::align_size_to_standard_page_size(metadataSize);
size_t paddingSize = size - metadataSize;
if (paddingSize > 0) {
std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp
index aabfac66e87..01cc49fc38c 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp
@@ -14,6 +14,9 @@ namespace utils {
constexpr std::size_t STANDARD_PAGE_SIZE = 4096;
+constexpr std::size_t DEFAULT_BATCH_SIZE = 1;
+constexpr std::size_t BATCH_AXIS = 0;
+
struct AlignedAllocator {
public:
AlignedAllocator(const size_t align_size) : _align_size(align_size) {}
@@ -41,7 +44,7 @@ static inline bool memory_and_size_aligned_to_standard_page_size(void* addr, siz
return (addr_int % STANDARD_PAGE_SIZE == 0) && (size % STANDARD_PAGE_SIZE == 0);
}
-static inline size_t align_size_to_standarg_page_size(size_t size) {
+static inline size_t align_size_to_standard_page_size(size_t size) {
return (size + utils::STANDARD_PAGE_SIZE - 1) & ~(utils::STANDARD_PAGE_SIZE - 1);
}
diff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
index 73ecdc818a1..e8c3fc24f83 100644
--- a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
@@ -146,7 +146,7 @@ bool ZeroRemoteTensor::deallocate() noexcept {
void ZeroRemoteTensor::allocate(const size_t bytes) {
switch (_mem_type) {
case MemType::L0_INTERNAL_BUF: {
- size_t size = (bytes + utils::STANDARD_PAGE_SIZE - 1) & ~(utils::STANDARD_PAGE_SIZE - 1);
+ size_t size = utils::align_size_to_standard_page_size(bytes);
ze_host_mem_alloc_desc_t desc = {};
if (_tensor_type == TensorType::INPUT) {
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.hpp
index 5404e80d563..b73aa6a07ee 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
@@ -138,9 +138,6 @@ void executeContiguousTensorBatchInfer(ov::InferRequest req,
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()
@@ -435,6 +432,8 @@ TEST_P(BatchedTensorsRunTests, SetInputDifferentRemoteTensorsMultipleInferMCL) {
}
}
+using DynamicBatchedTensorsRunTests = BatchedTensorsRunTests;
+
TEST_P(DynamicBatchedTensorsRunTests, DynamicSetInputRemoteTensorsMultipleInfer) {
// Skip test according to plugin specific disabledTestPatterns() (if any)
SKIP_IF_CURRENT_TEST_IS_DISABLED()
@@ -491,23 +490,28 @@ void executeMutlipleTensorsBatchInfer(ov::InferRequest req,
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);
+ std::vector<ov::Tensor> tensors0, tensors1;
+ tensors0.reserve(batch_value);
+ tensors1.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));
+ auto tensor0 = context.create_host_tensor(ov::element::f32, non_batched_shape);
+ auto tensor1 = context.create_host_tensor(ov::element::f32, non_batched_shape);
+ tensors0.push_back(std::move(tensor0));
+ tensors1.push_back(std::move(tensor1));
}
- req.set_tensors("tensor_input0", tensors);
+
+ req.set_tensors("tensor_input0", tensors0);
+ req.set_tensors("tensor_input1", tensors1);
auto actual_tensor = req.get_tensor("tensor_output0");
- ASSERT_EQ(actual_tensor.get_byte_size(), tensors.back().get_byte_size() * tensors.size())
+ ASSERT_EQ(actual_tensor.get_byte_size(), tensors0.back().get_byte_size() * tensors0.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>();
+ auto* f = tensors0[i].data<float>();
for (size_t j = 0; j < non_batched_shape_size; ++j) {
f[j] = static_cast<float>(testNum + 20 * (i + 1));
}
@@ -640,18 +644,21 @@ void executeContiguousTensorBatchInfer(ov::InferRequest req,
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);
+ auto tensorIn0 = context.create_host_tensor(ov::element::f32, tensor_shape);
+ auto tensorIn1 = context.create_host_tensor(ov::element::f32, tensor_shape);
- std::vector<ov::Tensor> tensors;
- tensors.push_back(std::move(tensor));
+ std::vector<ov::Tensor> tensors0, tensors1;
+ tensors0.push_back(std::move(tensorIn0));
+ tensors1.push_back(std::move(tensorIn1));
- req.set_tensors("tensor_input0", tensors);
+ req.set_tensors("tensor_input0", tensors0);
+ req.set_tensors("tensor_input1", tensors1);
auto actual_tensor = req.get_tensor("tensor_output0");
- ASSERT_EQ(actual_tensor.get_byte_size(), tensors.back().get_byte_size())
+ ASSERT_EQ(actual_tensor.get_byte_size(), tensors0.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>();
+ auto* f = tensors0.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));
}
@@ -689,7 +696,6 @@ TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBa
// 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
@@ -721,7 +727,6 @@ TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBa
// 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
diff --git a/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cpp b/src/plugins/intel_npu/tests/functional/behavior/infer_request_run.cpp
index ce181f493ce..a88566a5e8a 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
@@ -60,11 +60,10 @@ 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)}};
+const std::vector<ov::AnyMap> DynamicBatchedConfigs = {{ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN)}};
-INSTANTIATE_TEST_SUITE_P(smoke_DynamicBatchingSeqTests,
- DynamicBatchingRunSeqTests,
+INSTANTIATE_TEST_SUITE_P(smoke_DynamicBatchingTests,
+ DynamicBatchingTests,
::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),
::testing::ValuesIn(DynamicBatchedConfigs)),
InferRequestRunTests::getTestCaseName);
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.hpp
index d874cce25ba..86ad9bce902 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
@@ -1052,9 +1052,139 @@ TEST_P(BatchingRunSeqTests, CheckMultipleBatchingRunsSeq) {
}
}
-using DynamicBatchingRunSeqTests = InferRequestRunTests;
+using DynamicBatchingTests = InferRequestRunTests;
-TEST_P(DynamicBatchingRunSeqTests, DynamicCheckMultipleBatchingRunsSeq) {
+TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun0) {
+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 64, 64};
+ size_t batch_size = 1;
+ auto shape = Shape{batch_size, 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);
+
+ compiled_model = core->compile_model(model, target_device, configuration);
+
+ ov::InferRequest inference_request;
+ ov::Tensor input_tensor;
+
+ input_tensor = context.create_host_tensor(ov::element::f32, shape);
+
+ inference_request = compiled_model.create_infer_request();
+
+ inference_request.set_input_tensor(input_tensor);
+
+ auto* input_data = reinterpret_cast<float*>(input_tensor.data());
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = static_cast<float>(batch_size);
+ }
+
+ inference_request.infer(); // Adds '1' to each element
+
+ auto output_tensor = inference_request.get_output_tensor();
+
+ float expected_result = static_cast<float>(batch_size) + 1.f;
+ auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
+ for (size_t j = 0; j < shape_size; ++j) {
+ EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ << "Run=" << batch_size << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
+ << " for index " << j;
+ }
+
+ for (auto z = batch_size + 1; z <= 10; z++) {
+ auto host_shape = Shape{z, 2, 64, 64};
+ auto input_host_tensor = context.create_host_tensor(ov::element::f32, host_shape);
+
+ inference_request.set_input_tensor(input_host_tensor);
+
+ auto* input_data = reinterpret_cast<float*>(input_host_tensor.data());
+ for (size_t i = 0; i < input_host_tensor.get_size(); ++i) {
+ input_data[i] = static_cast<float>(z);
+ }
+
+ inference_request.infer(); // Adds '1' to each element
+
+ auto output_test_tensor = inference_request.get_output_tensor();
+
+ float expected_result = static_cast<float>(z) + 1.f;
+ auto* output_tensor_data = reinterpret_cast<float*>(output_test_tensor.data());
+
+ EXPECT_EQ(output_test_tensor.get_size(), input_host_tensor.get_size());
+
+ for (size_t j = 0; j < output_test_tensor.get_size(); ++j) {
+ EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ << "Run=" << z << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
+ << " for index " << j;
+ }
+ }
+}
+
+TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun1) {
+ auto modelShape = PartialShape{-1, 2, 64, 64};
+ size_t batch_size = 1;
+ auto shape = Shape{batch_size, 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);
+
+ compiled_model = core->compile_model(model, target_device, configuration);
+
+ ov::InferRequest inference_request;
+ ov::Tensor input_tensor;
+
+ input_tensor = ov::Tensor(ov::element::f32, shape);
+
+ inference_request = compiled_model.create_infer_request();
+
+ inference_request.set_input_tensor(input_tensor);
+
+ auto* input_data = reinterpret_cast<float*>(input_tensor.data());
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = static_cast<float>(batch_size);
+ }
+
+ inference_request.infer(); // Adds '1' to each element
+
+ auto output_tensor = inference_request.get_output_tensor();
+
+ float expected_result = static_cast<float>(batch_size) + 1.f;
+ auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
+ for (size_t j = 0; j < shape_size; ++j) {
+ EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ << "Run=" << batch_size << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
+ << " for index " << j;
+ }
+
+ for (auto z = batch_size + 1; z <= 10; z++) {
+ auto host_shape = Shape{z, 2, 64, 64};
+ auto input_host_tensor = ov::Tensor(ov::element::f32, host_shape);
+
+ inference_request.set_input_tensor(input_host_tensor);
+
+ auto* input_data = reinterpret_cast<float*>(input_host_tensor.data());
+ for (size_t i = 0; i < input_host_tensor.get_size(); ++i) {
+ input_data[i] = static_cast<float>(z);
+ }
+
+ inference_request.infer(); // Adds '1' to each element
+
+ auto output_test_tensor = inference_request.get_output_tensor();
+
+ float expected_result = static_cast<float>(z) + 1.f;
+ auto* output_tensor_data = reinterpret_cast<float*>(output_test_tensor.data());
+
+ EXPECT_EQ(output_test_tensor.get_size(), input_host_tensor.get_size());
+
+ for (size_t j = 0; j < output_test_tensor.get_size(); ++j) {
+ EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ << "Run=" << z << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
+ << " for index " << j;
+ }
+ }
+}
+
+TEST_P(DynamicBatchingTests, 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);