OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPU] Fix debatch issue and validate batch size on import path (#39950)
Bogdan Pereanue129bee452a4
diff --git a/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hppindex 192fea5a366..71637bc4e1f 100644--- a/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp+++ b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp@@ -92,7 +92,7 @@ private:/*** @brief If a batch size a stored, this method will be used to extract it.*/- virtual std::optional<int> extract_batch_size() const = 0;+ virtual std::optional<int64_t> extract_batch_size() const = 0;/*** @brief If input/output layouts were stored, this method will be used to extract them.@@ -111,7 +111,7 @@ private:* @brief A potential source of weights for weights separation. Can be `nullptr`.*/std::shared_ptr<const ov::Model> m_original_model;- std::optional<int> m_batch_size;+ std::optional<int64_t> m_batch_size;std::shared_ptr<IGraph> m_graph;};@@ -148,6 +148,24 @@ namespace blob_format_importer_utils {*/void validate_main_schedule_descriptors(const NetworkMetadata& metadata);+/**+ * @brief Checks that the batch size declared by the blob metadata is consistent with the compiled schedule.+ * @details A batch size, either static (greater than 0) or dynamic ("utils::DYNAMIC_BATCH_SIZE"), means that the+ * batching is handled by the plugin: the model has been compiled with a batch of 1 and the plugin runs the schedule+ * once per batch slice. Therefore, every I/O descriptor is expected to have a static batch dimension equal to 1 in the+ * compiled schedule (so no dynamic rank, scalar or dynamic batch dimension is accepted), and no state or shape tensor+ * descriptor is expected, as these cannot be combined with the plugin batching. Dynamic dimensions other than the batch+ * are accepted. The main schedule weights are not checked.+ *+ * @param metadata The I/O descriptors of the main schedule.+ * @param batch_size The batch size declared by the blob metadata, if any. No value means that the batching is not+ * handled by the plugin and nothing is checked. "utils::DYNAMIC_BATCH_SIZE" marks a dynamic batch, which is checked+ * as a static one.+ * @throws ov::Exception if the batch size is 0 or lower than "utils::DYNAMIC_BATCH_SIZE", or if a descriptor+ * doesn't have a static compiled batch dimension equal to 1.+ */+void validate_batch_size(const NetworkMetadata& metadata, const std::optional<int64_t>& batch_size);+} // namespace blob_format_importer_utils} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cppindex d32b228e454..8341ea0bc03 100644--- a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp+++ b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp@@ -86,7 +86,7 @@ void decrypt_payload(ov::Tensor& payload, const ov::EncryptionCallbacks& encrypt*/std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& inputDescriptors,const std::vector<IODescriptor>& outputDescriptors,- const std::optional<int> batchSize,+ const std::optional<int64_t> batchSize,const std::optional<std::vector<ov::Layout>>& inputLayouts,const std::optional<std::vector<ov::Layout>>& outputLayouts) {ov::ParameterVector parameters;@@ -215,7 +215,7 @@ private:* @note N/A* @return Always std::nullopt*/- std::optional<int> extract_batch_size() const override {+ std::optional<int64_t> extract_batch_size() const override {return std::nullopt;}@@ -326,13 +326,12 @@ private:return init_schedules;}- std::optional<int> extract_batch_size() const override {+ std::optional<int64_t> extract_batch_size() const override {const std::optional<int64_t> batch_size = m_metadata->get_batch_size();if (batch_size.has_value()) {- m_logger.debug("Extracted batch size: %d", batch_size.value());- return std::make_optional<int>(static_cast<int>(batch_size.value()));+ m_logger.debug("Extracted batch size: %lld", static_cast<long long>(batch_size.value()));}- return std::nullopt;+ return batch_size;}std::optional<std::pair<std::vector<ov::Layout>, std::vector<ov::Layout>>> extract_layouts() const override {@@ -436,6 +435,7 @@ std::shared_ptr<IGraph> IBlobFormatImporter::create_graph(const ov::SoPtr<IEnginm_graph->update_network_name(network_name);blob_format_importer_utils::validate_main_schedule_descriptors(m_graph->get_metadata());+ blob_format_importer_utils::validate_batch_size(m_graph->get_metadata(), m_batch_size);if (m_batch_size.has_value() && m_batch_size.value() > 0) {// Initial batch setup for static casesm_graph->set_batch_size(m_batch_size.value());@@ -513,6 +513,65 @@ void validate_main_schedule_descriptors(const NetworkMetadata& metadata) {check_descriptors(metadata.outputs);}+void validate_batch_size(const NetworkMetadata& metadata, const std::optional<int64_t>& batch_size) {+ if (!batch_size.has_value()) {+ return;+ }++ // Any non-positive value other than the dynamic batch marker cannot be produced by a valid export.+ OPENVINO_ASSERT(batch_size.value() > 0 || batch_size.value() == utils::DYNAMIC_BATCH_SIZE,+ "The blob metadata declares an invalid batch size: ",+ batch_size.value());++ // The schedule is compiled with a batch of 1 for both a static and a dynamic batch handled by the plugin. The+ // plugin runs it once per batch slice, advancing the I/O buffers by one slice per execution, so a descriptor which+ // is not batched would be written out of bounds when the actual batch is greater than 1.+ const std::string declared_batch_size = batch_size.value() == utils::DYNAMIC_BATCH_SIZE+ ? "a dynamic batch size"+ : "a batch size of " + std::to_string(batch_size.value());++ auto check_descriptors = [&declared_batch_size](const std::vector<IODescriptor>& descriptors, const char* kind) {+ for (const IODescriptor& descriptor : descriptors) {+ // States and shape tensors cannot be combined with the plugin batching: models with variables or with+ // dynamic dimensions other than the batch are compiled by the compiler as a whole+ OPENVINO_ASSERT(!descriptor.isStateInput && !descriptor.isStateOutput && !descriptor.isShapeTensor,+ "The blob metadata declares ",+ declared_batch_size,+ ", but the ",+ kind,+ " \"",+ descriptor.nameFromCompiler,+ "\" is a ",+ descriptor.isShapeTensor ? "shape tensor" : "state",+ ", which is not supported when batching is handled by the plugin");++ // The weights of the main schedule have nothing to do with the batch. The init schedule weights are+ // rejected by "validate_main_schedule_descriptors".+ if (descriptor.isMainInputWeights) {+ continue;+ }++ const ov::PartialShape& shape = descriptor.shapeFromCompiler;+ // Every descriptor must have a static batch of 1: a dynamic rank, a scalar or a dynamic batch dimension+ // means there is no batch slice to advance over. Dynamic dimensions other than the batch are accepted.+ OPENVINO_ASSERT(shape.rank().is_static() && shape.size() > 0 && shape[utils::BATCH_AXIS].is_static() &&+ static_cast<size_t>(shape[utils::BATCH_AXIS].get_length()) == utils::DEFAULT_BATCH_SIZE,+ "The blob metadata declares ",+ declared_batch_size,+ ", but the ",+ kind,+ " \"",+ descriptor.nameFromCompiler,+ "\" was compiled with the shape ",+ shape.to_string(),+ ". Batching on the plugin requires a batch of 1 in the compiled schedule");+ }+ };++ check_descriptors(metadata.inputs, "input");+ check_descriptors(metadata.outputs, "output");+}+} // namespace blob_format_importer_utils} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex e52d35d8e7f..1e560d84c95 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -477,7 +477,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;+ batch = originalBatch.value().is_static() ? originalBatch.value().get_length() : utils::DYNAMIC_BATCH_SIZE;if (batch > 0 && graph->get_kind() != GraphKind::Dynamic) {// Initial batch setup for static casesgraph->set_batch_size(batch.value());diff --git a/src/plugins/intel_npu/src/plugin/src/transformations.cpp b/src/plugins/intel_npu/src/plugin/src/transformations.cppindex 008d038509a..72d526227f4 100644--- a/src/plugins/intel_npu/src/plugin/src/transformations.cpp+++ b/src/plugins/intel_npu/src/plugin/src/transformations.cpp@@ -175,9 +175,12 @@ bool validateModelBatch(const std::shared_ptr<const ov::Model>& model, Logger lo}auto node_info_printer = [&logger](const auto& ov_node, std::string nodeType) {+ // The tensors are not required to have names, "get_any_name" throws in such a case+ const std::string name =+ ov_node.get_names().empty() ? ov_node.get_node()->get_friendly_name() : ov_node.get_any_name();logger.info("%s: %s has shape value: %s",nodeType.c_str(),- ov_node.get_any_name().c_str(),+ name.c_str(),ov_node.get_partial_shape().to_string().c_str());};@@ -269,6 +272,87 @@ std::tuple<std::shared_ptr<ov::Model>, bool> handlePluginBatching(logger.info("The model has been debatched successfully");successfullyDebatched = true;}++ // Only the ports of the model are validated below, not the operations between them: the plugin assumes that+ // the graph treats the batch slices independently, as it runs the schedule once per slice. An operation acting+ // along the batch axis which keeps the shapes of the ports (e.g. a Softmax on the axis 0) is not detected.+ //+ // validateModelBatch is heuristic (0th dim != 1), so a port which does not depend on the batch is wrongly+ // considered batched, e.g.:+ // - a ShapeOf result of shape [2] while the batch is 2;+ // - an input without the batch layout, as "ov::set_batch" reshapes only the inputs which have one.+ // Make sure every input and output actually ended up with batch 1 after reshaping, otherwise the compiled+ // schedule would not match the batch size expected by the plugin. A port which became a scalar (e.g. a Squeeze+ // removing the batch dimension of an input reshaped to batch 1) has no batch dimension at all, thus it is not+ // batched either. A batch dimension which is still dynamic was not set to 1 either (e.g. an input without the+ // batch layout, which keeps its bounds), so the schedule would not be compiled with a batch of 1.+ const auto isNotDebatched = [](const ov::PartialShape& shape) {+ if (shape.rank().is_dynamic()) {+ return false;+ }+ if (shape.size() == 0) {+ return true;+ }+ const auto& batchDimension = shape[intel_npu::utils::BATCH_AXIS];+ return batchDimension.is_dynamic() ||+ static_cast<size_t>(batchDimension.get_length()) != intel_npu::utils::DEFAULT_BATCH_SIZE;+ };++ const auto& parameters = resultModel->get_parameters();+ const auto notDebatchedInput =+ std::find_if(parameters.begin(), parameters.end(), [&isNotDebatched](const auto& parameter) {+ return isNotDebatched(parameter->get_partial_shape());+ });+ if (notDebatchedInput != parameters.end()) {+ OPENVINO_THROW("The input \"",+ (*notDebatchedInput)->get_friendly_name(),+ "\" has the shape ",+ (*notDebatchedInput)->get_partial_shape().to_string(),+ " after the model was reshaped to batch size 1, thus its batch was not changed.");+ }++ const auto& results = resultModel->get_results();+ const auto notDebatchedOutput =+ std::find_if(results.begin(), results.end(), [&isNotDebatched](const auto& result) {+ return isNotDebatched(result->get_output_partial_shape(0));+ });+ if (notDebatchedOutput != results.end()) {+ OPENVINO_THROW("The output \"",+ (*notDebatchedOutput)->get_friendly_name(),+ "\" has the shape ",+ (*notDebatchedOutput)->get_output_partial_shape(0).to_string(),+ " after the model was reshaped to batch size 1, thus it is not batched.");+ }++ // Only the batch dimension of an output is expected to change when the inputs are reshaped. If anything else+ // changed, the output does not have the batch as an independent leading dimension (e.g. MatMul(A, B^T) of two+ // batched inputs, where [4, 4] becomes [1, 1]), so running the schedule once per batch slice and stacking the+ // results does not give the output of the original model.+ const auto& originalResults = model->get_results();+ OPENVINO_ASSERT(originalResults.size() == results.size(),+ "The debatched model has a different number of outputs than the original one");+ for (size_t i = 0; i < results.size(); ++i) {+ const auto& originalShape = originalResults[i]->get_output_partial_shape(0);+ const auto& debatchedShape = results[i]->get_output_partial_shape(0);+ if (originalShape.rank().is_dynamic() || debatchedShape.rank().is_dynamic()) {+ continue;+ }++ bool onlyBatchChanged = originalShape.size() == debatchedShape.size();+ for (size_t dim = 1; onlyBatchChanged && dim < originalShape.size(); ++dim) {+ onlyBatchChanged = originalShape[dim] == debatchedShape[dim];+ }+ if (!onlyBatchChanged) {+ OPENVINO_THROW("The output \"",+ results[i]->get_friendly_name(),+ "\" has the shape ",+ debatchedShape.to_string(),+ " after the model was reshaped to batch size 1, while it was ",+ originalShape.to_string(),+ ", thus it is not batched independently.");+ }+ }+if (batchModeIsAvailable) {// If we have successfully debatched the model on the PLUGIN side, we should// avoid repeating the same in the compiler by resetting the batch mode@@ -278,6 +362,9 @@ std::tuple<std::shared_ptr<ov::Model>, bool> handlePluginBatching(} catch (const std::exception& ex) {// If plugin-side transformation failed, keep the original model and drop the cloneresultModel = std::const_pointer_cast<ov::Model>(model);+ // The model is left untouched, so the caller must not consider it debatched+ successfullyDebatched = false;+ originalBatch = std::nullopt;if (effectiveBatchMode == ov::intel_npu::BatchMode::AUTO) {logger.info("Couldn't validate and reshape the model. Batching will be handled by compiler. Error: %s",ex.what());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.hppindex da67c0274ca..1efc6fad9cc 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@@ -4,6 +4,7 @@#pragma once+#include <cstdint>#include <iostream>#include "openvino/runtime/allocator.hpp"@@ -17,6 +18,13 @@ constexpr std::size_t STANDARD_PAGE_SIZE = 4096;constexpr std::size_t DEFAULT_BATCH_SIZE = 1;constexpr std::size_t BATCH_AXIS = 0;+/**+ * @brief Batch size value stored by the plugin for a model whose batch is dynamic (e.g. an "ov::Dimension" with bounds)+ * and handled by the plugin. The batch size is known only at inference time in this case. It is also stored in the+ * blob metadata, where the absence of a batch size is encoded as 0.+ */+constexpr std::int64_t DYNAMIC_BATCH_SIZE = -1;+struct AlignedAllocator {public:AlignedAllocator(const size_t align_size) : _align_size(align_size) {}diff --git a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.cpp b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.cppindex 4ac5b80817c..47e267024e8 100644--- a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.cpp@@ -112,6 +112,18 @@ inline std::shared_ptr<ov::Model> createCustomNetModel(bool dynamicBatch = falsereturn model;}+// The tensors of the model intentionally have no names: the plugin batching must not depend on them+inline std::shared_ptr<ov::Model> createPluginBatchedModel(const ov::Dimension& batch) {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{batch, 2, 2, 2});+ input->set_friendly_name("tensor_input");+ input->set_layout("N...");+ auto bias = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 2, 2}, {1.f});+ auto add = std::make_shared<ov::op::v1::Add>(input, bias);+ auto result = std::make_shared<ov::op::v0::Result>(add);+ result->set_friendly_name("tensor_output");+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input});+}+using OVCompiledGraphImportExportTestNPU = OVCompiledGraphImportExportTest;TEST_P(OVCompiledGraphImportExportTestNPU, CanImportModelWithApplicationHeaderAndTensorAPI) {@@ -252,6 +264,49 @@ TEST_P(OVCompiledGraphImportExportTestNPU, SameBlobAfterImportExport) {ASSERT_EQ(blob_stream.str(), test_blob_stream_2.str());}+TEST_P(OVCompiledGraphImportExportTestNPU, BatchHandledByPluginIsKeptAfterImportExport) {+ ov::Core core;++ try {+ (void)core.get_property(target_device, ov::intel_npu::batch_mode);+ } catch (...) {+ GTEST_SKIP() << "The batch mode is not supported by the compiler";+ }+ configuration[ov::intel_npu::batch_mode.name()] = ov::intel_npu::BatchMode::PLUGIN;++ // A static batch is stored in the blob as it is, while a dynamic one is stored as "-1". Both of them must be+ // restored at import, which is checked through the shapes of the imported model.+ // The tensors of the model intentionally have no names: the plugin batching must not depend on them.+ for (const ov::Dimension& batch : {ov::Dimension(4), ov::Dimension(1, 10)}) {+ SCOPED_TRACE("batch: " + batch.to_string());++ auto model = createPluginBatchedModel(batch);++ std::stringstream blob_stream;+ ov::CompiledModel compiled_model, imported_model;+ OV_ASSERT_NO_THROW(compiled_model = core.compile_model(model, target_device, configuration));+ OV_ASSERT_NO_THROW(compiled_model.export_model(blob_stream));+ OV_ASSERT_NO_THROW(imported_model = core.import_model(blob_stream, target_device, configuration));++ // The blob keeps only "-1" for a dynamic batch, so its upper bound is not restored at import: both shapes must+ // have a dynamic batch dimension, while the rest of the dimensions must be the same+ const auto check_shapes = [&batch](const ov::PartialShape& expected, const ov::PartialShape& actual) {+ if (batch.is_static()) {+ ASSERT_EQ(expected, actual);+ return;+ }+ ASSERT_EQ(expected.size(), actual.size());+ ASSERT_TRUE(expected[0].is_dynamic());+ ASSERT_TRUE(actual[0].is_dynamic());+ for (size_t i = 1; i < expected.size(); ++i) {+ ASSERT_EQ(expected[i], actual[i]);+ }+ };+ check_shapes(compiled_model.input(0).get_partial_shape(), imported_model.input(0).get_partial_shape());+ check_shapes(compiled_model.output(0).get_partial_shape(), imported_model.output(0).get_partial_shape());+ }+}+TEST_P(OVCompiledGraphImportExportTestNPU, ImportingEncryptedBlobThrows) {// Encryption callbacks require L0 graph ext version >= 1.17NPU_SKIP_IF_GRAPH_EXT_LOWER_THAN(1, 17);diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cppindex 649734cdca3..c6c648384b9 100644--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp@@ -380,12 +380,6 @@ TEST_P(BooleanPrecisionInferRequestRunTests, BooleanTensorDataTypesForBooleanModov::CompiledModel compiled_model_boolean, compiled_model_boolean_imported;std::shared_ptr<ov::InferRequest> infer_request_boolean, infer_request_boolean_imported;- try {- (void)core->get_property(target_device, ov::intel_npu::batch_mode);- } catch (...) {- configuration.erase(ov::intel_npu::batch_mode.name());- }-bool isPVDriver = (core->get_property(target_device, ov::intel_npu::driver_version) == 1688);bool isDriverCompiler =@@ -3391,19 +3385,10 @@ const std::vector<ov::AnyMap> configsInferRequestRunTests = {{}};const std::vector<ov::AnyMap> configsBooleanPrecisionInferRequestRunTests = {{{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::PLUGIN),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN),- // platform needed only for NPU_COMPILER_TYPE_PLUGIN- ov::intel_npu::platform(ov::intel_npu::Platform::standardize(- ov::test::utils::getTestsPlatformFromEnvironmentOr(ov::test::utils::DEVICE_NPU)))}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::PLUGIN),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER),// platform needed only for NPU_COMPILER_TYPE_PLUGINov::intel_npu::platform(ov::intel_npu::Platform::standardize(ov::test::utils::getTestsPlatformFromEnvironmentOr(ov::test::utils::DEVICE_NPU)))}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN)}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER)}}};+ {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER)}}};const std::vector<ov::AnyMap> configsWithDifferentNumStreamsTest = {{{ov::num_streams(0)}},{{ov::num_streams(2)}},diff --git a/src/plugins/intel_npu/tests/functional/internal/backend/zero_infer_request_tests.cpp b/src/plugins/intel_npu/tests/functional/internal/backend/zero_infer_request_tests.cppindex 427d49c2b17..c65c56edc80 100644--- a/src/plugins/intel_npu/tests/functional/internal/backend/zero_infer_request_tests.cpp+++ b/src/plugins/intel_npu/tests/functional/internal/backend/zero_infer_request_tests.cpp@@ -27,7 +27,6 @@#include "openvino/runtime/make_tensor.hpp"#include "plugin_compiler_adapter.hpp"#include "shared_test_classes/base/ov_behavior_test_utils.hpp"-#include "transformations.hpp"#include "zero_backend.hpp"#include "zero_infer_request.hpp"@@ -158,7 +157,6 @@ public:auto options = std::make_shared<::intel_npu::OptionsDesc>();options->add<::intel_npu::PLATFORM>();options->add<::intel_npu::COMPILER_TYPE>();- options->add<::intel_npu::BATCH_MODE>();options->add<::intel_npu::MODEL_SERIALIZER_VERSION>();npu_config = std::make_unique<::intel_npu::Config>(options);for (const auto& [propertyName, propertyValue] : configuration) {@@ -225,29 +223,7 @@ TEST_P(ZeroInferRequestTests, BooleanSetTensorSetTensorsWork) {::intel_npu::MODEL_SERIALIZER_VERSION::toString(ov::intel_npu::ModelSerializerVersion::ALL_WEIGHTS_COPY));}- // logic for batch- auto copy_model = ov_model;- std::optional<int64_t> batch = std::nullopt;- if (npu_config->has<::intel_npu::BATCH_MODE>() &&- npu_config->get<::intel_npu::BATCH_MODE>() == ov::intel_npu::BatchMode::PLUGIN) {- std::optional<ov::Dimension> originalBatch = std::nullopt;- auto [batchedModel, successfullyDebatched] = intel_npu::batch_helpers::handlePluginBatching(- ov_model,- [&](ov::intel_npu::BatchMode mode) {- npu_config->update(::intel_npu::BATCH_MODE::key().data(), ::intel_npu::BATCH_MODE::toString(mode));- },- std::make_optional(npu_config->get<::intel_npu::BATCH_MODE>()),- originalBatch,- ::intel_npu::Logger::global());- OPENVINO_ASSERT(successfullyDebatched, "Couldn't debatch test model!");- batch = originalBatch.value().get_length();- copy_model = batchedModel;- }-- auto graph = compiler->compile(copy_model, *npu_config, ::intel_npu::AdapterDescriptor{});- if (batch) {- graph->set_batch_size(batch.value());- }+ auto graph = compiler->compile(ov_model, *npu_config, ::intel_npu::AdapterDescriptor{});ov::AnyMap unknownProperties = ov::AnyMap{};auto compiledModel = std::make_shared<intel_npu::CompiledModel>(@@ -257,7 +233,7 @@ TEST_P(ZeroInferRequestTests, BooleanSetTensorSetTensorsWork) {graph,*npu_config,unknownProperties,- batch);+ std::nullopt);OPENVINO_ASSERT(compiledModel->inputs()[0].get_element_type() == element_type);OPENVINO_ASSERT(compiledModel->inputs()[1].get_element_type() == element_type);@@ -340,19 +316,10 @@ using namespace ov::test::behavior;const std::vector<ov::AnyMap> configs = {{{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::PLUGIN),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN),- // platform needed only for NPU_COMPILER_TYPE_PLUGIN- ov::intel_npu::platform(ov::intel_npu::Platform::standardize(- ov::test::utils::getTestsPlatformFromEnvironmentOr(ov::test::utils::DEVICE_NPU)))}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::PLUGIN),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER),// platform needed only for NPU_COMPILER_TYPE_PLUGINov::intel_npu::platform(ov::intel_npu::Platform::standardize(ov::test::utils::getTestsPlatformFromEnvironmentOr(ov::test::utils::DEVICE_NPU)))}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN)}},- {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER),- ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER)}}};+ {{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER)}}};const std::vector<ov::element::Type> specialTensorDataTypes = {ov::element::boolean};diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 015e0e57d5a..c1576349326 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -180,6 +180,7 @@ install(TARGETS ${TARGET_NAME}target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npu/executor_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npu/should_use_host_compile_interpreter_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npu/handle_plugin_batching_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npu/compiler_option_support_helper_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npu/device_helpers_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npu/option_support_cache_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cppindex 824f1b07dda..b60eab7adae 100644--- a/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp+++ b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp@@ -11,6 +11,7 @@#include <string_view>#include "common_test_utils/test_assertions.hpp"+#include "intel_npu/utils/utils.hpp"#include "metadata.hpp"#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"@@ -156,6 +157,7 @@ TEST_F(BlobFormatImportersTest, CannotCreateModelBeforeGraph) {}using blob_format_importer_utils::validate_main_schedule_descriptors;+using intel_npu::utils::DYNAMIC_BATCH_SIZE;namespace {@@ -192,3 +194,127 @@ TEST_F(BlobFormatImportersTest, MainScheduleRejectsInitWeightsDescriptors) {metadata.outputs.push_back(std::move(init_output));OV_EXPECT_THROW_HAS_SUBSTRING(validate_main_schedule_descriptors(metadata), ov::Exception, "init_output");}++/**+ * @brief A static or dynamic batch size declared by the metadata means that the schedule was compiled with a batch of 1+ */+TEST_F(BlobFormatImportersTest, BatchSizeRequiresBatchOfOneInCompiledSchedule) {+ NetworkMetadata metadata;+ metadata.inputs.push_back(create_descriptor("input", ov::Shape{1, 3}));+ metadata.outputs.push_back(create_descriptor("output", ov::Shape{1, 3}));++ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, 2));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE));+ // no batch size declared by the metadata means that the batching is not handled by the plugin+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, std::nullopt));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 0),+ ov::Exception,+ "invalid batch size");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE - 1),+ ov::Exception,+ "invalid batch size");++ // e.g. an output that does not depend on the batch, like the ShapeOf of a NonZero result+ metadata.outputs.push_back(create_descriptor("not_batched_output", ov::Shape{2}));+ // a dynamic batch is handled by the plugin in the same way as a static one, so the compiled schedule must have a+ // batch of 1 in this case as well, otherwise the outputs would be written out of bounds+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE),+ ov::Exception,+ "not_batched_output");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 2),+ ov::Exception,+ "not_batched_output");++ metadata.outputs.pop_back();+ metadata.inputs.push_back(create_descriptor("not_batched_input", ov::Shape{4, 3}));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 4),+ ov::Exception,+ "not_batched_input");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE),+ ov::Exception,+ "not_batched_input");++ // the weights of the main schedule are not batched, thus they are skipped+ metadata.inputs.pop_back();+ IODescriptor main_weights = create_descriptor("main_weights", ov::Shape{5});+ main_weights.isMainInputWeights = true;+ metadata.inputs.push_back(std::move(main_weights));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, 2));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE));+ metadata.inputs.pop_back();++ // states and shape tensors cannot be combined with the plugin batching+ IODescriptor shape_tensor = create_descriptor("shape_tensor", ov::Shape{1});+ shape_tensor.isShapeTensor = true;+ metadata.inputs.push_back(std::move(shape_tensor));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE),+ ov::Exception,+ "shape_tensor");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 2),+ ov::Exception,+ "shape_tensor");+ metadata.inputs.pop_back();++ IODescriptor state_input = create_descriptor("state_input", ov::Shape{1, 3});+ state_input.isStateInput = true;+ metadata.inputs.push_back(std::move(state_input));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 2),+ ov::Exception,+ "state_input");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE),+ ov::Exception,+ "state_input");+ metadata.inputs.pop_back();++ IODescriptor state_output = create_descriptor("state_output", ov::Shape{1, 3});+ state_output.isStateOutput = true;+ metadata.outputs.push_back(std::move(state_output));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, 2),+ ov::Exception,+ "state_output");+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE),+ ov::Exception,+ "state_output");+}++/**+ * @brief Dynamic dimensions other than the batch are accepted, as the batch is still 1 in the compiled schedule+ */+TEST_F(BlobFormatImportersTest, BatchSizeAcceptsDynamicDimensionsOtherThanBatch) {+ NetworkMetadata metadata;+ metadata.inputs.push_back(create_descriptor("input", ov::PartialShape{1, ov::Dimension(1, 10), -1}));+ metadata.outputs.push_back(create_descriptor("output", ov::PartialShape{1, ov::Dimension(1, 10)}));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, 2));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(metadata, DYNAMIC_BATCH_SIZE));+}++/**+ * @brief A declared batch requires every descriptor to have a static batch dimension of 1+ */+TEST_F(BlobFormatImportersTest, BatchSizeRejectsDescriptorsWithoutStaticBatchDimension) {+ const std::vector<std::pair<std::string, ov::PartialShape>> invalid_shapes = {+ {"dynamic_batch", ov::PartialShape{ov::Dimension(1, 10), 3}},+ {"unbounded_batch", ov::PartialShape{-1, 3}},+ {"dynamic_rank", ov::PartialShape::dynamic()},+ {"scalar", ov::PartialShape{}}};++ for (const auto& [name, shape] : invalid_shapes) {+ for (const int64_t batch_size : {int64_t{2}, DYNAMIC_BATCH_SIZE}) {+ NetworkMetadata input_metadata;+ input_metadata.inputs.push_back(create_descriptor(name, shape));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(input_metadata, batch_size),+ ov::Exception,+ name);++ NetworkMetadata output_metadata;+ output_metadata.outputs.push_back(create_descriptor(name, shape));+ OV_EXPECT_THROW_HAS_SUBSTRING(blob_format_importer_utils::validate_batch_size(output_metadata, batch_size),+ ov::Exception,+ name);++ // nothing is checked if no batch size is declared+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(input_metadata, std::nullopt));+ OV_ASSERT_NO_THROW(blob_format_importer_utils::validate_batch_size(output_metadata, std::nullopt));+ }+ }+}diff --git a/src/plugins/intel_npu/tests/unit/npu/handle_plugin_batching_test.cpp b/src/plugins/intel_npu/tests/unit/npu/handle_plugin_batching_test.cppnew file mode 100644index 00000000000..6131897ef11--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npu/handle_plugin_batching_test.cpp@@ -0,0 +1,303 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <memory>+#include <optional>+#include <vector>++#include "common_test_utils/test_assertions.hpp"+#include "intel_npu/utils/logger/logger.hpp"+#include "openvino/core/layout.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/non_zero.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/relu.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/runtime/intel_npu/properties.hpp"+#include "transformations.hpp"++using namespace intel_npu;++namespace {++// The tensors of the models used here intentionally have no names: the plugin batching must not depend on them.++std::shared_ptr<ov::Model> make_batched_relu_model(const ov::PartialShape& shape) {+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ param->set_layout("N...");+ auto relu = std::make_shared<ov::op::v0::Relu>(param);+ auto result = std::make_shared<ov::op::v0::Result>(relu);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param}, "batched_relu");+}++// The output is the shape of the NonZero result, so its shape is always [2] no matter what the batch is. When the batch+// is 2 as well, the output looks like a batched one, although it does not depend on the batch.+std::shared_ptr<ov::Model> make_not_batched_output_model(const ov::Shape& shape) {+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ param->set_layout("N...");+ auto nonZero = std::make_shared<ov::op::v3::NonZero>(param);+ auto shapeOf = std::make_shared<ov::op::v3::ShapeOf>(nonZero);+ auto result = std::make_shared<ov::op::v0::Result>(shapeOf);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param}, "not_batched_output");+}++// The input [4] with the layout "N" is reshaped to [1] when debatching, so the output of Squeeze, which removes all the+// dimensions equal to 1 when no axes are given, becomes a scalar, while it was [4] before.+std::shared_ptr<ov::Model> make_scalar_after_debatching_model(size_t batch) {+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{batch});+ param->set_layout("N");+ auto squeeze = std::make_shared<ov::op::v0::Squeeze>(param);+ auto result = std::make_shared<ov::op::v0::Result>(squeeze);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param}, "scalar_after_debatching");+}++// Both inputs have the batch in their leading dimension, but only the first one has the batch layout, so only this one+// is reshaped when debatching. The second input keeps the batch of 4, while the output becomes [1, 4].+std::shared_ptr<ov::Model> make_mixed_layout_model() {+ auto paramA = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 3});+ paramA->set_layout("N...");+ auto paramB = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 3});+ auto matMul = std::make_shared<ov::op::v0::MatMul>(paramA, paramB, false, true);+ auto result = std::make_shared<ov::op::v0::Result>(matMul);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{paramA, paramB}, "mixed_layout");+}++// Both inputs are reshaped when debatching, but the output of the MatMul with the transposed second input depends on+// the batch in both of its dimensions: it is [4, 4] in the given model and [1, 1] after debatching.+std::shared_ptr<ov::Model> make_two_layouts_matmul_model() {+ auto paramA = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 3});+ paramA->set_layout("N...");+ auto paramB = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 3});+ paramB->set_layout("N...");+ auto matMul = std::make_shared<ov::op::v0::MatMul>(paramA, paramB, false, true);+ auto result = std::make_shared<ov::op::v0::Result>(matMul);+ return std::make_shared<ov::Model>(ov::ResultVector{result},+ ov::ParameterVector{paramA, paramB},+ "two_layouts_matmul");+}++// Same as above, but with a bounded dynamic batch: the second input and the output keep the bounds of the batch+// ([1..10, 3]) after debatching, as only the first input is reshaped.+std::shared_ptr<ov::Model> make_dynamic_mixed_layout_model() {+ const ov::PartialShape shape{ov::Dimension(1, 10), 3};+ auto paramA = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ paramA->set_layout("N...");+ auto paramB = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ auto add = std::make_shared<ov::op::v1::Add>(paramA, paramB);+ auto result = std::make_shared<ov::op::v0::Result>(add);+ return std::make_shared<ov::Model>(ov::ResultVector{result},+ ov::ParameterVector{paramA, paramB},+ "dynamic_mixed_layout");+}++class HandlePluginBatchingTest : public ::testing::Test {+protected:+ std::tuple<std::shared_ptr<ov::Model>, bool> handle(const std::shared_ptr<const ov::Model>& model,+ std::optional<ov::intel_npu::BatchMode> batchMode) {+ return batch_helpers::handlePluginBatching(+ model,+ [this](ov::intel_npu::BatchMode mode) {+ updatedBatchModes.push_back(mode);+ },+ batchMode,+ originalBatch,+ Logger::global());+ }++ std::vector<ov::intel_npu::BatchMode> updatedBatchModes;+ std::optional<ov::Dimension> originalBatch;+};++} // namespace++TEST_F(HandlePluginBatchingTest, StaticBatchIsReshapedToOne) {+ const auto model = make_batched_relu_model({4, 3, 2, 2});++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_TRUE(successfullyDebatched);+ ASSERT_TRUE(originalBatch.has_value());+ ASSERT_EQ(originalBatch.value(), ov::Dimension(4));+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({1, 3, 2, 2}));+ ASSERT_EQ(resultModel->output(0).get_partial_shape(), ov::PartialShape({1, 3, 2, 2}));+ // The given model must not be modified+ ASSERT_EQ(model->input(0).get_partial_shape(), ov::PartialShape({4, 3, 2, 2}));+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, DynamicBoundedBatchIsReshapedToOne) {+ const auto model = make_batched_relu_model({ov::Dimension(1, 10), 3, 2, 2});++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_TRUE(successfullyDebatched);+ ASSERT_TRUE(originalBatch.has_value());+ ASSERT_TRUE(originalBatch->is_dynamic());+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({1, 3, 2, 2}));+ ASSERT_EQ(resultModel->output(0).get_partial_shape(), ov::PartialShape({1, 3, 2, 2}));+}++/**+ * @brief The output of this model is [2] before and after reshaping the input batch, which is 2 as well. Therefore, it+ * passes the validation of the batch, but it is not batched, so the model cannot be handled by the plugin.+ */+TEST_F(HandlePluginBatchingTest, NotBatchedOutputFallsBackToCompilerInAutoMode) {+ const auto model = make_not_batched_output_model({2, 16, 16, 16});++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ // The original model is returned, with the original batch+ ASSERT_EQ(resultModel, model);+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({2, 16, 16, 16}));+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, NotBatchedOutputThrowsInPluginMode) {+ const auto model = make_not_batched_output_model({2, 16, 16, 16});++ OV_EXPECT_THROW_HAS_SUBSTRING(handle(model, ov::intel_npu::BatchMode::PLUGIN), ov::Exception, "PLUGIN batch mode");+ // The given model must not be modified+ ASSERT_EQ(model->input(0).get_partial_shape(), ov::PartialShape({2, 16, 16, 16}));+}++/**+ * @brief The output has the shape [4] in the given model, but it becomes a scalar once the input is reshaped to [1].+ * A scalar has no batch dimension, so debatching must be reported as failed.+ */+TEST_F(HandlePluginBatchingTest, OutputBecomingScalarFallsBackToCompilerInAutoMode) {+ const auto model = make_scalar_after_debatching_model(4);++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({4}));+ ASSERT_EQ(resultModel->output(0).get_partial_shape(), ov::PartialShape({4}));+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, OutputBecomingScalarThrowsInPluginMode) {+ const auto model = make_scalar_after_debatching_model(4);++ OV_EXPECT_THROW_HAS_SUBSTRING(handle(model, ov::intel_npu::BatchMode::PLUGIN), ov::Exception, "PLUGIN batch mode");+ // The given model must not be modified+ ASSERT_EQ(model->input(0).get_partial_shape(), ov::PartialShape({4}));+ ASSERT_EQ(model->output(0).get_partial_shape(), ov::PartialShape({4}));+}++/**+ * @brief Only the inputs having the batch layout are reshaped when debatching, although the model validation accepts+ * the inputs by their leading dimension. The output looks debatched ([1, 4]), but one input keeps the batch of 4.+ */+TEST_F(HandlePluginBatchingTest, InputWithoutBatchLayoutFallsBackToCompilerInAutoMode) {+ const auto model = make_mixed_layout_model();++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(resultModel->input(1).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, InputWithoutBatchLayoutThrowsInPluginMode) {+ const auto model = make_mixed_layout_model();++ OV_EXPECT_THROW_HAS_SUBSTRING(handle(model, ov::intel_npu::BatchMode::PLUGIN), ov::Exception, "PLUGIN batch mode");+ // The given model must not be modified+ ASSERT_EQ(model->input(0).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(model->input(1).get_partial_shape(), ov::PartialShape({4, 3}));+}++/**+ * @brief The output of the model is [1, 1] after debatching, so its leading dimension is 1, but its other dimension+ * changed as well: the results of the slices cannot be stacked to obtain the original [4, 4] output.+ */+TEST_F(HandlePluginBatchingTest, OutputWithChangedNonBatchDimensionFallsBackToCompilerInAutoMode) {+ const auto model = make_two_layouts_matmul_model();++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(resultModel->input(1).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(resultModel->output(0).get_partial_shape(), ov::PartialShape({4, 4}));+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, OutputWithChangedNonBatchDimensionThrowsInPluginMode) {+ const auto model = make_two_layouts_matmul_model();++ OV_EXPECT_THROW_HAS_SUBSTRING(handle(model, ov::intel_npu::BatchMode::PLUGIN), ov::Exception, "PLUGIN batch mode");+ // The given model must not be modified+ ASSERT_EQ(model->input(0).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(model->input(1).get_partial_shape(), ov::PartialShape({4, 3}));+ ASSERT_EQ(model->output(0).get_partial_shape(), ov::PartialShape({4, 4}));+}++/**+ * @brief The batch dimension of the input without the batch layout, and of the output, remains dynamic after reshaping.+ * It must not be mistaken for a batch of 1.+ */+TEST_F(HandlePluginBatchingTest, DynamicInputWithoutBatchLayoutFallsBackToCompilerInAutoMode) {+ const auto model = make_dynamic_mixed_layout_model();++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::AUTO);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ const ov::PartialShape expectedShape{ov::Dimension(1, 10), 3};+ ASSERT_EQ(resultModel->input(0).get_partial_shape(), expectedShape);+ ASSERT_EQ(resultModel->input(1).get_partial_shape(), expectedShape);+ ASSERT_EQ(updatedBatchModes, std::vector<ov::intel_npu::BatchMode>{ov::intel_npu::BatchMode::COMPILER});+}++TEST_F(HandlePluginBatchingTest, DynamicInputWithoutBatchLayoutThrowsInPluginMode) {+ const auto model = make_dynamic_mixed_layout_model();++ OV_EXPECT_THROW_HAS_SUBSTRING(handle(model, ov::intel_npu::BatchMode::PLUGIN), ov::Exception, "PLUGIN batch mode");+ // The given model must not be modified+ const ov::PartialShape expectedShape{ov::Dimension(1, 10), 3};+ ASSERT_EQ(model->input(0).get_partial_shape(), expectedShape);+ ASSERT_EQ(model->input(1).get_partial_shape(), expectedShape);+}++/**+ * @brief The batch mode is not available when the compiler is too old to support it, thus the batch mode cannot be+ * updated either+ */+TEST_F(HandlePluginBatchingTest, NotBatchedOutputWithoutBatchModeKeepsOriginalModel) {+ const auto model = make_not_batched_output_model({2, 16, 16, 16});++ auto [resultModel, successfullyDebatched] = handle(model, std::nullopt);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ ASSERT_TRUE(updatedBatchModes.empty());+}++TEST_F(HandlePluginBatchingTest, CompilerBatchModeDoesNotChangeModel) {+ const auto model = make_batched_relu_model({4, 3, 2, 2});++ auto [resultModel, successfullyDebatched] = handle(model, ov::intel_npu::BatchMode::COMPILER);++ ASSERT_FALSE(successfullyDebatched);+ ASSERT_FALSE(originalBatch.has_value());+ ASSERT_EQ(resultModel, model);+ ASSERT_TRUE(updatedBatchModes.empty());+}