Skip to content

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

[NPUW] Reject import blob where kvcache size table disagrees with generate variant count (#37664)

Wei Wangd93023a9b218
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.cpp
index cc3d4589021..73094fa9ff5 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
@@ -1784,6 +1784,18 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
uint32_t num_variants = 0;
stream & num_variants;
+ // m_kvcache_sizes and the generate variants are conceptually one object: the size table
+ // has exactly one entry per variant. They are serialized as two independent fields, so a
+ // corrupted blob can declare a size table that disagrees with the variant count. The two
+ // containers are later indexed by each other's size, so a mismatch is an out-of-bounds
+ // access. Enforce the invariant here, at restore time, before anything can consume it.
+ OPENVINO_ASSERT(compiled->m_kvcache_sizes.size() == num_variants,
+ "NPUW blob: kvcache size table (",
+ compiled->m_kvcache_sizes.size(),
+ ") does not match generate variant count (",
+ num_variants,
+ ").");
+
compiled->m_generate_compiled_variants.reserve(num_variants);
// Deserialize CompiledModels
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
index 570f646c92f..5521daef150 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
@@ -563,8 +563,12 @@ std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::LLMInferRequest::select_genera
int64_t expected_total_tokens = prompt_length + min_response_len;
const auto& kvcache_sizes = m_npuw_llm_compiled_model->m_kvcache_sizes;
+ // Defence in depth: kvcache_sizes and m_generate_requests are parallel containers (one size per
+ // variant). We index m_generate_requests by a kvcache_sizes position below, so never walk past the
+ // shorter of the two even if a tampered blob slipped an inconsistent size table past the loader.
+ const size_t num_variants = std::min(kvcache_sizes.size(), m_generate_requests.size());
// Find the smallest variant that can accommodate the expected token count
- for (size_t i = 0; i < kvcache_sizes.size(); ++i) {
+ for (size_t i = 0; i < num_variants; ++i) {
if (expected_total_tokens <= kvcache_sizes[i]) {
LOG_DEBUG("Selected generate request " << (i + 1) << "/" << kvcache_sizes.size() << " with size "
<< kvcache_sizes[i] << " for prompt_length=" << prompt_length
@@ -697,8 +701,12 @@ void ov::npuw::LLMInferRequest::bind_generate_variant(int64_t prompt_length) {
m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);
// Record the selected variant index for O(1) capacity queries and mid-decode switching.
const auto& reqs = m_generate_requests;
- m_kvcache_variant_idx =
- static_cast<size_t>(std::distance(reqs.begin(), std::find(reqs.begin(), reqs.end(), m_kvcache_request)));
+ const auto it = std::find(reqs.begin(), reqs.end(), m_kvcache_request);
+ // A miss would make std::distance yield reqs.size(), an out-of-bounds index later used to look up
+ // m_kvcache_sizes (get_current_variant_capacity). select_generate_request() always returns an
+ // element of m_generate_requests, so a miss means invariants upstream are broken.
+ OPENVINO_ASSERT(it != reqs.end(), "NPUW: active kvcache request is not among the generate variants.");
+ m_kvcache_variant_idx = static_cast<size_t>(std::distance(reqs.begin(), it));
}
void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_length) {
@@ -912,7 +920,7 @@ void ov::npuw::LLMInferRequest::copy_lincache(
uint32_t ov::npuw::LLMInferRequest::get_current_variant_capacity() const {
// The generate model's past KV input tensor is shaped to (kv_size - max_generation_token_len)
// by ReshapeToStatic. Capacity is the number of past tokens that fit, not the total KV window.
- const uint32_t kv_size = m_npuw_llm_compiled_model->m_kvcache_sizes[m_kvcache_variant_idx];
+ const uint32_t kv_size = m_npuw_llm_compiled_model->m_kvcache_sizes.at(m_kvcache_variant_idx);
const uint32_t max_gen_len = m_npuw_llm_compiled_model->m_kvcache_desc.max_generation_token_len;
OPENVINO_ASSERT(kv_size >= max_gen_len,
"KV cache size ",
@@ -925,10 +933,14 @@ uint32_t ov::npuw::LLMInferRequest::get_current_variant_capacity() const {
bool ov::npuw::LLMInferRequest::try_switch_to_larger_variant() {
const size_t next_idx = m_kvcache_variant_idx + 1;
- if (next_idx >= m_generate_requests.size()) {
+ const auto& kvcache_sizes = m_npuw_llm_compiled_model->m_kvcache_sizes;
+ // Guard against both: m_generate_requests[next_idx] and kvcache_sizes[next_idx]. They are
+ // parallel (one size per variant) and the loader enforces equal length, but bounding only
+ // one while indexing the other is the anti-pattern that makes out-of-bounds vulnerabilities
+ // exploitable.
+ if (next_idx >= m_generate_requests.size() || next_idx >= kvcache_sizes.size()) {
return false; // already at the largest variant
}
- const auto& kvcache_sizes = m_npuw_llm_compiled_model->m_kvcache_sizes;
LOG_INFO("KV cache capacity (" << kvcache_sizes[m_kvcache_variant_idx] << ") reached at "
<< m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens
<< " stored tokens; switching to variant with capacity " << kvcache_sizes[next_idx]
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.cpp
index 49c1ef97480..1e17dbf0828 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
@@ -7,7 +7,10 @@
#include <algorithm>
#include <cstdint>
#include <cstring>
+#include <limits>
#include <memory>
+#include <sstream>
+#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
@@ -19,6 +22,7 @@
#include "llm_compiled_model.hpp"
#include "llm_test_helpers.hpp"
#include "openvino/openvino.hpp"
+#include "serialization.hpp"
#include "util.hpp"
namespace ov::test::npuw {
@@ -78,6 +82,77 @@ struct LLMVariantSwitchTestAccess {
static const auto& kvcache_request(const ov::npuw::LLMInferRequest& req) {
return req.m_kvcache_request;
}
+
+ static void set_kvcache_sizes(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,
+ std::vector<uint32_t> sizes) {
+ compiled->m_kvcache_sizes = std::move(sizes);
+ }
+
+ static std::size_t generate_request_count(const ov::npuw::LLMInferRequest& req) {
+ return req.m_generate_requests.size();
+ }
+
+ static std::shared_ptr<ov::IAsyncInferRequest> select_generate_request(ov::npuw::LLMInferRequest& req,
+ int64_t prompt_length) {
+ return req.select_generate_request(prompt_length);
+ }
+
+ static bool is_known_generate_request(const ov::npuw::LLMInferRequest& req,
+ const std::shared_ptr<ov::IAsyncInferRequest>& request) {
+ return std::find(req.m_generate_requests.begin(), req.m_generate_requests.end(), request) !=
+ req.m_generate_requests.end();
+ }
+
+ static void set_current_variant_index(ov::npuw::LLMInferRequest& req, std::size_t idx) {
+ req.m_kvcache_variant_idx = idx;
+ }
+
+ // Re-serialize the model's metadata in the exact field order LLMCompiledModel::serialize() uses
+ // (write_model_meta), but write a forged trailing variant count instead of the real one. All
+ // fields except that count come straight from the real, valid compiled model, so the blob
+ // deserializes successfully right up to the size-table/variant-count invariant check.
+ static std::string serialize_meta_with_variant_count(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled,
+ uint32_t forged_variant_count) {
+ namespace s = ov::npuw::s11n;
+ std::ostringstream os;
+ s::write(os, compiled->m_name);
+ s::write(os, compiled->inputs());
+ s::write(os, compiled->outputs());
+ auto& d = compiled->m_kvcache_desc;
+ s::write(os, d.max_prompt_size);
+ s::write(os, d.total_size);
+ s::write(os, d.num_stored_tokens);
+ s::write(os, d.dim);
+ s::write(os, d.max_generation_token_len);
+ s::write(os, d.v_tensors_transposed_pre);
+ s::write(os, d.v_tensors_transposed_gen);
+ s::write(os, compiled->m_prefill_chunk_size);
+ s::write(os, compiled->m_use_chunk_prefill);
+ s::write(os, compiled->m_max_lora_rank);
+ s::write(os, compiled->m_enable_prefix_caching);
+ s::write(os, compiled->m_prefix_caching_block_size);
+ s::write(os, compiled->m_prefix_caching_max_num_blocks);
+ s::write(os, compiled->m_longrope_context_limit);
+ s::write(os, compiled->m_is_whisper);
+ s::write(os, compiled->m_eos_token_id);
+ s::write(os, compiled->m_decomposed_sdpa_size);
+ s::write(os, compiled->m_is_eagle);
+ s::write(os, compiled->m_is_embedding);
+ s::write(os, compiled->m_is_block_kv_cache);
+ s::write(os, compiled->m_is_encoder_embedding);
+ s::write(os, compiled->m_swa_window_size);
+ s::write(os, compiled->m_longrope_tables);
+ s::write(os, compiled->m_cfg);
+ s::write(os, compiled->m_kvcache_sizes);
+ s::write(os, forged_variant_count);
+ return os.str();
+ }
+
+ static std::shared_ptr<ov::npuw::LLMCompiledModel> deserialize(std::istream& stream,
+ const std::shared_ptr<const ov::IPlugin>& plugin) {
+ ov::npuw::s11n::CompiledContext ctx(false, nullptr, nullptr);
+ return ov::npuw::LLMCompiledModel::deserialize(stream, plugin, {}, ctx);
+ }
};
} // namespace ov::test::npuw
@@ -318,4 +393,62 @@ TEST_F(LLMInferRequestVariantSwitchTest, BlockKvVariantsExposeCompatibleBindings
EXPECT_EQ(small_value_block0, large_value_block0);
}
+// The deserializer restores m_kvcache_sizes and the generate-variant count as two independent blob
+// fields. A corrupted blob can therefore declare a size table that disagrees with the variant count,
+// which downstream turns into an out-of-bounds read. LLMCompiledModel::deserialize() now rejects the
+// mismatch at restore time. This exercises the real import path: it re-serializes a valid model's
+// metadata but forges the trailing variant count so it no longer matches the 2-entry size table.
+TEST_F(LLMInferRequestVariantSwitchTest, ImportRejectsSizeTableThatDisagreesWithVariantCount) {
+ VariantSwitchFactory factory;
+ auto compiled = create_compiled_model({}, factory);
+ ASSERT_NE(compiled, nullptr);
+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);
+
+ const std::string blob = LLMVariantSwitchTestAccess::serialize_meta_with_variant_count(compiled, /*forged=*/3u);
+ std::istringstream in(blob);
+
+ try {
+ LLMVariantSwitchTestAccess::deserialize(in, m_plugin);
+ FAIL() << "Expected import to reject a kvcache size table that disagrees with the variant count";
+ } catch (const ov::Exception& ex) {
+ EXPECT_NE(std::string(ex.what()).find("does not match generate variant count"), std::string::npos) << ex.what();
+ }
+}
+
+// The loader now enforces the invariant, and this test pins the defence-in-depth guard in the consumer:
+// even if a mismatched size table reaches it, the walk is bounded to the shorter container.
+TEST_F(LLMInferRequestVariantSwitchTest, SelectGenerateRequestStaysInBoundsWhenSizeTableExceedsVariants) {
+ VariantSwitchFactory factory;
+ auto compiled = create_compiled_model({}, factory);
+ ASSERT_NE(compiled, nullptr);
+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);
+
+ ov::npuw::LLMInferRequest req(compiled);
+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_request_count(req), 2u);
+
+ LLMVariantSwitchTestAccess::set_kvcache_sizes(
+ compiled,
+ {0u, 0u, std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()});
+
+ auto selected = LLMVariantSwitchTestAccess::select_generate_request(req, /*prompt_length=*/16);
+
+ EXPECT_TRUE(LLMVariantSwitchTestAccess::is_known_generate_request(req, selected));
+}
+
+// m_kvcache_variant_idx is derived from a std::find over m_generate_requests and then used to index
+// the independently sized m_kvcache_sizes. An out-of-range index must fault loudly via .at() instead
+// of reading past the size table.
+TEST_F(LLMInferRequestVariantSwitchTest, CurrentVariantCapacityRejectsOutOfRangeVariantIndex) {
+ VariantSwitchFactory factory;
+ auto compiled = create_compiled_model({}, factory);
+ ASSERT_NE(compiled, nullptr);
+
+ ov::npuw::LLMInferRequest req(compiled);
+
+ LLMVariantSwitchTestAccess::set_kvcache_sizes(compiled, {128u});
+ LLMVariantSwitchTestAccess::set_current_variant_index(req, 1u);
+
+ EXPECT_THROW(LLMVariantSwitchTestAccess::current_variant_capacity(req), std::out_of_range);
+}
+
} // namespace