Skip to content

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

[NPU] Remove obsolete plugin-side batching from dynamic execution (#37108)

Shaojie Zhudeb5b4f5d7d2
diff --git a/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp b/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
index 33ee5bca308..7df9045df5d 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_dynamic_pipeline.hpp
@@ -134,8 +134,7 @@ public:
const std::shared_ptr<IGraph>& graph,
const Config& config,
const std::vector<std::vector<std::shared_ptr<ZeroTensor>>>& input_tensors,
- const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors,
- size_t batch_size = 1);
+ const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors);
DynamicPipeline(const DynamicPipeline&) = delete;
DynamicPipeline& operator=(const DynamicPipeline&) = delete;
@@ -168,7 +167,7 @@ private:
// VM execution context owned by this pipeline; shared between shape prediction and execution.
VMExecutionContext _executionContext;
- std::vector<std::unique_ptr<PipelinedCommandLists>> _command_lists;
+ std::unique_ptr<PipelinedCommandLists> _command_list_group;
};
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp
index d628fbb54c9..a39e32b9ace 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_dynamic_infer_request.cpp
@@ -20,15 +20,12 @@ ZeroDynamicInferRequest::ZeroDynamicInferRequest(const std::shared_ptr<ZeroInitS
void ZeroDynamicInferRequest::create_pipeline_impl() {
_logger.debug("create_pipeline_impl - constructing pipeline");
- auto batchSize = _graph->get_batch_size();
// Construct pipeline. The pipeline owns the VM execution context shared by shape prediction and execution.
- _pipeline =
- std::make_unique<DynamicPipeline>(_initStructs,
- _graph,
- _config,
- _levelZeroInputTensors,
- _levelZeroOutputTensors,
- batchSize.has_value() ? batchSize.value() : utils::DEFAULT_BATCH_SIZE);
+ _pipeline = std::make_unique<DynamicPipeline>(_initStructs,
+ _graph,
+ _config,
+ _levelZeroInputTensors,
+ _levelZeroOutputTensors);
_logger.debug("create_pipeline_impl - completed");
}
@@ -43,7 +40,8 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest
auto& levelZeroTensor =
foundPort.is_input() ? get_level_zero_input(foundPort.idx) : _levelZeroOutputTensors.at(foundPort.idx);
- auto originallevelZeroTensor = levelZeroTensor;
+ const auto originalShape =
+ levelZeroTensor != nullptr ? std::make_optional(levelZeroTensor->get_shape()) : std::nullopt;
try {
_logger.debug("sync_zero_tensor_with_graph - create zero tensor");
@@ -58,26 +56,26 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest
// Check if the current Level Zero tensor was previously shared with the user. If so, it cannot be reused;
// allocate a new tensor to back up the user tensor (which cannot be imported or used directly).
- if (_dynamicBatchValueChanged || levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused() ||
+ if (levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused() ||
(levelZeroTensor != nullptr && (levelZeroTensor->get_byte_size() < tensor->get_byte_size()))) {
_logger.debug("sync_zero_tensor_with_graph - allocate locally L0 tensor");
OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "allocate tensor");
- auto batch = _graph->get_batch_size();
- levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input(), batch);
+ levelZeroTensor = allocate_tensor(foundPort.idx, foundPort.is_input());
} else {
_logger.debug("sync_zero_tensor_with_graph - reusing the level zero tensor since it is not shared with "
"the user, and old L0 tensor is large enough");
+ levelZeroTensor->set_shape(tensor->get_shape());
}
}
- if (_pipelineIsCreated && !_dynamicBatchValueChanged) {
+ if (_pipelineIsCreated) {
_logger.debug("sync_zero_tensor_with_graph - update graph arguments");
OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");
OV_ITT_TASK_NEXT(ZERO_SET_TENSOR, "update_graph_arguments");
- if (originallevelZeroTensor != nullptr && originallevelZeroTensor->get_shape() != tensor->get_shape()) {
+ if (originalShape.has_value() && originalShape.value() != tensor->get_shape()) {
_logger.debug("sync_zero_tensor_with_graph - update graph arguments with user tensor pointer since "
"shape is changed");
_pipeline->update_graph_arguments(foundPort.is_input()
@@ -106,63 +104,43 @@ void ZeroDynamicInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest
void ZeroDynamicInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequest::FoundPort& foundPort,
const std::vector<ov::SoPtr<ov::ITensor>>& tensors,
- const std::optional<size_t>& batchSize) {
+ const std::optional<size_t>&) {
OV_ITT_TASK_CHAIN(ZERO_SET_TENSORS,
itt::domains::LevelZeroBackend,
"ZeroDynamicInferRequest",
"sync_zero_tensors_with_graph");
- if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) && batchSize.has_value()) {
- get_level_zero_inputs(foundPort.idx).resize(tensors.size());
-
- for (size_t i = 0; i < tensors.size(); i++) {
- auto originalLevelZeroTensor = get_level_zero_input(foundPort.idx, i);
- try {
- _logger.debug("sync_zero_tensors_with_graph - create zero tensor");
- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "create_zero_tensor");
- get_level_zero_input(foundPort.idx, i) = std::make_shared<ZeroTensor>(_initStructs, tensors.at(i));
- } catch (const ZeroMemException& exception) {
- _logger.debug("sync_zero_tensors_with_graph - exception caught while trying to create a Level Zero "
- "tensor from the user tensor: %s",
- exception.what());
-
- _logger.debug("sync_zero_tensors_with_graph - allocate locally L0 tensor");
- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "allocate_tensor");
- get_level_zero_input(foundPort.idx, i) = allocate_tensor(foundPort.idx, INPUT, batchSize);
- }
+ auto& levelZeroTensors = get_level_zero_inputs(foundPort.idx);
+ levelZeroTensors.resize(1);
+ auto& levelZeroTensor = get_level_zero_input(foundPort.idx);
+
+ ov::Shape batchedShape = tensors.at(SINGLE_TENSOR)->get_shape();
+ batchedShape[utils::BATCH_AXIS] = tensors.size();
+ const bool inputShapeChanged = levelZeroTensor == nullptr || levelZeroTensor->get_shape() != batchedShape;
+
+ if (levelZeroTensor == nullptr || !levelZeroTensor->can_be_reused()) {
+ levelZeroTensor = allocate_tensor(foundPort.idx, INPUT);
+ } else {
+ levelZeroTensor->set_shape(batchedShape);
+ }
- if (_pipelineIsCreated && !_dynamicBatchValueChanged) {
- OPENVINO_ASSERT(get_level_zero_input(foundPort.idx, i)->data(), "Empty buffer");
- OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");
- if (originalLevelZeroTensor != nullptr &&
- originalLevelZeroTensor->get_shape() != tensors.at(i)->get_shape()) {
- _logger.debug(
- "set_tensors - update graph arguments with user tensor pointer since shape is changed");
- _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,
- get_level_zero_input(foundPort.idx, i),
- i,
- tensors.at(i)._ptr);
- _isTensorChanged = true;
- } else {
- _logger.debug(
- "set_tensors - update graph arguments without user tensor pointer since shape is not changed");
- _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver,
- get_level_zero_input(foundPort.idx, i),
- i);
- }
- }
- }
+ const auto& userTensorElementType = tensors.at(SINGLE_TENSOR)->get_element_type();
+ if (userTensorElementType == ov::element::boolean && levelZeroTensor->get_element_type() == ov::element::u8) {
+ levelZeroTensor->set_element_type(userTensorElementType);
}
- if (!_pipelineIsCreated) {
- // If pipeline is not created, need to predict real output shape
- _isTensorChanged = true;
+
+ if (_pipelineIsCreated) {
+ OPENVINO_ASSERT(levelZeroTensor->data(), "Empty buffer");
+ OV_ITT_TASK_NEXT(ZERO_SET_TENSORS, "update_graph_arguments");
+ _pipeline->update_graph_arguments(_metadata.inputs.at(foundPort.idx).indexUsedByDriver, levelZeroTensor);
}
- // If command list updates are not supported, fallback to copying tensors every time.
+
+ // Preserve shape changes from other inputs until the next inference predicts all output shapes.
+ _isTensorChanged = _isTensorChanged || !_pipelineIsCreated || inputShapeChanged;
}
-std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(
- const size_t index,
- const bool isInput,
- const std::optional<std::size_t>& batchSize) const {
+std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(const size_t index,
+ const bool isInput,
+ const std::optional<std::size_t>&) const {
IODescriptor descriptor = isInput ? _metadata.inputs.at(index) : _metadata.outputs.at(index);
// Create new IODescriptor based on user input|output and descriptor
if (isInput && get_user_input(index) != nullptr) {
@@ -181,8 +159,8 @@ std::shared_ptr<ZeroTensor> ZeroDynamicInferRequest::allocate_tensor(
ov::Shape allocatedTensorShape = descriptor.shapeFromCompiler.get_max_shape();
- if (batchSize.has_value()) {
- allocatedTensorShape[utils::BATCH_AXIS] = *batchSize;
+ if (isInput && is_batched_input(index)) {
+ allocatedTensorShape[utils::BATCH_AXIS] = get_user_inputs(index).size();
}
auto tensor = std::make_shared<ZeroTensor>(_initStructs, descriptor.precision, allocatedTensorShape, isInput);
@@ -205,10 +183,18 @@ void ZeroDynamicInferRequest::infer_async() {
// shares the pipeline-owned VM execution context with execution.
prepare_inputs();
- // Predict output shapes and validate user output tensors; prepare_outputs() then allocates and resizes the
- // Level Zero output buffers to the predicted shapes.
- predict_output_shapes(_predictedShapes);
- check_tensor_and_predicted_shapes(_predictedShapes);
+ const bool requiresOutputShapePrediction =
+ std::any_of(_metadata.outputs.begin(), _metadata.outputs.end(), [](const IODescriptor& output) {
+ // Compiler metadata may contain static allocation maxima for dynamic IR outputs.
+ return !output.shapeFromIRModel.has_value() || output.shapeFromIRModel->is_dynamic();
+ });
+ // Only outputs known to be static in IR metadata can skip the optional VM output_shape entrypoint.
+ if (requiresOutputShapePrediction) {
+ // Predict dynamic output shapes and validate user output tensors; prepare_outputs() then resizes the Level
+ // Zero output buffers to the predicted shapes.
+ predict_output_shapes(_predictedShapes);
+ check_tensor_and_predicted_shapes(_predictedShapes);
+ }
prepare_outputs();
OV_ITT_TASK_NEXT(ZERO_INFER, "push");
@@ -232,7 +218,9 @@ void ZeroDynamicInferRequest::predict_output_shapes(std::vector<ov::Shape>& pred
// A null entry lets the pipeline fall back to the graph metadata max shape.
for (size_t i = 0; i < inputTensors.size(); ++i) {
const auto& userTensor = get_user_input(i);
- if (userTensor != nullptr) {
+ if (is_batched_input(i)) {
+ inputTensors[i] = get_level_zero_input(i);
+ } else if (userTensor != nullptr) {
// If userTensor is set, use userTensor to update memref handle in prediction
inputTensors[i] = userTensor._ptr;
} else {
diff --git a/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
index 6d630904641..e0c543253ed 100644
--- a/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
+++ b/src/plugins/intel_npu/src/backend/src/zero_dynamic_pipeline.cpp
@@ -13,6 +13,7 @@
#include "intel_npu/config/options.hpp"
#include "intel_npu/prefix.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/vm/mem_ref_type.hpp"
#include "intel_npu/utils/vm/npu_vm_runtime_api.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
@@ -173,109 +174,62 @@ DynamicPipeline::DynamicPipeline(const std::shared_ptr<ZeroInitStructsHolder>& i
const std::shared_ptr<IGraph>& graph,
const Config& config,
const std::vector<std::vector<std::shared_ptr<ZeroTensor>>>& input_tensors,
- const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors,
- size_t batch_size)
- : IPipeline(init_structs, graph, batch_size, config, "DynamicPipeline") {
+ const std::vector<std::shared_ptr<ZeroTensor>>& output_tensors)
+ : IPipeline(init_structs, graph, utils::DEFAULT_BATCH_SIZE, config, "DynamicPipeline") {
OV_ITT_SCOPED_TASK(itt::domains::LevelZeroBackend, "Zero_infer_request::DynamicPipeline::DynamicPipeline");
OPENVINO_ASSERT(!_run_inferences_sequentially, "In-order execution doesn't work for dynamic pipeline");
- _logger.debug("Initialization started, batch size: %zu", _batch_size);
+ _logger.debug("Initialization started");
if (!_sync_output_with_fences) {
- _event_pool = std::make_shared<EventPool>(_init_structs, _batch_size ? static_cast<uint32_t>(_batch_size) : 1);
-
- _events.reserve(_batch_size);
- for (size_t i = 0; i < _batch_size; i++) {
- _events.emplace_back(std::make_shared<Event>(_event_pool, static_cast<uint32_t>(i)));
- }
+ _event_pool = std::make_shared<EventPool>(_init_structs, 1);
+ _events.emplace_back(std::make_shared<Event>(_event_pool, 0));
}
_logger.debug("Event pool and command queue setup completed");
const uint64_t num_of_subgraphs = _graph->get_metadata().numberOfSubgraphs;
- _command_lists.reserve(_batch_size);
- if (batch_size >= 1) {
- _logger.debug("Initializing %zu command list group(s) (batch size %zu)", batch_size, batch_size);
- for (size_t i = 0; i < _batch_size; i++) {
- _command_lists.emplace_back(std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs));
- }
- } else {
- OPENVINO_THROW("Batch size must be greater than 0, but got ", batch_size);
- }
+ _command_list_group = std::make_unique<PipelinedCommandLists>(num_of_subgraphs, _init_structs);
if (_sync_output_with_fences) {
- _fences.reserve(_batch_size);
- for (size_t i = 0; i < _batch_size; i++) {
- _fences.emplace_back(std::make_unique<Fence>(_command_queue));
- }
+ _fences.emplace_back(std::make_unique<Fence>(_command_queue));
}
- for (size_t i = 0; i < _batch_size; i++) {
- _logger.debug("Set args for command list number: %zu", i);
-
- _command_lists.at(i)->initArguments(_graph->get_metadata());
- auto& dynamicArguments = _command_lists.at(i)->getArguments();
-
- size_t io_index = 0;
- for (const auto& desc : _graph->get_metadata().inputs) {
- // DynamicPipeline does not currently support weightless model, just thrown exception.
- OPENVINO_ASSERT(!desc.isMainInputWeights,
- "DynamicPipeline does not support weightless graphs (input '",
- desc.nameFromCompiler,
- "' is a main-input weight)");
-
- if (input_tensors.at(io_index).size() > 1) {
- _logger.debug("Set args for input index: %zu", io_index);
- const auto& tensor = input_tensors.at(io_index).at(i);
- size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,
- tensor->data(),
- tensor->get_shape(),
- get_strides(tensor->get_strides(), elementSize));
- ++io_index;
- continue;
- }
-
- _logger.debug("Update tensor property for input desc index: %u", desc.indexUsedByDriver);
- const auto& tensor = input_tensors.at(io_index).at(0);
- size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() || tensor->get_strides().empty()) {
- dynamicArguments.setArgumentProperties(
- desc.indexUsedByDriver,
- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size,
- tensor->get_shape(),
- get_strides(tensor->get_strides(), elementSize));
- } else {
- dynamicArguments.setArgumentProperties(
- desc.indexUsedByDriver,
- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),
- tensor->get_shape(),
- get_strides(tensor->get_strides(), elementSize));
- }
- ++io_index;
- }
+ auto& commandLists = _command_list_group;
+ commandLists->initArguments(_graph->get_metadata());
+ auto& dynamicArguments = commandLists->getArguments();
+
+ size_t io_index = 0;
+ for (const auto& desc : _graph->get_metadata().inputs) {
+ // DynamicPipeline does not currently support weightless model, just thrown exception.
+ OPENVINO_ASSERT(!desc.isMainInputWeights,
+ "DynamicPipeline does not support weightless graphs (input '",
+ desc.nameFromCompiler,
+ "' is a main-input weight)");
+ OPENVINO_ASSERT(input_tensors.at(io_index).size() == 1,
+ "DynamicPipeline requires one full-batch tensor per input");
+
+ _logger.debug("Update tensor property for input desc index: %u", desc.indexUsedByDriver);
+ const auto& tensor = input_tensors.at(io_index).at(SINGLE_TENSOR);
+ size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,
+ tensor->data(),
+ tensor->get_shape(),
+ get_strides(tensor->get_strides(), elementSize));
+ ++io_index;
+ }
- io_index = 0;
- for (const auto& desc : _graph->get_metadata().outputs) {
- _logger.debug("Update tensor property for output desc index: %u", desc.indexUsedByDriver);
- const auto& tensor = output_tensors.at(io_index);
- size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() || tensor->get_strides().empty()) {
- dynamicArguments.setArgumentProperties(
- desc.indexUsedByDriver,
- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_byte_size()) / _batch_size,
- tensor->get_shape(),
- get_strides(tensor->get_strides(), elementSize));
- } else {
- dynamicArguments.setArgumentProperties(
- desc.indexUsedByDriver,
- static_cast<unsigned char*>(tensor->data()) + (i * tensor->get_strides()[0]),
- tensor->get_shape(),
- get_strides(tensor->get_strides(), elementSize));
- }
- ++io_index;
- }
+ io_index = 0;
+ for (const auto& desc : _graph->get_metadata().outputs) {
+ _logger.debug("Update tensor property for output desc index: %u", desc.indexUsedByDriver);
+ const auto& tensor = output_tensors.at(io_index);
+ size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
+ dynamicArguments.setArgumentProperties(desc.indexUsedByDriver,
+ tensor->data(),
+ tensor->get_shape(),
+ get_strides(tensor->get_strides(), elementSize));
+ ++io_index;
}
_logger.debug("Initialization completed");
}
@@ -298,32 +252,28 @@ void DynamicPipeline::push() {
}
}
- auto commandQueueHandle = _command_queue->handle();
- for (size_t i = 0; i < _command_lists.size(); ++i) {
- OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PUSH, itt::domains::LevelZeroBackend, "Pipeline", "push");
-
- ze_fence_handle_t fence = nullptr;
- ze_event_handle_t event = nullptr;
- if (_sync_output_with_fences) {
- fence = _fences.at(i)->handle();
+ OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PUSH, itt::domains::LevelZeroBackend, "Pipeline", "push");
+ const ze_fence_handle_t fence = _sync_output_with_fences ? _fences.front()->handle() : nullptr;
+ auto& commandLists = _command_list_group;
+ auto& dynamicArguments = commandLists->getArguments();
+ if (_logger.level() >= ov::log::Level::DEBUG) {
+ _logger.debug("push - inputs info for dynamic graph:");
+ for (auto& memType : dynamicArguments._inputsMemRef) {
+ _logger.debug("push - input: %s", memType.toString().c_str());
}
-
- auto& command_lists = _command_lists.at(i);
- auto& dynamicArguments = command_lists->getArguments();
- if (_logger.level() >= ov::log::Level::DEBUG) {
- _logger.debug("push - inputs info for dynamic graph:");
- for (auto& memType : dynamicArguments._inputsMemRef) {
- _logger.debug("push - input: %s", memType.toString().c_str());
- }
- _logger.debug("push - outputs info for dynamic graph:");
- for (auto& memType : dynamicArguments._outputsMemRef) {
- _logger.debug("push - output: %s", memType.toString().c_str());
- }
+ _logger.debug("push - outputs info for dynamic graph:");
+ for (auto& memType : dynamicArguments._outputsMemRef) {
+ _logger.debug("push - output: %s", memType.toString().c_str());
}
-
- execute_vm_runtime(vmRuntime, dynamicArguments, command_lists->getHandles(), commandQueueHandle, fence, event);
}
+ execute_vm_runtime(vmRuntime,
+ dynamicArguments,
+ commandLists->getHandles(),
+ _command_queue->handle(),
+ fence,
+ nullptr);
+
_logger.debug("push - completed");
}
@@ -527,6 +477,7 @@ std::vector<ov::Shape> DynamicPipeline::predict_output_shapes(
for (int64_t j = 0; j < outputsMemRefs[i]._dimsCount; ++j) {
shape.push_back(static_cast<size_t>(outputsMemRefs[i]._sizes[j]));
}
+
predictedShapes[i] = std::move(shape);
if (!outputShapeChanged && !outputsMemRefs[i].compare(originalOutputMemRefs[i])) {
@@ -551,16 +502,14 @@ void DynamicPipeline::pull() {
_logger.debug("pull - started");
OV_ITT_TASK_CHAIN(ZERO_PIPELINE_IP_PULL, itt::domains::LevelZeroBackend, "DynamicPipeline", "pull");
- for (size_t i = 0; i < _command_lists.size(); ++i) {
- if (_sync_output_with_fences) {
- _fences.at(i)->hostSynchronize();
- } else {
- _events.at(i)->hostSynchronize();
- }
- /// sample npu timestamps if feature was activated
- if (_npu_profiling != nullptr) {
- _npu_profiling->sampleNpuTimestamps();
- }
+ if (_sync_output_with_fences) {
+ _fences.front()->hostSynchronize();
+ } else {
+ _events.front()->hostSynchronize();
+ }
+ /// sample npu timestamps if feature was activated
+ if (_npu_profiling != nullptr) {
+ _npu_profiling->sampleNpuTimestamps();
}
_logger.debug("pull - completed");
@@ -568,12 +517,10 @@ void DynamicPipeline::pull() {
void DynamicPipeline::reset() const {
_logger.debug("reset - started");
- for (size_t i = 0; i < _command_lists.size(); ++i) {
- if (_sync_output_with_fences) {
- _fences.at(i)->reset();
- } else {
- _events.at(i)->reset();
- }
+ if (_sync_output_with_fences) {
+ _fences.front()->reset();
+ } else {
+ _events.front()->reset();
}
_logger.debug("reset - completed");
}
@@ -584,26 +531,13 @@ void DynamicPipeline::update_graph_arguments(uint32_t index,
OV_ITT_TASK_CHAIN(ZERO_EXECUTOR_IP_UMCL, itt::domains::LevelZeroBackend, "DynamicPipeline", "updateCommandList");
_logger.debug("update_graph_arguments - started");
// This is the tensor with right shape and strides
- // The required check is alredy done in inferRequest
+ // The required check is already done in inferRequest
const std::shared_ptr<ov::ITensor>& tensor = userTensor ? userTensor : zeroTensor;
size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- const size_t number_of_command_lists = _command_lists.size();
-
- for (size_t i = 0; i < number_of_command_lists; i++) {
- if (tensor->get_element_type().bitwidth() < 8 || tensor->is_continuous() || tensor->get_strides().empty()) {
- _command_lists.at(i)->updateMutableCommandList(index,
- static_cast<const unsigned char*>(zeroTensor->data()) +
- (i * tensor->get_byte_size()) / number_of_command_lists,
- get_strides(tensor->get_strides(), elementSize),
- tensor->get_shape());
- } else {
- _command_lists.at(i)->updateMutableCommandList(
- index,
- static_cast<const unsigned char*>(zeroTensor->data()) + (i * tensor->get_strides()[0]),
- get_strides(tensor->get_strides(), elementSize),
- tensor->get_shape());
- }
- }
+ _command_list_group->updateMutableCommandList(index,
+ zeroTensor->data(),
+ get_strides(tensor->get_strides(), elementSize),
+ tensor->get_shape());
_logger.debug("update_graph_arguments - completed");
}
@@ -617,20 +551,15 @@ void DynamicPipeline::update_graph_arguments(uint32_t index,
"updateCommandListIndex");
_logger.debug("update_graph_arguments - update command list by index");
// This is the tensor with right shape and strides
- // The required check is alredy done in inferRequest
+ // The required check is already done in inferRequest
const std::shared_ptr<ov::ITensor>& tensor = userTensor ? userTensor : zeroTensor;
size_t elementSize = tensor->get_element_type().bitwidth() < 8 ? 1 : tensor->get_element_type().size();
- const size_t number_of_command_lists = _command_lists.size();
-
- OPENVINO_ASSERT(batch_index < number_of_command_lists,
- "Command list index is higher than the number of Command lists ",
- batch_index);
+ OPENVINO_ASSERT(batch_index == 0, "DynamicPipeline owns only one command-list group");
- _command_lists.at(batch_index)
- ->updateMutableCommandList(index,
- zeroTensor->data(),
- get_strides(tensor->get_strides(), elementSize),
- tensor->get_shape());
+ _command_list_group->updateMutableCommandList(index,
+ zeroTensor->data(),
+ get_strides(tensor->get_strides(), elementSize),
+ tensor->get_shape());
}
} // namespace intel_npu
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 c97794f7451..ae658023bae 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
@@ -282,7 +282,10 @@ std::vector<ov::SoPtr<ov::IVariableState>> ZeroInferRequest::query_state() const
void ZeroInferRequest::setup_pipeline() {
_logger.debug("setup_pipeline - started");
- auto batchSize = _graph->get_batch_size();
+ std::optional<size_t> batchSize;
+ if (!_graph->is_dynamic()) {
+ batchSize = _graph->get_batch_size();
+ }
for (size_t inputIndex = 0; inputIndex < _metadata.inputs.size(); ++inputIndex) {
if (_metadata.inputs.at(inputIndex).isMainInputWeights) {
@@ -424,10 +427,12 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
return;
}
- const auto& ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();
- auto batchSizeCandidate =
- determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);
-
+ std::optional<size_t> batchSizeCandidate;
+ if (!_graph->is_dynamic()) {
+ const auto& ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();
+ batchSizeCandidate =
+ determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);
+ }
if (batchSizeCandidate.has_value()) {
if (!_dynamicBatchValueChanged) {
if (get_user_input(foundPort.idx)._ptr != nullptr &&
@@ -447,7 +452,6 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
OPENVINO_THROW("Batching size is not matching all the tensors.");
}
}
-
if (get_level_zero_inputs(foundPort.idx).size() > 1) {
// Reset vector size to 1 if set_tensor is called after set_tensors
get_level_zero_inputs(foundPort.idx).resize(1);
@@ -469,10 +473,12 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
return;
}
- const auto& ioShape = _compiledModel->outputs()[foundPort.idx].get_partial_shape();
- auto batchSizeCandidate =
- determine_dynamic_batch_size(_metadata.outputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);
-
+ std::optional<size_t> batchSizeCandidate;
+ if (!_graph->is_dynamic()) {
+ const auto& ioShape = _compiledModel->outputs()[foundPort.idx].get_partial_shape();
+ batchSizeCandidate =
+ determine_dynamic_batch_size(_metadata.outputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);
+ }
if (batchSizeCandidate.has_value()) {
if (!_dynamicBatchValueChanged) {
if (_userOutputTensors.at(foundPort.idx)._ptr != nullptr &&
@@ -491,7 +497,6 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, const
OPENVINO_THROW("Batching size is not matching all the tensors.");
}
}
-
_userOutputTensors.at(foundPort.idx) = tensor;
}
@@ -588,10 +593,12 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,
_logger.debug("set_tensors - tensor count: %zu", tensors.size());
- const auto& ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();
- auto batchSizeCandidate =
- determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, nullptr, tensors.size());
-
+ std::optional<size_t> batchSizeCandidate;
+ if (!_graph->is_dynamic()) {
+ const auto& ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();
+ batchSizeCandidate =
+ determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, nullptr, tensors.size());
+ }
// Check if batch has been changed
if (batchSizeCandidate.has_value()) {
if (!_dynamicBatchValueChanged) {
@@ -609,7 +616,7 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,
} else if (batchSizeCandidate.value() != _graph->get_batch_size().value()) {
OPENVINO_THROW("Batching size is not matching all the tensors.");
}
- } else {
+ } else if (!_graph->is_dynamic()) {
batchSizeCandidate = _graph->get_batch_size();
}
@@ -720,7 +727,10 @@ ov::SoPtr<ov::ITensor> ZeroInferRequest::get_tensor(const ov::Output<const ov::N
auto& userTensor = isInput ? get_user_input(ioIndex) : _userOutputTensors.at(ioIndex);
- auto batchSize = _graph->get_batch_size();
+ std::optional<size_t> batchSize;
+ if (!_graph->is_dynamic()) {
+ batchSize = _graph->get_batch_size();
+ }
// LIMITATION for dynamic batch implementation:
// Output tensors must have the same batch size as input tensors, so input batch sizes must be determined first.
@@ -939,7 +949,10 @@ void ZeroInferRequest::prepare_inputs() {
}
}
- auto batch_size = _graph->get_batch_size();
+ std::optional<size_t> batch_size;
+ if (!_graph->is_dynamic()) {
+ batch_size = _graph->get_batch_size();
+ }
size_t inputIndex = 0;
for (const auto& userTensor : _userInputTensors) {
const IODescriptor& inputDescriptor = _metadata.inputs.at(inputIndex);
@@ -1013,7 +1026,7 @@ void ZeroInferRequest::prepare_inputs() {
for (size_t i = 0; i < userTensor.size(); i++) {
auto viewTensor = ov::make_tensor(
levelZeroTensor->get_element_type(),
- levelZeroTensor->get_shape(),
+ userTensor.at(i)->get_shape(),
static_cast<unsigned char*>(levelZeroTensor->data()) + (i * userTensor.at(i)->get_byte_size()));
userTensor.at(i)->copy_to(viewTensor);
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
index 9d9a1d2e9ad..9b7a32d26b6 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/dynamic_graph.hpp
@@ -31,6 +31,11 @@ public:
return true;
}
+ // HostCompile has no fixed plugin-side batch size; return nullopt for the shared import path.
+ const std::optional<std::size_t> get_batch_size() const override {
+ return std::nullopt;
+ }
+
~DynamicGraph() override;
const NetworkMetadata& get_metadata() const override;
@@ -41,10 +46,6 @@ public:
void set_workload_type(const ov::WorkloadType workloadType) override;
void set_model_priority(const ov::hint::Priority modelPriority) 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;
@@ -59,8 +60,6 @@ private:
void initialize_impl(const FilteredConfig& config) override;
bool release_blob(const FilteredConfig& config);
- std::optional<size_t> determine_batch_size();
-
void initialize_engine();
void create_execution_engine();
void prepare_metadata();
@@ -88,12 +87,6 @@ private:
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;
-
Logger _logger;
npu_vm_runtime_handle_t _engine = nullptr;
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
index afcabbbd3c2..8fec1b9b31f 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/dynamic_graph.cpp
@@ -5,8 +5,8 @@
#include "dynamic_graph.hpp"
#include <array>
-#include <iostream>
#include <iterator>
+#include <ostream>
#include "compiler_impl.hpp"
#include "intel_npu/common/compiler_adapter_factory.hpp"
@@ -16,7 +16,6 @@
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_cmd_queue_pool.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
-#include "openvino/runtime/make_tensor.hpp"
namespace intel_npu {
@@ -67,7 +66,7 @@ static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,
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
+ // We need to keep batch dimension dynamic
shapeFromIRModel.push_back(ov::Dimension(1, dynamicDim));
} else {
shapeFromIRModel.push_back(ov::Dimension(1, shapeFromCompiler[id]));
@@ -370,8 +369,6 @@ void DynamicGraph::initialize_impl(const FilteredConfig& config) {
_logger.debug("Graph initialize finish");
- _batchSize = determine_batch_size();
-
// To ensure that the initialization of the graph does not exit prematurely due to nullptrs
_init_completed.store(true, std::memory_order_release);
}
@@ -381,10 +378,6 @@ bool DynamicGraph::release_blob(const FilteredConfig& config) {
return false;
};
-void DynamicGraph::set_batch_size(std::size_t batch) {
- _batchSize = batch;
-}
-
uint32_t DynamicGraph::get_unique_id() {
return _uniqueId++;
}
@@ -397,62 +390,6 @@ uint32_t DynamicGraph::get_last_submitted_id() const {
return _lastSubmittedId;
}
-std::optional<size_t> DynamicGraph::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> DynamicGraph::get_batch_size() const {
- return _batchSize;
-}
-
DynamicGraph::~DynamicGraph() {
if (!_lastSubmittedEvent.empty()) {
_lastSubmittedEvent.clear();
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp
index 86d7d68a7fe..0a2053251e9 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp
@@ -73,34 +73,11 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<con
const FilteredConfig& config) const {
OV_ITT_TASK_CHAIN(COMPILE_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "compile");
- // specify HostCompile_Interpreter mode for dynamic model (inputs and outputs both dynamic) if NPU_COMPILATION_MODE
- // is not set
- FilteredConfig effectiveConfig = config;
- if (!config.has<COMPILATION_MODE>() &&
- !(config.has<DYNAMIC_SHAPE_TO_STATIC>() && config.get<DYNAMIC_SHAPE_TO_STATIC>())) {
- const auto isDynamic = [](const auto& port) {
- auto& shape = port.get_partial_shape();
- return shape.is_dynamic() && (shape.rank().get_length() == 4) && shape[0].is_static();
- };
-
- if (model) {
- const auto& inputs = model->inputs();
- const auto& outputs = model->outputs();
- const bool inputsDynamic = std::any_of(inputs.begin(), inputs.end(), isDynamic);
- const bool outputsDynamic = std::any_of(outputs.begin(), outputs.end(), isDynamic);
- if (inputsDynamic && outputsDynamic) {
- _logger.info("NPU_COMPILATION_MODE not set; selecting 'HostCompile_Interpreter' "
- "for fully-dynamic model (inputs and outputs both dynamic)");
- effectiveConfig.update({{ov::intel_npu::compilation_mode.name(), "HostCompile_Interpreter"}});
- }
- }
- }
-
_logger.debug("compile start");
- auto [tensor, compatibilityDescriptor] = _compiler->compile(model, effectiveConfig);
+ auto [tensor, compatibilityDescriptor] = _compiler->compile(model, config);
_logger.debug("compile end");
- const auto& compilationMode = effectiveConfig.get<COMPILATION_MODE>();
+ const auto& compilationMode = config.get<COMPILATION_MODE>();
const bool isHostCompile = compilationMode.find("HostCompile") != std::string::npos;
const BlobType blobType =
isHostCompile ? (compilationMode.find("HostCompile_Interpreter") != std::string::npos ? BlobType::BYTECODE
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index f704efb591a..e39f0d37cc9 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -365,6 +365,48 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
localConfig.update({{ov::intel_npu::batch_mode.name(), strStream.str()}});
};
+ // Resolve HostCompile before batching so the selected mode controls subsequent model and batch handling.
+ if (compilerType == ov::intel_npu::CompilerType::PLUGIN && !localConfig.has<COMPILATION_MODE>() &&
+ !localConfig.get<DYNAMIC_SHAPE_TO_STATIC>()) {
+ // HostCompile allocates dynamic buffers from I/O upper bounds, so every dynamic dimension must be bounded.
+ const auto hasFiniteUpperBounds = [](const auto& port) {
+ const auto& shape = port.get_partial_shape();
+ const auto rank = shape.rank();
+ return rank.is_static() && std::all_of(shape.begin(), shape.end(), [](const ov::Dimension& dimension) {
+ return dimension.get_interval().has_upper_bound();
+ });
+ };
+
+ // Detect a bounded dynamic 4D I/O port that makes the model a HostCompile candidate.
+ const auto isDynamicHostCompilePort = [&hasFiniteUpperBounds](const auto& port) {
+ const auto& shape = port.get_partial_shape();
+ const auto rank = shape.rank();
+ return shape.is_dynamic() && rank.is_static() && rank.get_length() == 4 && hasFiniteUpperBounds(port);
+ };
+
+ const auto& modelInputs = model->inputs();
+ const auto& modelOutputs = model->outputs();
+ const bool inputsDynamic = std::any_of(modelInputs.begin(), modelInputs.end(), isDynamicHostCompilePort);
+ const bool outputsDynamic = std::any_of(modelOutputs.begin(), modelOutputs.end(), isDynamicHostCompilePort);
+
+ // Candidate detection above uses any_of; validate every I/O separately because one unrelated unbounded port
+ // still prevents HostCompile from allocating all dynamic buffers.
+ const bool allPortsHaveFiniteUpperBounds =
+ std::all_of(modelInputs.begin(), modelInputs.end(), hasFiniteUpperBounds) &&
+ std::all_of(modelOutputs.begin(), modelOutputs.end(), hasFiniteUpperBounds);
+ if (inputsDynamic && outputsDynamic && allPortsHaveFiniteUpperBounds) {
+ _logger.info("NPU_COMPILATION_MODE not set; selecting 'HostCompile_Interpreter' "
+ "for fully-dynamic model (inputs and outputs both dynamic)");
+ localConfig.update({{ov::intel_npu::compilation_mode.name(), "HostCompile_Interpreter"}});
+ }
+ }
+
+ // Read the default or explicit compilation mode so automatic and user-selected HostCompile take the same path.
+ // HostCompile dynamic models retain their dynamic dimensions for the VM runtime instead of plugin debatching.
+ const bool useDynamicGraphForDynamicModel = model->is_dynamic() &&
+ compilerType == ov::intel_npu::CompilerType::PLUGIN &&
+ localConfig.get<COMPILATION_MODE>().find("HostCompile") == 0;
+
// Handle batch mode configuration
std::optional<ov::Dimension> originalBatch = std::nullopt;
std::shared_ptr<ov::Model> batchedModel;
@@ -378,18 +420,24 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
updateBatchMode(ov::intel_npu::BatchMode::AUTO);
}
- // Handle models with variables (states)
- if (!model->get_variables().empty()) {
- if (localConfig.get<BATCH_MODE>() == ov::intel_npu::BatchMode::PLUGIN) {
- OPENVINO_THROW(
- "This model contains states, thus it is not supported when handling batching on the plugin");
- }
+ if (useDynamicGraphForDynamicModel) {
+ // Preserve the dynamic model for HostCompile by skipping plugin-side batching.
+ _logger.info("HostCompile compilation bypasses plugin-side batch handling.");
updateBatchMode(ov::intel_npu::BatchMode::COMPILER);
+ } else {
+ // Handle models with variables (states)
+ if (!model->get_variables().empty()) {
+ if (localConfig.get<BATCH_MODE>() == ov::intel_npu::BatchMode::PLUGIN) {
+ OPENVINO_THROW(
+ "This model contains states, thus it is not supported when handling batching on the plugin");
+ }
+ updateBatchMode(ov::intel_npu::BatchMode::COMPILER);
+ }
+ shouldHandleBatching = true;
}
- shouldHandleBatching = true;
} else {
// If the model contains states, it is not supported when handling batching on the plugin
- shouldHandleBatching = model->get_variables().empty();
+ shouldHandleBatching = !useDynamicGraphForDynamicModel && model->get_variables().empty();
}
if (shouldHandleBatching) {
@@ -404,7 +452,8 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
!intel_npu::batch_helpers::checkModelDynamicDims(model),
"Dynamic shape tensors are not supported with the dynamic strides feature (ENABLE_STRIDES_FOR).");
- OPENVINO_ASSERT(successfullyDebatched || !localConfig.isAvailable(ov::intel_npu::batch_mode.name()) ||
+ OPENVINO_ASSERT(useDynamicGraphForDynamicModel || successfullyDebatched ||
+ !localConfig.isAvailable(ov::intel_npu::batch_mode.name()) ||
localConfig.get<BATCH_MODE>() != ov::intel_npu::BatchMode::COMPILER,
"Dynamic batching is not supported with the dynamic strides feature (ENABLE_STRIDES_FOR).");
}
@@ -502,7 +551,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
std::optional<int64_t> batch = std::nullopt;
if (originalBatch.has_value() && successfullyDebatched) {
batch = originalBatch.value().is_static() ? originalBatch.value().get_length() : -1;
- if (batch > 0) {
+ if (batch > 0 && !graph->is_dynamic()) {
// Initial batch setup for static cases
graph->set_batch_size(batch.value());
}
diff --git a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
index ec91acb6391..a466c100c64 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/dynamic_host_pipeline/infer_with_host_compile.cpp
@@ -77,10 +77,10 @@ inline std::shared_ptr<ov::Model> createMaxPoolModel(bool dynamicBatch = false,
return model;
}
-inline std::shared_ptr<ov::Model> createCustomNetModel() {
- auto input = std::make_shared<ov::op::v0::Parameter>(
- ov::element::f16,
- ov::PartialShape{1, 16, ov::Dimension(1, 1080), ov::Dimension(10, 1920)});
+inline std::shared_ptr<ov::Model> createCustomNetModel(bool dynamicBatch = false) {
+ const ov::Dimension batchDimension = dynamicBatch ? ov::Dimension(1, 10) : ov::Dimension(1);
+ const ov::PartialShape inputShape{batchDimension, 16, ov::Dimension(1, 1080), ov::Dimension(10, 1920)};
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, inputShape);
input->set_friendly_name("Parameter_59");
auto make_conv_add = [](const ov::Output<ov::Node>& data,
@@ -342,6 +342,9 @@ std::shared_ptr<ov::Model> InferWithHostCompileTests::createModelByName(const st
if (modelName == "CustomNet") {
return createCustomNetModel();
}
+ if (modelName == "CustomNet_DynBatch") {
+ return createCustomNetModel(true);
+ }
if (modelName == "MaxPool") {
return createMaxPoolModel();
}
@@ -681,6 +684,76 @@ TEST_P(InferWithHostCompileTests, CompileAndInferWithZeroTensor) {
<< logCapture.str();
}
+TEST_P(InferWithHostCompileTests, DynamicBatchUsesOneVMExecution) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ if (!isTargetDevice) {
+ GTEST_SKIP() << "Skip test for current device";
+ }
+ // MaxPool dynamic models contain operators that are not yet supported by the dynamic pipeline.
+ // CustomNet_DynBatch is used to verify aggregation of N=1 tensors into one N=2 VM execution.
+ if (selectedModelName != "CustomNet_DynBatch") {
+ GTEST_SKIP() << "Only applies to the dynamic-batch model";
+ }
+
+ auto model = createModelByName(selectedModelName);
+ ScopedLogCapture logCapture;
+
+ core->set_property("NPU", ov::log::level(ov::log::Level::DEBUG));
+ auto setupResult = prepareRuntimeCompareContext(model);
+ if (setupResult.status == RuntimeCompareStatus::fail) {
+ FAIL() << setupResult.message;
+ }
+ if (setupResult.status == RuntimeCompareStatus::skip) {
+ GTEST_SKIP() << setupResult.message;
+ }
+ auto& testContext = setupResult.context;
+
+ ov::InferRequest reqDynamic1 = testContext.compiledModel.create_infer_request();
+ ov::InferRequest reqReference1 = testContext.referenceCompiledModel.create_infer_request();
+
+ // A single N=2 tensor must execute as one dynamic VM inference.
+ const ov::Shape batchShape = {2, 720, 1280, 16};
+ auto fullBatchTensor =
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), batchShape, 100, 0);
+ setInputInferAndCompare(model,
+ reqDynamic1,
+ reqReference1,
+ fullBatchTensor,
+ "DynamicBatchUsesOneVMExecution_full_batch");
+ ASSERT_EQ(reqDynamic1.get_tensor(model->output()).get_shape(), batchShape);
+
+ const auto countVMExecutions = [](const std::string& log) {
+ constexpr std::string_view marker = "Start to execute graph with runtime engine";
+ size_t count = 0;
+ size_t position = 0;
+ while ((position = log.find(marker, position)) != std::string::npos) {
+ ++count;
+ position += marker.size();
+ }
+ return count;
+ };
+ ASSERT_EQ(countVMExecutions(logCapture.str()), 1u) << logCapture.str();
+
+ logCapture.clear();
+ // Two N=1 tensors must be aggregated into one N=2 inference rather than executed separately.
+ const ov::Shape singleBatchShape = {1, 720, 1280, 16};
+ std::vector<ov::Tensor> tensorBatch;
+ tensorBatch.push_back(
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), singleBatchShape, 100, 0));
+ tensorBatch.push_back(
+ ov::test::utils::create_and_fill_tensor(model->input().get_element_type(), singleBatchShape, 100, 100));
+ OV_ASSERT_NO_THROW(reqDynamic1.set_tensors(testContext.compiledModel.input(), tensorBatch));
+ OV_ASSERT_NO_THROW(reqReference1.set_tensors(testContext.referenceCompiledModel.input(), tensorBatch));
+ OV_ASSERT_NO_THROW(reqDynamic1.infer());
+ OV_ASSERT_NO_THROW(reqReference1.infer());
+ ASSERT_EQ(reqDynamic1.get_tensor(model->output()).get_shape(), batchShape);
+ ov::test::utils::compare(reqReference1.get_tensor(model->output()),
+ reqDynamic1.get_tensor(model->output()),
+ model->output().get_element_type());
+
+ ASSERT_EQ(countVMExecutions(logCapture.str()), 1u) << logCapture.str();
+}
+
using InferWithDefaultHostCompileTests = InferWithHostCompileTests;
inline bool isByteCodeBlob(const std::string& blob) {
@@ -752,10 +825,22 @@ const std::vector<ov::AnyMap> configs = {
{"NPU_COMPILER_TYPE", "PLUGIN"},
{"NPU_COMPILATION_MODE", "HostCompile_Interpreter"},
},
+ {
+ {"NPU_COMPILER_TYPE", "PLUGIN"},
+ {"NPU_COMPILATION_MODE", "HostCompile_Interpreter"},
+ {"NPU_CREATE_EXECUTOR", "0"},
+ {"NPU_BATCH_MODE", "PLUGIN"},
+ },
+ {
+ {"NPU_COMPILER_TYPE", "PLUGIN"},
+ {"NPU_COMPILATION_MODE", "HostCompile_Interpreter"},
+ {"NPU_BATCH_MODE", "PLUGIN"},
+ },
};
-// Ensure the added test model's input and output shapes are identical and accept concrete NHWC shapes for reuse shape in tests.
-const std::vector<std::string> modelNames = {"CustomNet", "MaxPool"};
+// Ensure the added test model's input and output shapes are identical and accept concrete NHWC shapes for reuse shape
+// in tests.
+const std::vector<std::string> modelNames = {"CustomNet", "CustomNet_DynBatch", "MaxPool"};
INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,
InferWithHostCompileTests,
@@ -768,7 +853,12 @@ const std::vector<ov::AnyMap> defaultHostCompileconfigs = {
{
{"NPU_COMPILER_TYPE", "PLUGIN"},
{"NPU_CREATE_EXECUTOR", "0"},
- }
+ },
+ {
+ {"NPU_COMPILER_TYPE", "PLUGIN"},
+ {"NPU_CREATE_EXECUTOR", "0"},
+ {"NPU_BATCH_MODE", "PLUGIN"},
+ },
};
const std::vector<std::string> defaultHCModelNames = {"MaxPool_NCHW", "MaxPool_NCHW_DynBatch"};
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.xml
index 100920cbbc5..99d64edba28 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
@@ -373,4 +373,38 @@ Example:
</filters>
</skip_config>
+ <!-- C#191823 -->
+ <skip_config>
+ <message>HostCompile cannot compile the dynamic Add model because AdjustScaleShiftForDWConv requires static Reshape shapes.</message>
+ <enable_rules>
+ <device>4000</device>
+ <device>5010</device>
+ </enable_rules>
+ <filters>
+ <filter>.*DynamicBatchingTests.DynamicCheckMultipleBatchingRun0.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchingTests.DynamicCheckMultipleBatchingRunsSeq.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.DynamicSetInputRemoteTensorsMultipleInfer.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.DynamicSetInputRemoteTensorsDynamicBatchInflation.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.DynamicSetInputRemoteTensorsDynamicBatchDeflation.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.SetInputRemoteSingleBatchedTensorSingleInfer.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.SetInputRemoteSingleBatchedTensorSingleInferWithExportImport.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.SetInputRemoteSingleBatchedTensorDynamicBatchInflation.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.SetInputRemoteSingleBatchedTensorDynamicBatchInflationWithExportImport.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.SetInputRemoteSingleBatchedTensorDynamicBatchDeflation.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*DynamicBatchedTensorsRunTests.DynamicSetInputDifferentTensorsMultipleInfer.*NPU_BATCH_MODE_PLUGIN.*</filter>
+ <filter>.*RoiTensorsTestsRun.RunStridedTensorWithDynamicBoundedBatching.*</filter>
+ </filters>
+ </skip_config>
+
+ <skip_config>
+ <message>HostCompile cannot compile the dynamic MaxPool model because ConvertBatchedLayerTo1N requires static AffineReshape shapes.</message>
+ <enable_rules>
+ <device>4000</device>
+ <device>5010</device>
+ </enable_rules>
+ <filters>
+ <filter>.*InferWithDefaultHostCompileTests.CompileDynamicModelWithNoHostCompileMode.*model=MaxPool_NCHW_DynBatch.*</filter>
+ </filters>
+ </skip_config>
+
</skip_configs>