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] Validate weightless Const offset/size against the weights file (CWE-125) (#37507)
Xu Xingd0bc3d328a06
diff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cppindex 3d3c137e327..973e0a0da7b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp@@ -9,6 +9,7 @@#include <variant>#include "logging.hpp"+#include "openvino/core/memory_util.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/reference/convert.hpp"@@ -57,6 +58,27 @@ bool Const::operator==(const Const& other) const {m_cached_ptr == other.m_cached_ptr);}+void Const::validate_weight_range(std::size_t weights_size) const {+ // m_cached_type, m_cached_shape, m_offset and m_byte_size are read verbatim from the+ // (untrusted) blob - see serialize(). Check them before any pointer into the weights+ // storage is handed out or copied from.++ // element::string is rejected too: its "elements" are std::string objects, so a view over+ // the mmaped file would reinterpret raw file bytes as objects holding pointers.+ OPENVINO_ASSERT(m_cached_type.is_static() && m_cached_type != ov::element::string,+ "[NPU] ORC weight has unsupported element type");+ // get_memory_size_safe() returns the *packed* size, matching both Constant::get_byte_size()+ // (the source of m_byte_size) and ITensor::get_byte_size() (the span of the view built from+ // it), hence correct for sub-byte types. Overflowing shape/byte size comes back as nullopt.+ const auto expected_byte_size = ov::util::get_memory_size_safe(m_cached_type, m_cached_shape);+ OPENVINO_ASSERT(expected_byte_size && *expected_byte_size == m_byte_size,+ "[NPU] ORC weight byte_size does not match tensor shape");+ // Subtraction, not m_offset + m_byte_size: the sum can wrap. The first clause guards the+ // (unsigned) subtraction in the second.+ OPENVINO_ASSERT(m_offset <= weights_size && m_byte_size <= weights_size - m_offset,+ "[NPU] ORC weight offset/size out of range");+}+ov::Tensor Const::eval() const {if (m_node) {return ov::npuw::util::copy_tensor_from_const(m_node);@@ -74,6 +96,9 @@ ov::Tensor Const::eval() const {} else {mapped_memory = ov::load_mmap_object(ov::util::make_path(m_weights_path));}+ // Re-check: read_weight() saw the file as it was at import time, but it is mapped again+ // right above - possibly much later, and the file may have changed since.+ validate_weight_range(mapped_memory->size());m_mmaped_weights =std::make_shared<ov::npuw::s11n::Weights>(mapped_memory->data(), mapped_memory->size(), mapped_memory);return ov::Tensor(m_cached_type, m_cached_shape, m_mmaped_weights->get_ptr(m_offset));@@ -105,6 +130,9 @@ void Const::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {return;}if (ctx.weights) {+ // ctx.weights maps the very same file eval() maps lazily later on, so a malformed+ // weight description is rejected already at import time - for both branches below.+ validate_weight_range(ctx.weights->size());if (ctx.bf16_consts.find({m_offset, m_byte_size}) != ctx.bf16_consts.end()) {NPUW_ASSERT(m_cached_type == ov::element::f16);// Read original bf16 weightdiff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hppindex 42c5aec7251..d1054a71964 100644--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp@@ -103,6 +103,10 @@ public:void serialize(ov::npuw::orc::Stream& stream);private:+ // Checks the deserialized weight description (type/shape/offset/byte_size) against the+ // size of the weights storage it is about to be read from. Throws if it does not fit.+ void validate_weight_range(std::size_t weights_size) const;+std::shared_ptr<ov::op::v0::Constant> m_node = nullptr;ov::element::Type m_cached_type;ov::Shape m_cached_shape;diff --git a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp b/src/plugins/intel_npu/tests/unit/npuw/serialization.cppindex 1d4e79fe1a6..d6d0cae5b3a 100644--- a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp@@ -10,6 +10,7 @@#include <fstream>#include <iostream>#include <limits>+#include <system_error>#include "attention.hpp"#include "common_test_utils/file_utils.hpp"@@ -21,6 +22,7 @@#include "lazy_tensor.hpp"#include "model_builder.hpp"#include "moe_transformations/moe_transformation.hpp"+#include "openvino/core/memory_util.hpp"#include "openvino/core/parallel.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/op/constant.hpp"@@ -231,6 +233,189 @@ std::shared_ptr<ov::op::v0::Constant> make_weightless_constant(const ov::elementreturn constant;}+// Like make_weightless_constant(), but takes packed bytes - for sub-byte types they differ from the element count.+std::shared_ptr<ov::op::v0::Constant> make_weightless_constant_from_bytes(const ov::element::Type& type,+ const ov::Shape& shape,+ const std::vector<uint8_t>& bytes,+ std::size_t offset) {+ auto storage = std::make_shared<std::vector<uint8_t>>(bytes);+ auto constant = std::make_shared<ov::op::v0::Constant>(type, shape, storage->data(), storage);+ constant->get_rt_info()[ov::WeightlessCacheAttribute::get_type_info_static()] =+ ov::WeightlessCacheAttribute(constant->get_byte_size(), offset, type);+ return constant;+}++// RAII: a gtest ASSERT_* failure only returns from the enclosing helper, skipping trailing cleanup.+// Declare it before the LazyTensors: on Windows the file can't be removed while a mapping is open.+struct ScopedFile {+ explicit ScopedFile(std::filesystem::path p) : path(std::move(p)) {}+ ScopedFile(ScopedFile&&) = default;+ ScopedFile(const ScopedFile&) = delete;+ ScopedFile& operator=(const ScopedFile&) = delete;+ ~ScopedFile() {+ std::error_code ec;+ std::filesystem::remove(path, ec); // never throws from a destructor+ }++ std::filesystem::path path;+};++ScopedFile write_binary_file(const std::string& tag, const std::vector<uint8_t>& bytes) {+ std::filesystem::path path = ov::test::utils::generateTestFilePrefix() + "_npuw_lazy_" + tag + "_weights.bin";+ {+ std::ofstream os(path, std::ios::binary);+ os.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));+ }+ return ScopedFile(std::move(path));+}++// Full import path of one weightless Const: serialize -> deserialize -> read_weight() (lazy-mmap)+// -> eval(). The file is `offset` filler + packed weight + `tail_size` filler: the leading filler+// proves the view starts at `offset`, and `tail_size == 0` is the exact-fit case.+void expect_lazy_weightless_mmap_roundtrip(const ov::element::Type& type,+ const ov::Shape& shape,+ std::size_t offset,+ std::size_t tail_size,+ const std::string& tag) {+ using namespace ov::npuw::s11n;++ const auto packed_size = ov::util::get_memory_size(type, ov::shape_size(shape));+ ASSERT_GT(packed_size, 0u);++ std::vector<uint8_t> payload(packed_size);+ for (std::size_t i = 0; i < payload.size(); ++i) {+ payload[i] = static_cast<uint8_t>(0x5Au + i);+ }++ auto constant = make_weightless_constant_from_bytes(type, shape, payload, offset);+ // The invariant the importer relies on: Constant::get_byte_size() is the *packed* size.+ ASSERT_EQ(constant->get_byte_size(), packed_size);++ std::vector<uint8_t> file_bytes(offset, 0xCCu);+ file_bytes.insert(file_bytes.end(), payload.begin(), payload.end());+ file_bytes.insert(file_bytes.end(), tail_size, 0xDDu);++ const ScopedFile weights_file = write_binary_file(tag, file_bytes);++ ov::npuw::weights::LazyTensor var(constant);+ ov::npuw::weights::LazyTensor res;++ std::stringstream ss;+ write(ss, var);+ read(ss, res);++ {+ auto mapped = ov::load_mmap_object(weights_file.path);+ ASSERT_NE(mapped, nullptr);+ auto weights = std::make_shared<Weights>(reinterpret_cast<char*>(mapped->data()), mapped->size(), mapped);++ // Non-null weights + weights_path + empty consts_cache -> lazy-mmap branch.+ WeightsContext import_ctx(weights, weights_file.path.string(), {}, {});+ ASSERT_NO_THROW(res.read_weight(import_ctx));+ } // import-time mapping released here; eval() maps the file on its own++ ov::Tensor evaluated;+ ASSERT_NO_THROW(evaluated = res.eval());+ EXPECT_EQ(evaluated.get_element_type(), type);+ EXPECT_EQ(evaluated.get_shape(), shape);+ ASSERT_EQ(evaluated.get_byte_size(), packed_size);+ // The view must start exactly at `offset` - i.e. hold the payload, not the filler+ EXPECT_EQ(std::memcmp(static_cast<const ov::Tensor&>(evaluated).data(), payload.data(), packed_size), 0);+ expect_tensors_equal(var.eval(), evaluated);+}++// Same import path, but the weight description is malformed (by default: it does not fit the+// weights file). read_weight() must reject the blob instead of handing out an OOB view.+void expect_lazy_weightless_mmap_rejected(+ const ov::element::Type& type,+ const ov::Shape& shape,+ std::size_t offset,+ std::size_t file_size,+ const std::string& tag,+ const std::string& expected_message = "[NPU] ORC weight offset/size out of range") {+ using namespace ov::npuw::s11n;++ const auto packed_size = ov::util::get_memory_size(type, ov::shape_size(shape));+ auto constant = make_weightless_constant_from_bytes(type, shape, std::vector<uint8_t>(packed_size, 0u), offset);++ const ScopedFile weights_file = write_binary_file(tag, std::vector<uint8_t>(file_size, 0xABu));++ ov::npuw::weights::LazyTensor var(constant);+ ov::npuw::weights::LazyTensor res;++ std::stringstream ss;+ write(ss, var);+ read(ss, res);++ {+ auto mapped = ov::load_mmap_object(weights_file.path);+ ASSERT_NE(mapped, nullptr);+ auto weights = std::make_shared<Weights>(reinterpret_cast<char*>(mapped->data()), mapped->size(), mapped);++ WeightsContext import_ctx(weights, weights_file.path.string(), {}, {});+ // Match the message - read_weight() has several asserts, and ASSERT_THROW would pass on any of them.+ OV_EXPECT_THROW_HAS_SUBSTRING(res.read_weight(import_ctx), ov::AssertFailure, expected_message);+ }+}++// Rewrites one u64 field of an already serialized blob in place - safe because the ORC wire format+// is raw little-endian with no checksum (orc.hpp) and the section length is unchanged. `from` must+// be unique, so a format change turns the test red instead of patching a different field.+void patch_u64_field(std::string& blob, std::uint64_t from, std::uint64_t to) {+ char needle[sizeof(std::uint64_t)] = {};+ char replacement[sizeof(std::uint64_t)] = {};+ for (std::size_t i = 0; i < sizeof(std::uint64_t); ++i) {+ needle[i] = static_cast<char>((from >> (8 * i)) & 0xFFu);+ replacement[i] = static_cast<char>((to >> (8 * i)) & 0xFFu);+ }++ const auto pos = blob.find(needle, 0, sizeof(needle));+ ASSERT_NE(pos, std::string::npos) << "u64 field " << from << " not found in the serialized blob";+ ASSERT_EQ(blob.find(needle, pos + 1, sizeof(needle)), std::string::npos)+ << "u64 field " << from << " is not unique in the serialized blob";+ blob.replace(pos, sizeof(replacement), replacement, sizeof(replacement));+}++// Same path as expect_lazy_weightless_mmap_rejected(), but one u64 field is patched between write()+// and read(): a Constant can't hold a byte_size that disagrees with its shape, so this is the only+// way to reach the metadata-integrity assert.+void expect_lazy_weightless_mmap_crafted_rejected(+ const ov::element::Type& type,+ const ov::Shape& shape,+ std::size_t offset,+ std::size_t file_size,+ std::uint64_t patch_from,+ std::uint64_t patch_to,+ const std::string& tag,+ const std::string& expected_message = "[NPU] ORC weight byte_size does not match tensor shape") {+ using namespace ov::npuw::s11n;++ const auto packed_size = ov::util::get_memory_size(type, ov::shape_size(shape));+ auto constant = make_weightless_constant_from_bytes(type, shape, std::vector<uint8_t>(packed_size, 0u), offset);++ const ScopedFile weights_file = write_binary_file(tag, std::vector<uint8_t>(file_size, 0xABu));++ ov::npuw::weights::LazyTensor var(constant);+ ov::npuw::weights::LazyTensor res;++ std::stringstream out;+ write(out, var);+ std::string blob = out.str();+ ASSERT_NO_FATAL_FAILURE(patch_u64_field(blob, patch_from, patch_to));++ std::stringstream in(blob);+ read(in, res);++ {+ auto mapped = ov::load_mmap_object(weights_file.path);+ ASSERT_NE(mapped, nullptr);+ auto weights = std::make_shared<Weights>(reinterpret_cast<char*>(mapped->data()), mapped->size(), mapped);++ WeightsContext import_ctx(weights, weights_file.path.string(), {}, {});+ OV_EXPECT_THROW_HAS_SUBSTRING(res.read_weight(import_ctx), ov::AssertFailure, expected_message);+ }+}+ov::npuw::s11n::WeightsContext::ConstsCache make_consts_cache(const std::vector<std::shared_ptr<ov::op::v0::Constant>>& constants) {ov::npuw::s11n::WeightsContext::ConstsCache cache;@@ -1444,4 +1629,138 @@ TEST(SerializationTest, CompiledModelDesc_rejects_weightless_non_cpu_closure_indkExpectedNonCpuOobIndexMessage);}+// Sub-byte coverage: the byte size is the *packed* size (ov::util::get_memory_size), which is what+// both Constant::get_byte_size() and ov::Tensor::get_byte_size() report - not shape_size * size(),+// which over-reports a 4-bit weight 2x and would reject most of NPUW's mostly-4-bit LLM blobs.+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_u4_roundtrip) {+ // 16 nibbles -> 8 bytes+ expect_lazy_weightless_mmap_roundtrip(ov::element::u4, ov::Shape{2, 8}, 8, 16, "u4");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_u4_odd_element_count_roundtrip) {+ // 5 nibbles -> 3 bytes, the high nibble of the last byte is unused+ expect_lazy_weightless_mmap_roundtrip(ov::element::u4, ov::Shape{5}, 3, 4, "u4_odd");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_i4_roundtrip) {+ // 9 nibbles -> 5 bytes+ expect_lazy_weightless_mmap_roundtrip(ov::element::i4, ov::Shape{3, 3}, 0, 8, "i4");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_nf4_roundtrip) {+ // 32 nibbles -> 16 bytes; non-zero tail so that exact_fit below stays the only edge case+ expect_lazy_weightless_mmap_roundtrip(ov::element::nf4, ov::Shape{1, 32}, 16, 8, "nf4");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_u1_roundtrip) {+ // 12 bits -> 2 bytes+ expect_lazy_weightless_mmap_roundtrip(ov::element::u1, ov::Shape{12}, 4, 4, "u1");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_u3_roundtrip) {+ // Split-bit type: 8 elements share one 24-bit storage unit -> 3 bytes+ expect_lazy_weightless_mmap_roundtrip(ov::element::u3, ov::Shape{8}, 1, 4, "u3");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_f32_roundtrip) {+ expect_lazy_weightless_mmap_roundtrip(ov::element::f32, ov::Shape{2, 2}, 8, 8, "f32");+}++// offset + byte_size == weights size must still be accepted - the guard is inclusive on purpose.+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_exact_fit_roundtrip) {+ expect_lazy_weightless_mmap_roundtrip(ov::element::u4, ov::Shape{2, 8}, 8, 0, "u4_exact");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_offset_oob) {+ // shape {4} u8 = 4 bytes, but the offset is far past the 8-byte weights file+ expect_lazy_weightless_mmap_rejected(ov::element::u8, ov::Shape{4}, 64 * 1024, 8, "u8_oob");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_size_overflow) {+ // offset 0, but the shape spans 128 bytes while the weights file holds only 8+ expect_lazy_weightless_mmap_rejected(ov::element::u8, ov::Shape{128}, 0, 8, "u8_size");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_string_type_rejected) {+ expect_lazy_weightless_mmap_rejected(ov::element::string,+ ov::Shape{2},+ 0,+ 4096,+ "string",+ "[NPU] ORC weight has unsupported element type");+}++TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_u4_off_by_one_oob) {+ // 8-byte weight at offset 1 in an 8-byte file: one byte short+ expect_lazy_weightless_mmap_rejected(ov::element::u4, ov::Shape{2, 8}, 1, 8, "u4_off_by_one");+}++// The three tests below patch the blob to break the byte_size/shape agreement - a Constant-derived+// one never can. That is the bypass: the range check sees only byte_size, eval() uses the shape.++// byte_size = 0 satisfies any range check, but f32 {7,1013} spans 28364 bytes of an 8-byte file.+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_crafted_byte_size_zeroed) {+ expect_lazy_weightless_mmap_crafted_rejected(ov::element::f32, ov::Shape{7, 1013}, 0, 8, 28364, 0, "craft_bs0");+}++// The declared byte_size (4024) fits the 4096-byte file, but the inflated shape spans 8056 bytes.+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_crafted_shape_inflated) {+ expect_lazy_weightless_mmap_crafted_rejected(ov::element::f32, ov::Shape{2, 503}, 0, 4096, 503, 1007, "craft_shp");+}++// 7 * SIZE_MAX wraps, so get_memory_size_safe() returns nullopt.+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_crafted_shape_product_overflow) {+ expect_lazy_weightless_mmap_crafted_rejected(ov::element::f32,+ ov::Shape{7, 1013},+ 0,+ 8,+ 1013,+ std::numeric_limits<std::size_t>::max(),+ "craft_ovf");+}++// Covers the validate_weight_range() call in eval(): eval() maps the file again, possibly long+// after import, so it may have been truncated or replaced in the meantime (TOCTOU).+TEST(SerializationTest, OVTypes_LazyTensor_weightless_mmap_file_shrunk_after_import) {+ using namespace ov::npuw::s11n;++ const auto type = ov::element::u4;+ const ov::Shape shape{2, 8}; // 16 nibbles -> 8 packed bytes+ const std::size_t offset = 8;+ const auto packed_size = ov::util::get_memory_size(type, ov::shape_size(shape));++ // Initially the file holds the whole weight: 8 filler bytes + 8 payload bytes.+ std::vector<uint8_t> file_bytes(offset, 0xCCu);+ file_bytes.insert(file_bytes.end(), packed_size, 0x5Au);+ const ScopedFile weights_file = write_binary_file("u4_shrunk", file_bytes);++ auto constant = make_weightless_constant_from_bytes(type, shape, std::vector<uint8_t>(packed_size, 0x5Au), offset);+ ov::npuw::weights::LazyTensor var(constant);+ ov::npuw::weights::LazyTensor res;++ std::stringstream ss;+ write(ss, var);+ read(ss, res);++ {+ auto mapped = ov::load_mmap_object(weights_file.path);+ ASSERT_NE(mapped, nullptr);+ auto weights = std::make_shared<Weights>(reinterpret_cast<char*>(mapped->data()), mapped->size(), mapped);++ // The description is valid against the file as it is right now, so import succeeds.+ WeightsContext import_ctx(weights, weights_file.path.string(), {}, {});+ ASSERT_NO_THROW(res.read_weight(import_ctx));+ } // import-time mapping released here - the file can be rewritten now++ // Truncate down to the filler - kept non-empty, mapping an empty file fails differently.+ {+ std::ofstream os(weights_file.path, std::ios::binary | std::ios::trunc);+ const std::vector<uint8_t> tiny(offset, 0xCCu);+ os.write(reinterpret_cast<const char*>(tiny.data()), static_cast<std::streamsize>(tiny.size()));+ }++ // offset (8) <= weights_size (8), but byte_size (8) > weights_size - offset (0)+ OV_EXPECT_THROW_HAS_SUBSTRING(res.eval(), ov::AssertFailure, "[NPU] ORC weight offset/size out of range");+}+// TODO: add tests on CompiledModel and LLMCompiledModel once tests have access to any model to test on