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
[Dynamic batch] Investigate refactoring opportunities for batch management in Plugin and Compiler - new metadata version (#32350)
Daria Mityagina6872b07b2ca0
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hppindex 1976b3ebfbc..50d7b85607c 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp@@ -442,6 +442,7 @@ struct INTERNAL_SUPPORTED_PROPERTIES final : OptionBase<INTERNAL_SUPPORTED_PROPE}};+// BATCH_MODE is required to maintain backward/forward compatibilitystruct BATCH_MODE final : OptionBase<BATCH_MODE, ov::intel_npu::BatchMode> {static std::string_view key() {return ov::intel_npu::batch_mode.name();diff --git a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cppindex 3b95a4f91a3..d04517b7416 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@@ -72,13 +72,21 @@ void check_level_zero_attributes_match(const IODescriptor& ioDescriptor, const A}std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,+ const ov::PartialShape& ioShape,const std::shared_ptr<ov::ITensor>& tensor,const std::optional<size_t> batchSize) {if (tensor == nullptr && !batchSize.has_value()) {return std::nullopt;}- if (!desc.shapeFromIRModel.has_value() || !desc.shapeFromIRModel.value().is_dynamic()) {+ if (!ioShape.size()) {+ return std::nullopt;+ }++ auto batchFromModel = ioShape[intel_npu::utils::BATCH_AXIS];+ auto batchModelFromIR =+ desc.shapeFromIRModel.has_value() && desc.shapeFromIRModel.value()[intel_npu::utils::BATCH_AXIS].is_dynamic();+ if (!batchFromModel.is_dynamic() && !batchModelFromIR) {return std::nullopt;}@@ -90,11 +98,7 @@ std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,return std::nullopt;}- if ((*desc.shapeFromIRModel)[intel_npu::utils::BATCH_AXIS].is_dynamic()) {- return tensor->get_shape()[intel_npu::utils::BATCH_AXIS];- }-- return std::nullopt;+ return tensor->get_shape()[intel_npu::utils::BATCH_AXIS];}} // namespace@@ -310,8 +314,9 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, constreturn;}+ auto ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();auto batchSizeCandidate =- determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), tensor._ptr, std::nullopt);+ determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);if (batchSizeCandidate.has_value()) {if (!_dynamicBatchValueChanged) {@@ -351,8 +356,9 @@ void ZeroInferRequest::set_tensor(const ov::Output<const ov::Node>& port, constreturn;}+ auto ioShape = _compiledModel->outputs()[foundPort.idx].get_partial_shape();auto batchSizeCandidate =- determine_dynamic_batch_size(_metadata.outputs.at(foundPort.idx), tensor._ptr, std::nullopt);+ determine_dynamic_batch_size(_metadata.outputs.at(foundPort.idx), ioShape, tensor._ptr, std::nullopt);if (batchSizeCandidate.has_value()) {if (!_dynamicBatchValueChanged) {@@ -443,7 +449,9 @@ void ZeroInferRequest::set_tensors(const ov::Output<const ov::Node>& port,_logger.debug("ZeroInferRequest::set_tensors: %zu", tensors.size());- auto batchSizeCandidate = determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), nullptr, tensors.size());+ auto ioShape = _compiledModel->inputs()[foundPort.idx].get_partial_shape();+ auto batchSizeCandidate =+ determine_dynamic_batch_size(_metadata.inputs.at(foundPort.idx), ioShape, nullptr, tensors.size());// Check if batch has been changedif (batchSizeCandidate.has_value()) {diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cppindex c63e39a11d3..b24ee977dd4 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp@@ -232,7 +232,9 @@ void Graph::initialize(const Config& config) {// releasing it here to avoid unnecessary memory usage._blobIsReleased = release_blob(config);- _batchSize = determine_batch_size();+ if (!_batchSize.has_value()) {+ _batchSize = determine_batch_size();+ }if (_zeroInitStruct->getCommandQueueDdiTable().version() < ZE_MAKE_VERSION(1, 1) &&config.get<RUN_INFERENCES_SEQUENTIALLY>()) {diff --git a/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/include/compiled_model.hppindex afde2e31bf9..b7fc338a542 100644--- a/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp@@ -33,7 +33,8 @@ public:const std::shared_ptr<const ov::IPlugin>& plugin,const std::shared_ptr<IDevice>& device,const std::shared_ptr<IGraph>& graph,- const FilteredConfig& config);+ const FilteredConfig& config,+ const std::optional<int64_t>& batchSize);CompiledModel(const CompiledModel&) = delete;@@ -68,6 +69,8 @@ private:std::unique_ptr<Properties> _properties;std::shared_ptr<IGraph> _graph;++ std::optional<int64_t> _batchSize;};} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hppindex 1289c8b6152..9c86c02ab3a 100644--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp@@ -43,6 +43,11 @@ public:*/virtual std::optional<std::vector<uint64_t>> get_init_sizes() const = 0;+ /**+ * @returns Batch size. Populated in case of plugin batching.+ */+ virtual std::optional<int64_t> get_batch_size() const = 0;+virtual ~MetadataBase() = default;static std::streampos getFileSize(std::istream& stream);@@ -101,11 +106,12 @@ constexpr std::string_view MAGIC_BYTES = "OVNPU";*/constexpr uint32_t METADATA_VERSION_2_0{MetadataBase::make_version(2, 0)};constexpr uint32_t METADATA_VERSION_2_1{MetadataBase::make_version(2, 1)};+constexpr uint32_t METADATA_VERSION_2_2{MetadataBase::make_version(2, 2)};/*** @brief Current metadata version.*/-constexpr uint32_t CURRENT_METADATA_VERSION{METADATA_VERSION_2_1};+constexpr uint32_t CURRENT_METADATA_VERSION{METADATA_VERSION_2_2};constexpr uint16_t CURRENT_METADATA_MAJOR_VERSION{MetadataBase::get_major(CURRENT_METADATA_VERSION)};constexpr uint16_t CURRENT_METADATA_MINOR_VERSION{MetadataBase::get_minor(CURRENT_METADATA_VERSION)};@@ -210,6 +216,8 @@ public:std::optional<std::vector<uint64_t>> get_init_sizes() const override;+ std::optional<int64_t> get_batch_size() const override;+size_t get_metadata_size() const override;protected:@@ -242,6 +250,8 @@ public:std::optional<std::vector<uint64_t>> get_init_sizes() const override;+ std::optional<int64_t> get_batch_size() const override;+size_t get_metadata_size() const override;private:@@ -249,6 +259,39 @@ private:uint64_t _numberOfInits = 0;};+/**+ * @brief The version that adds support for batch value storage.+ */+template <>+class Metadata<METADATA_VERSION_2_2> : public Metadata<METADATA_VERSION_2_1> {+public:+ Metadata(uint64_t blobSize,+ std::optional<OpenvinoVersion> ovVersion = std::nullopt,+ const std::optional<std::vector<uint64_t>> initSizes = std::nullopt,+ const std::optional<int64_t> batchSize = std::nullopt);++ /**+ * @details The number of init schedules, along with the size of each init binary object are read in addition to the+ * information provided by the previous metadata versions.+ */+ void read(std::istream& stream) override;++ void read(const ov::Tensor& tensor) override;++ /**+ * @details The number of init schedules, along with the size of each init binary object are written in addition to+ * the information registered by the previous metadata versions.+ */+ void write(std::ostream& stream) override;++ std::optional<int64_t> get_batch_size() const override;++ size_t get_metadata_size() const override;++private:+ std::optional<int64_t> _batchSize;+};+/*** @brief Creates a Metadata object.*diff --git a/src/plugins/intel_npu/src/plugin/include/transformations.hpp b/src/plugins/intel_npu/src/plugin/include/transformations.hppnew file mode 100644index 00000000000..6089deb6213--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/include/transformations.hpp@@ -0,0 +1,72 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <functional>+#include <memory>+#include <optional>+#include <set>+#include <string>++#include "intel_npu/common/filtered_config.hpp"+#include "intel_npu/config/config.hpp"+#include "intel_npu/config/options.hpp"+#include "intel_npu/utils/logger/logger.hpp"+#include "openvino/openvino.hpp"+#include "openvino/runtime/intel_npu/properties.hpp"++namespace intel_npu {+namespace batch_helpers {++/**+ * @brief Detects if shape contains dynamic dimensions other than the batch dimension+ * Plugin-side batch handling can only be applied when batch is the sole dynamic dimension+ * @param shape The partial shape to check+ * @return true if there are dynamic dimensions other than batch, false otherwise+ */+bool hasOtherDynamicDims(const ov::PartialShape& shape);++/**+ * @brief Checks if model has dynamic dimensions other than batch in inputs or outputs+ * @param model The OpenVINO model to check+ * @return true if model has other dynamic dimensions, false otherwise+ */+bool checkModelDynamicDims(const std::shared_ptr<const ov::Model>& model);++/**+ * @brief Validates if the model is suitable for plugin-side batching+ * @param model The OpenVINO model to validate+ * @param logger Logger instance for diagnostic messages+ * @return true if model supports plugin batching, false otherwise+ */+bool validateModelBatch(const std::shared_ptr<const ov::Model>& model, Logger logger);++/**+ * @brief Attempts to debatch a model by setting batch dimension to specified value+ * @param model The model to debatch (modified in-place)+ * @param newBatch The new batch dimension value+ * @param originalBatch Output parameter to store the original batch dimension+ * @return true if debatching was successful, false otherwise+ */+bool deBatchModel(std::shared_ptr<ov::Model>& model,+ ov::Dimension newBatch,+ std::optional<ov::Dimension>& originalBatch);++/**+ * @brief Handles plugin-side batching logic including validation and model reshaping+ * @param model The model to process+ * @param localConfig Configuration+ * @param originalBatch Output parameter to store original batch dimension+ * @param logger Logger instance for diagnostic messages+ */+std::tuple<std::shared_ptr<ov::Model>, bool> handlePluginBatching(+ std::shared_ptr<const ov::Model> model,+ FilteredConfig& localConfig,+ const std::function<void(ov::intel_npu::BatchMode)>& updateBatchMode,+ std::optional<ov::Dimension>& originalBatch,+ Logger logger);++} // namespace batch_helpers+} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/src/compiled_model.cppindex 8475ebd6b2f..f38fe4a2df0 100644--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp@@ -26,12 +26,14 @@ CompiledModel::CompiledModel(const std::shared_ptr<const ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,const std::shared_ptr<IDevice>& device,const std::shared_ptr<IGraph>& graph,- const FilteredConfig& config)+ const FilteredConfig& config,+ const std::optional<int64_t>& batchSize): ICompiledModel(model, plugin),_config(config),_logger("CompiledModel", config.get<LOG_LEVEL>()),_device(device),- _graph(graph) {+ _graph(graph),+ _batchSize(batchSize) {OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "CompiledModel::CompiledModel");OV_ITT_TASK_CHAIN(COMPILED_MODEL, itt::domains::NPUPlugin, "CompiledModel::CompiledModel", "initialize_properties");@@ -83,8 +85,12 @@ void CompiledModel::export_model(std::ostream& stream) const {_logger.debug("CompiledModel::export_model");auto [blobSizesBeforeVersioning, initBlobSizes] = _graph->export_blob(stream);+ auto originalBatchSize = _batchSize;- Metadata<CURRENT_METADATA_VERSION>(blobSizesBeforeVersioning, CURRENT_OPENVINO_VERSION, initBlobSizes)+ Metadata<CURRENT_METADATA_VERSION>(blobSizesBeforeVersioning,+ CURRENT_OPENVINO_VERSION,+ initBlobSizes,+ originalBatchSize).write(stream);}diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cppindex 67b3213ad6c..e3cc3c31974 100644--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp@@ -71,6 +71,15 @@ Metadata<METADATA_VERSION_2_1>::Metadata(uint64_t blobSize,_version = METADATA_VERSION_2_1;}+Metadata<METADATA_VERSION_2_2>::Metadata(uint64_t blobSize,+ std::optional<OpenvinoVersion> ovVersion,+ const std::optional<std::vector<uint64_t>> initSizes,+ const std::optional<int64_t> batchSize)+ : Metadata<METADATA_VERSION_2_1>{blobSize, ovVersion, initSizes},+ _batchSize{batchSize} {+ _version = METADATA_VERSION_2_2;+}+void Metadata<METADATA_VERSION_2_0>::read(std::istream& stream) {_ovVersion.read(stream);}@@ -114,6 +123,32 @@ void Metadata<METADATA_VERSION_2_1>::read(const ov::Tensor& tensor) {}}+void Metadata<METADATA_VERSION_2_2>::read(std::istream& stream) {+ Metadata<METADATA_VERSION_2_1>::read(stream);++ int64_t batchSize;+ stream.read(reinterpret_cast<char*>(&batchSize), sizeof(batchSize));++ _batchSize = batchSize != 0 ? std::optional(batchSize) : std::nullopt;+}++void Metadata<METADATA_VERSION_2_2>::read(const ov::Tensor& tensor) {+ Metadata<METADATA_VERSION_2_1>::read(tensor);++ auto roiTensor =+ ov::Tensor(tensor,+ ov::Coordinate{sizeof(decltype(std::declval<OpenvinoVersion>().get_major())) ++ sizeof(decltype(std::declval<OpenvinoVersion>().get_minor())) ++ sizeof(decltype(std::declval<OpenvinoVersion>().get_patch())) + sizeof(uint64_t) ++ sizeof(uint64_t) * (get_init_sizes() ? get_init_sizes()->size() : 0)},+ ov::Coordinate{tensor.get_byte_size()});++ int64_t batchSize;+ batchSize = *reinterpret_cast<const decltype(batchSize)*>(roiTensor.data<const char>());++ _batchSize = batchSize != 0 ? std::optional(batchSize) : std::nullopt;+}+void MetadataBase::append_padding_blob_size_and_magic(std::ostream& stream) {size_t metadataSize = get_metadata_size() + sizeof(_blobDataSize) + MAGIC_BYTES.size();size_t size = utils::align_size_to_standard_page_size(metadataSize);@@ -142,6 +177,14 @@ void Metadata<METADATA_VERSION_2_1>::write(std::ostream& stream) {stream.write(reinterpret_cast<const char*>(&initSize), sizeof(initSize));}}+}++void Metadata<METADATA_VERSION_2_2>::write(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_1>::write(stream);++ // _batchSize is std::optional, so either the value or std::nullopt will be written+ int64_t batchValue = _batchSize.value_or(0);+ stream.write(reinterpret_cast<const char*>(&batchValue), sizeof(batchValue));append_padding_blob_size_and_magic(stream);}@@ -157,6 +200,8 @@ std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSizreturn std::make_unique<Metadata<METADATA_VERSION_2_0>>(blobSize, std::nullopt);case METADATA_VERSION_2_1:return std::make_unique<Metadata<METADATA_VERSION_2_1>>(blobSize, std::nullopt);+ case METADATA_VERSION_2_2:+ return std::make_unique<Metadata<METADATA_VERSION_2_2>>(blobSize, std::nullopt);default:OPENVINO_THROW("Metadata version is not supported!");}@@ -299,6 +344,18 @@ std::optional<std::vector<uint64_t>> Metadata<METADATA_VERSION_2_1>::get_init_sireturn _initSizes;}+std::optional<int64_t> Metadata<METADATA_VERSION_2_0>::get_batch_size() const {+ return std::nullopt;+}++std::optional<int64_t> Metadata<METADATA_VERSION_2_1>::get_batch_size() const {+ return std::nullopt;+}++std::optional<int64_t> Metadata<METADATA_VERSION_2_2>::get_batch_size() const {+ return _batchSize;+}+size_t Metadata<METADATA_VERSION_2_0>::get_metadata_size() const {return sizeof(_version) + _ovVersion.get_openvino_version_size();}@@ -315,4 +372,10 @@ size_t Metadata<METADATA_VERSION_2_1>::get_metadata_size() const {return metadataSize;}+size_t Metadata<METADATA_VERSION_2_2>::get_metadata_size() const {+ size_t metadataSize = Metadata<METADATA_VERSION_2_1>::get_metadata_size() + sizeof(int64_t);++ return metadataSize;+}+} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex 01085db9e53..6424945406a 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -27,6 +27,7 @@#include "openvino/runtime/properties.hpp"#include "openvino/runtime/shared_buffer.hpp"#include "remote_context.hpp"+#include "transformations.hpp"using namespace intel_npu;@@ -53,7 +54,8 @@ constexpr std::string_view ONNX_EXTENSION = ".onnx";* @returns The dummy "ov::Model" composed of "parameter" and "result" nodes built using the given descriptors.*/std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& inputDescriptors,- const std::vector<IODescriptor>& outputDescriptors) {+ const std::vector<IODescriptor>& outputDescriptors,+ std::optional<int64_t> batchSize) {ov::ParameterVector parameters;ov::ResultVector results;@@ -63,10 +65,15 @@ std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& icontinue;}- std::shared_ptr<ov::op::v0::Parameter> parameter = std::make_shared<ov::op::v0::Parameter>(- inputDescriptor.precision,- inputDescriptor.shapeFromIRModel.has_value() ? *inputDescriptor.shapeFromIRModel- : inputDescriptor.shapeFromCompiler);+ auto shape = inputDescriptor.shapeFromIRModel.has_value() ? *inputDescriptor.shapeFromIRModel+ : inputDescriptor.shapeFromCompiler;++ if (batchSize.has_value()) {+ shape[intel_npu::utils::BATCH_AXIS] = ov::Dimension(batchSize.value());+ }++ std::shared_ptr<ov::op::v0::Parameter> parameter =+ std::make_shared<ov::op::v0::Parameter>(inputDescriptor.precision, shape);parameter->set_friendly_name(inputDescriptor.nodeFriendlyName);parameter->output(0).get_tensor().set_names(inputDescriptor.outputTensorNames);@@ -86,11 +93,17 @@ std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& istd::shared_ptr<ov::Node> constantDummy =std::make_shared<ov::op::v0::Constant>(outputDescriptor.precision, CONSTANT_NODE_DUMMY_SHAPE);- const std::shared_ptr<ov::descriptor::Tensor>& tensorDummy = std::make_shared<ov::descriptor::Tensor>(- outputDescriptor.precision,- outputDescriptor.shapeFromIRModel.has_value() ? *outputDescriptor.shapeFromIRModel- : outputDescriptor.shapeFromCompiler,- outputDescriptor.outputTensorNames);+ auto shape = outputDescriptor.shapeFromIRModel.has_value() ? *outputDescriptor.shapeFromIRModel+ : outputDescriptor.shapeFromCompiler;++ if (batchSize.has_value()) {+ shape[intel_npu::utils::BATCH_AXIS] = ov::Dimension(batchSize.value());+ }++ const std::shared_ptr<ov::descriptor::Tensor>& tensorDummy =+ std::make_shared<ov::descriptor::Tensor>(outputDescriptor.precision,+ shape,+ outputDescriptor.outputTensorNames);auto& result = results.emplace_back(std::make_shared<ov::op::v0::Result>(constantDummy));result->output(0).set_tensor_ptr(tensorDummy);@@ -594,21 +607,44 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<auto device = _backend == nullptr ? nullptr : _backend->getDevice(localConfig.get<DEVICE_ID>());localConfig.update({{ov::intel_npu::platform.name(), platform}});- if (localConfig.isAvailable(ov::intel_npu::batch_mode.name()) &&- !localConfig.has(ov::intel_npu::batch_mode.name())) {+ auto updateBatchMode = [&](ov::intel_npu::BatchMode mode) {std::stringstream strStream;- strStream << ov::intel_npu::BatchMode::AUTO;+ strStream << mode;+ _logger.info("Setting batching mode to %s.", strStream.str().c_str());localConfig.update({{ov::intel_npu::batch_mode.name(), strStream.str()}});- }+ };++ // Handle batch mode configuration+ std::optional<ov::Dimension> originalBatch = std::nullopt;+ std::shared_ptr<ov::Model> batchedModel;++ bool shouldHandleBatching = false;+ bool successfullyDebatched = false;- if (localConfig.isAvailable(ov::intel_npu::batch_mode.name()) && !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 (localConfig.isAvailable(ov::intel_npu::batch_mode.name())) {+ // Set default batch mode if not configured+ if (!localConfig.has(ov::intel_npu::batch_mode.name())) {+ updateBatchMode(ov::intel_npu::BatchMode::AUTO);}- std::stringstream strStream;- strStream << ov::intel_npu::BatchMode::COMPILER;- localConfig.update({{ov::intel_npu::batch_mode.name(), strStream.str()}});+ // 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;+ } else {+ // If the model contains states, it is not supported when handling batching on the plugin+ shouldHandleBatching = model->get_variables().empty();+ }++ if (shouldHandleBatching) {+ // Process batching+ std::tie(batchedModel, successfullyDebatched) =+ intel_npu::batch_helpers::handlePluginBatching(model, localConfig, updateBatchMode, originalBatch, _logger);}// Update stepping w/ information from driver, unless provided by user or we are off-device@@ -659,10 +695,10 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<_logger.debug("performing compile");if (!localConfig.get<WEIGHTLESS_BLOB>()) {- graph = compiler->compile(model->clone(), localConfig);+ graph = compiler->compile(successfullyDebatched ? batchedModel : model->clone(), localConfig);} else {check_weightless_cache_attribute_occurrence(model);- graph = compiler->compileWS(model->clone(), localConfig);+ graph = compiler->compileWS(successfullyDebatched ? batchedModel : model->clone(), localConfig);}} catch (const std::exception& ex) {OPENVINO_THROW(ex.what());@@ -671,9 +707,18 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<OPENVINO_THROW("NPU plugin: got an unexpected exception from compiler");}+ 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) {+ // Initial batch setup for static cases+ graph->set_batch_size(batch.value());+ }+ }+std::shared_ptr<ov::ICompiledModel> compiledModel;try {- compiledModel = std::make_shared<CompiledModel>(model, shared_from_this(), device, graph, localConfig);+ compiledModel = std::make_shared<CompiledModel>(model, shared_from_this(), device, graph, localConfig, batch);} catch (const std::exception& ex) {OPENVINO_THROW(ex.what());} catch (...) {@@ -878,6 +923,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::parse(const ov::Tensor& tensorBig,uint64_t mainSize = tensorBig.get_byte_size();std::optional<std::vector<uint64_t>> initSizes;+ std::optional<int64_t> batchSize = std::nullopt;if (metadata) {size_t accumulator = 0;@@ -885,6 +931,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::parse(const ov::Tensor& tensorBig,mainSize = initSizes.has_value()? metadata->get_blob_size() - std::accumulate(initSizes->begin(), initSizes->end(), accumulator): metadata->get_blob_size();+ batchSize = metadata->get_batch_size();} else {_logger.info("Blob compatibility check skipped.");}@@ -941,13 +988,21 @@ std::shared_ptr<ov::ICompiledModel> Plugin::parse(const ov::Tensor& tensorBig,localConfig,weightsSeparationEnabled ? std::make_optional(std::move(tensorsInits)) : std::nullopt,weightsSeparationEnabled ? std::make_optional(originalModel) : std::nullopt);+graph->update_network_name("net" + std::to_string(_compiledModelLoadCounter++));const std::shared_ptr<ov::Model> modelDummy =- create_dummy_model(graph->get_metadata().inputs, graph->get_metadata().outputs);+ create_dummy_model(graph->get_metadata().inputs, graph->get_metadata().outputs, batchSize);++ if (batchSize.has_value()) {+ if (batchSize.value() > 0) {+ // Initial batch setup for static cases+ graph->set_batch_size(batchSize.value());+ }+ }OV_ITT_TASK_NEXT(PLUGIN_PARSE_MODEL, "parse");- return std::make_shared<CompiledModel>(modelDummy, shared_from_this(), device, graph, localConfig);+ return std::make_shared<CompiledModel>(modelDummy, shared_from_this(), device, graph, localConfig, batchSize);}std::atomic<int> Plugin::_compiledModelLoadCounter{1};diff --git a/src/plugins/intel_npu/src/plugin/src/transformations.cpp b/src/plugins/intel_npu/src/plugin/src/transformations.cppnew file mode 100644index 00000000000..b30d054598e--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/src/transformations.cpp@@ -0,0 +1,251 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations.hpp"++#include <map>+#include <sstream>++#include "intel_npu/utils/utils.hpp"+#include "openvino/core/layout.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"++namespace intel_npu {+namespace batch_helpers {++bool hasOtherDynamicDims(const ov::PartialShape& shape) {+ for (size_t dim_idx = 1; dim_idx < shape.size(); dim_idx++) {+ if (shape[dim_idx].is_dynamic()) {+ return true; // Found dynamic dimension other than batch+ }+ }+ return false;+}++bool checkModelDynamicDims(const std::shared_ptr<const ov::Model>& model) {+ // Check parameters (inputs)+ const auto& params = model->get_parameters();+ for (const auto& param : params) {+ const auto& shape = param->get_partial_shape();+ if (hasOtherDynamicDims(shape)) {+ return true;+ }+ }++ // Check results (outputs)+ const auto& results = model->get_results();+ for (const auto& result : results) {+ const auto& shape = result->get_output_partial_shape(0);+ if (hasOtherDynamicDims(shape)) {+ return true;+ }+ }++ return false;+}++bool validateModelBatch(const std::shared_ptr<const ov::Model>& model, Logger logger) {+ std::set<ov::Output<const ov::Node>> batchedInputs;+ std::set<ov::Output<const ov::Node>> batchedOutputs;+ std::set<size_t> sBatchSize;++ // Limitation: Plugin batching is not supported when there are dynamic+ // dimensions other than the batch dimension.+ if (checkModelDynamicDims(model) && model->is_dynamic()) {+ return false;+ }++ const auto& params = model->get_parameters();+ for (size_t input_id = 0; input_id < params.size(); input_id++) {+ const auto& input = params[input_id];+ const auto& shape = input->get_partial_shape();+ ov::Layout layout = ov::layout::get_layout(input);++ // Batching on plugin is working only when batching is found on 0th dimension+ if ((shape.size() &&+ shape[intel_npu::utils::BATCH_AXIS].get_max_length() != intel_npu::utils::DEFAULT_BATCH_SIZE) ||+ (ov::layout::has_batch(layout) && ov::layout::batch_idx(layout) == intel_npu::utils::BATCH_AXIS)) {+ const auto& staticShape = shape.is_dynamic() ? shape.get_max_shape() : input->get_shape();+ batchedInputs.insert(params[input_id]->output(0));++ if (shape.rank().is_dynamic()) {+ OPENVINO_THROW("Shapes with dynamic rank are not supported.");+ } else {+ sBatchSize.insert(staticShape[intel_npu::utils::BATCH_AXIS]);+ }+ } else {+ // gather some diagnostic info+ std::optional<size_t> batch_dim_index_detected;+ for (size_t i = 1; i < shape.size(); i++) {+ if (shape[i].has_symbol()) {+ batch_dim_index_detected = i;+ break;+ }+ }+ std::stringstream sstream;+ sstream << "Only networks with inputs batched by 0th dimension are supported. ";+ if (batch_dim_index_detected.has_value()) {+ sstream << "The batch has been detected on: " << batch_dim_index_detected.value()+ << " dimension instead. ";+ } else {+ sstream << "The batch hasn't been detected at all. ";+ }+ sstream << "Please check input id: " << input_id << " by the name: " << input->get_friendly_name()+ << ", layout: " << layout.to_string() << ", is_dynamic: " << shape.is_dynamic();+ logger.info("%s", sstream.str().c_str());+ return false;+ }+ }+ for (const auto& output : model->get_results()) {+ const auto& shape = output->get_output_partial_shape(0);+ ov::Layout layout = ov::layout::get_layout(output);++ // Batching on plugin is working only when batching is found on 0th dimension+ if ((shape.size() &&+ shape[intel_npu::utils::BATCH_AXIS].get_max_length() != intel_npu::utils::DEFAULT_BATCH_SIZE) ||+ (ov::layout::has_batch(layout) && ov::layout::batch_idx(layout) == intel_npu::utils::BATCH_AXIS)) {+ const auto& node = output->input_value(0);+ const auto& staticShape = shape.is_dynamic() ? shape.get_max_shape() : output->get_shape();+ batchedOutputs.insert(ov::Output<const ov::Node>(node.get_node(), node.get_index()));++ if (shape.rank().is_dynamic()) {+ OPENVINO_THROW("Shapes with dynamic rank are not supported.");+ } else {+ sBatchSize.insert(staticShape[intel_npu::utils::BATCH_AXIS]);+ }+ } else {+ logger.info("Only networks with outputs batched by 0th dimension are supported. Please check an output by "+ "the name: %s, layout: %s",+ output->get_friendly_name().c_str(),+ layout.to_string().c_str());+ return false;+ }+ }+ if (!batchedInputs.size() || !batchedOutputs.size()) {+ logger.info(+ "Only networks with inputs/outputs featuring batched dim are supported! Got inputs: %ld, outputs: %ld",+ batchedInputs.size(),+ batchedOutputs.size());+ return false;+ }++ if (sBatchSize.size() != 1) {+ logger.info("Batching size shall have same value for all tensors! Got unique batch sizes number: %ld",+ sBatchSize.size());+ return false;+ }++ if (*sBatchSize.begin() == intel_npu::utils::DEFAULT_BATCH_SIZE) {+ logger.info("PLUGIN batch won't be applied, got default batch value : %ld", *sBatchSize.begin());+ return false;+ }++ auto node_info_printer = [&logger](const auto& ov_node, std::string nodeType) {+ logger.info("%s: %s has shape value: %s",+ nodeType.c_str(),+ ov_node.get_any_name().c_str(),+ ov_node.get_partial_shape().to_string().c_str());+ };++ for (const auto& ov_node : batchedInputs) {+ node_info_printer(ov_node, "Input");+ }+ for (const auto& ov_node : batchedOutputs) {+ node_info_printer(ov_node, "Output");+ }++ return true;+}++bool deBatchModel(std::shared_ptr<ov::Model>& model,+ ov::Dimension newBatch,+ std::optional<ov::Dimension>& originalBatch) {+ try {+ std::map<std::string, ov::PartialShape> newShapes;+ auto shapeChanged = false;+ for (auto&& item : model->get_parameters()) {+ auto layout = item->get_layout();+ auto partShape = item->get_partial_shape();+ if (ov::layout::has_batch(layout)) {+ shapeChanged = true;+ originalBatch = partShape[ov::layout::batch_idx(layout)];+ partShape[ov::layout::batch_idx(layout)] = newBatch;+ }+ newShapes.emplace(item->get_friendly_name(), partShape);+ }+ model->reshape(newShapes);+ return shapeChanged;+ } catch (const std::exception&) {+ // Don't throw - let caller handle the failure+ return false;+ }+}++std::tuple<std::shared_ptr<ov::Model>, bool> handlePluginBatching(+ std::shared_ptr<const ov::Model> model,+ FilteredConfig& localConfig,+ const std::function<void(ov::intel_npu::BatchMode)>& updateBatchMode,+ std::optional<ov::Dimension>& originalBatch,+ Logger logger) {+ auto reshapedModel = model->clone();+ auto successfullyDebatched = false;++ auto batchModeIsAvailable = localConfig.isAvailable(ov::intel_npu::batch_mode.name());+ ov::intel_npu::BatchMode batchMode;+ if (batchModeIsAvailable) {+ batchMode = localConfig.get<BATCH_MODE>();+ const auto isAutoOrPluginBatch =+ (batchMode == ov::intel_npu::BatchMode::PLUGIN || batchMode == ov::intel_npu::BatchMode::AUTO);++ if (!isAutoOrPluginBatch) {+ return {reshapedModel, successfullyDebatched};+ }+ } else {+ // If the compiler doesn't support BATCH_MODE, we can still try using the PLUGIN batch+ batchMode = ov::intel_npu::BatchMode::PLUGIN;+ }++ try {+ const auto pluginBatchingIsSupported = validateModelBatch(reshapedModel, logger);++ if (!pluginBatchingIsSupported) {+ if (batchModeIsAvailable && batchMode == ov::intel_npu::BatchMode::AUTO) {+ logger.info("Batching will be handled by compiler.");+ updateBatchMode(ov::intel_npu::BatchMode::COMPILER);+ }+ return {reshapedModel, successfullyDebatched};+ }++ logger.info("Attempting to handle batching on the plugin side.");++ try {+ originalBatch = ov::get_batch(reshapedModel);+ ov::set_batch(reshapedModel, ov::Dimension(1));+ successfullyDebatched = true;+ } catch (const std::exception& ex) {+ logger.warning("The plugin couldn't resize a batched model due to exception: %s.\n"+ "Trying to debatch it...",+ ex.what());++ if (!deBatchModel(reshapedModel, ov::Dimension(1), originalBatch)) {+ OPENVINO_THROW("Cannot debatch a model");+ }+ logger.info("The model has been debatched successfully");+ successfullyDebatched = true;+ }+ 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+ updateBatchMode(ov::intel_npu::BatchMode::COMPILER);+ }+ } catch (const std::exception& ex) {+ logger.info("Couldn't validate and reshape the model. Batching will be handled by compiler. Error: %s",+ ex.what());+ }+ return {reshapedModel, successfullyDebatched};+}++} // namespace batch_helpers+} // namespace intel_npudiff --git a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hppindex 182b9a910f7..55a86ad6a15 100644--- a/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/batched_tensors_tests/batched_run.hpp@@ -75,7 +75,8 @@ public:auto hash = std::to_string(std::hash<std::string>()(test_name));std::stringstream ss;auto ts = duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch());- ss << hash << "_" << "_" << ts.count();+ ss << hash << "_"+ << "_" << ts.count();return ss.str();}@@ -216,6 +217,63 @@ TEST_P(BatchedTensorsRunTests, SetInputDifferentTensorsMultipleInfer) {}}+TEST_P(BatchedTensorsRunTests, SetInputDifferentTensorsMultipleInferWithExportImport) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ auto one_shape_size = ov::shape_size(one_shape);+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ // Compile model+ auto execNet = core->compile_model(model, target_device, configuration);++ // Export model+ std::stringstream modelStream;+ execNet.export_model(modelStream);++ // Import model+ auto importedExecNet = core->import_model(modelStream, target_device, configuration);++ auto context = core->get_default_context(target_device);++ // Create InferRequest from imported model+ ov::InferRequest req;+ req = importedExecNet.create_infer_request();+ std::vector<ov::Tensor> tensors;++ std::vector<float> buffer(one_shape_size * 2 * 2, 0);++ auto tensor0 = ov::Tensor(element::f32, one_shape, &buffer[(0 * 2) * one_shape_size]);+ auto tensor1 = context.create_host_tensor(ov::element::f32, one_shape);+ auto tensor2 = ov::Tensor(element::f32, one_shape, &buffer[(1 * 2) * one_shape_size]);+ auto tensor3 = context.create_host_tensor(ov::element::f32, one_shape);++ tensors.push_back(std::move(tensor0));+ tensors.push_back(std::move(tensor1));+ tensors.push_back(std::move(tensor2));+ tensors.push_back(std::move(tensor3));++ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ auto* actual = actual_tensor.data<float>();+ for (auto testNum = 0; testNum < 5; testNum++) {+ for (size_t i = 0; i < batch; ++i) {+ auto* f = tensors[i].data<float>();+ for (size_t j = 0; j < one_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20);+ }+ }+ req.infer(); // Adds '1' to each element+ for (size_t j = 0; j < one_shape_size * batch; ++j) {+ ASSERT_EQ(actual[j], testNum + 21) << "Infer " << testNum << ": Expected=" << testNum + 21+ << ", actual=" << actual[j] << " for index " << j;+ }+ }+}+TEST_P(BatchedTensorsRunTests, SetInputDifferentTensorsMultipleInferMCL) {SKIP_IF_CURRENT_TEST_IS_DISABLED();@@ -622,6 +680,67 @@ TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorSingleInf}}+TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorSingleInferWithExportImport) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();++ size_t batch = 4;+ size_t tensor_batch = 3;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ auto one_shape_size = ov::shape_size(one_shape);+ auto tensor_shape = Shape{tensor_batch, 2, 2, 2};+ auto tensor_shape_size = ov::shape_size(tensor_shape);+ auto modelShape = PartialShape{ov::Dimension(1, 10), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);++ // Compile model+ auto execNet = core->compile_model(model, target_device, configuration);++ // Export model+ std::stringstream modelStream;+ execNet.export_model(modelStream);++ // Import model+ auto importedExecNet = core->import_model(modelStream, target_device, configuration);++ auto context = core->get_default_context(target_device);++ // Create InferRequest from imported model+ ov::InferRequest req;+ req = importedExecNet.create_infer_request();+ std::vector<ov::Tensor> tensors;++ // contiguous memory+ auto tensor = context.create_host_tensor(ov::element::f32, tensor_shape);+ tensors.push_back(std::move(tensor));++ req.set_tensors("tensor_input0", tensors);++ auto actual_tensor = req.get_tensor("tensor_output0");+ auto* actual = actual_tensor.data<float>();++ for (auto testNum = 0; testNum < 5; testNum++) {+ auto* f = tensors[0].data<float>();+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ f[j] = static_cast<float>(testNum + 20 * (j / one_shape_size + 1));+ }+ req.infer(); // Adds '1' to each element+ for (size_t j = 0; j < tensor_shape_size; ++j) {+ auto expected = testNum + 20 * (j / one_shape_size + 1) + 1;+ ASSERT_EQ(actual[j], expected)+ << "Infer " << testNum << ": Expected=" << expected << ", actual=" << actual[j] << " for index " << j+ << ", batch: " << j / one_shape_size;+ }+ }+}+void executeContiguousTensorBatchInfer(ov::InferRequest req,size_t batch_value,const Shape& non_batched_shape,@@ -682,7 +801,48 @@ TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBaov::InferRequest req;req = execNet.create_infer_request();for (size_t tensor_batch = model_batch_bottom_bound; tensor_batch <= model_batch_upper_bound; tensor_batch++) {- // dynamically change N of contiduous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]+ // dynamically change N of contiguous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]+ // and check that the output tensor kept modified accordingly+ executeContiguousTensorBatchInfer(req, tensor_batch, one_shape, context);+ }+}++TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBatchInflationWithExportImport) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();++ size_t batch = 4;+ auto one_shape = Shape{1, 2, 2, 2};+ auto batch_shape = Shape{batch, 2, 2, 2};+ size_t model_batch_bottom_bound = 1;+ size_t model_batch_upper_bound = 10;+ auto modelShape = PartialShape{ov::Dimension(model_batch_bottom_bound, model_batch_upper_bound), 2, 2, 2};+ auto model = BatchedTensorsRunTests::create_n_inputs(2, element::f32, batch_shape, "N...");++ const std::string tensor_name_0 = "tensor_input0";+ const std::string tensor_name_1 = "tensor_input1";+ std::map<std::string, ov::PartialShape> shapes;+ shapes[tensor_name_0] = modelShape;+ shapes[tensor_name_1] = modelShape;+ model->reshape(shapes);++ // Compile model+ auto execNet = core->compile_model(model, target_device, configuration);++ // Export model+ std::stringstream modelStream;+ execNet.export_model(modelStream);++ // Import model+ auto importedExecNet = core->import_model(modelStream, target_device, configuration);++ auto context = core->get_default_context(target_device);++ // Create InferRequest from imported model+ ov::InferRequest req;+ req = importedExecNet.create_infer_request();++ for (size_t tensor_batch = model_batch_bottom_bound; tensor_batch <= model_batch_upper_bound; tensor_batch++) {+ // dynamically change N of contiguous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]// and check that the output tensor kept modified accordinglyexecuteContiguousTensorBatchInfer(req, tensor_batch, one_shape, context);}@@ -712,7 +872,7 @@ TEST_P(DynamicBatchedTensorsRunTests, SetInputRemoteSingleBatchedTensorDynamicBaov::InferRequest req;req = execNet.create_infer_request();for (size_t tensor_batch = model_batch_upper_bound; tensor_batch >= model_batch_bottom_bound; tensor_batch--) {- // dynamically change N of contiduous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]+ // dynamically change N of contiguous memory tensor in [model_batch_bottom_bound..model_batch_upper_bound]// and check that the output tensor kept modified accordinglyexecuteContiguousTensorBatchInfer(req, tensor_batch, one_shape, context);}diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xmlindex 4f551aced93..a4ed16e1224 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@@ -823,15 +823,6 @@ Example:</filters></skip_config>- <!-- E#168772 -->- <skip_config>- <message>Tests currently skipped until dynamic batch is fully supported (need NPU compiler alignment/driver update)</message>- <filters>- <filter>.*DynamicBatchingRunSeqTests.*</filter>- <filter>.*DynamicBatchedTensorsRunTests.*</filter>- </filters>- </skip_config>-<skip_config><message>The "one shot" implementation of the weights separation feature is supported only in the compiler-in-plugin flow</message><filters>