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
[NPUW] Bounds-check KVCacheDesc::dim to prevent OOB write on imported blobs (#37674)
Wei Wang5ba946d0ff9e
diff --git a/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cppindex 23b25df3277..3bc27fb6d96 100644--- a/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp@@ -16,9 +16,21 @@ ov::SoPtr<ov::ITensor> ov::npuw::util::make_tensor_slice(ov::SoPtr<ov::ITensor>uint32_t dim,uint32_t start_pos,uint32_t end_pos) {- ov::Shape start_shape(std::vector<size_t>(tensor->get_shape().size(), 0u));+ // `dim` may originate from a deserialized KVCacheDesc and is used below to subscript+ // freshly-allocated ov::Shape vectors. Validate it against the actual tensor rank before+ // the stores, otherwise a malformed axis is an out-of-bounds write on the shape vectors.+ const auto& shape = tensor->get_shape();+ OPENVINO_ASSERT(dim < shape.size(), "KV slice axis ", dim, " is out of range for a rank-", shape.size(), " tensor");+ OPENVINO_ASSERT(start_pos <= end_pos && end_pos <= shape[dim],+ "KV slice [",+ start_pos,+ ", ",+ end_pos,+ ") is out of range for extent ",+ shape[dim]);+ ov::Shape start_shape(std::vector<size_t>(shape.size(), 0u));start_shape[dim] = start_pos;- ov::Shape end_shape = tensor->get_shape();+ ov::Shape end_shape = shape;end_shape[dim] = end_pos;return ov::get_tensor_impl(ov::Tensor(ov::make_tensor(tensor), start_shape, end_shape));}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 46a9662f9d1..36ae9cf8989 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -3,6 +3,8 @@//#include "llm_compiled_model.hpp"+#include <algorithm>+#include "embedding/embedding_infer_request.hpp"#include "embedding/encoder_embedding_infer_request.hpp"#include "embedding/prepare_embedding_model.hpp"@@ -1829,6 +1831,9 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);}+ // Reject blobs whose KVCacheDesc::dim is not a valid axis for the restored KV tensors.+ compiled->validate_imported_kvcache_dim();+return compiled;};@@ -1847,6 +1852,47 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialreturn compiled;}+void ov::npuw::LLMCompiledModel::validate_imported_kvcache_dim() const {+ // On the compile path every KV axis is in [0, rank), so an out-of-range one means a tampered blob.+ auto validate_ports = [this](const std::vector<ov::Output<const ov::Node>>& ports, bool v_transposed) {+ for (const auto& port : ports) {+ // Check every alias, so get_any_name()'s choice can't hide a KV port.+ for (const auto& name : port.get_names()) {+ const auto past_name = ov::npuw::util::present_to_past_key_values_name(name);+ const bool is_key = ov::npuw::util::isPastKeyParam(name) ||+ ov::npuw::util::isPresentKeyValuesKey(name).has_value() ||+ ov::npuw::util::isDQScaleOrZPKey(past_name);+ const bool is_value = ov::npuw::util::isPastValueParam(name) ||+ ov::npuw::util::isPresentKeyValuesValue(name).has_value() ||+ ov::npuw::util::isDQScaleOrZPValue(past_name);+ if (!is_key && !is_value) {+ continue;+ }+ // Same axis selection as the runtime KV copy/slice helpers.+ const uint32_t axis = (is_value && v_transposed) ? 3u : m_kvcache_desc.dim;+ const auto& rank = port.get_partial_shape().rank();+ OPENVINO_ASSERT(rank.is_static() && axis < static_cast<uint32_t>(rank.get_length()),+ "NPUW blob: KV axis ",+ axis,+ " is out of range for tensor '",+ name,+ "' of rank ",+ rank,+ ".");+ }+ }+ };++ for (const auto& variant : m_generate_compiled_variants) {+ validate_ports(variant->inputs(), m_kvcache_desc.v_tensors_transposed_gen);+ validate_ports(variant->outputs(), m_kvcache_desc.v_tensors_transposed_gen);+ }+ if (m_prefill_compiled) {+ validate_ports(m_prefill_compiled->inputs(), m_kvcache_desc.v_tensors_transposed_pre);+ validate_ports(m_prefill_compiled->outputs(), m_kvcache_desc.v_tensors_transposed_pre);+ }+}+std::shared_ptr<const ov::Model> ov::npuw::LLMCompiledModel::get_runtime_model() const {OPENVINO_NOT_IMPLEMENTED;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex fbe034f18ba..013b53a1a37 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp@@ -112,6 +112,12 @@ protected:const ov::AnyMap& properties,const ov::npuw::s11n::CompiledContext& ctx);+ // Trust-boundary check for imported blobs: KVCacheDesc::dim and the V-transposed flags are read+ // from the stream and select the axis used to subscript shape vectors in the KV-slice helpers.+ // Reject them unless that axis is valid for every KV input/output of the restored prefill and+ // generate models.+ void validate_imported_kvcache_dim() const;+std::string m_name;std::shared_ptr<::intel_npu::OptionsDesc> m_options_desc;::intel_npu::Config m_cfg;diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 3a937803d82..8b5fe32ceb4 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -980,8 +980,8 @@ bool ov::npuw::util::matchLoRAMatMulAlphaString(const std::string& input) {}bool ov::npuw::util::matchLinCacheString(const std::string& input, const std::string& past_or_present) {- static std::regex past_regex_pattern("^cache_params\\.past\\.(conv|ssm)\\.(\\d+)$");- static std::regex present_regex_pattern("^cache_params\\.present\\.(conv|ssm)\\.(\\d+)$");+ static const std::regex past_regex_pattern("^cache_params\\.past\\.(conv|ssm)\\.(\\d+)$");+ static const std::regex present_regex_pattern("^cache_params\\.present\\.(conv|ssm)\\.(\\d+)$");const std::regex& regex_pattern = (past_or_present == "past") ? past_regex_pattern : present_regex_pattern;return std::regex_match(input, regex_pattern);}@@ -1042,7 +1042,6 @@ bool ov::npuw::util::isRestoredPastKeyValueParam(const std::string& str) {// Match badly handled KVCache states by StatefulToStateless pass for Whisper.static const std::regex restored_pattern(R"((input_restored\.past_key_values\.(\d+)\.decoder\.(key|value))(present\.(\d+)\.decoder\.(key|value)))");- ;return std::regex_match(str, restored_pattern);}@@ -1050,7 +1049,7 @@ std::optional<int> ov::npuw::util::isPastKeyValuesKeyContiguous(const std::strin// Match only the single contiguous past key param (no _block_ suffix).// Allows optional intermediate parts like "encoder" or "decoder" (for Whisper).// Returns the layer index if matched.- std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.key)");+ static const std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.key)");std::smatch match;if (std::regex_match(str, match, pattern)) {int index = std::stoi(match[1].str());@@ -1063,7 +1062,7 @@ std::optional<int> ov::npuw::util::isPastKeyValuesValueContiguous(const std::str// Match only the single contiguous past value param (no _block_ suffix).// Allows optional intermediate parts like "encoder" or "decoder" (for Whisper).// Returns the layer index if matched.- std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.value)");+ static const std::regex pattern(R"(past_key_values\.(\d+)(?:\.[^.]+)*\.value)");std::smatch match;if (std::regex_match(str, match, pattern)) {int index = std::stoi(match[1].str());@@ -1073,7 +1072,7 @@ std::optional<int> ov::npuw::util::isPastKeyValuesValueContiguous(const std::str}std::optional<int> ov::npuw::util::isPresentKeyValuesKey(const std::string& str) {- std::regex pattern(R"(present\.(\d+)(?:\.[^.]+)*\.key)");+ static const std::regex pattern(R"(present\.(\d+)(?:\.[^.]+)*\.key)");std::smatch match;if (std::regex_match(str, match, pattern)) {int index = std::stoi(match[1].str());@@ -1083,7 +1082,7 @@ std::optional<int> ov::npuw::util::isPresentKeyValuesKey(const std::string& str)}std::optional<int> ov::npuw::util::isPresentKeyValuesValue(const std::string& str) {- std::regex pattern(R"(present\.(\d+)(?:\.[^.]+)*\.value)");+ static const std::regex pattern(R"(present\.(\d+)(?:\.[^.]+)*\.value)");std::smatch match;if (std::regex_match(str, match, pattern)) {int index = std::stoi(match[1].str());diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 7d67f988365..0964960d1d1 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -217,4 +217,5 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/host_flash_attention_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_k_tag_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_executor_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/make_tensor_slice_bounds_test.cpp)diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cppindex 6a1c8bdef10..bb3689898c8 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp@@ -46,6 +46,34 @@ struct LLMVariantSwitchTestAccess {compiled->m_kvcache_desc.num_stored_tokens = num_tokens;}+ static void set_kv_dim(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled, uint32_t dim) {+ compiled->m_kvcache_desc.dim = dim;+ }++ static void validate_imported_kvcache_dim(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {+ compiled->validate_imported_kvcache_dim();+ }++ static void set_prefill_compiled(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,+ std::shared_ptr<ov::npuw::ICompiledModel_v0> prefill) {+ compiled->m_prefill_compiled = std::move(prefill);+ }++ // Mirrors the production name-matching in validate_imported_kvcache_dim(): a port may carry+ // several names, so match against all of them rather than get_any_name()'s single alias.+ static uint32_t past_key_tensor_rank(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {+ for (const auto& port : compiled->m_generate_compiled_variants.back()->inputs()) {+ const auto& names = port.get_names();+ const bool is_past_key = std::any_of(names.begin(), names.end(), [](const std::string& name) {+ return ov::npuw::util::isPastKeyParam(name);+ });+ if (is_past_key) {+ return static_cast<uint32_t>(port.get_partial_shape().rank().get_length());+ }+ }+ return 0u;+ }+static uint32_t kv_dim_for_name(const ov::npuw::LLMInferRequest& req, const std::string& name) {const auto& desc = req.m_npuw_llm_compiled_model->m_kvcache_desc;// Mirror copy_kvcache()/on_generate_variant_switch(): classify via the present name so@@ -493,4 +521,51 @@ TEST_F(LLMInferRequestVariantSwitchTest, CurrentVariantCapacityRejectsOutOfRangeEXPECT_THROW(LLMVariantSwitchTestAccess::current_variant_capacity(req), std::out_of_range);}+// KVCacheDesc::dim is read verbatim from an imported blob and is later used to subscript shape+// vectors in the KV-slice helpers, so a malformed value is a heap out-of-bounds write. deserialize()+// runs validate_imported_kvcache_dim() at the trust boundary to reject such blobs.+TEST_F(LLMInferRequestVariantSwitchTest, RejectsImportedKvcacheDimOutOfTensorRank) {+ VariantSwitchFactory factory;+ auto compiled = create_compiled_model({}, factory);+ ASSERT_NE(compiled, nullptr);++ const uint32_t rank = LLMVariantSwitchTestAccess::past_key_tensor_rank(compiled);+ ASSERT_GT(rank, 0u) << "test model is expected to expose past-key KV tensors";++ for (uint32_t dim = 0; dim < rank; ++dim) {+ LLMVariantSwitchTestAccess::set_kv_dim(compiled, dim);+ EXPECT_NO_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled)) << "dim=" << dim;+ }++ LLMVariantSwitchTestAccess::set_kv_dim(compiled, rank);+ EXPECT_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled), ov::Exception);++ LLMVariantSwitchTestAccess::set_kv_dim(compiled, 0xFFFFFFFFu);+ EXPECT_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled), ov::Exception);+}++// A dim valid for the rank-4 generate KV tensors must still be rejected when a restored prefill KV+// tensor has a smaller rank, since prefill SWA updates slice along it too.+TEST_F(LLMInferRequestVariantSwitchTest, RejectsImportedKvcacheDimOutOfPrefillTensorRank) {+ VariantSwitchFactory factory;+ auto compiled = create_compiled_model({}, factory);+ ASSERT_NE(compiled, nullptr);+ ASSERT_EQ(LLMVariantSwitchTestAccess::past_key_tensor_rank(compiled), 4u);++ auto past = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 8});+ past->output(0).set_names({"past_key_values.0.swa.key"});+ auto present = std::make_shared<ov::op::v0::Result>(past);+ present->output(0).set_names({"present.0.swa.key"});+ auto prefill_model = std::make_shared<ov::Model>(ov::ResultVector{present}, ov::ParameterVector{past});+ LLMVariantSwitchTestAccess::set_prefill_compiled(+ compiled,+ std::make_shared<FakeSubCompiledModel>(prefill_model, m_plugin, ov::AnyMap{}));++ LLMVariantSwitchTestAccess::set_kv_dim(compiled, 1u);+ EXPECT_NO_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled));++ LLMVariantSwitchTestAccess::set_kv_dim(compiled, 2u);+ EXPECT_THROW(LLMVariantSwitchTestAccess::validate_imported_kvcache_dim(compiled), ov::Exception);+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/make_tensor_slice_bounds_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/make_tensor_slice_bounds_test.cppnew file mode 100644index 00000000000..38c0ba75ec7--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/make_tensor_slice_bounds_test.cpp@@ -0,0 +1,70 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <cstdint>++#include "infer_request_utils.hpp"+#include "openvino/core/except.hpp"+#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/tensor.hpp"++namespace {++class SliceableTensor {+public:+ explicit SliceableTensor(const ov::Shape& shape) : m_tensor(ov::element::f32, shape) {}++ ov::SoPtr<ov::ITensor> impl() const {+ return ov::get_tensor_impl(m_tensor);+ }++private:+ ov::Tensor m_tensor;+};++// These tests pin the bounds checks in ov::npuw::util::make_tensor_slice(), the single choke point+// every KV-slice caller funnels through.+TEST(MakeTensorSliceBoundsTest, ValidSliceProducesExpectedShape) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});++ ov::SoPtr<ov::ITensor> slice;+ ASSERT_NO_THROW(slice = ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/2u, /*start=*/2u, /*end=*/5u));+ EXPECT_EQ(slice->get_shape(), (ov::Shape{1, 4, 3, 16}));+}++TEST(MakeTensorSliceBoundsTest, FullExtentSliceIsAccepted) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});++ ov::SoPtr<ov::ITensor> slice;+ ASSERT_NO_THROW(slice = ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/2u, /*start=*/0u, /*end=*/8u));+ EXPECT_EQ(slice->get_shape(), (ov::Shape{1, 4, 8, 16}));+}++TEST(MakeTensorSliceBoundsTest, AxisEqualToRankIsRejected) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});+ EXPECT_THROW(ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/4u, /*start=*/0u, /*end=*/1u),+ ov::Exception);+}++TEST(MakeTensorSliceBoundsTest, AxisFarBeyondRankIsRejected) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});+ EXPECT_THROW(ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/0xFFFFFFFFu, /*start=*/0u, /*end=*/1u),+ ov::Exception);+}++TEST(MakeTensorSliceBoundsTest, EndBeyondExtentIsRejected) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});+ EXPECT_THROW(ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/2u, /*start=*/0u, /*end=*/9u),+ ov::Exception);+}++TEST(MakeTensorSliceBoundsTest, InvertedIntervalIsRejected) {+ SliceableTensor tensor(ov::Shape{1, 4, 8, 16});+ EXPECT_THROW(ov::npuw::util::make_tensor_slice(tensor.impl(), /*dim=*/2u, /*start=*/5u, /*end=*/2u),+ ov::Exception);+}++} // namespace