Skip to content

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

[NPU] Implement a class that can handle both "istream" and "ov::Tensor" objects using the same API (#37397)

Razvan Apetroaie468972791fd6
diff --git a/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp
index bae78bc85d9..ba93585bf87 100644
--- a/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp
@@ -7,6 +7,7 @@
#include <map>
#include <string>
+#include "blob_source.hpp"
#include "intel_npu/common/filtered_config.hpp"
#include "intel_npu/common/igraph.hpp"
#include "intel_npu/common/npu.hpp"
@@ -130,23 +131,7 @@ namespace blob_format_importer_factory {
* level, weights path, decryption callbacks.
* @return An importer object of the type that corresponds to the format of the blob.
*/
-std::unique_ptr<IBlobFormatImporter> create(std::istream& npu_formatted_blob,
- const bool is_raw_blob,
- const std::shared_ptr<const ov::Model>& original_model,
- const FilteredConfig& config);
-
-/**
- * @brief Identifies the blob format used for the given blob and creates the corresponding importer for it.
- *
- * @param npu_formatted_blob The target blob.
- * @param is_raw_blob Flag indicating whether or not the whole blob is just a compiler main schedule.
- * @param original_model A potential source of weights for the weights separation feature if necessary. Can be
- * `nullptr`.
- * @param config Will be held by the newly created importer and used for multiple purposes, such as: extracting the log
- * level, weights path, decryption callbacks.
- * @return An importer object of the type that corresponds to the format of the blob.
- */
-std::unique_ptr<IBlobFormatImporter> create(const ov::Tensor& npu_formatted_blob,
+std::unique_ptr<IBlobFormatImporter> create(BlobSource& npu_formatted_blob,
const bool is_raw_blob,
const std::shared_ptr<const ov::Model>& original_model,
const FilteredConfig& config);
diff --git a/src/plugins/intel_npu/src/plugin/include/blob_source.hpp b/src/plugins/intel_npu/src/plugin/include/blob_source.hpp
new file mode 100644
index 00000000000..b0455e2d27c
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/include/blob_source.hpp
@@ -0,0 +1,105 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <istream>
+#include <variant>
+
+#include "intel_npu/utils/logger/logger.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace intel_npu {
+
+/**
+ * @brief Class that allows reading from either an "std::istream" or "ov::Tensor" object using a single set of common
+ * methods.
+ * @details The "stream" type is handled using the "std" API. The tensor is handled by managing a data cursor. Only the
+ * tensor type supports extracting data without copying, since the "stream" type is not guaranteed to have a contiguous
+ * buffer under the hood.
+ */
+class BlobSource {
+public:
+ explicit BlobSource(std::istream& source, const ov::log::Level log_level = Logger::global().level());
+
+ explicit BlobSource(const ov::Tensor& source, const ov::log::Level log_level = Logger::global().level());
+
+ /**
+ * @brief Copies data from the blob source to the given destination.
+ * @details The data is copied from where the data cursor currently points to; the cursor is then advanced by "size"
+ * bytes.
+ *
+ * @param destination The data will be copied into this buffer
+ * @param size The amount of data that will be copied. The data cursor will also be advanced by this amount.
+ */
+ void read_into_buffer(void* destination, const size_t size);
+
+ /**
+ * @brief Extracts data from the blob source without copying it.
+ * @details The returned address is the position where the data cursor currently points to. Before returning, the
+ * cursor is also advanced by "size" bytes.
+ * @throws ov::Exception if the underlying type does not have a guaranteed contiguous buffer (e.g. "std::istream").
+ * @note "BlobSource::is_contiguous" can be used to determine if this function can be called safely.
+ *
+ * @param size The data cursor will be advanced by this amount.
+ * @return The blob content location where the data cursor currently points to (prior to advancing the cursor).
+ */
+ const void* read_view(const size_t size);
+
+ /**
+ * @brief Extracts a region-of-interest tensor from the blob source without copying it.
+ * @details The tensor is a view towards the content of the blob, delimited by [data cursor:data cursor + size).
+ * Before returning, the cursor is also advanced by "size" bytes.
+ * @throws ov::Exception if the underlying type does not have a guaranteed contiguous buffer (e.g. "std::istream").
+ * @note "BlobSource::is_contiguous" can be used to determine if this function can be called safely.
+ *
+ * @param size The data cursor will be advanced by this amount.
+ * @return A region-of-interest tensor as a view towards the content of the blob, delimited by [data cursor:data
+ * cursor + size).
+ */
+ ov::Tensor create_roi_tensor(const size_t size);
+
+ /**
+ * @brief Moves the data cursor by "offset" bytes starting from the given reference.
+ *
+ * @param offset The amount of bytes the cursor will be moved.
+ * @param reference "std::ios::beg", "std::ios::cur" and "std::ios::end" are the only supported values. These
+ * correspond to the beginning of the blob source, the current position of the cursor and the end of the source.
+ */
+ void seekg(const int64_t offset, const std::ios_base::seekdir reference = std::ios::beg);
+
+ /**
+ * @return The current position of the data cursor
+ */
+ size_t tellg() const;
+
+ /**
+ * @return The total size of the blob
+ */
+ size_t get_total_size() const;
+
+ /**
+ * @return The remaining size of the blob, starting from the current position of the data cursor
+ */
+ size_t get_remaining_size() const;
+
+ /**
+ * @return true The blob is contiguous (the "tensor" scenario).
+ * @return false Otherwise (the "stream" scenario)
+ */
+ bool is_contiguous() const;
+
+private:
+ /**
+ * @brief A union that captures all possible data types of the blob. The tensor type also has a separate data cursor
+ * attached to it.
+ */
+ std::variant<std::reference_wrapper<std::istream>, std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>
+ m_source;
+ size_t m_size;
+
+ Logger m_logger;
+};
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hpp
index 116da2d2016..528fa5d067d 100644
--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp
@@ -14,6 +14,7 @@
#include <variant>
#include <vector>
+#include "blob_source.hpp"
#include "intel_npu/common/igraph.hpp"
#include "intel_npu/utils/logger/logger.hpp"
#include "openvino/core/layout.hpp"
@@ -29,44 +30,31 @@ public:
std::variant<std::monostate, std::reference_wrapper<std::istream>, std::reference_wrapper<const ov::Tensor>>;
/**
- * @brief Reads metadata from a stream.
+ * @brief Reads metadata from a blob source.
+ * @details The last position of the data cursor is checked after reading.
*/
- void read(std::istream& stream);
-
- /**
- * @brief Reads metadata from a ov::Tensor.
- */
- void read(const ov::Tensor& tensor);
+ void read(BlobSource& source);
/**
* @brief Populates this object from a pre-parsed human-readable metadata attribute map.
- */
- void read_as_text(std::map<std::string, std::string, std::less<>> attrs);
-
- virtual void read() = 0;
-
- /**
+ *
+ * @param textAttrs Parsed key-value attributes from the human-readable metadata string.
* @note Layouts and encryption are intentionally omitted from the human-readable compatibility
* string. They are internal implementation details that don't affect cross-version compatibility and would only add
* noise for consumers.
* Compiler version is already contained within the compiler requirements field.
*
*/
- virtual void read_as_text() = 0;
+ virtual void read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) = 0;
/**
* @brief Writes metadata to a stream. The footer (blob size & magic) is included.
*/
void write(std::ostream& stream);
- /**
- * @brief Writes metadata to a stream. The footer (blob size & magic) is omitted.
- */
- virtual void write_without_footer(std::ostream& stream) = 0;
-
virtual void write_as_text(std::ostream& stream) = 0;
- virtual uint64_t get_blob_size() const;
+ virtual uint64_t get_compiler_payload_size() const;
virtual uint64_t get_main_schedule_size() const;
@@ -94,8 +82,6 @@ public:
virtual ~MetadataBase() = default;
- static size_t get_stream_remaining_size(std::istream& stream);
-
/**
* @brief Returns a uint32_t value which represents two uint16_t values concatenated.
* @details Convention for bumping the metadata version:
@@ -126,37 +112,18 @@ public:
protected:
/**
- * @brief Reads data from the source containing the binary metadata. The implementation depends on the type of
- * source.
+ * @brief Reads metadata from a blob source. The last position of the data cursor is not checked after reading.
*/
- void read_data_from_source(char* destination, const size_t size);
+ virtual void read_unchecked(BlobSource& source) = 0;
/**
- * @return The number of bytes until the cursor reaches the end of the source
+ * @brief Writes metadata to a stream. The footer (blob size & magic) is omitted.
*/
- size_t get_remaining_source_size() const;
+ virtual void write_without_footer(std::ostream& stream) = 0;
uint32_t _version;
- uint64_t _blobDataSize;
+ uint64_t _compilerPayloadSize;
Logger _logger;
-
- /**
- * @brief Parsed key-value attributes from the human-readable metadata string.
- */
- std::map<std::string, std::string, std::less<>> _textAttrs;
-
- /**
- * @brief Where the metadata is read from. The type can be a stream, an OpenVINO tensor or "uninitialized_source".
- * @details Stored as attribute in order to avoid repeatedly passing the same arguments to some methods.
- * "uninitialized_source" (void*) is the default type assigned upon creation.
- */
- Source _source;
- size_t _sourceSize;
-
- /**
- * @brief Used only when the source buffer is an OV tensor for managing the read coursor.
- */
- size_t _cursorOffset = 0;
};
/**
@@ -226,14 +193,9 @@ public:
~OpenvinoVersion() = default;
/**
- * @brief Reads version data from a stream.
- */
- void read(std::istream& istream);
-
- /**
- * @brief Reads version data from a ov::Tensor.
+ * @brief Reads version data from a blob source.
*/
- void read(const ov::Tensor& tensor);
+ void read(BlobSource& source);
/**
* @brief Writes version data to a stream.
@@ -274,9 +236,12 @@ class Metadata<METADATA_VERSION_2_0> : public MetadataBase {
public:
Metadata(uint64_t blobSize, const std::optional<OpenvinoVersion>& ovVersion = std::nullopt);
- void read() override;
+ void read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) override;
- void read_as_text() override;
+ void write_as_text(std::ostream& stream) override;
+
+protected:
+ void read_unchecked(BlobSource& source) override;
/**
* @attention It's a must to first write metadata version in any metadata specialization.
@@ -287,9 +252,6 @@ public:
*/
void write_without_footer(std::ostream& stream) override;
- void write_as_text(std::ostream& stream) override;
-
-protected:
OpenvinoVersion _ovVersion;
};
@@ -305,13 +267,18 @@ public:
const std::optional<OpenvinoVersion>& ovVersion = std::nullopt,
const std::optional<std::vector<uint64_t>>& initSizes = std::nullopt);
+ void read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) override;
+
+ void write_as_text(std::ostream& stream) override;
+
+ std::optional<std::vector<uint64_t>> get_init_sizes() const override;
+
+protected:
/**
* @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() override;
-
- void read_as_text() override;
+ void read_unchecked(BlobSource& source) override;
/**
* @details The number of init schedules, along with the size of each init binary object are written in addition to
@@ -319,10 +286,6 @@ public:
*/
void write_without_footer(std::ostream& stream) override;
- void write_as_text(std::ostream& stream) override;
-
- std::optional<std::vector<uint64_t>> get_init_sizes() const override;
-
private:
std::optional<std::vector<uint64_t>> _initSizes;
uint64_t _numberOfInits = 0;
@@ -339,16 +302,17 @@ public:
const std::optional<std::vector<uint64_t>>& initSizes = std::nullopt,
const std::optional<int64_t>& batchSize = std::nullopt);
- void read() override;
-
- void read_as_text() override;
-
- void write_without_footer(std::ostream& stream) override;
+ void read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) override;
void write_as_text(std::ostream& stream) override;
std::optional<int64_t> get_batch_size() const override;
+protected:
+ void read_unchecked(BlobSource& source) override;
+
+ void write_without_footer(std::ostream& stream) override;
+
private:
std::optional<int64_t> _batchSize;
};
@@ -367,14 +331,15 @@ public:
const std::optional<std::vector<ov::Layout>>& inputLayouts = std::nullopt,
const std::optional<std::vector<ov::Layout>>& outputLayouts = std::nullopt);
- void read() override;
-
- void write_without_footer(std::ostream& stream) override;
-
std::optional<std::vector<ov::Layout>> get_input_layouts() const override;
std::optional<std::vector<ov::Layout>> get_output_layouts() const override;
+protected:
+ void read_unchecked(BlobSource& source) override;
+
+ void write_without_footer(std::ostream& stream) override;
+
private:
std::optional<std::vector<ov::Layout>> _inputLayouts;
std::optional<std::vector<ov::Layout>> _outputLayouts;
@@ -394,11 +359,12 @@ public:
const std::optional<std::vector<ov::Layout>>& outputLayouts = std::nullopt,
const std::optional<uint32_t>& compilerVersion = std::nullopt);
- void read() override;
+ std::optional<uint32_t> get_compiler_version() const override;
- void write_without_footer(std::ostream& stream) override;
+protected:
+ void read_unchecked(BlobSource& source) override;
- std::optional<uint32_t> get_compiler_version() const override;
+ void write_without_footer(std::ostream& stream) override;
private:
std::optional<uint32_t> _compilerVersion;
@@ -420,11 +386,12 @@ public:
const std::optional<uint32_t>& compilerVersion = std::nullopt,
const std::optional<uint64_t>& blobSizeAfterEncryption = std::nullopt);
- void read() override;
+ std::optional<bool> is_encrypted_blob() const override;
- void write_without_footer(std::ostream& stream) override;
+protected:
+ void read_unchecked(BlobSource& source) override;
- std::optional<bool> is_encrypted_blob() const override;
+ void write_without_footer(std::ostream& stream) override;
private:
std::optional<bool> _isEncryptedBlob;
@@ -446,16 +413,17 @@ public:
const std::optional<uint64_t>& blobSizeAfterEncryption = std::nullopt,
const std::optional<std::string_view> compatibilityDescriptor = std::nullopt);
- void read() override;
-
- void read_as_text() override;
-
- void write_without_footer(std::ostream& stream) override;
+ void read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) override;
void write_as_text(std::ostream& stream) override;
std::optional<std::string_view> get_compatibility_descriptor() const override;
+protected:
+ void read_unchecked(BlobSource& source) override;
+
+ void write_without_footer(std::ostream& stream) override;
+
private:
std::optional<std::string> _compatibilityDescriptor;
};
@@ -477,11 +445,12 @@ public:
const std::optional<std::string_view> compatibilityDescriptor = std::nullopt,
BlobType blobType = BlobType::ELF);
- void read() override;
+ std::optional<BlobType> get_blob_type() const override;
- void write_without_footer(std::ostream& stream) override;
+protected:
+ void read_unchecked(BlobSource& source) override;
- std::optional<BlobType> get_blob_type() const override;
+ void write_without_footer(std::ostream& stream) override;
private:
BlobType _blobType;
@@ -496,7 +465,7 @@ private:
std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSize);
/**
- * @brief Reads metadata from a blob (istream).
+ * @brief Reads metadata from a blob source.
*
* @return If the blob is versioned and its major version is supported, returns an unique pointer to the read
* MetadataBase object; otherwise, returns 'nullptr'.
@@ -504,15 +473,7 @@ std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSiz
* @note The read of metadata can be disabled if the "OV_NPU_IMPORT_RAW_BLOB" environment variable is set to
* 'YES'.
*/
-std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream);
-
-/**
- * @brief Reads metadata from a blob (ov::Tensor).
- *
- * @return If the blob is versioned and its major version is supported, returns an unique pointer to the read
- * MetadataBase object; otherwise, returns 'nullptr'.
- */
-std::unique_ptr<MetadataBase> read_metadata_from(const ov::Tensor& tensor);
+std::unique_ptr<MetadataBase> read_metadata_from(BlobSource& source);
std::unique_ptr<MetadataBase> read_as_text(std::string_view input);
diff --git a/src/plugins/intel_npu/src/plugin/include/plugin.hpp b/src/plugins/intel_npu/src/plugin/include/plugin.hpp
index 1473006608f..5766d12eedd 100644
--- a/src/plugins/intel_npu/src/plugin/include/plugin.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/plugin.hpp
@@ -9,7 +9,7 @@
#include <string>
#include "backends_registry.hpp"
-#include "blob_format_importers.hpp"
+#include "blob_source.hpp"
#include "compiler_option_support_helper.hpp"
#include "intel_npu/common/npu.hpp"
#include "intel_npu/utils/logger/logger.hpp"
@@ -71,9 +71,7 @@ private:
*/
bool should_import_raw_blob(const ov::AnyMap& properties) const;
- std::shared_ptr<ov::ICompiledModel> import_model(const std::unique_ptr<IBlobFormatImporter>& blobFormatHandler,
- FilteredConfig& localConfig,
- ov::AnyMap& localProperties) const;
+ std::shared_ptr<ov::ICompiledModel> import_model(BlobSource& blobSource, ov::AnyMap& properties) const;
std::unique_ptr<BackendsRegistry> _backendsRegistry;
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index 909e0484574..891e3fa949e 100644
--- a/src/plugins/intel_npu/src/plugin/sources.cmake
+++ b/src/plugins/intel_npu/src/plugin/sources.cmake
@@ -6,6 +6,7 @@ set(SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/include/async_infer_request.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/backends_registry.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/blob_format_importers.hpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/include/blob_source.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/compiler_option_support_helper.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/compiled_model.hpp
${CMAKE_CURRENT_SOURCE_DIR}/include/compiled_model_property_manager.hpp
@@ -19,6 +20,7 @@ set(SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/async_infer_request.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/backends_registry.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/blob_format_importers.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/blob_source.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/compiler_option_support_helper.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model_property_manager.cpp
diff --git a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp
index 24171833edb..125ec429668 100644
--- a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp
@@ -25,14 +25,13 @@ ov::Tensor allocate_aligned_tensor(size_t blobSize) {
if (blobSize > static_cast<decltype(blobSize)>(std::numeric_limits<std::streamsize>::max())) {
OPENVINO_THROW("Blob size is too large to be represented on a std::streamsize!");
}
- ov::Tensor tensor(ov::element::u8, ov::Shape{blobSize}, customAllocator);
- return tensor;
+ return ov::Tensor(ov::element::u8, ov::Shape{blobSize}, customAllocator);
}
-constexpr std::string_view HANDLER_FACTOR_LOGGER_NAME = "blob_format_importer_factory";
+constexpr std::string_view HANDLER_FACTORY_LOGGER_NAME = "blob_format_importer_factory";
constexpr std::string_view RAW_BLOB_HANDLER_LOGGER_NAME = "RawBlobImporter";
-constexpr std::string_view BLOB_V1_HADNLER_LOGGER_NAME = "BlobFormatV1Importer";
+constexpr std::string_view BLOB_V1_HANDLER_LOGGER_NAME = "BlobFormatV1Importer";
constexpr std::string_view BLOB_COMPATIBILITY_SKIPPED_MESSAGE = "Blob compatibility check skipped.";
constexpr std::string_view MISSING_METADATA_MESSAGE = "The blob is missing the NPU metadata!";
@@ -42,6 +41,8 @@ constexpr std::string_view BLOB_SIZE_SMALLER_THAN_MAGIC =
constexpr std::string_view EMPTY_COMPILER_PAYLOAD_MESSAGE =
"The blob provided for import doesn't have any compiler payload";
constexpr std::string_view DECRYPTING_PAYLOAD_MESSAGE = "Decrypting the compiler payload";
+constexpr std::string_view NEW_PAGE_ALIGNED_BUFFER_MESSAGE =
+ "The compiler payload has been copied into a new, page aligned buffer";
const std::vector<size_t> CONSTANT_NODE_DUMMY_SHAPE{1};
@@ -175,29 +176,24 @@ std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& i
*/
class RawBlobImporter : public IBlobFormatImporter {
public:
- explicit RawBlobImporter(std::istream& compiler_main_schedule,
+ explicit RawBlobImporter(BlobSource& compiler_main_schedule,
const std::shared_ptr<const ov::Model>& original_model,
const FilteredConfig& config)
: IBlobFormatImporter(original_model,
config,
Logger(RAW_BLOB_HANDLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {
- const size_t blob_size = MetadataBase::get_stream_remaining_size(compiler_main_schedule);
+ const size_t blob_size = compiler_main_schedule.get_remaining_size();
OPENVINO_ASSERT(blob_size > 0, EMPTY_BLOB_MESSAGE);
- m_main_schedule = allocate_aligned_tensor(blob_size);
- compiler_main_schedule.read(m_main_schedule.data<char>(), static_cast<std::streamsize>(blob_size));
- }
+ if (!compiler_main_schedule.is_contiguous()) {
+ m_main_schedule = allocate_aligned_tensor(blob_size);
+ compiler_main_schedule.read_into_buffer(m_main_schedule.data(), blob_size);
- explicit RawBlobImporter(const ov::Tensor& compiler_main_schedule,
- const std::shared_ptr<const ov::Model>& original_model,
- const FilteredConfig& config)
- : IBlobFormatImporter(original_model,
- config,
- Logger(RAW_BLOB_HANDLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {
- const size_t blob_size = compiler_main_schedule.get_byte_size();
- OPENVINO_ASSERT(blob_size > 0, EMPTY_BLOB_MESSAGE);
+ m_logger.info(NEW_PAGE_ALIGNED_BUFFER_MESSAGE.data());
+ return;
+ }
- m_main_schedule = ov::Tensor(compiler_main_schedule, ov::Coordinate{0}, ov::Coordinate{blob_size});
+ m_main_schedule = compiler_main_schedule.create_roi_tensor(blob_size);
}
private:
@@ -271,38 +267,28 @@ private:
*/
class BlobFormatV1Importer : public IBlobFormatImporter {
public:
- explicit BlobFormatV1Importer(std::istream& npu_formatted_blob,
+ explicit BlobFormatV1Importer(BlobSource& npu_formatted_blob,
const std::shared_ptr<const ov::Model>& original_model,
const FilteredConfig& config)
: IBlobFormatImporter(original_model,
config,
- Logger(BLOB_V1_HADNLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {
- // Read only the metadata from the stream and check if the blob is compatible. Load the blob into memory only if
+ Logger(BLOB_V1_HANDLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {
+ // Read only the metadata from the source and check if the blob is compatible. Load the blob into memory only if
// it passes the compatibility checks.
m_metadata = read_metadata_from(npu_formatted_blob);
- const size_t blob_size = m_metadata->get_blob_size();
- OPENVINO_ASSERT(blob_size > 0, EMPTY_COMPILER_PAYLOAD_MESSAGE);
+ const size_t compiler_payload_size = m_metadata->get_compiler_payload_size();
+ OPENVINO_ASSERT(compiler_payload_size > 0, EMPTY_COMPILER_PAYLOAD_MESSAGE);
- m_compiler_payload = allocate_aligned_tensor(blob_size);
- npu_formatted_blob.read(m_compiler_payload.data<char>(), static_cast<std::streamsize>(blob_size));
+ if (!npu_formatted_blob.is_contiguous()) {
+ m_compiler_payload = allocate_aligned_tensor(compiler_payload_size);
+ npu_formatted_blob.read_into_buffer(m_compiler_payload.data(), compiler_payload_size);
- register_compiler_version();
- }
-
- explicit BlobFormatV1Importer(const ov::Tensor& npu_formatted_blob,
- const std::shared_ptr<const ov::Model>& original_model,
- const FilteredConfig& config)
- : IBlobFormatImporter(original_model,
- config,
- Logger(BLOB_V1_HADNLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {
- m_metadata = read_metadata_from(npu_formatted_blob);
-
- const size_t blob_size = m_metadata->get_blob_size();
- OPENVINO_ASSERT(blob_size > 0, EMPTY_COMPILER_PAYLOAD_MESSAGE);
-
- // ROI tensor to skip the NPU plugin metadata
- m_compiler_payload = ov::Tensor(npu_formatted_blob, ov::Coordinate{0}, ov::Coordinate{blob_size});
+ m_logger.info(NEW_PAGE_ALIGNED_BUFFER_MESSAGE.data());
+ } else {
+ // ROI tensor to skip the NPU plugin metadata
+ m_compiler_payload = npu_formatted_blob.create_roi_tensor(compiler_payload_size);
+ }
register_compiler_version();
}
@@ -497,67 +483,35 @@ FilteredConfig IBlobFormatImporter::get_config() const {
namespace blob_format_importer_factory {
-std::unique_ptr<IBlobFormatImporter> create(std::istream& npu_formatted_blob,
+std::unique_ptr<IBlobFormatImporter> create(BlobSource& npu_formatted_blob,
const bool is_raw_blob,
const std::shared_ptr<const ov::Model>& original_model,
const FilteredConfig& config) {
- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "blob_format_importer_factory::create(std::istream)");
- const size_t input_size = MetadataBase::get_stream_remaining_size(npu_formatted_blob);
+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "blob_format_importer_factory::create");
+ const size_t input_size = npu_formatted_blob.get_remaining_size();
OPENVINO_ASSERT(input_size > 0, EMPTY_BLOB_MESSAGE);
- const Logger logger(HANDLER_FACTOR_LOGGER_NAME.data(), config.get<LOG_LEVEL>());
+ const Logger logger(HANDLER_FACTORY_LOGGER_NAME.data(), config.get<LOG_LEVEL>());
if (is_raw_blob) {
logger.info(BLOB_COMPATIBILITY_SKIPPED_MESSAGE.data());
- logger.debug("Creating a raw blob format import handler from a stream using the factory");
+ logger.debug("Creating a raw blob format import handler using the factory");
return std::make_unique<RawBlobImporter>(npu_formatted_blob, original_model, config);
}
// The V1 format is identified by some magic bytes at the end of the input
- const size_t magic_bytes_size = MAGIC_BYTES.size();
- OPENVINO_ASSERT(input_size >= magic_bytes_size, BLOB_SIZE_SMALLER_THAN_MAGIC);
-
- std::string blob_magic_bytes;
- blob_magic_bytes.resize(magic_bytes_size);
-
- std::streampos compiler_payload_beggining = npu_formatted_blob.tellg();
- npu_formatted_blob.seekg(-std::streampos(magic_bytes_size), std::ios::end);
- npu_formatted_blob.read(blob_magic_bytes.data(), magic_bytes_size);
-
- OPENVINO_ASSERT(MAGIC_BYTES == blob_magic_bytes, MISSING_METADATA_MESSAGE);
-
- npu_formatted_blob.seekg(compiler_payload_beggining, std::ios::beg);
-
- logger.debug("Creating a blob format v1 import handler from a stream using the factory");
- return std::make_unique<BlobFormatV1Importer>(npu_formatted_blob, original_model, config);
-}
-
-std::unique_ptr<IBlobFormatImporter> create(const ov::Tensor& npu_formatted_blob,
- const bool is_raw_blob,
- const std::shared_ptr<const ov::Model>& original_model,
- const FilteredConfig& config) {
- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "blob_format_importer_factory::create(ov::Tensor)");
-
- const Logger logger(HANDLER_FACTOR_LOGGER_NAME.data(), config.get<LOG_LEVEL>());
- if (is_raw_blob) {
- logger.info(BLOB_COMPATIBILITY_SKIPPED_MESSAGE.data());
-
- logger.debug("Creating a raw blob format import handler from a tensor using the factory");
- return std::make_unique<RawBlobImporter>(npu_formatted_blob, original_model, config);
- }
-
- const size_t input_size = npu_formatted_blob.get_byte_size();
- OPENVINO_ASSERT(input_size > 0, EMPTY_BLOB_MESSAGE);
+ OPENVINO_ASSERT(input_size >= MAGIC_BYTES.size(), BLOB_SIZE_SMALLER_THAN_MAGIC);
- const size_t magic_bytes_size = MAGIC_BYTES.size();
- OPENVINO_ASSERT(input_size >= magic_bytes_size, BLOB_SIZE_SMALLER_THAN_MAGIC);
+ const size_t compiler_payload_beginning = npu_formatted_blob.tellg();
+ npu_formatted_blob.seekg(-static_cast<int>(MAGIC_BYTES.size()), std::ios::end);
- std::string_view blob_magic_bytes(npu_formatted_blob.data<const char>() + input_size - magic_bytes_size,
- magic_bytes_size);
+ std::string blob_magic_bytes(MAGIC_BYTES.size(), 0);
+ npu_formatted_blob.read_into_buffer(blob_magic_bytes.data(), MAGIC_BYTES.size());
OPENVINO_ASSERT(MAGIC_BYTES == blob_magic_bytes, MISSING_METADATA_MESSAGE);
+ npu_formatted_blob.seekg(compiler_payload_beginning, std::ios::beg);
- logger.debug("Creating a blob format v1 import handler from a tensor using the factory");
+ logger.debug("Creating a blob format v1 import handler using the factory");
return std::make_unique<BlobFormatV1Importer>(npu_formatted_blob, original_model, config);
}
diff --git a/src/plugins/intel_npu/src/plugin/src/blob_source.cpp b/src/plugins/intel_npu/src/plugin/src/blob_source.cpp
new file mode 100644
index 00000000000..e049d35b769
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/src/blob_source.cpp
@@ -0,0 +1,185 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "blob_source.hpp"
+
+#include "openvino/core/except.hpp"
+
+namespace {
+
+constexpr std::string_view STREAM_BAD_STATUS_MESSAGE = "The stream is in bad status";
+constexpr std::string_view STREAM_READ_WITHOUT_COPY_MESSAGE =
+ "The underlying data type of the blob source is a stream. Cannot read from a stream without copying the data.";
+constexpr std::string_view INVALID_CURSOR_MESSAGE =
+ "The cursor of the blob source points outside its designated buffer";
+constexpr std::string_view INVALID_MOVE_MESSAGE =
+ "Attempted to move the blob source cursor outside its designated buffer";
+constexpr std::string_view LOGGER_NAME = "BlobSource";
+constexpr size_t STARTING_CURSOR_POSITION = 0;
+
+/**
+ * @return The size of the underlying buffer, from the beginning of the stream to its end.
+ */
+size_t get_stream_total_size(std::istream& stream) {
+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
+
+ const std::streampos backupCursor = stream.tellg();
+ OPENVINO_ASSERT(backupCursor != std::streampos(-1), STREAM_BAD_STATUS_MESSAGE);
+
+ stream.seekg(0, std::ios_base::end);
+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
+
+ const std::streampos streamEnd = stream.tellg();
+ OPENVINO_ASSERT(streamEnd != std::streampos(-1), STREAM_BAD_STATUS_MESSAGE);
+ OPENVINO_ASSERT(streamEnd >= backupCursor, "Invalid stream size");
+
+ stream.seekg(backupCursor, std::ios_base::beg);
+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
+
+ return static_cast<size_t>(streamEnd);
+}
+
+} // namespace
+
+namespace intel_npu {
+
+BlobSource::BlobSource(std::istream& source, const ov::log::Level log_level)
+ : m_source(source),
+ m_size(get_stream_total_size(source)),
+ m_logger(Logger(LOGGER_NAME.data(), log_level)) {
+ m_logger.debug("Initialized a BlobSource using a stream object");
+}
+
+BlobSource::BlobSource(const ov::Tensor& source, const ov::log::Level log_level)
+ : m_source(std::make_pair<>(std::cref(source), STARTING_CURSOR_POSITION)),
+ m_size(source.get_byte_size()),
+ m_logger(Logger(LOGGER_NAME.data(), log_level)) {
+ OPENVINO_ASSERT(source.get_shape().size() == 1 && source.get_shape().at(0) == source.get_byte_size(),
+ "Only streams and unidimensional tensors are supported as blob sources");
+ m_logger.debug("Initialized a BlobSource using a tensor object");
+}
+
+void BlobSource::read_into_buffer(void* destination, const size_t size) {
+ m_logger.trace("Copying %zu bytes", size);
+
+ const size_t remaining = get_remaining_size();
+ OPENVINO_ASSERT(size <= remaining,
+ "Attempted to read ",
+ size,
+ " bytes from the blob but only ",
+ remaining,
+ " bytes remain");
+
+ if (const std::reference_wrapper<std::istream>* stream =
+ std::get_if<std::reference_wrapper<std::istream>>(&m_source)) {
+ OPENVINO_ASSERT(stream->get(), STREAM_BAD_STATUS_MESSAGE);
+ stream->get().read(reinterpret_cast<char*>(destination), size);
+ OPENVINO_ASSERT(stream->get(), STREAM_BAD_STATUS_MESSAGE);
+ return;
+ }
+
+ auto& [tensor, cursor] = std::get<std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>(m_source);
+ std::memcpy(destination, tensor.get().data<const char>() + cursor, size);
+ cursor += size;
+}
+
+const void* BlobSource::read_view(const size_t size) {
+ m_logger.trace("Reading %zu bytes without copying", size);
+ OPENVINO_ASSERT(!std::get_if<std::reference_wrapper<std::istream>>(&m_source), STREAM_READ_WITHOUT_COPY_MESSAGE);
+
+ const size_t remaining = get_remaining_size();
+ OPENVINO_ASSERT(size <= remaining,
+ "Attempted to read ",
+ size,
+ " bytes from the blob but only ",
+ remaining,
+ " bytes remain");
+
+ auto& [tensor, cursor] = std::get<std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>(m_source);
+ cursor += size;
+ return tensor.get().data<const char>() + cursor - size;
+}
+
+ov::Tensor BlobSource::create_roi_tensor(const size_t size) {
+ m_logger.trace("Creating an roi tensor of %zu bytes without copying", size);
+ OPENVINO_ASSERT(!std::get_if<std::reference_wrapper<std::istream>>(&m_source), STREAM_READ_WITHOUT_COPY_MESSAGE);
+
+ const size_t remaining = get_remaining_size();
+ OPENVINO_ASSERT(size <= remaining,
+ "Attempted to read ",
+ size,
+ " bytes from the blob but only ",
+ remaining,
+ " bytes remain");
+
+ auto& [tensor, cursor] = std::get<std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>(m_source);
+ cursor += size;
+ return ov::Tensor(tensor, ov::Coordinate{cursor - size}, ov::Coordinate{cursor});
+}
+
+void BlobSource::seekg(const int64_t offset, const std::ios_base::seekdir reference) {
+ if (const std::reference_wrapper<std::istream>* stream =
+ std::get_if<std::reference_wrapper<std::istream>>(&m_source)) {
+ OPENVINO_ASSERT(stream->get(), STREAM_BAD_STATUS_MESSAGE);
+ stream->get().seekg(std::streamoff(offset), reference);
+ OPENVINO_ASSERT(stream->get(), STREAM_BAD_STATUS_MESSAGE);
+ return;
+ }
+
+ auto& [tensor, cursor] = std::get<std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>(m_source);
+ OPENVINO_ASSERT(cursor <= m_size, INVALID_CURSOR_MESSAGE);
+
+ switch (reference) {
+ case std::ios::beg: {
+ OPENVINO_ASSERT(offset >= 0 && static_cast<size_t>(offset) <= m_size, INVALID_MOVE_MESSAGE);
+ cursor = static_cast<size_t>(offset);
+ break;
+ }
+ case std::ios::cur: {
+ OPENVINO_ASSERT(
+ offset > 0 ? static_cast<size_t>(offset) <= m_size - cursor : static_cast<size_t>(-offset) <= cursor,
+ INVALID_MOVE_MESSAGE);
+ cursor += offset;
+ break;
+ }
+ case std::ios::end: {
+ OPENVINO_ASSERT(offset <= 0 && static_cast<size_t>(-offset) <= m_size, INVALID_MOVE_MESSAGE);
+ cursor = m_size + offset;
+ break;
+ }
+ default: {
+ OPENVINO_THROW("A request to move the blob source cursor was made, but the given reference is invalid");
+ }
+ }
+}
+
+size_t BlobSource::tellg() const {
+ if (const std::reference_wrapper<std::istream>* stream =
+ std::get_if<std::reference_wrapper<std::istream>>(&m_source)) {
+ OPENVINO_ASSERT(stream->get(), STREAM_BAD_STATUS_MESSAGE);
+
+ const std::streampos cursor = stream->get().tellg();
+ OPENVINO_ASSERT(cursor != std::streampos(-1), STREAM_BAD_STATUS_MESSAGE);
+ return static_cast<size_t>(cursor);
+ }
+
+ auto& [tensor, cursor] = std::get<std::pair<std::reference_wrapper<const ov::Tensor>, size_t>>(m_source);
+ OPENVINO_ASSERT(cursor <= m_size, INVALID_CURSOR_MESSAGE);
+ return cursor;
+}
+
+size_t BlobSource::get_total_size() const {
+ return m_size;
+}
+
+size_t BlobSource::get_remaining_size() const {
+ return m_size - tellg();
+}
+
+bool BlobSource::is_contiguous() const {
+ // The buffer behind a "stream" object is not guaranteed to be contiguous
+ return !std::get_if<std::reference_wrapper<std::istream>>(&m_source);
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
index 00bb2c8d87b..a55ad0325f6 100644
--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
@@ -68,18 +68,13 @@ std::vector<uint16_t> parse_version(std::string_view sv) {
return parts;
}
-/**
- * @return The size of the underlying buffer, from the beginning of the stream to its end.
- */
-size_t get_stream_total_size(std::istream& stream) {
- OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
+size_t get_and_check_remaining_source_size(intel_npu::BlobSource& source) {
+ const size_t remaining = source.get_remaining_size();
- const std::streampos backupCursor = stream.tellg();
- stream.seekg(0, std::ios_base::end);
- const std::streampos streamEnd = stream.tellg();
- stream.seekg(backupCursor, std::ios_base::beg);
-
- return streamEnd;
+ OPENVINO_ASSERT(remaining >= FOOTER_SIZE,
+ "Invalid state. While parsing the NPU plugin metadata, it was found that the remaining number of "
+ "bytes within the blob source is lower than the size of the footer.");
+ return remaining;
}
} // namespace
@@ -107,16 +102,10 @@ OpenvinoVersion::OpenvinoVersion(const OpenvinoVersion& version)
_minor(version.get_minor()),
_patch(version.get_patch()) {}
-void OpenvinoVersion::read(std::istream& stream) {
- stream.read(reinterpret_cast<char*>(&_major), sizeof(_major));
- stream.read(reinterpret_cast<char*>(&_minor), sizeof(_minor));
- stream.read(reinterpret_cast<char*>(&_patch), sizeof(_patch));
-}
-
-void OpenvinoVersion::read(const ov::Tensor& tensor) {
- _major = *reinterpret_cast<const decltype(_major)*>(tensor.data<const char>());
- _minor = *reinterpret_cast<const decltype(_minor)*>(tensor.data<const char>() + sizeof(_major));
- _patch = *reinterpret_cast<const decltype(_patch)*>(tensor.data<const char>() + sizeof(_major) + sizeof(_minor));
+void OpenvinoVersion::read(BlobSource& source) {
+ source.read_into_buffer(&_major, sizeof(_major));
+ source.read_into_buffer(&_minor, sizeof(_minor));
+ source.read_into_buffer(&_patch, sizeof(_patch));
}
void OpenvinoVersion::write(std::ostream& stream) {
@@ -131,9 +120,8 @@ size_t OpenvinoVersion::get_openvino_version_size() const {
MetadataBase::MetadataBase(uint32_t version, uint64_t blobDataSize)
: _version(version),
- _blobDataSize(blobDataSize),
- _logger("NPUBlobMetadata", Logger::global().level()),
- _source() {}
+ _compilerPayloadSize(blobDataSize),
+ _logger("NPUBlobMetadata", Logger::global().level()) {}
std::optional<BlobType> MetadataBase::get_blob_type() const {
return std::nullopt;
@@ -247,128 +235,63 @@ Metadata<METADATA_VERSION_2_7>::Metadata(uint64_t blobSize,
_version = METADATA_VERSION_2_7;
}
-void MetadataBase::read(std::istream& stream) {
- _source = Source(stream);
- _sourceSize = get_stream_total_size(stream);
- read();
-
- // Note: we could have placed an additional safeguard here. Something like "cursorPosition = streamEnd -
- // footerSize", to make sure the whole content of the metadata section has been read. However, such a safeguard
- // would break compatibility, because some previous plugin versions are padding the space between the end of the
- // metadata and the footer.
-}
-
-void MetadataBase::read(const ov::Tensor& tensor) {
- _source = Source(tensor);
- _sourceSize = tensor.get_byte_size();
- read();
-}
-
-void MetadataBase::read_as_text(std::map<std::string, std::string, std::less<>> attrs) {
- _textAttrs = std::move(attrs);
- read_as_text();
-}
-
-size_t MetadataBase::get_remaining_source_size() const {
- size_t remaining;
- if (const std::reference_wrapper<std::istream>* stream =
- std::get_if<std::reference_wrapper<std::istream>>(&_source)) {
- OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
+void MetadataBase::read(BlobSource& source) {
+ read_unchecked(source);
+ get_and_check_remaining_source_size(source);
- const auto offset = static_cast<size_t>(stream->get().tellg());
- remaining = (offset <= _sourceSize) ? _sourceSize - offset : 0;
- } else if (std::get_if<std::reference_wrapper<const ov::Tensor>>(&_source)) {
- remaining = (_cursorOffset <= _sourceSize) ? _sourceSize - _cursorOffset : 0;
- } else {
- OPENVINO_THROW(MISSING_BLOB_MESSAGE);
- }
-
- OPENVINO_ASSERT(remaining >= FOOTER_SIZE,
- "Invalid state. While parsing the NPU plugin metadata, it was found that the remaining number of "
- "bytes within the blob source is lower than the size of the footer.");
- return remaining;
-}
-
-void MetadataBase::read_data_from_source(char* destination, const size_t size) {
- const size_t remaining = get_remaining_source_size();
- OPENVINO_ASSERT(size <= remaining,
- "NPU metadata: attempted to read ",
- size,
- " bytes but only ",
- remaining,
- " bytes remain in the metadata buffer.");
-
- if (const std::reference_wrapper<std::istream>* stream =
- std::get_if<std::reference_wrapper<std::istream>>(&_source)) {
- OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);
-
- stream->get().read(destination, size);
- } else if (const std::reference_wrapper<const ov::Tensor>* tensor =
- std::get_if<std::reference_wrapper<const ov::Tensor>>(&_source)) {
- std::memcpy(destination, tensor->get().data<const char>() + _cursorOffset, size);
- _cursorOffset += size;
- } else {
- OPENVINO_THROW(MISSING_BLOB_MESSAGE);
- }
+ // Note: we could have placed an additional safeguard here. Something like "cursor = streamEnd - footerSize", to
+ // make sure the whole content of the metadata section has been read. However, such a safeguard would break
+ // compatibility, because some previous plugin versions are padding the space between the end of the metadata and
+ // the footer.
}
void MetadataBase::write(std::ostream& stream) {
write_without_footer(stream);
- stream.write(reinterpret_cast<const char*>(&_blobDataSize), sizeof(_blobDataSize));
+ stream.write(reinterpret_cast<const char*>(&_compilerPayloadSize), sizeof(_compilerPayloadSize));
stream.write(MAGIC_BYTES.data(), MAGIC_BYTES.size());
}
-void Metadata<METADATA_VERSION_2_0>::read() {
- if (const std::reference_wrapper<std::istream>* source =
- std::get_if<std::reference_wrapper<std::istream>>(&_source)) {
- _ovVersion.read(*source);
- } else if (const std::reference_wrapper<const ov::Tensor>* source =
- std::get_if<std::reference_wrapper<const ov::Tensor>>(&_source)) {
- _ovVersion.read(*source);
- _cursorOffset = _ovVersion.get_openvino_version_size();
- } else {
- OPENVINO_THROW("No blob has been provided to NPU plugin's metadata reader.");
- }
+void Metadata<METADATA_VERSION_2_0>::read_unchecked(BlobSource& source) {
+ _ovVersion.read(source);
}
-void Metadata<METADATA_VERSION_2_1>::read() {
- Metadata<METADATA_VERSION_2_0>::read();
+void Metadata<METADATA_VERSION_2_1>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_0>::read_unchecked(source);
uint64_t numberOfInits;
- read_data_from_source(reinterpret_cast<char*>(&numberOfInits), sizeof(numberOfInits));
+ source.read_into_buffer(&numberOfInits, sizeof(numberOfInits));
if (numberOfInits) {
OPENVINO_ASSERT(
- numberOfInits <= (get_remaining_source_size() - FOOTER_SIZE) / SIZE_OF_INIT_SCHEDULE_SIZE,
+ numberOfInits <= (get_and_check_remaining_source_size(source) - FOOTER_SIZE) / SIZE_OF_INIT_SCHEDULE_SIZE,
"The number of init schedules read from the blob is too great relative to the size of the blob");
_initSizes = std::vector<uint64_t>(numberOfInits);
for (uint64_t initIndex = 0; initIndex < numberOfInits; ++initIndex) {
- read_data_from_source(reinterpret_cast<char*>(&_initSizes->at(initIndex)),
- sizeof(_initSizes->at(initIndex)));
+ source.read_into_buffer(&_initSizes->at(initIndex), sizeof(_initSizes->at(initIndex)));
}
}
}
-void Metadata<METADATA_VERSION_2_2>::read() {
- Metadata<METADATA_VERSION_2_1>::read();
+void Metadata<METADATA_VERSION_2_2>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_1>::read_unchecked(source);
int64_t batchSize;
- read_data_from_source(reinterpret_cast<char*>(&batchSize), sizeof(batchSize));
+ source.read_into_buffer(&batchSize, sizeof(batchSize));
_batchSize = batchSize != 0 ? std::optional(batchSize) : std::nullopt;
}
-void Metadata<METADATA_VERSION_2_3>::read() {
- Metadata<METADATA_VERSION_2_2>::read();
+void Metadata<METADATA_VERSION_2_3>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_2>::read_unchecked(source);
uint64_t numberOfInputLayouts, numberOfOutputLayouts;
- read_data_from_source(reinterpret_cast<char*>(&numberOfInputLayouts), sizeof(numberOfInputLayouts));
- read_data_from_source(reinterpret_cast<char*>(&numberOfOutputLayouts), sizeof(numberOfOutputLayouts));
+ source.read_into_buffer(&numberOfInputLayouts, sizeof(numberOfInputLayouts));
+ source.read_into_buffer(&numberOfOutputLayouts, sizeof(numberOfOutputLayouts));
OPENVINO_ASSERT(numberOfInputLayouts + numberOfOutputLayouts <=
- (get_remaining_source_size() - FOOTER_SIZE) / SIZE_OF_LAYOUT_SIZE,
+ (get_and_check_remaining_source_size(source) - FOOTER_SIZE) / SIZE_OF_LAYOUT_SIZE,
"The number of I/O layouts read from the blob is too great relative to the size of the blob");
const auto readNLayouts = [&](const uint64_t numberOfLayouts, const char* loggerAddition) {
@@ -381,12 +304,12 @@ void Metadata<METADATA_VERSION_2_3>::read() {
layouts = std::vector<ov::Layout>();
layouts->reserve(numberOfLayouts);
for (uint64_t layoutIndex = 0; layoutIndex < numberOfLayouts; ++layoutIndex) {
- read_data_from_source(reinterpret_cast<char*>(&stringLength), sizeof(stringLength));
- OPENVINO_ASSERT(stringLength <= get_remaining_source_size() - FOOTER_SIZE,
+ source.read_into_buffer(&stringLength, sizeof(stringLength));
+ OPENVINO_ASSERT(stringLength <= get_and_check_remaining_source_size(source) - FOOTER_SIZE,
"The size of at least one layout exceeds the limit of the blob");
std::string layoutString(stringLength, 0);
- read_data_from_source(const_cast<char*>(layoutString.c_str()), stringLength);
+ source.read_into_buffer(layoutString.data(), stringLength);
try {
layouts->push_back(ov::Layout(std::move(layoutString)));
@@ -406,43 +329,43 @@ void Metadata<METADATA_VERSION_2_3>::read() {
_outputLayouts = readNLayouts(numberOfOutputLayouts, "Output");
}
-void Metadata<METADATA_VERSION_2_4>::read() {
- Metadata<METADATA_VERSION_2_3>::read();
+void Metadata<METADATA_VERSION_2_4>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_3>::read_unchecked(source);
uint32_t compilerVersion;
- read_data_from_source(reinterpret_cast<char*>(&compilerVersion), sizeof(compilerVersion));
+ source.read_into_buffer(&compilerVersion, sizeof(compilerVersion));
_compilerVersion = compilerVersion != 0 ? std::optional(compilerVersion) : std::nullopt;
}
-void Metadata<METADATA_VERSION_2_5>::read() {
- Metadata<METADATA_VERSION_2_4>::read();
+void Metadata<METADATA_VERSION_2_5>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_4>::read_unchecked(source);
uint8_t isEncryptedBlob;
- read_data_from_source(reinterpret_cast<char*>(&isEncryptedBlob), sizeof(isEncryptedBlob));
+ source.read_into_buffer(&isEncryptedBlob, sizeof(isEncryptedBlob));
_isEncryptedBlob = isEncryptedBlob;
}
-void Metadata<METADATA_VERSION_2_6>::read() {
- Metadata<METADATA_VERSION_2_5>::read();
+void Metadata<METADATA_VERSION_2_6>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_5>::read_unchecked(source);
uint64_t reqs_len;
- read_data_from_source(reinterpret_cast<char*>(&reqs_len), sizeof(reqs_len));
+ source.read_into_buffer(&reqs_len, sizeof(reqs_len));
if (reqs_len > 0) {
- OPENVINO_ASSERT(reqs_len <= (get_remaining_source_size() - FOOTER_SIZE),
+ OPENVINO_ASSERT(reqs_len <= (get_and_check_remaining_source_size(source) - FOOTER_SIZE),
"The size of the runtime requirements surpasses the limit of the blob");
std::string reqs(reqs_len, '\0');
- read_data_from_source(reqs.data(), reqs_len);
+ source.read_into_buffer(reqs.data(), reqs_len);
_compatibilityDescriptor = std::move(reqs);
}
}
-void Metadata<METADATA_VERSION_2_7>::read() {
- Metadata<METADATA_VERSION_2_6>::read();
+void Metadata<METADATA_VERSION_2_7>::read_unchecked(BlobSource& source) {
+ Metadata<METADATA_VERSION_2_6>::read_unchecked(source);
uint8_t blobType;
- read_data_from_source(reinterpret_cast<char*>(&blobType), sizeof(blobType));
+ source.read_into_buffer(&blobType, sizeof(blobType));
const auto type = static_cast<BlobType>(blobType);
OPENVINO_ASSERT(type == BlobType::ELF || type == BlobType::LLVM || type == BlobType::BYTECODE,
"Invalid blob type in NPU blob metadata: ",
@@ -454,9 +377,9 @@ std::optional<BlobType> Metadata<METADATA_VERSION_2_7>::get_blob_type() const {
return _blobType;
}
-void Metadata<METADATA_VERSION_2_0>::read_as_text() {
- const auto it = _textAttrs.find(MetadataTextKeys::OV);
- if (it == _textAttrs.end()) {
+void Metadata<METADATA_VERSION_2_0>::read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) {
+ const auto it = textAttrs.find(MetadataTextKeys::OV);
+ if (it == textAttrs.end()) {
OPENVINO_THROW("Human-readable metadata missing '" + std::string(MetadataTextKeys::OV) + "' field.");
}
const auto ovParts = parse_version(it->second);
@@ -467,11 +390,11 @@ void Metadata<METADATA_VERSION_2_0>::read_as_text() {
_ovVersion = OpenvinoVersion(ovParts[0], ovParts[1], ovParts[2]);
}
-void Metadata<METADATA_VERSION_2_1>::read_as_text() {
- Metadata<METADATA_VERSION_2_0>::read_as_text();
+void Metadata<METADATA_VERSION_2_1>::read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) {
+ Metadata<METADATA_VERSION_2_0>::read_as_text(textAttrs);
- const auto it = _textAttrs.find(MetadataTextKeys::WS_INITS);
- if (it == _textAttrs.end()) {
+ const auto it = textAttrs.find(MetadataTextKeys::WS_INITS);
+ if (it == textAttrs.end()) {
return;
}
if (it->second != "1") {
@@ -481,22 +404,22 @@ void Metadata<METADATA_VERSION_2_1>::read_as_text() {
_initSizes = std::vector<uint64_t>{};
}
-void Metadata<METADATA_VERSION_2_2>::read_as_text() {
- Metadata<METADATA_VERSION_2_1>::read_as_text();
+void Metadata<METADATA_VERSION_2_2>::read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) {
+ Metadata<METADATA_VERSION_2_1>::read_as_text(textAttrs);
- const auto it = _textAttrs.find(MetadataTextKeys::BATCH);
- if (it == _textAttrs.end()) {
+ const auto it = textAttrs.find(MetadataTextKeys::BATCH);
+ if (it == textAttrs.end()) {
return;
}
const int64_t batchValue = std::stoll(it->second);
_batchSize = batchValue != 0 ? std::optional<int64_t>(batchValue) : std::nullopt;
}
-void Metadata<METADATA_VERSION_2_6>::read_as_text() {
- Metadata<METADATA_VERSION_2_5>::read_as_text();
+void Metadata<METADATA_VERSION_2_6>::read_as_text(const std::map<std::string, std::string, std::less<>>& textAttrs) {
+ Metadata<METADATA_VERSION_2_5>::read_as_text(textAttrs);
- const auto it = _textAttrs.find(MetadataTextKeys::COMPAT_DESC);
- if (it == _textAttrs.end() || it->second.empty()) {
+ const auto it = textAttrs.find(MetadataTextKeys::COMPAT_DESC);
+ if (it == textAttrs.end() || it->second.empty()) {
return;
}
@@ -666,98 +589,39 @@ std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSiz
}
}
-size_t MetadataBase::get_stream_remaining_size(std::istream& stream) {
- auto log = Logger::global().clone("get_stream_remaining_size");
- OPENVINO_ASSERT(stream, "Stream is in bad status! Please check the passed stream status!");
+std::unique_ptr<MetadataBase> read_metadata_from(BlobSource& source) {
+ const size_t startingPosition = source.tellg();
+ const size_t npuBlobSize = source.get_remaining_size();
- if (dynamic_cast<ov::SharedStreamBuffer*>(stream.rdbuf()) != nullptr) {
- return stream.rdbuf()->in_avail();
- }
- const std::streampos streamStart = stream.tellg();
- stream.seekg(0, std::ios_base::end);
- const std::streampos streamEnd = stream.tellg();
- stream.seekg(streamStart, std::ios_base::beg);
+ OPENVINO_ASSERT(npuBlobSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, npuBlobSize);
- log.debug("Read blob size: streamStart=%zu, streamEnd=%zu",
- static_cast<size_t>(streamStart),
- static_cast<size_t>(streamEnd));
-
- OPENVINO_ASSERT(streamEnd >= streamStart,
- "Invalid stream size: streamEnd (",
- streamEnd,
- ") is not larger than streamStart (",
- streamStart,
- ")!");
-
- return streamEnd - streamStart;
-}
-
-std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream) {
- std::streampos currentStreamPos = stream.tellg();
- const size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
-
- OPENVINO_ASSERT(streamSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, streamSize);
-
- std::string blobMagicBytes;
- blobMagicBytes.resize(MAGIC_BYTES.size());
- stream.seekg(-std::streampos(MAGIC_BYTES.size()), std::ios::end);
- stream.read(blobMagicBytes.data(), MAGIC_BYTES.size());
+ std::string blobMagicBytes(MAGIC_BYTES.size(), 0);
+ source.seekg(-static_cast<int>(MAGIC_BYTES.size()), std::ios::end);
+ source.read_into_buffer(blobMagicBytes.data(), MAGIC_BYTES.size());
OPENVINO_ASSERT(MAGIC_BYTES == blobMagicBytes, MISSING_METADATA_MESSAGE);
uint64_t payloadSize;
- stream.seekg(-std::streampos(MAGIC_BYTES.size()) - sizeof(payloadSize), std::ios::end);
- stream.read(reinterpret_cast<char*>(&payloadSize), sizeof(payloadSize));
+ source.seekg(-static_cast<int>(MAGIC_BYTES.size()) - static_cast<int>(sizeof(payloadSize)), std::ios::end);
+ source.read_into_buffer(&payloadSize, sizeof(payloadSize));
// Subtraction form avoids integer overflow when payloadSize is near UINT64_MAX.
- OPENVINO_ASSERT(payloadSize <= streamSize - MINIMUM_BLOB_SIZE, INVALID_PAYLOAD_SIZE_MESSAGE, payloadSize);
- stream.seekg(-stream.tellg() + currentStreamPos + payloadSize, std::ios::cur);
+ OPENVINO_ASSERT(payloadSize <= npuBlobSize - MINIMUM_BLOB_SIZE, INVALID_PAYLOAD_SIZE_MESSAGE, payloadSize);
uint32_t metaVersion;
- stream.read(reinterpret_cast<char*>(&metaVersion), sizeof(metaVersion));
+ source.seekg(startingPosition + payloadSize, std::ios::beg);
+ source.read_into_buffer(&metaVersion, sizeof(metaVersion));
std::unique_ptr<MetadataBase> storedMeta;
try {
storedMeta = create_metadata(metaVersion, payloadSize);
- storedMeta->read(stream);
+ storedMeta->read(source);
} catch (const std::exception& ex) {
OPENVINO_THROW("Can't read NPU metadata: ", ex.what());
} catch (...) {
OPENVINO_THROW("Unexpected exception while reading blob NPU metadata");
}
- stream.seekg(-stream.tellg() + currentStreamPos, std::ios::cur);
-
- return storedMeta;
-}
-
-std::unique_ptr<MetadataBase> read_metadata_from(const ov::Tensor& tensor) {
- const size_t blobSize = tensor.get_byte_size();
- OPENVINO_ASSERT(blobSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, blobSize);
-
- const std::string_view blobMagicBytes(tensor.data<const char>() + blobSize - MAGIC_BYTES.size(),
- MAGIC_BYTES.size());
- OPENVINO_ASSERT(MAGIC_BYTES == blobMagicBytes, MISSING_METADATA_MESSAGE);
-
- uint64_t payloadSize;
- payloadSize = *reinterpret_cast<const decltype(payloadSize)*>(tensor.data<const char>() + blobSize -
- MAGIC_BYTES.size() - sizeof(payloadSize));
-
- // Subtraction form avoids integer overflow when payloadSize is near UINT64_MAX.
- OPENVINO_ASSERT(payloadSize <= blobSize - MINIMUM_BLOB_SIZE, INVALID_PAYLOAD_SIZE_MESSAGE, payloadSize);
-
- uint32_t metaVersion;
- metaVersion = *reinterpret_cast<const decltype(metaVersion)*>(tensor.data<const char>() + payloadSize);
-
- std::unique_ptr<MetadataBase> storedMeta;
- try {
- const ov::Tensor roiTensor(tensor, ov::Coordinate{payloadSize + sizeof(metaVersion)}, ov::Coordinate{blobSize});
- storedMeta = create_metadata(metaVersion, payloadSize);
- storedMeta->read(roiTensor);
- } catch (const std::exception& ex) {
- OPENVINO_THROW("Can't read NPU metadata: ", ex.what());
- } catch (...) {
- OPENVINO_THROW("Unexpected exception while reading blob NPU metadata");
- }
+ source.seekg(startingPosition, std::ios::beg);
return storedMeta;
}
@@ -782,7 +646,7 @@ std::unique_ptr<MetadataBase> read_as_text(std::string_view input) {
std::unique_ptr<MetadataBase> storedMeta;
try {
storedMeta = create_metadata(metaVersion, 0);
- storedMeta->read_as_text(std::move(attrs));
+ storedMeta->read_as_text(attrs);
} catch (const std::exception& ex) {
OPENVINO_THROW("Can't read NPU human-readable metadata: ", ex.what());
} catch (...) {
@@ -792,15 +656,16 @@ std::unique_ptr<MetadataBase> read_as_text(std::string_view input) {
return storedMeta;
}
-uint64_t MetadataBase::get_blob_size() const {
- return _blobDataSize;
+uint64_t MetadataBase::get_compiler_payload_size() const {
+ return _compilerPayloadSize;
}
uint64_t MetadataBase::get_main_schedule_size() const {
uint64_t accumulator = 0;
const auto initSizes = get_init_sizes();
- return initSizes.has_value() ? get_blob_size() - std::accumulate(initSizes->begin(), initSizes->end(), accumulator)
- : get_blob_size();
+ return initSizes.has_value()
+ ? get_compiler_payload_size() - std::accumulate(initSizes->begin(), initSizes->end(), accumulator)
+ : get_compiler_payload_size();
}
std::optional<std::vector<uint64_t>> MetadataBase::get_init_sizes() const {
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index 8e5ba7796ee..b0c9e4e7b8e 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -7,6 +7,7 @@
#include <fstream>
#include <numeric>
+#include "blob_format_importers.hpp"
#include "compiled_model.hpp"
#include "intel_npu/common/compiler_adapter_factory.hpp"
#include "intel_npu/common/device_helpers.hpp"
@@ -39,6 +40,8 @@ using namespace intel_npu;
constexpr std::string_view NPU_PLUGIN_LIB_NAME = "openvino_intel_npu_plugin";
constexpr std::string_view NO_BACKEND_MESSAGE = "No backend registered during model import";
constexpr std::string_view NPUW_MODEL_IMPORTED_MESSAGE = "Finished importing the NPUW compiled model";
+constexpr std::string_view FAILED_IMPORT_MODEL_PREFACE = "Could not import the model:";
+constexpr std::string_view IMPORT_MODEL_UNEXPECTED_FAILURE_MESSAGE = "Unexpected exception while importing the model";
/**
* @brief Just checks if there is any "WeightlessCacheAttribute" present in the model. In the negative case, an error is
@@ -623,31 +626,21 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, c
"import_model(tensor) API instead.");
}
- auto npuPluginProperties = properties;
- // NPUW properties from npuPluginProperties will be erased if import_model_npuw returns nullptr
- if (auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this())) {
+ auto localProperties = properties;
+ // NPUW properties from localProperties will be erased if import_model_npuw returns nullptr
+ if (auto compiledModel = import_model_npuw(stream, localProperties, shared_from_this())) {
_logger.debug(NPUW_MODEL_IMPORTED_MESSAGE.data());
return compiledModel;
}
- OPENVINO_ASSERT(_backend != nullptr, NO_BACKEND_MESSAGE);
- _backend->updateInfo(npuPluginProperties);
-
- OV_ITT_TASK_CHAIN(PLUGIN_PARSE_MODEL, itt::domains::NPUPlugin, "Plugin::import_model", "fork_local_config");
- FilteredConfig localConfig = _propertiesManager->getConfigWithCompilerPropertiesDisabled(npuPluginProperties);
+ BlobSource blobSource(stream, _logger.level());
try {
- std::unique_ptr<IBlobFormatImporter> blobFormatImporter =
- blob_format_importer_factory::create(stream,
- should_import_raw_blob(npuPluginProperties),
- get_model_ptr_from_map(properties),
- localConfig);
-
- return import_model(blobFormatImporter, localConfig, npuPluginProperties);
+ return import_model(blobSource, localProperties);
} catch (const std::exception& ex) {
- OPENVINO_THROW("Can't import network: ", ex.what());
+ OPENVINO_THROW(FAILED_IMPORT_MODEL_PREFACE, ex.what());
} catch (...) {
- OPENVINO_THROW("NPU import_model got unexpected exception from CompiledModel");
+ OPENVINO_THROW(IMPORT_MODEL_UNEXPECTED_FAILURE_MESSAGE);
}
}
@@ -662,42 +655,41 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compi
ov::SharedStreamBuffer buffer{compiledBlob.data(), compiledBlob.get_byte_size()};
std::istream stream{&buffer};
- auto npuPluginProperties = properties;
- // NPUW properties from npuPluginProperties will be erased if import_model_npuw returns nullptr
- if (auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this())) {
+ auto localProperties = properties;
+ // NPUW properties from localProperties will be erased if import_model_npuw returns nullptr
+ if (auto compiledModel = import_model_npuw(stream, localProperties, shared_from_this())) {
_logger.debug(NPUW_MODEL_IMPORTED_MESSAGE.data());
return compiledModel;
}
- OPENVINO_ASSERT(_backend != nullptr, NO_BACKEND_MESSAGE);
- _backend->updateInfo(npuPluginProperties);
-
- OV_ITT_TASK_CHAIN(PLUGIN_PARSE_MODEL, itt::domains::NPUPlugin, "Plugin::import_model", "fork_local_config");
- FilteredConfig localConfig = _propertiesManager->getConfigWithCompilerPropertiesDisabled(npuPluginProperties);
+ BlobSource blobSource(compiledBlob, _logger.level());
try {
- std::unique_ptr<IBlobFormatImporter> blobFormatImporter =
- blob_format_importer_factory::create(compiledBlob,
- should_import_raw_blob(npuPluginProperties),
- get_model_ptr_from_map(properties),
- localConfig);
-
- return import_model(blobFormatImporter, localConfig, npuPluginProperties);
+ return import_model(blobSource, localProperties);
} catch (const std::exception& ex) {
- OPENVINO_THROW("Can't import network: ", ex.what());
+ OPENVINO_THROW(FAILED_IMPORT_MODEL_PREFACE, ex.what());
} catch (...) {
- OPENVINO_THROW("NPU import_model got unexpected exception from CompiledModel");
+ OPENVINO_THROW(IMPORT_MODEL_UNEXPECTED_FAILURE_MESSAGE);
}
}
-std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const std::unique_ptr<IBlobFormatImporter>& blobFormatImporter,
- FilteredConfig& localConfig,
- ov::AnyMap& localProperties) const {
- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model(IBlobFormatImporter)");
- _logger.trace("Importing a compiled model using an import handler object");
+std::shared_ptr<ov::ICompiledModel> Plugin::import_model(BlobSource& blobSource, ov::AnyMap& properties) const {
+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model(BlobSource)");
+ _logger.trace("Importing a compiled model using a BlobSource object");
+
+ OPENVINO_ASSERT(_backend != nullptr, NO_BACKEND_MESSAGE);
+ _backend->updateInfo(properties);
+
+ OV_ITT_TASK_CHAIN(PLUGIN_PARSE_MODEL, itt::domains::NPUPlugin, "Plugin::import_model", "fork_local_config");
+ FilteredConfig localConfig = _propertiesManager->getConfigWithCompilerPropertiesDisabled(properties);
- std::shared_ptr<IDevice> device =
- utils::getDeviceById(_backend, _propertiesManager->determineDeviceId(localProperties));
+ std::unique_ptr<IBlobFormatImporter> blobFormatImporter =
+ blob_format_importer_factory::create(blobSource,
+ should_import_raw_blob(properties),
+ get_model_ptr_from_map(properties),
+ localConfig);
+
+ std::shared_ptr<IDevice> device = utils::getDeviceById(_backend, _propertiesManager->determineDeviceId(properties));
OPENVINO_ASSERT(device != nullptr, "Device not found.");
if (!localConfig.get<LOADED_FROM_CACHE>()) {
@@ -722,10 +714,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream,
const ov::SoPtr<ov::IRemoteContext>& context,
const ov::AnyMap& properties) const {
auto casted = std::dynamic_pointer_cast<RemoteContextImpl>(context._ptr);
- if (casted == nullptr) {
- OPENVINO_THROW("Invalid remote context type. Can't cast to ov::intel_npu::RemoteContext type");
- }
-
+ OPENVINO_ASSERT(casted, "Invalid remote context type. Can't cast to ov::intel_npu::RemoteContext type");
return import_model(stream, properties);
}
@@ -733,9 +722,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compi
const ov::SoPtr<ov::IRemoteContext>& context,
const ov::AnyMap& properties) const {
auto casted = std::dynamic_pointer_cast<RemoteContextImpl>(context._ptr);
- if (casted == nullptr) {
- OPENVINO_THROW("Invalid remote context type. Can't cast to ov::intel_npu::RemoteContext type");
- }
+ OPENVINO_ASSERT(casted, "Invalid remote context type. Can't cast to ov::intel_npu::RemoteContext type");
return import_model(compiledBlob, properties);
}
diff --git a/src/plugins/intel_npu/tests/functional/CMakeLists.txt b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
index 3d486717ad1..ae1bdc202e9 100644
--- a/src/plugins/intel_npu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
@@ -42,6 +42,7 @@ ov_add_test_target(
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/compiled_model_property_manager.cpp"
+ "${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/blob_source.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/metadata.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/compiler_option_support_helper.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/plugin_property_manager.cpp"
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 4cfad627c8c..249d6408451 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -45,6 +45,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/executor.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/metadata.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/blob_source.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/compiler_option_support_helper.cpp
# npuw core
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp
index 5ab493b3287..65d36437f64 100644
--- a/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp
+++ b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp
@@ -63,11 +63,14 @@ struct BlobFormatImportersTest : public ::testing::Test {
* @brief Empty blobs should not be accepted by the importer factory
*/
TEST_F(BlobFormatImportersTest, FactoryEmptyInputFails) {
- std::istringstream input_stream("");
- const ov::Tensor input_tensor;
-
- OV_EXPECT_THROW(blob_format_importer_factory::create(input_stream, false, nullptr, config), ov::Exception, _);
- OV_EXPECT_THROW(blob_format_importer_factory::create(input_tensor, false, nullptr, config), ov::Exception, _);
+ const std::string empty_buffer("");
+ std::istringstream input_stream(empty_buffer);
+ BlobSource source(input_stream);
+ OV_EXPECT_THROW(blob_format_importer_factory::create(source, false, nullptr, config), ov::Exception, _);
+
+ const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({0}), empty_buffer.data());
+ source = BlobSource(input_tensor);
+ OV_EXPECT_THROW(blob_format_importer_factory::create(source, false, nullptr, config), ov::Exception, _);
}
/**
@@ -81,7 +84,8 @@ TEST_F(BlobFormatImportersTest, FactoryTensorSmallerThanMagicFails) {
const ov::Tensor input_tensor(ov::element::Type_t::u8,
ov::Shape({blob.size()}),
const_cast<char*>(blob.data()));
- OV_EXPECT_THROW(blob_format_importer_factory::create(input_tensor, false, nullptr, config), ov::Exception, _);
+ BlobSource source(input_tensor);
+ OV_EXPECT_THROW(blob_format_importer_factory::create(source, false, nullptr, config), ov::Exception, _);
}
}
@@ -90,11 +94,14 @@ TEST_F(BlobFormatImportersTest, FactoryTensorSmallerThanMagicFails) {
*/
TEST_F(BlobFormatImportersTest, FactoryNoMagicNoRawFails) {
const std::string blob = build_blob_format_v1_without_magic();
+
std::istringstream input_stream(blob);
- const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ BlobSource source(input_stream);
+ OV_EXPECT_THROW(blob_format_importer_factory::create(source, false, nullptr, config), ov::Exception, _);
- OV_EXPECT_THROW(blob_format_importer_factory::create(input_stream, false, nullptr, config), ov::Exception, _);
- OV_EXPECT_THROW(blob_format_importer_factory::create(input_tensor, false, nullptr, config), ov::Exception, _);
+ const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ source = BlobSource(input_tensor);
+ OV_EXPECT_THROW(blob_format_importer_factory::create(source, false, nullptr, config), ov::Exception, _);
}
/**
@@ -102,11 +109,14 @@ TEST_F(BlobFormatImportersTest, FactoryNoMagicNoRawFails) {
*/
TEST_F(BlobFormatImportersTest, FactoryNoMagicRawPasses) {
const std::string blob(RAW_BLOB);
+
std::istringstream input_stream(blob);
- const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ BlobSource source(input_stream);
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(source, true, nullptr, config));
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_stream, true, nullptr, config));
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_tensor, true, nullptr, config));
+ const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ source = BlobSource(input_tensor);
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(source, true, nullptr, config));
}
/**
@@ -116,17 +126,21 @@ TEST_F(BlobFormatImportersTest, FactoryCanCreateImporterForBlobFormatV1) {
const std::string blob = build_blob_format_v1_with_magic();
std::istringstream input_stream(blob);
const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ BlobSource stream_source(input_stream);
+ BlobSource tensor_source(input_tensor);
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_stream, true, nullptr, config));
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_tensor, true, nullptr, config));
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(stream_source, true, nullptr, config));
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(tensor_source, true, nullptr, config));
- input_stream.seekg(0, std::ios::beg);
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_stream, false, nullptr, config));
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_tensor, false, nullptr, config));
+ stream_source.seekg(0, std::ios::beg);
+ tensor_source.seekg(0, std::ios::beg);
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(stream_source, false, nullptr, config));
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(tensor_source, false, nullptr, config));
- input_stream.seekg(0, std::ios::beg);
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_stream, false, create_simple_model(), config));
- OV_ASSERT_NO_THROW(blob_format_importer_factory::create(input_tensor, false, create_simple_model(), config));
+ stream_source.seekg(0, std::ios::beg);
+ tensor_source.seekg(0, std::ios::beg);
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(stream_source, false, create_simple_model(), config));
+ OV_ASSERT_NO_THROW(blob_format_importer_factory::create(tensor_source, false, create_simple_model(), config));
}
/**
@@ -135,7 +149,8 @@ TEST_F(BlobFormatImportersTest, FactoryCanCreateImporterForBlobFormatV1) {
TEST_F(BlobFormatImportersTest, CannotCreateModelBeforeGraph) {
const std::string blob = build_blob_format_v1_with_magic();
const ov::Tensor input_tensor(ov::element::Type_t::u8, ov::Shape({blob.size()}), blob.data());
+ BlobSource source(input_tensor);
- OV_ASSERT_NO_THROW(importer = blob_format_importer_factory::create(input_tensor, true, nullptr, config));
+ OV_ASSERT_NO_THROW(importer = blob_format_importer_factory::create(source, true, nullptr, config));
OV_EXPECT_THROW(importer->create_dummy_model(), ov::Exception, _);
}
diff --git a/src/plugins/intel_npu/tests/unit/npu/blob_source.cpp b/src/plugins/intel_npu/tests/unit/npu/blob_source.cpp
new file mode 100644
index 00000000000..9efa262ac4c
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npu/blob_source.cpp
@@ -0,0 +1,645 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "blob_source.hpp"
+
+#include <gtest/gtest.h>
+
+#include <limits>
+#include <set>
+#include <sstream>
+#include <string_view>
+
+#include "common_test_utils/test_assertions.hpp"
+#include "intel_npu/utils/utils.hpp"
+
+using namespace intel_npu;
+
+namespace {
+
+enum class BlobContentType { STANDARD_STRING, SPECIAL_CHARS_STRING, BUFFER };
+const std::set<BlobContentType> ALL_BLOB_CONTENT_TYPES({BlobContentType::STANDARD_STRING,
+ BlobContentType::SPECIAL_CHARS_STRING,
+ BlobContentType::BUFFER});
+
+enum class BlobSourceDataType { STREAM, TENSOR };
+const std::set<BlobSourceDataType> ALL_BLOB_SOURCE_DATA_TYPES({BlobSourceDataType::STREAM, BlobSourceDataType::TENSOR});
+
+constexpr std::string_view TEST_STRING_STANDARD = "This is a test string";
+constexpr std::string_view TEST_STRING_SPECIAL_CHARS = "This i\t a \ntest s\rtr!@#$%^()_+i&*ng";
+const std::vector<uint8_t> TEST_BUFFER{0, 1, 2, 3};
+
+constexpr std::string_view INVALID_BLOB_TYPE_MESSAGE = "Invalid blob type";
+
+inline std::string get_content_type_name(const BlobContentType content_type) {
+ switch (content_type) {
+ case BlobContentType::STANDARD_STRING: {
+ return "standard_string";
+ }
+ case BlobContentType::SPECIAL_CHARS_STRING: {
+ return "special_chars_string";
+ }
+ case BlobContentType::BUFFER: {
+ return "buffer";
+ }
+ default: {
+ OPENVINO_THROW(INVALID_BLOB_TYPE_MESSAGE);
+ }
+ }
+}
+
+inline std::string get_source_data_type_name(const BlobSourceDataType source_data_type) {
+ switch (source_data_type) {
+ case BlobSourceDataType::STREAM: {
+ return "stream";
+ }
+ case BlobSourceDataType::TENSOR: {
+ return "tensor";
+ }
+ default: {
+ OPENVINO_THROW(INVALID_BLOB_TYPE_MESSAGE);
+ }
+ }
+}
+
+} // namespace
+
+using testing::_;
+
+class BlobSourceDifferentBlobs : public testing::TestWithParam<std::tuple<BlobContentType, BlobSourceDataType>> {
+public:
+ static std::string getTestCaseName(
+ const testing::TestParamInfo<std::tuple<BlobContentType, BlobSourceDataType>>& obj) {
+ BlobContentType content_type;
+ BlobSourceDataType source_data_type;
+ std::tie(content_type, source_data_type) = obj.param;
+
+ return get_content_type_name(content_type) + "_" + get_source_data_type_name(source_data_type);
+ }
+
+protected:
+ void SetUp() override {
+ BlobContentType content_type;
+ std::tie(content_type, source_data_type) = GetParam();
+
+ switch (content_type) {
+ case BlobContentType::STANDARD_STRING: {
+ blob_content = std::vector<uint8_t>(TEST_STRING_STANDARD.begin(), TEST_STRING_STANDARD.end());
+ break;
+ }
+ case BlobContentType::SPECIAL_CHARS_STRING: {
+ blob_content = std::vector<uint8_t>(TEST_STRING_SPECIAL_CHARS.begin(), TEST_STRING_SPECIAL_CHARS.end());
+ break;
+ }
+ case BlobContentType::BUFFER: {
+ blob_content = TEST_BUFFER;
+ break;
+ }
+ default: {
+ OPENVINO_THROW(INVALID_BLOB_TYPE_MESSAGE);
+ }
+ }
+ }
+
+ BlobSource create_blob_source() {
+ switch (source_data_type) {
+ case BlobSourceDataType::STREAM: {
+ stream = std::istringstream(std::string(blob_content.begin(), blob_content.end()));
+ return BlobSource(stream);
+ }
+ case BlobSourceDataType::TENSOR: {
+ tensor = ov::Tensor(ov::element::Type_t::u8, ov::Shape({blob_content.size()}), blob_content.data());
+ return BlobSource(tensor);
+ }
+ default: {
+ OPENVINO_THROW("Invalid blob source data type");
+ }
+ }
+ }
+
+ std::vector<uint8_t> blob_content;
+ BlobSourceDataType source_data_type;
+ std::istringstream stream;
+ ov::Tensor tensor;
+};
+
+using BlobSourceDifferentBlobsCommon = BlobSourceDifferentBlobs;
+
+// The data types can be contiguous (tensor) or non-contiguous (stream). Some functions behave differently based on
+// this.
+using BlobSourceDifferentBlobsNonContiguous = BlobSourceDifferentBlobs;
+using BlobSourceDifferentBlobsContiguous = BlobSourceDifferentBlobs;
+
+/**
+ * @brief The first byte from the blob source can be copied correctly
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, CopyFirstByte) {
+ BlobSource blob_source = create_blob_source();
+
+ const size_t copy_size = 1;
+ std::vector<uint8_t> copied_payload(copy_size);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.begin(), blob_content.begin() + copy_size));
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, copy_size);
+}
+
+/**
+ * @brief All bytes from the blob source can be copied correctly
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, CopyAllBytes) {
+ BlobSource blob_source = create_blob_source();
+
+ std::vector<uint8_t> copied_payload(blob_content.size());
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, blob_content);
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size());
+}
+
+/**
+ * @brief The read cursor can be moved to the beginning of the source when using the start as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorToStartReferenceBeginning) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(0, std::ios::beg);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 0);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.begin(), blob_content.begin() + 1));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, copied_payload.size());
+}
+
+/**
+ * @brief The read cursor can be moved to the last byte of the source when using the start as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorToLastByteReferenceBeginning) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(blob_content.size() - 1, std::ios::beg);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size() - 1);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.end() - 1, blob_content.end()));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size());
+}
+
+/**
+ * @brief The read cursor can be moved to the begining of the source when using the end as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorToStartReferenceEnd) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(-static_cast<int64_t>(blob_content.size()), std::ios::end);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 0);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.begin(), blob_content.begin() + 1));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, copied_payload.size());
+}
+
+/**
+ * @brief The read cursor can be moved to the last byte of the source when using the end as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorToLastByteReferenceEnd) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(-1, std::ios::end);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size() - 1);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.end() - 1, blob_content.end()));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size());
+}
+
+/**
+ * @brief The read cursor can be moved twice forward when using the current position as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorTwiceForward) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(1, std::ios::cur);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 1);
+
+ blob_source.seekg(1, std::ios::cur);
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 2);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.begin() + 2, blob_content.begin() + 3));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 3);
+}
+
+/**
+ * @brief The read cursor can be moved twice backwards when using the current position as reference
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorTwiceBackwards) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(0, std::ios::end);
+ blob_source.seekg(-1, std::ios::cur);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size() - 1);
+
+ blob_source.seekg(-1, std::ios::cur);
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size() - 2);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.end() - 2, blob_content.end() - 1));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size() - 1);
+}
+
+/**
+ * @brief The read cursor will stay in the previous spot when moved by 0 bytes
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorSamePlaceReferenceCurrent) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(1, std::ios::beg);
+ blob_source.seekg(0, std::ios::cur);
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 1);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+ ASSERT_EQ(copied_payload, std::vector<uint8_t>(blob_content.begin() + 1, blob_content.begin() + 2));
+
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, 2);
+}
+
+/**
+ * @brief The remaining size should be equal to the size of the source when the cursor is at origin
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, GetRemainingSizeFromStart) {
+ BlobSource blob_source = create_blob_source();
+
+ size_t remaining_size = 0;
+ OV_ASSERT_NO_THROW(remaining_size = blob_source.get_remaining_size());
+ ASSERT_EQ(remaining_size, blob_content.size());
+}
+
+/**
+ * @brief No remaining bytes should be reported is the cursor is at the end of the source
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, GetRemainingSizeFromEnd) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(blob_content.size());
+
+ size_t remaining_size = 0;
+ OV_ASSERT_NO_THROW(remaining_size = blob_source.get_remaining_size());
+ ASSERT_EQ(remaining_size, 0);
+}
+
+/**
+ * @brief The total size of the blob source is the same as the size of the underlying buffer
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, GetTotalSize) {
+ BlobSource blob_source = create_blob_source();
+
+ size_t size = 0;
+ OV_ASSERT_NO_THROW(size = blob_source.get_total_size());
+ ASSERT_EQ(size, blob_content.size());
+}
+
+/**
+ * @brief The total size of the blob source is not affected by the position of the cursor
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, GetTotalSizeAfterCursorMove) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(blob_content.size());
+
+ size_t size = 0;
+ OV_ASSERT_NO_THROW(size = blob_source.get_total_size());
+ ASSERT_EQ(size, blob_content.size());
+}
+
+/**
+ * @brief The total size of the source should not be influenced by previous "read" operations
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, GetTotalSizeAfterRead) {
+ BlobSource blob_source = create_blob_source();
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_ASSERT_NO_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()));
+
+ size_t size = 0;
+ OV_ASSERT_NO_THROW(size = blob_source.get_total_size());
+ ASSERT_EQ(size, blob_content.size());
+}
+
+/**
+ * @brief Requesting to copy more bytes than available should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, CopyTooMuch) {
+ BlobSource blob_source = create_blob_source();
+
+ std::vector<uint8_t> copied_payload(blob_content.size() + 1);
+ OV_EXPECT_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()), ov::Exception, _);
+}
+
+/**
+ * @brief Requesting to copy beyond the end limit should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, CopyAfterEnd) {
+ BlobSource blob_source = create_blob_source();
+
+ blob_source.seekg(0, std::ios::end);
+
+ std::vector<uint8_t> copied_payload(1);
+ OV_EXPECT_THROW(blob_source.read_into_buffer(copied_payload.data(), copied_payload.size()), ov::Exception, _);
+}
+
+/**
+ * @brief Moving the cursor before the start of the source should fail; the reference used for moving the cursor is the
+ * beginning of the source.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorBeforeStartReferenceStart) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(-1, std::ios::beg), ov::Exception, _);
+}
+
+/**
+ * @brief Moving the cursor after the end of the source should fail; the reference used for moving the cursor is the
+ * beginning of the source.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorAfterEndReferenceStart) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(blob_content.size() + 1, std::ios::beg), ov::Exception, _);
+}
+
+/**
+ * @brief Moving the cursor before the start of the source should fail; the reference used for moving the cursor is the
+ * current cursor position.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorBeforeStartReferenceCurrent) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(-1, std::ios::cur), ov::Exception, _);
+}
+
+/**
+ * @brief Moving the cursor after the end of the source should fail; the reference used for moving the cursor is the
+ * current cursor position.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorAfterEndReferenceCurrent) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(blob_content.size() + 1, std::ios::cur), ov::Exception, _);
+}
+
+/**
+ * @brief Moving the cursor before the start of the source should fail; the reference used for moving the cursor is the
+ * end of the source.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorBeforeStartReferenceEnd) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(-(static_cast<int64_t>(blob_content.size()) + 1), std::ios::end),
+ ov::Exception,
+ _);
+}
+
+/**
+ * @brief Moving the cursor after the end of the source should fail; the reference used for moving the cursor is the
+ * end of the source.
+ */
+TEST_P(BlobSourceDifferentBlobsCommon, MoveCursorAfterEndReferenceEnd) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.seekg(1, std::ios::end), ov::Exception, _);
+}
+
+/**
+ * @brief Cannot extract data without copying if the underlying buffer is not contiguous.
+ */
+TEST_P(BlobSourceDifferentBlobsNonContiguous, ReadViewFails) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.read_view(0), ov::Exception, _);
+}
+
+/**
+ * @brief Cannot extract RoI tensors without copying if the underlying buffer is not contiguous.
+ */
+TEST_P(BlobSourceDifferentBlobsNonContiguous, GetROITensorFails) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.create_roi_tensor(0), ov::Exception, _);
+}
+
+/**
+ * @brief If the underlying buffer is not contiguous, then the "is_contiguous" call should return "false"
+ */
+TEST_P(BlobSourceDifferentBlobsNonContiguous, FalseIsContiguous) {
+ BlobSource blob_source = create_blob_source();
+ ASSERT_FALSE(blob_source.is_contiguous());
+}
+
+/**
+ * @brief Extract the first byte without copying
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, ReadViewFirstByte) {
+ BlobSource blob_source = create_blob_source();
+
+ const size_t read_size = 1;
+ const char* payload_ptr = nullptr;
+ OV_ASSERT_NO_THROW(payload_ptr = reinterpret_cast<const char*>(blob_source.read_view(read_size)));
+
+ std::vector<uint8_t> extracted_payload(payload_ptr, payload_ptr + read_size);
+ ASSERT_EQ(extracted_payload, std::vector<uint8_t>(blob_content.begin(), blob_content.begin() + read_size));
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, read_size);
+}
+
+/**
+ * @brief Extract all bytes without copying
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, ReadViewAllBytes) {
+ BlobSource blob_source = create_blob_source();
+
+ const char* payload_ptr = nullptr;
+ OV_ASSERT_NO_THROW(payload_ptr = reinterpret_cast<const char*>(blob_source.read_view(blob_content.size())));
+
+ std::vector<uint8_t> extracted_payload(payload_ptr, payload_ptr + blob_content.size());
+ ASSERT_EQ(extracted_payload, blob_content);
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size());
+}
+
+/**
+ * @brief Move the read cursor and then extract one byte without copying
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, ReadViewFirstByteAfterMove) {
+ BlobSource blob_source = create_blob_source();
+ blob_source.seekg(1);
+
+ const size_t read_size = 1;
+ const char* payload_ptr = nullptr;
+ OV_ASSERT_NO_THROW(payload_ptr = reinterpret_cast<const char*>(blob_source.read_view(read_size)));
+
+ std::vector<uint8_t> extracted_payload(payload_ptr, payload_ptr + read_size);
+ ASSERT_EQ(extracted_payload, std::vector<uint8_t>(blob_content.begin() + 1, blob_content.begin() + 1 + read_size));
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, read_size + 1);
+}
+
+/**
+ * @brief Attempting to extract more bytes than available without copying should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, ReadViewTooMuch) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.read_view(blob_content.size() + 1), ov::Exception, _);
+}
+
+/**
+ * @brief Attempting to extract data (without copying) beyond the end limit should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, ReadViewAfterEnd) {
+ BlobSource blob_source = create_blob_source();
+ blob_source.seekg(0, std::ios::end);
+ OV_EXPECT_THROW(blob_source.read_view(1), ov::Exception, _);
+}
+
+/**
+ * @brief Extract an roi tensor containing only the first byte of the source
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, GetROITensorFirstByte) {
+ BlobSource blob_source = create_blob_source();
+
+ const size_t tensor_size = 1;
+ ov::Tensor roi_tensor;
+ OV_ASSERT_NO_THROW(roi_tensor = blob_source.create_roi_tensor(tensor_size));
+
+ ASSERT_EQ(roi_tensor.get_byte_size(), tensor_size);
+ ASSERT_EQ(std::memcmp(roi_tensor.data(), blob_content.data(), 1), 0);
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, tensor_size);
+}
+
+/**
+ * @brief Extract an roi tensor containing the whole source
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, GetROITensorAllBytes) {
+ BlobSource blob_source = create_blob_source();
+
+ ov::Tensor roi_tensor;
+ OV_ASSERT_NO_THROW(roi_tensor = blob_source.create_roi_tensor(blob_content.size()));
+
+ ASSERT_EQ(roi_tensor.get_byte_size(), blob_content.size());
+ ASSERT_EQ(std::memcmp(roi_tensor.data(), blob_content.data(), blob_content.size()), 0);
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, blob_content.size());
+}
+
+/**
+ * @brief Extract an roi tensor containing only one byte of the source after moving the cursor
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, GetROITensorFirstByteAfterMove) {
+ BlobSource blob_source = create_blob_source();
+ blob_source.seekg(1);
+
+ const size_t tensor_size = 1;
+ ov::Tensor roi_tensor;
+ OV_ASSERT_NO_THROW(roi_tensor = blob_source.create_roi_tensor(tensor_size));
+
+ ASSERT_EQ(roi_tensor.get_byte_size(), tensor_size);
+ ASSERT_EQ(std::memcmp(roi_tensor.data(), blob_content.data() + 1, 1), 0);
+
+ size_t cursor = 0;
+ OV_ASSERT_NO_THROW(cursor = blob_source.tellg());
+ ASSERT_EQ(cursor, tensor_size + 1);
+}
+
+/**
+ * @brief Attempting to extract an roi tensor that is bigger than the available bytes should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, GetROITensorTooMuch) {
+ BlobSource blob_source = create_blob_source();
+ OV_EXPECT_THROW(blob_source.create_roi_tensor(blob_content.size() + 1), ov::Exception, _);
+}
+
+/**
+ * @brief Attempting to extract an roi tensor beyond the end limit of the source should yield an exception
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, GetROITensorAfterEnd) {
+ BlobSource blob_source = create_blob_source();
+ blob_source.seekg(0, std::ios::end);
+ OV_EXPECT_THROW(blob_source.create_roi_tensor(1), ov::Exception, _);
+}
+
+/**
+ * @brief "is_contiguous" should return true if the underlying buffer is contiguous
+ */
+TEST_P(BlobSourceDifferentBlobsContiguous, TrueIsContiguous) {
+ BlobSource blob_source = create_blob_source();
+ ASSERT_TRUE(blob_source.is_contiguous());
+}
+
+using BlobSourceContiguous = testing::Test;
+
+TEST_F(BlobSourceContiguous, NotUnidimensionalTensorFails) {
+ const auto tensor = ov::Tensor(ov::element::Type_t::u8, ov::Shape({2, TEST_BUFFER.size() / 2}), TEST_BUFFER.data());
+ OV_EXPECT_THROW(BlobSource blob_source(tensor), ov::Exception, _);
+}
+
+INSTANTIATE_TEST_SUITE_P(UnitTests,
+ BlobSourceDifferentBlobsCommon,
+ testing::Combine(testing::ValuesIn(ALL_BLOB_CONTENT_TYPES),
+ testing::ValuesIn(ALL_BLOB_SOURCE_DATA_TYPES)),
+ BlobSourceDifferentBlobsCommon::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(UnitTests,
+ BlobSourceDifferentBlobsNonContiguous,
+ testing::Combine(testing::ValuesIn(ALL_BLOB_CONTENT_TYPES),
+ testing::Values(BlobSourceDataType::STREAM)),
+ BlobSourceDifferentBlobsCommon::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(UnitTests,
+ BlobSourceDifferentBlobsContiguous,
+ testing::Combine(testing::ValuesIn(ALL_BLOB_CONTENT_TYPES),
+ testing::Values(BlobSourceDataType::TENSOR)),
+ BlobSourceDifferentBlobsCommon::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp b/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp
index 1a5217f5ec4..6f93fb039ff 100644
--- a/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp
+++ b/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp
@@ -24,19 +24,33 @@ constexpr size_t MINIMUM_BLOB_SIZE = sizeof(uint32_t) + FOOTER_SIZE;
constexpr size_t SIZE_OF_INIT_SCHEDULE_SIZE = sizeof(uint64_t);
constexpr size_t SIZE_OF_LAYOUT_SIZE = sizeof(uint16_t);
+// intel_npu::BlobSource create_tensor_blob_source_from_stream(istream& stream) {
+// size_t totalSize = source.get_total_size();
+// auto tensor = ov::Tensor(ov::element::u8, ov::Shape{totalSize});
+
+// source.seekg(0, std::ios::beg);
+// source.read_into_buffer(tensor.data<char>(), tensor.get_byte_size());
+// return intel_npu::BlobSource(tensor);
+// }
+
+intel_npu::BlobSource create_tensor_blob_source_from_stream_source(intel_npu::BlobSource& source, ov::Tensor& tensor) {
+ source.seekg(0, std::ios::beg);
+ source.read_into_buffer(tensor.data<char>(), tensor.get_byte_size());
+ return intel_npu::BlobSource(tensor);
+}
+
} // namespace
TEST_F(MetadataUnitTests, readUnversionedBlob) {
- std::stringstream blob("this_is an_unversioned bl0b");
+ std::stringstream stream("this_is an_unversioned bl0b");
+ BlobSource blob(stream);
std::unique_ptr<MetadataBase> storedMeta;
OV_EXPECT_THROW(storedMeta = read_metadata_from(blob), ov::Exception, _);
- blob.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(blob);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- blob.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.get_total_size()});
+ blob = create_tensor_blob_source_from_stream_source(blob, tensor);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(blob), ov::Exception, _);
}
TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {
@@ -47,23 +61,31 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {
OV_ASSERT_NO_THROW(meta.write(stream));
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
+ BlobSource blob(stream);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(blob));
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.get_total_size()});
+ blob = create_tensor_blob_source_from_stream_source(blob, tensor);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(blob));
}
TEST_F(MetadataUnitTests, writeAndReadBlobTypes) {
for (const BlobType blobType : {BlobType::ELF, BlobType::LLVM, BlobType::BYTECODE}) {
std::stringstream stream;
- MetadataTest(0, CURRENT_OPENVINO_VERSION, std::nullopt, std::nullopt,
- std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, blobType)
+ MetadataTest(0,
+ CURRENT_OPENVINO_VERSION,
+ std::nullopt,
+ std::nullopt,
+ std::nullopt,
+ std::nullopt,
+ std::nullopt,
+ std::nullopt,
+ std::nullopt,
+ blobType)
.write(stream);
- auto storedMeta = read_metadata_from(stream);
+ BlobSource source(stream);
+ auto storedMeta = read_metadata_from(source);
ASSERT_NE(storedMeta, nullptr);
ASSERT_EQ(storedMeta->get_blob_type(), std::make_optional(blobType));
}
@@ -79,15 +101,15 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContent) {
OV_ASSERT_NO_THROW(meta.write(stream));
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
-
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
+ BlobSource source(stream);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
+
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
}
TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWeightsSeparation) {
@@ -97,14 +119,13 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWeightsSeparation)
OV_ASSERT_NO_THROW(meta.write(stream));
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
}
TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContentAllAttributes) {
@@ -121,9 +142,10 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContentAllAttri
auto meta = MetadataTest(blobSize, CURRENT_OPENVINO_VERSION, initSizes, batchSize, inputLayouts, outputLayouts);
OV_ASSERT_NO_THROW(meta.write(stream));
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
ASSERT_TRUE(storedMeta->get_init_sizes().has_value());
ASSERT_TRUE(storedMeta->get_init_sizes()->size() == initSizes.size());
for (size_t i = 0; i < initSizes.size(); ++i) {
@@ -142,12 +164,10 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContentAllAttri
ASSERT_TRUE(storedMeta->get_output_layouts()->at(i) == outputLayouts.at(i));
}
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
ASSERT_TRUE(storedMeta->get_init_sizes().has_value());
ASSERT_TRUE(storedMeta->get_init_sizes()->size() == initSizes.size());
for (size_t i = 0; i < initSizes.size(); ++i) {
@@ -185,18 +205,17 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithCompatibilityDe
compatDesc);
OV_ASSERT_NO_THROW(meta.write(stream));
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
ASSERT_TRUE(storedMeta->get_compatibility_descriptor().has_value());
ASSERT_EQ(storedMeta->get_compatibility_descriptor().value(), compatDesc);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
- ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
+ ASSERT_TRUE(storedMeta->get_compiler_payload_size() == blobSize);
ASSERT_TRUE(storedMeta->get_compatibility_descriptor().has_value());
ASSERT_EQ(storedMeta->get_compatibility_descriptor().value(), compatDesc);
}
@@ -216,15 +235,14 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithEmptyCompatibil
std::string{});
OV_ASSERT_NO_THROW(meta.write(stream));
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
ASSERT_FALSE(storedMeta->get_compatibility_descriptor().has_value());
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(source));
ASSERT_FALSE(storedMeta->get_compatibility_descriptor().has_value());
}
@@ -249,11 +267,13 @@ TEST_F(MetadataUnitTests, compatibilityDescriptorLenExceedsBounds) {
std::memcpy(&blob[compatDescLenOffset], &badCompatibilityDescriptorSize, sizeof(badCompatibilityDescriptorSize));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {
@@ -265,13 +285,12 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_EXPECT_THROW(auto storedMeta = read_metadata_from(stream), ov::Exception, _);
+ BlobSource source(stream);
+ OV_EXPECT_THROW(auto storedMeta = read_metadata_from(source), ov::Exception, _);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(auto storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(auto storedMeta = read_metadata_from(source), ov::Exception, _);
}
TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {
@@ -284,14 +303,14 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
+
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
}
TEST_P(MetadataVersionTestFixture, writeAndReadInvalidMetadataVersion) {
@@ -305,13 +324,12 @@ TEST_P(MetadataVersionTestFixture, writeAndReadInvalidMetadataVersion) {
dummyMeta.set_version(metaVersion);
OV_ASSERT_NO_THROW(dummyMeta.write(blob));
- OV_EXPECT_THROW(read_metadata_from(blob), ov::Exception, _);
+ BlobSource source(blob);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
- blob.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(blob);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- blob.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
const std::vector badMetadataVersions = {
@@ -346,14 +364,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtEnd) {
stream.str("");
stream << temp;
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
}
TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {
@@ -375,14 +392,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {
stream.str("");
stream << temp;
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
}
TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {
@@ -404,14 +420,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {
stream.str("");
stream << temp;
+ BlobSource source(stream);
std::unique_ptr<MetadataBase> storedMeta;
- OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
- stream.seekg(0, std::ios::beg);
- size_t streamSize = MetadataBase::get_stream_remaining_size(stream);
- auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});
- stream.read(tensor.data<char>(), tensor.get_byte_size());
- OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);
+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{source.get_total_size()});
+ source = create_tensor_blob_source_from_stream_source(source, tensor);
+ OV_EXPECT_THROW(storedMeta = read_metadata_from(source), ov::Exception, _);
}
/**
@@ -429,11 +444,13 @@ TEST_F(MetadataUnitTests, compilerPayloadSizeExceedsBlobLimit) {
std::memcpy(&blob[compilerPayloadSizeOffset], &badCompilerPayloadSize, sizeof(badCompilerPayloadSize));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
/**
@@ -452,13 +469,15 @@ TEST_F(MetadataUnitTests, payloadSizeIntegerOverflowIsRejected) {
std::memcpy(&blob[blobSize - MAGIC_BYTES.size() - sizeof(payloadSize)], &payloadSize, sizeof(payloadSize));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream),
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source),
ov::Exception,
testing::HasSubstr("compiler payload parsed from the blob"));
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blobSize});
std::memcpy(tensor.data<char>(), blob.data(), blobSize);
- OV_EXPECT_THROW(read_metadata_from(tensor),
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source),
ov::Exception,
testing::HasSubstr("compiler payload parsed from the blob"));
}
@@ -480,11 +499,13 @@ TEST_F(MetadataUnitTests, numberOfInitSchedulesExceedsBlobLimit) {
std::memcpy(&blob[numberOfInitsOffset], &badNumberOfInits, sizeof(badNumberOfInits));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
/**
@@ -507,11 +528,13 @@ TEST_F(MetadataUnitTests, numberOfInputLayoutsExceedsBlobLimit) {
std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
/**
@@ -534,11 +557,13 @@ TEST_F(MetadataUnitTests, numberOfOutputLayoutsExceedsBlobLimit) {
std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}
/**
@@ -561,9 +586,11 @@ TEST_F(MetadataUnitTests, layoutLengthExceedsBlobLimit) {
std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));
std::stringstream malformedStream(blob);
- OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);
+ BlobSource source(malformedStream);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});
std::memcpy(tensor.data<char>(), blob.data(), blob.size());
- OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);
+ source = BlobSource(tensor);
+ OV_EXPECT_THROW(read_metadata_from(source), ov::Exception, _);
}