Skip to content

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

[NPU] Fix dynamic bounds (#35402)

Bogdan Pereanuad5d8e0f99b3
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 8987914d4e9..f1490d060bf 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
@@ -19,8 +19,6 @@
#include "transformations/utils/utils.hpp"
#include "zero_variable_state.hpp"
-namespace intel_npu {
-
namespace {
std::shared_ptr<const ov::ICompiledModel> validate_compiled_model(
@@ -29,8 +27,47 @@ std::shared_ptr<const ov::ICompiledModel> validate_compiled_model(
return compiledModel;
}
+bool has_related_shape_tensor(const std::vector<intel_npu::IODescriptor>& metadata, size_t descriptorIdx) {
+ const auto& relatedDescriptor = metadata.at(descriptorIdx).relatedDescriptorIndex;
+ return relatedDescriptor.has_value() && metadata.at(relatedDescriptor.value()).isShapeTensor;
+}
+
+void copy_tensor_with_optional_shape_view(const std::shared_ptr<ov::ITensor>& srcTensor,
+ const std::shared_ptr<ov::ITensor>& dstTensor,
+ bool srcTensorIsUserTensor,
+ bool hasRelatedShapeTensor) {
+ if (hasRelatedShapeTensor && srcTensor->get_shape() != dstTensor->get_shape()) {
+ // With dynamic bounds (shape tensor present), Level Zero tensor is allocated for max shape.
+ // User tensor can be smaller for the current inference, so we create a smaller view over
+ // the same Level Zero buffer and copy using the user-visible shape.
+ if (srcTensorIsUserTensor) {
+ OPENVINO_ASSERT(srcTensor->get_byte_size() <= dstTensor->get_byte_size(),
+ "Source byte size exceeds destination tensor allocation for dynamic-shape view copy");
+
+ auto viewTensor = ov::make_tensor(dstTensor->get_element_type(),
+ srcTensor->get_shape(),
+ static_cast<unsigned char*>(dstTensor->data()));
+ srcTensor->copy_to(viewTensor);
+ return;
+ }
+
+ OPENVINO_ASSERT(dstTensor->get_byte_size() <= srcTensor->get_byte_size(),
+ "Source byte size exceeds destination tensor allocation for dynamic-shape view copy");
+
+ auto viewTensor = ov::make_tensor(srcTensor->get_element_type(),
+ dstTensor->get_shape(),
+ static_cast<unsigned char*>(srcTensor->data()));
+ viewTensor->copy_to(dstTensor);
+ return;
+ }
+
+ srcTensor->copy_to(dstTensor);
+}
+
} // namespace
+namespace intel_npu {
+
std::optional<size_t> determine_dynamic_batch_size(const IODescriptor& desc,
const ov::PartialShape& ioShape,
const std::shared_ptr<ov::ITensor>& tensor,
@@ -467,10 +504,14 @@ void ZeroInferRequest::sync_zero_tensor_with_graph(const ZeroInferRequest::Found
itt::domains::LevelZeroBackend,
"ZeroInferRequest",
"sync_zero_tensor_with_graph");
+ const auto& metadata = foundPort.is_input() ? _metadata.inputs : _metadata.outputs;
auto& levelZeroTensor =
foundPort.is_input() ? get_level_zero_input(foundPort.idx) : _levelZeroOutputTensors.at(foundPort.idx);
- if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {
+ // For dynamic bounds (related shape tensor present), we must keep Level Zero allocation at max shape.
+ // Therefore user-memory import is allowed only when there is no related shape tensor.
+ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) &&
+ !has_related_shape_tensor(metadata, foundPort.idx)) {
bool updateCommandListArg = false;
try {
_logger.debug("sync_zero_tensor_with_graph - create zero tensor");
@@ -586,7 +627,10 @@ void ZeroInferRequest::sync_zero_tensors_with_graph(const ZeroInferRequest::Foun
"ZeroInferRequest",
"sync_zero_tensors_with_graph");
- if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {
+ // For dynamic bounds (related shape tensor present), we must keep Level Zero allocation at max shape.
+ // Therefore user-memory import is allowed only when there is no related shape tensor.
+ if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0) &&
+ !has_related_shape_tensor(_metadata.inputs, foundPort.idx)) {
if (batchSize.has_value()) {
get_level_zero_inputs(foundPort.idx).resize(tensors.size());
for (size_t i = 0; i < tensors.size(); i++) {
@@ -903,6 +947,11 @@ void ZeroInferRequest::prepare_inputs() {
OPENVINO_ASSERT(!inputDescriptor.isInitInputWeights,
"This path should not be used for running inferences for the \"init\" model");
+ if (inputDescriptor.isMainInputWeights) {
+ // These values were set while running the "WeightlessGraph::init" method
+ continue;
+ }
+
if (inputDescriptor.isShapeTensor) {
OPENVINO_ASSERT(inputDescriptor.relatedDescriptorIndex.has_value(),
"The link between the dynamic tensor and its shape tensor is missing, entry name: ",
@@ -978,11 +1027,6 @@ void ZeroInferRequest::prepare_inputs() {
continue;
}
- if (inputDescriptor.isMainInputWeights) {
- // These values were set while running the "WeightlessGraph::init" method
- continue;
- }
-
const auto& levelZeroTensor = get_level_zero_input(inputIndex);
OPENVINO_ASSERT(levelZeroTensor, "Input zero tensor is not allocated.");
@@ -1000,7 +1044,10 @@ void ZeroInferRequest::prepare_inputs() {
_logger.info("prepare_inputs - tensor is not allocated in the current Level Zero context");
OV_ITT_TASK_NEXT(ZERO_INFER, "memcpy");
- userTensor.at(SINGLE_TENSOR)->copy_to(levelZeroTensor);
+ copy_tensor_with_optional_shape_view(userTensor.at(SINGLE_TENSOR)._ptr,
+ levelZeroTensor,
+ true,
+ has_related_shape_tensor(_metadata.inputs, inputIndex));
}
++inputIndex;
@@ -1057,7 +1104,10 @@ void ZeroInferRequest::get_result() {
_logger.info("get_result - output tensor by index: %zu is not allocated in the current Level Zero context",
outputIndex);
OV_ITT_TASK_NEXT(ZERO_RESULT, "memcpy");
- levelZeroTensor->copy_to(userTensor._ptr);
+ copy_tensor_with_optional_shape_view(levelZeroTensor,
+ userTensor._ptr,
+ false,
+ has_related_shape_tensor(_metadata.outputs, outputIndex));
}
levelZeroTensor->detach_imported_allocation_for_custom_tensor();
@@ -1130,13 +1180,21 @@ void ZeroInferRequest::check_tensor(const ov::Output<const ov::Node>& port,
if (port_length > 0) {
const auto& port_max_shape = port_partial_shape.get_max_shape();
+ const auto& port_min_shape = port_partial_shape.get_min_shape();
for (auto i = 0; i < port_length; ++i) {
- if (tensor_shape[i] > port_max_shape[i]) {
+ if (port_min_shape[i] != port_max_shape[i] && tensor_shape[i] > port_max_shape[i]) {
OPENVINO_THROW("The tensor shape is not compatible with the model input/output max shape: got ",
tensor_shape,
" expecting max shape ",
port_max_shape);
}
+
+ if (port_min_shape[i] == port_max_shape[i] && tensor_shape[i] != port_min_shape[i]) {
+ OPENVINO_THROW("The tensor shape is not compatible with the model input/output shape: got ",
+ tensor_shape,
+ " expecting shape ",
+ port_min_shape);
+ }
}
}
}
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.cpp
index d679b2e0e8d..6b6c89593be 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
@@ -76,6 +76,12 @@ INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest,
::testing::ValuesIn(configsInferRequestRunTests)),
InferRequestRunTests::getTestCaseName);
+INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest,
+ DynamicBoundsTests,
+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),
+ ::testing::ValuesIn(configsInferRequestRunTests)),
+ InferRequestRunTests::getTestCaseName);
+
const std::vector<ov::AnyMap> batchingConfigs = {{ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN)},
{ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER)},
{ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::AUTO)}};
diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
index 3c4d5053795..ad3a649c1fa 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
@@ -2595,6 +2595,241 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRunningWithSameRawMemoryMultipleTimes
::operator delete(output_data, std::align_val_t(4096));
}
+using DynamicBoundsTests = InferRequestRunTests;
+
+TEST_P(DynamicBoundsTests, ChangeShapeAfterTensorIsSet) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ auto model_shape = PartialShape{1, ov::Dimension(1, 10), 2, 2};
+ auto model = createModel(element::f32, model_shape, "N...");
+
+ auto compiled_model = core->compile_model(model, target_device, configuration);
+ // Create InferRequest
+ ov::InferRequest req;
+ req = compiled_model.create_infer_request();
+
+ auto shape = Shape{1, 4, 2, 2};
+ auto shape_size = ov::shape_size(shape);
+ auto input_tensor = ov::Tensor{ov::element::f32, shape};
+ auto output_tensor = ov::Tensor{ov::element::f32, shape};
+
+ ASSERT_EQ(shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(shape, input_tensor.get_shape());
+ ASSERT_EQ(shape, output_tensor.get_shape());
+
+ req.set_input_tensor(input_tensor);
+ req.set_output_tensor(output_tensor);
+
+ auto input_data = input_tensor.data<float>();
+ auto output_data = output_tensor.data<float>();
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = 21.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ auto expected = 22.f;
+ for (size_t i = 0; i < shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ auto input_data_after_run = input_tensor.data<float>();
+ auto output_data_after_run = output_tensor.data<float>();
+
+ ASSERT_EQ(input_data, input_data_after_run);
+ ASSERT_EQ(output_data, output_data_after_run);
+
+ auto new_shape = Shape{1, 6, 2, 2};
+ auto new_shape_size = ov::shape_size(new_shape);
+ input_tensor.set_shape(new_shape);
+ output_tensor.set_shape(new_shape);
+
+ ASSERT_EQ(new_shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(new_shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(new_shape, input_tensor.get_shape());
+ ASSERT_EQ(new_shape, output_tensor.get_shape());
+
+ input_data = input_tensor.data<float>();
+ output_data = output_tensor.data<float>();
+
+ for (size_t i = 0; i < new_shape_size; ++i) {
+ input_data[i] = 25.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ expected = 26.f;
+ for (size_t i = 0; i < new_shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ ASSERT_EQ(new_shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(new_shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(new_shape, input_tensor.get_shape());
+ ASSERT_EQ(new_shape, output_tensor.get_shape());
+
+ input_data_after_run = input_tensor.data<float>();
+ output_data_after_run = output_tensor.data<float>();
+
+ ASSERT_EQ(input_data, input_data_after_run);
+ ASSERT_EQ(output_data, output_data_after_run);
+}
+
+TEST_P(DynamicBoundsTests, ChangeShapeAfterTensorIsSetUsingAlignedExternalMemory) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ auto model_shape = PartialShape{1, ov::Dimension(1, 10), 4, 64};
+ auto model = createModel(element::f32, model_shape, "N...");
+
+ auto compiled_model = core->compile_model(model, target_device, configuration);
+ // Create InferRequest
+ ov::InferRequest req;
+ req = compiled_model.create_infer_request();
+
+ ov::Allocator allocator{ov::test::utils::DefaultAllocatorAligned{}};
+
+ auto shape = Shape{1, 8, 4, 64};
+ auto shape_size = ov::shape_size(shape);
+ auto input_tensor = ov::Tensor{ov::element::f32, shape, allocator};
+ auto output_tensor = ov::Tensor{ov::element::f32, shape, allocator};
+
+ ASSERT_EQ(shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(shape, input_tensor.get_shape());
+ ASSERT_EQ(shape, output_tensor.get_shape());
+
+ req.set_input_tensor(input_tensor);
+ req.set_output_tensor(output_tensor);
+
+ auto* input_data = input_tensor.data<float>();
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = 21.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ auto expected = 22.f;
+ auto* output_data = output_tensor.data<float>();
+ for (size_t i = 0; i < shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ auto new_shape = Shape{1, 6, 4, 64};
+ auto new_shape_size = ov::shape_size(new_shape);
+ input_tensor.set_shape(new_shape);
+ output_tensor.set_shape(new_shape);
+
+ ASSERT_EQ(new_shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(new_shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(new_shape, input_tensor.get_shape());
+ ASSERT_EQ(new_shape, output_tensor.get_shape());
+
+ input_data = input_tensor.data<float>();
+ output_data = output_tensor.data<float>();
+
+ for (size_t i = 0; i < new_shape_size; ++i) {
+ input_data[i] = 25.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ expected = 26.f;
+ for (size_t i = 0; i < new_shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ ASSERT_EQ(new_shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(new_shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(new_shape, input_tensor.get_shape());
+ ASSERT_EQ(new_shape, output_tensor.get_shape());
+}
+
+TEST_P(DynamicBoundsTests, RunningTwiceWithRemoteTensor) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ auto model_shape = PartialShape{1, ov::Dimension(1, 10), 4, 64};
+ auto model = createModel(element::f32, model_shape, "N...");
+
+ auto compiled_model = core->compile_model(model, target_device, configuration);
+ // Create InferRequest
+ ov::InferRequest req;
+ req = compiled_model.create_infer_request();
+
+ auto context = core->get_default_context(target_device);
+
+ auto shape = Shape{1, 8, 4, 64};
+ auto shape_size = ov::shape_size(shape);
+ auto input_tensor = context.create_host_tensor(ov::element::f32, shape);
+ auto output_tensor = context.create_host_tensor(ov::element::f32, shape);
+
+ ASSERT_EQ(shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(shape, input_tensor.get_shape());
+ ASSERT_EQ(shape, output_tensor.get_shape());
+
+ req.set_input_tensor(input_tensor);
+ req.set_output_tensor(output_tensor);
+
+ auto* input_data = input_tensor.data<float>();
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = 21.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ auto expected = 22.f;
+ auto* output_data = output_tensor.data<float>();
+ for (size_t i = 0; i < shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ for (size_t i = 0; i < shape_size; ++i) {
+ input_data[i] = 25.f;
+ }
+
+ req.infer(); // Adds '1' to each element
+
+ expected = 26.f;
+ for (size_t i = 0; i < shape_size; ++i) {
+ ASSERT_EQ(output_data[i], expected)
+ << ": Expected=" << expected << ", actual=" << output_data[i] << " for index " << i;
+ }
+
+ ASSERT_EQ(shape_size * sizeof(float), input_tensor.get_byte_size());
+ ASSERT_EQ(shape_size * sizeof(float), output_tensor.get_byte_size());
+ ASSERT_EQ(shape, input_tensor.get_shape());
+ ASSERT_EQ(shape, output_tensor.get_shape());
+}
+
+TEST_P(DynamicBoundsTests, ExpectErrorFromWrongTensorShape) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ auto model_shape = PartialShape{1, ov::Dimension(1, 10), 4, 64};
+ auto model = createModel(element::f32, model_shape, "N...");
+
+ auto compiled_model = core->compile_model(model, target_device, configuration);
+ // Create InferRequest
+ ov::InferRequest req;
+ req = compiled_model.create_infer_request();
+
+ auto context = core->get_default_context(target_device);
+ auto input_tensor = context.create_host_tensor(ov::element::f32, Shape{1, 8, 2, 64});
+ OV_EXPECT_THROW(req.set_input_tensor(input_tensor),
+ ov::Exception,
+ HasSubstr("The tensor shape is not compatible with the model input/output shape"));
+
+ auto output_tensor = context.create_host_tensor(ov::element::f32, Shape{1, 8, 12, 64});
+ OV_EXPECT_THROW(req.set_output_tensor(output_tensor),
+ ov::Exception,
+ HasSubstr("The tensor shape is not compatible with the model input/output shape"));
+}
+
} // namespace behavior
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/common/utils.hpp b/src/plugins/intel_npu/tests/functional/common/utils.hpp
index 5199d41f11e..441a0c7b79c 100644
--- a/src/plugins/intel_npu/tests/functional/common/utils.hpp
+++ b/src/plugins/intel_npu/tests/functional/common/utils.hpp
@@ -134,7 +134,7 @@ public:
void deallocate(void* handle, const size_t bytes, size_t alignment = 4096) noexcept {
::operator delete(static_cast<uint8_t*>(handle) - _offset, std::align_val_t(alignment));
}
- bool is_equal(const DefaultAllocatorNotAligned& other) const {
+ bool is_equal(const DefaultAllocatorNotAligned&) const {
return false;
}
@@ -142,6 +142,19 @@ private:
size_t _offset = 16;
};
+class DefaultAllocatorAligned final {
+public:
+ void* allocate(const size_t bytes, const size_t) {
+ return ::operator new(bytes, std::align_val_t(4096));
+ }
+ void deallocate(void* handle, const size_t, size_t) noexcept {
+ ::operator delete(static_cast<uint8_t*>(handle), std::align_val_t(4096));
+ }
+ bool is_equal(const DefaultAllocatorAligned&) const {
+ return false;
+ }
+};
+
std::tuple</* importMemoryBatched */ ov::Tensor,
/* importMemoryTensor_1 */ ov::Tensor,
/* importMemoryTensor_2 */ ov::Tensor,