OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPU] Refactor `Plugin::import_model` in order to allow integrating the upcoming blob format in an OOP friendly manner (#36770)
Razvan Apetroaie9eca1cde8758
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/iparser.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/iparser.hppindex da98dc0c290..e647fdb717d 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/iparser.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/iparser.hpp@@ -4,9 +4,15 @@#pragma once+#include <variant>+#include "intel_npu/common/filtered_config.hpp"#include "intel_npu/common/igraph.hpp"+namespace ov {+class ICore;+}+namespace intel_npu {class IParser {@@ -19,16 +25,21 @@ public:* @param config Used to influence the downstream flow of the implementation based on preferences.* @param initBlobs Optional. If provided, the "weights separation" flow is enabled and the binary objects* corresponding to the init schedules will be parsed as well.- * @param model Optional, but required if "initBlobs" is provided. The "ov::Model" object is leveraged in the- * "weights separation" implementation in order to extract the buffers of the weights.+ * @param weightsSource The source of weights that should be used if the weights separation feature is enabled.+ * "monostate" indicates the absence of weights. The "string" & "core" pair corresponds to the "weights path"+ * config option.+ * @param compatibilityDescriptor A string that describes the compatibility requirements of the blob from compiler's+ * pov.* @return A wrapper over the corresponding L0 graph handles (multiple only if "initBlobs" has been provided). This* wrapper further details the compiled model and brings it in a state closer to execution.*/virtual std::shared_ptr<IGraph> parse(const ov::Tensor& mainBlob,const FilteredConfig& config,+ std::variant<std::monostate,+ std::shared_ptr<const ov::Model>,+ std::pair<std::string, std::shared_ptr<ov::ICore>>>&& weightsSource,const std::optional<std::vector<ov::Tensor>>& initBlobs = std::nullopt,- std::optional<std::shared_ptr<const ov::Model>>&& model = std::nullopt,const std::optional<std::string>& compatibilityDescriptor = std::nullopt) const = 0;virtual ~IParser() = default;diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/parser.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/parser.hppindex 4d96c46dfca..1d40870a1bb 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/parser.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/parser.hpp@@ -21,8 +21,10 @@ public:std::shared_ptr<IGraph> parse(const ov::Tensor& mainBlob,const FilteredConfig& config,+ std::variant<std::monostate,+ std::shared_ptr<const ov::Model>,+ std::pair<std::string, std::shared_ptr<ov::ICore>>>&& weightsSource,const std::optional<std::vector<ov::Tensor>>& initBlobs = std::nullopt,- std::optional<std::shared_ptr<const ov::Model>>&& model = std::nullopt,const std::optional<std::string>& compatibilityDescriptor = std::nullopt) const override;private:diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hppindex 322f69c54ae..fd1bbf4ad43 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp@@ -13,13 +13,19 @@#include "openvino/op/constant.hpp"#include "openvino/runtime/iremote_context.hpp"+namespace ov {+class ICore;+}+namespace intel_npu {/*** @brief Wrapper over multiple "ze_graph_handle_t" objects, one for each init/main schedule (weights separation).- ** @details This class contains most implementation details for running the init schedules and setting the results as* inputs to the main one.+ *+ * @param weightsSource The source of weights for the weights separation pipeline. Should be either an `ov::Model` or a+ * weights path along with the core object that may be used to parse the weights.*/class WeightlessGraph final : public Graph {public:@@ -31,7 +37,9 @@ public:const std::vector<GraphDescriptor>& initGraphDesc,std::vector<NetworkMetadata> initMetadata,std::optional<std::vector<ov::Tensor>> initBlobs,- std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>>&& constants,+ std::variant<std::monostate,+ std::shared_ptr<const ov::Model>,+ std::pair<std::string, std::shared_ptr<ov::ICore>>>&& weightsSource,const FilteredConfig& config,const bool blobIsPersistent = false);diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_utils.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_utils.hppindex 296a2b7101b..605da73453e 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_utils.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_utils.hpp@@ -4,24 +4,10 @@#pragma once-#include <memory>-#include <string>-#include <unordered_map>-#include <vector>-#include "intel_npu/common/network_metadata.hpp"-#include "openvino/core/model.hpp"-#include "openvino/op/constant.hpp"namespace intel_npu {bool isInitMetadata(const NetworkMetadata& networkMetadata);-std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_in_topological_order(- const std::shared_ptr<const ov::Model>& model);--std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_memory_mapped(- const std::string& weightsPath,- const std::vector<NetworkMetadata>& initNetworkMetadata);-} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cppindex 1851842a71c..294aafa5126 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/driver_compiler_adapter.cpp@@ -204,11 +204,6 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(std::shared_ptr<ov::Mod_logger.info("Compilation memory usage: Peak %lld KB", compile_model_mem_end - compile_model_mem_start);}- auto constants = get_all_constants_in_topological_order(model);- // Note: Delete model prematurely, constants are still valid due to- // shared_ptr semantics.- model = nullptr;-return std::make_shared<WeightlessGraph>(_zeGraphExt,_zeroInitStruct,mainGraphHandle,@@ -217,7 +212,7 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(std::shared_ptr<ov::ModinitGraphDescriptors,std::move(initNetworkMetadata),/* initBlobs = */ std::nullopt,- std::move(constants),+ std::move(model),updatedConfig);}diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cppindex 03528249e5c..f2a73a2c89f 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp@@ -35,6 +35,10 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,_compatibilityDescriptor(compatibilityDescriptor),_blobIsPersistent(blobIsPersistent),_logger("Graph", config.get<LOG_LEVEL>()) {+ if (!calledFromWeightlessGraph) {+ _logger.info("The current compiled model is a weightful one");+ }+if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {_logger.info("Graph initialize is deferred from the \"Graph\" constructor");return;diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cppindex 76c10d46ac6..7b5817fb27b 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/parser.cpp@@ -25,11 +25,13 @@ Parser::Parser(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)"Failed to create ZeGraphExtWrappers in Parser. Please check if the driver is properly installed.");}-std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,- const FilteredConfig& config,- const std::optional<std::vector<ov::Tensor>>& initBlobs,- std::optional<std::shared_ptr<const ov::Model>>&& model,- const std::optional<std::string>& compatibilityDescriptor) const {+std::shared_ptr<IGraph> Parser::parse(+ const ov::Tensor& mainBlob,+ const FilteredConfig& config,+ std::variant<std::monostate, std::shared_ptr<const ov::Model>, std::pair<std::string, std::shared_ptr<ov::ICore>>>&&+ weightsSource,+ const std::optional<std::vector<ov::Tensor>>& initBlobs,+ const std::optional<std::string>& compatibilityDescriptor) const {OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "Parser", "parse");// Detect blob format@@ -57,11 +59,6 @@ std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,OV_ITT_TASK_NEXT(PARSE_BLOB, "getNetworkMetaMainGraph");mainNetworkMetadata = _zeGraphExt->getNetworkMeta(mainGraphDesc);_logger.debug("main schedule parse end");- if (model.has_value()) {- mainNetworkMetadata.name = model.value()->get_friendly_name();- } else {- _logger.debug("networkMeta name is empty in parse!");- }// exporting the blob when we get it from cache or ov::hint::compiled_blob property// shall be available@@ -97,13 +94,6 @@ std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,}_logger.debug("inits schedule parse end");- auto constants = model.has_value()- ? get_all_constants_in_topological_order(model.value())- : get_all_constants_memory_mapped(config.get<WEIGHTS_PATH>(), initNetworkMetadata);- // Note: Delete model prematurely, constants are still valid due to- // shared_ptr semantics.- model = std::nullopt;-return std::make_shared<WeightlessGraph>(_zeGraphExt,_zeroInitStruct,mainGraphDesc,@@ -112,7 +102,7 @@ std::shared_ptr<IGraph> Parser::parse(const ov::Tensor& mainBlob,initGraphDescriptors,std::move(initNetworkMetadata),initBlobs,- std::move(constants),+ std::move(weightsSource),config,blobIsPersistent);}diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cppindex 402d9e41525..a8d54796dd1 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/plugin_compiler_adapter.cpp@@ -266,11 +266,6 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compileWS(std::shared_ptr<ov::Mod_logger.debug("compile end");- auto constants = get_all_constants_in_topological_order(model);- // Note: Delete model prematurely, constants are still valid due to- // shared_ptr semantics.- model = nullptr;-return std::make_shared<WeightlessGraph>(_zeGraphExt,_zeroInitStruct,@@ -280,7 +275,7 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compileWS(std::shared_ptr<ov::ModinitGraphDescriptors,std::move(initNetworkMetadata),tensorsInits,- std::move(constants),+ std::move(model),localConfig,/* persistentBlob = */ true); // exporting the blob shall be available in such a scenario}diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cppindex 7c606e1c4b1..054824f7677 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp@@ -16,9 +16,13 @@#include "intel_npu/utils/zero/zero_cmd_queue_pool.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"#include "openvino/core/memory_util.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/core/weight_sharing_util.hpp"+#include "openvino/runtime/icore.hpp"#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/shared_buffer.hpp"#include "openvino/util/common_util.hpp"+#include "openvino/util/mmap_object.hpp"#define USE_SINGLE_THREADED_RUN_INIT 1@@ -27,6 +31,118 @@ namespace intel_npu {namespace {constexpr uint8_t MAIN_SCHEDULE_INDEX = 0;+constexpr std::string_view WEIGHTS_IR_EXTENSION = ".bin";+constexpr std::string_view ONNX_EXTENSION = ".onnx";++std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_in_topological_order(+ const std::shared_ptr<const ov::Model>& model) {+ std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> constants;++ OPENVINO_ASSERT(model != nullptr, "Model is required to extract constants in topological order.");+ bool at_least_one_wca_found = false;++ // Match the inputs of the "init" model with the Constant nodes of the original model+ for (auto&& node : model->get_ops()) {+ if (!ov::is_type<ov::op::v0::Constant>(node)) {+ continue;+ }++ auto constantNode = std::static_pointer_cast<ov::op::v0::Constant>(node);+ ov::RTMap& runtimeInfoMap = constantNode->get_rt_info();+ const auto& weightlessCacheAttrIt = runtimeInfoMap.find(ov::WeightlessCacheAttribute::get_type_info_static());+ if (weightlessCacheAttrIt != runtimeInfoMap.end()) {+ at_least_one_wca_found = true;+ auto& weightlessCacheAttr = weightlessCacheAttrIt->second.as<ov::WeightlessCacheAttribute>();++ auto& constant = constants[weightlessCacheAttr.bin_offset];+ if (constant != nullptr) {+ // if multiple constants point to the same buffer, ensure that+ // their binary sizes are the same+ OPENVINO_ASSERT(constant->get_byte_size() == constantNode->get_byte_size(),+ "Found ov::Constant that points to the common buffer but has mismatching byte size. "+ "This may indicate a bug in OV model compression.");+ continue;+ }+ constant = std::move(constantNode);+ }+ }++ OPENVINO_ASSERT(at_least_one_wca_found,+ "No \"WeightlessCacheAttribute\" has been found in any of the model's Constant nodes. This "+ "attribute is required for running the \"weights separation\" flow.");++ return constants;+}++std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_memory_mapped(+ std::string_view weightsPath,+ const std::vector<NetworkMetadata>& initNetworkMetadata) {+ std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> constants;++ auto mapped_memory = ov::load_mmap_object(weightsPath);+ for (const auto& initMetadata : initNetworkMetadata) {+ for (const IODescriptor& descriptor : initMetadata.inputs) {+ const auto& opt = ov::util::view_to_number<size_t>(descriptor.nameFromCompiler);+ OPENVINO_ASSERT(opt.has_value(), "Failed to parse id for constant: ", descriptor.nameFromCompiler);++ const size_t id = opt.value();+ const size_t byte_size =+ ov::util::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));+ OPENVINO_ASSERT(id <= mapped_memory->size() && byte_size <= mapped_memory->size() - id,+ "Constant offset/size is out of bounds for mapped weights file: offset=",+ id,+ ", size=",+ byte_size,+ ", file_size=",+ mapped_memory->size(),+ ", name=",+ descriptor.nameFromCompiler);+ auto weight_buffer =+ std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mapped_memory->data() + id,+ byte_size,+ mapped_memory);++ auto [it, inserted] =+ constants.emplace(id,+ std::make_shared<ov::op::v0::Constant>(descriptor.precision,+ descriptor.shapeFromCompiler.to_shape(),+ weight_buffer));+ if (!inserted) {+ OPENVINO_ASSERT(it->second->get_byte_size() == byte_size,+ "Duplicate constant offset found with mismatching byte size: offset=",+ id);+ }+ }+ }++ return constants;+}++std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> extract_constants_map(+ std::variant<std::monostate, std::shared_ptr<const ov::Model>, std::pair<std::string, std::shared_ptr<ov::ICore>>>&&+ weightsSource,+ const std::vector<NetworkMetadata>& initNetworkMetadata) {+ if (const std::shared_ptr<const ov::Model>* model = std::get_if<std::shared_ptr<const ov::Model>>(&weightsSource)) {+ return get_all_constants_in_topological_order(*model);+ } else if (const std::pair<std::string, std::shared_ptr<ov::ICore>>* weightsPathAndCore =+ std::get_if<std::pair<std::string, std::shared_ptr<ov::ICore>>>(&weightsSource)) {+ auto [weightsPath, core] = *weightsPathAndCore;++ auto ext = ov::util::path_to_string(ov::util::make_path(weightsPath).extension());+ if (ext == ONNX_EXTENSION) {+ const auto model = core->read_model(weightsPath, weightsPath, {});+ return get_all_constants_in_topological_order(model);+ } else if (ext == WEIGHTS_IR_EXTENSION) {+ return get_all_constants_memory_mapped(weightsPath, initNetworkMetadata);+ } else {+ OPENVINO_THROW("Invalid path to the weights: ",+ weightsPath,+ ". A \".bin\" or \".onnx\" extension was expected.");+ }+ }++ OPENVINO_THROW("No source of weights has been provided to the \"WeightlessGraph\" ctor");+}struct QueueData {int64_t initIndex = -1;@@ -129,17 +245,19 @@ void merge_two_maps(std::unordered_map<std::string, std::shared_ptr<ov::ITensor>} // namespace-WeightlessGraph::WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,- const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,- const GraphDescriptor& mainGraphDesc,- NetworkMetadata mainMetadata,- std::optional<ov::Tensor> mainBlob,- const std::vector<GraphDescriptor>& initGraphDesc,- std::vector<NetworkMetadata> initMetadata,- std::optional<std::vector<ov::Tensor>> initBlobs,- std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>>&& constants,- const FilteredConfig& config,- const bool blobIsPersistent)+WeightlessGraph::WeightlessGraph(+ const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,+ const GraphDescriptor& mainGraphDesc,+ NetworkMetadata mainMetadata,+ std::optional<ov::Tensor> mainBlob,+ const std::vector<GraphDescriptor>& initGraphDesc,+ std::vector<NetworkMetadata> initMetadata,+ std::optional<std::vector<ov::Tensor>> initBlobs,+ std::variant<std::monostate, std::shared_ptr<const ov::Model>, std::pair<std::string, std::shared_ptr<ov::ICore>>>&&+ weightsSource,+ const FilteredConfig& config,+ const bool blobIsPersistent): Graph(zeGraphExt,zeroInitStruct,mainGraphDesc,@@ -152,8 +270,10 @@ WeightlessGraph::WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGr_initsGraphDesc(initGraphDesc),_initBlobs(std::move(initBlobs)),_initsMetadata(std::move(initMetadata)),- _constants(std::move(constants)),+ _constants(extract_constants_map(std::move(weightsSource), _initsMetadata)),_wgLogger("WeightlessGraph", config.get<LOG_LEVEL>()) {+ _wgLogger.info("The current compiled model is a weightless one");+if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {_wgLogger.info("Graph initialize is deferred from the \"WeightlessGraph\" constructor");return;diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_utils.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_utils.cppindex e56b1061e1a..e3dee88c77a 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_utils.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_utils.cpp@@ -4,12 +4,6 @@#include "weightless_utils.hpp"-#include "openvino/core/memory_util.hpp"-#include "openvino/core/rt_info/weightless_caching_attributes.hpp"-#include "openvino/runtime/shared_buffer.hpp"-#include "openvino/util/common_util.hpp"-#include "openvino/util/mmap_object.hpp"-namespace intel_npu {bool isInitMetadata(const NetworkMetadata& networkMetadata) {@@ -19,82 +13,4 @@ bool isInitMetadata(const NetworkMetadata& networkMetadata) {return networkMetadata.inputs.at(0).isInitInputWeights;}-std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_in_topological_order(- const std::shared_ptr<const ov::Model>& model) {- std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> constants;-- OPENVINO_ASSERT(model != nullptr, "Model is required to extract constants in topological order.");-- // Match the inputs of the "init" model with the Constant nodes of the original model- for (auto&& node : model->get_ops()) {- if (!ov::is_type<ov::op::v0::Constant>(node)) {- continue;- }-- auto constantNode = std::static_pointer_cast<ov::op::v0::Constant>(node);- ov::RTMap& runtimeInfoMap = constantNode->get_rt_info();- const auto& weightlessCacheAttrIt = runtimeInfoMap.find(ov::WeightlessCacheAttribute::get_type_info_static());- if (weightlessCacheAttrIt != runtimeInfoMap.end()) {- auto& weightlessCacheAttr = weightlessCacheAttrIt->second.as<ov::WeightlessCacheAttribute>();-- auto& constant = constants[weightlessCacheAttr.bin_offset];- if (constant != nullptr) {- // if multiple constants point to the same buffer, ensure that- // their binary sizes are the same- OPENVINO_ASSERT(constant->get_byte_size() == constantNode->get_byte_size(),- "Found ov::Constant that points to the common buffer but has mismatching byte size. "- "This may indicate a bug in OV model compression.");- continue;- }- constant = std::move(constantNode);- }- }-- return constants;-}--std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> get_all_constants_memory_mapped(- const std::string& weightsPath,- const std::vector<NetworkMetadata>& initNetworkMetadata) {- std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> constants;-- auto mapped_memory = ov::load_mmap_object(weightsPath);- for (const auto& initMetadata : initNetworkMetadata) {- for (const IODescriptor& descriptor : initMetadata.inputs) {- const auto& opt = ov::util::view_to_number<size_t>(descriptor.nameFromCompiler);- OPENVINO_ASSERT(opt.has_value(), "Failed to parse id for constant: ", descriptor.nameFromCompiler);-- const size_t id = opt.value();- const size_t byte_size =- ov::util::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));- OPENVINO_ASSERT(id <= mapped_memory->size() && byte_size <= mapped_memory->size() - id,- "Constant offset/size is out of bounds for mapped weights file: offset=",- id,- ", size=",- byte_size,- ", file_size=",- mapped_memory->size(),- ", name=",- descriptor.nameFromCompiler);- auto weight_buffer =- std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mapped_memory->data() + id,- byte_size,- mapped_memory);-- auto [it, inserted] =- constants.emplace(id,- std::make_shared<ov::op::v0::Constant>(descriptor.precision,- descriptor.shapeFromCompiler.to_shape(),- weight_buffer));- if (!inserted) {- OPENVINO_ASSERT(it->second->get_byte_size() == byte_size,- "Duplicate constant offset found with mismatching byte size: offset=",- id);- }- }- }-- return constants;-}-} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hppnew file mode 100644index 00000000000..4271ffa081c--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/include/blob_format_importers.hpp@@ -0,0 +1,154 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <map>+#include <string>++#include "intel_npu/common/filtered_config.hpp"+#include "intel_npu/common/igraph.hpp"+#include "intel_npu/common/npu.hpp"+#include "metadata.hpp"+#include "openvino/runtime/tensor.hpp"++namespace ov {++class ICore;++}++namespace intel_npu {++/**+ * @brief Abstract class used as the base for importing blobs of different formats.+ */+class IBlobFormatImporter {+public:+ /**+ * @param original_model The model used for compiling the target blob. This parameter may be used as a source of+ * weights only if the blob was compiled using the weights separation feature. Can be "nullptr", in which case the+ * "weights path" from the configuration object may be used as the source of weights instead.+ * @param config Used for multiple purposes such as: extracting the log level, weights path, decryption callbacks.+ * @param logger A logger that should already use the name of the subclass.+ */+ IBlobFormatImporter(const std::shared_ptr<const ov::Model>& original_model,+ const FilteredConfig& config,+ const Logger& logger);++ /**+ * @brief Parses the current blob to create a graph type of object.+ * @details This function calls multiple virtual methods in order to extract from the current format all information+ * it needs (e.g. the compiler main schedule) to build the graph object.+ *+ * @param backend The current backend in use, required for creating and using a parser.+ * @param network_name The resulted graph object will use this network name.+ * @param device_name The name of the device. Used to update the compiler type if "perf count" was enabled via the+ * configuration.+ * @param core The OV core. The weights separation feature may depend on this object to extract the original+ * weights.+ * @return A graph object. The type of graph depends on the content of the blob. E.g. a "weightless" graph will be+ * returned if the weights separation feature was detected.+ */+ std::shared_ptr<IGraph> create_graph(const ov::SoPtr<IEngineBackend>& backend,+ const std::string_view network_name,+ const std::string_view device_name,+ const std::shared_ptr<ov::ICore>& core);++ /**+ * @brief Uses the metadata of the resulted graph object to build a minimalistic OV model.+ * @note This should be called only after "create_graph".+ * @throws ov::AssertFailure if called before "create_graph" (invalid state).+ *+ * @return A model object containing only "Parameter" and "Result" nodes, according to the metadata stored in the+ * graph object.+ */+ std::shared_ptr<ov::Model> create_dummy_model() const;++ FilteredConfig get_config() const;++ virtual ~IBlobFormatImporter() = default;++protected:+ FilteredConfig m_config;+ Logger m_logger;++private:+ /**+ * @brief Decrypts all schedules (main and inits if applicable) if all conditions are met (e.g. a decryption+ * callback was provided).+ */+ virtual void decrypt_schedules() = 0;++ /**+ * @brief Extracts the compiler main schedule as a tensor.+ */+ virtual ov::Tensor extract_main_schedule() const = 0;++ /**+ * @brief If weights separation was used, the init schedules will be extracted as tensors.+ */+ virtual std::optional<std::vector<ov::Tensor>> extract_init_schedules() const = 0;++ /**+ * @brief If a batch size a stored, this method will be used to extract it.+ */+ virtual std::optional<int> extract_batch_size() const = 0;++ /**+ * @brief If input/output layouts were stored, this method will be used to extract them.+ * @note The layouts are only used as optional information within the "dummy" model.+ */+ virtual std::optional<std::pair<std::vector<ov::Layout>, std::vector<ov::Layout>>> extract_layouts() const = 0;++ /**+ * @brief If a compiler compatibility string was stored, this method will be used to extract it.+ */+ virtual std::optional<std::string> extract_compiler_compatibility_descriptor() const = 0;++ /**+ * @brief A potential source of weights for weights separation. Can be `nullptr`.+ */+ std::shared_ptr<const ov::Model> m_original_model;+ std::optional<int> m_batch_size;+ std::shared_ptr<IGraph> m_graph;+};++namespace blob_format_importer_factory {++/**+ * @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(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,+ const bool is_raw_blob,+ const std::shared_ptr<const ov::Model>& original_model,+ const FilteredConfig& config);++} // namespace blob_format_importer_factory++} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hppindex 6b21959ae86..e19f1971eab 100644--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp@@ -63,6 +63,8 @@ public:virtual uint64_t get_blob_size() const;+ virtual uint64_t get_main_schedule_size() const;+/*** @returns The sizes of the init schedules. Populated only if "weights separation" has been enabled.*/@@ -85,7 +87,7 @@ public:virtual ~MetadataBase() = default;- static std::streampos getFileSize(std::istream& stream);+ static size_t getFileSize(std::istream& stream);/*** @brief Returns a uint32_t value which represents two uint16_t values concatenated.diff --git a/src/plugins/intel_npu/src/plugin/include/plugin.hpp b/src/plugins/intel_npu/src/plugin/include/plugin.hppindex d759a27083e..69124140950 100644--- a/src/plugins/intel_npu/src/plugin/include/plugin.hpp+++ b/src/plugins/intel_npu/src/plugin/include/plugin.hpp@@ -9,9 +9,9 @@#include <string>#include "backends_registry.hpp"+#include "blob_format_importers.hpp"#include "intel_npu/common/npu.hpp"#include "intel_npu/utils/logger/logger.hpp"-#include "metadata.hpp"#include "openvino/runtime/iplugin.hpp"#include "openvino/runtime/so_ptr.hpp"#include "plugin_property_manager.hpp"@@ -65,20 +65,14 @@ private:void update_log_level(const ov::AnyMap& properties) const;/**- * @brief Parses the compiled model found within the stream and tensor and returns a wrapper over the L0 handle that- * can be used for running predictions.- * @details The binary data corresponding to the compiled model is made of NPU plugin metadata, the schedule of- * the model and its weights. If weights separation has been enabled, the size of the weights is reduced, and there- * will be one or multiple weights initialization schedules found there as well.- *- * @param tensorBig Contains the whole binary object.- * @param metadata Parsed metadata at the end of the blob. Can be nullptr if compatibility checks were disabled.- * @param properties Configuration taking the form of an "ov::AnyMap".- * @return A compiled model+ * @brief Looks for "DISABLE_VERSION_CHECK" and "IMPORT_RAW_BLOB" to determine whether or not the blob to be+ * imported should be treated as a "raw" one (i.e. the whole blob is a compiler main schedule).*/- std::shared_ptr<ov::ICompiledModel> parse(const ov::Tensor& tensorBig,- std::unique_ptr<MetadataBase> metadata,- const ov::AnyMap& properties) const;+ 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::unique_ptr<BackendsRegistry> _backendsRegistry;diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex 3b06312172a..d4eec6fdc49 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -5,6 +5,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/compiled_model.hpp${CMAKE_CURRENT_SOURCE_DIR}/include/compiled_model_property_manager.hpp${CMAKE_CURRENT_SOURCE_DIR}/include/executor.hpp@@ -16,6 +17,7 @@ set(SOURCES${CMAKE_CURRENT_SOURCE_DIR}/include/transformations.hpp${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/compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model_property_manager.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/executor.cppdiff --git a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cppnew file mode 100644index 00000000000..3b727e76039--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp@@ -0,0 +1,553 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "blob_format_importers.hpp"++#include "intel_npu/common/compiler_adapter_factory.hpp"+#include "intel_npu/common/itt.hpp"+#include "intel_npu/common/parser_factory.hpp"+#include "intel_npu/config/options.hpp"+#include "intel_npu/utils/utils.hpp"+#include "metadata.hpp"+#include "openvino/core/model.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/runtime/allocator.hpp"++namespace {++using namespace intel_npu;++constexpr std::string_view HANDLER_FACTOR_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_COMPATIBILITY_SKIPPED_MESSAGE = "Blob compatibility check skipped.";+constexpr std::string_view MISSING_METADATA_MESSAGE = "The blob is missing the NPU metadata!";+constexpr std::string_view EMPTY_BLOB_MESSAGE = "The blob provided for import is empty";+constexpr std::string_view BLOB_SIZE_SMALLER_THAN_MAGIC =+ "Received a blob for import that is not a raw one and its size is smaller than the size of the magic bytes";+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";++const std::vector<size_t> CONSTANT_NODE_DUMMY_SHAPE{1};++ov::Tensor allocate_aligned_tensor(size_t blobSize) {+ ov::Allocator customAllocator{utils::AlignedAllocator{utils::STANDARD_PAGE_SIZE}};+ ov::Tensor tensor(ov::element::u8, ov::Shape{blobSize}, customAllocator);+ 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!");+ }++ return tensor;+}++/**+ * @brief Special case for PERF_COUNT as it requires compiler_type detection in case it is still set to PREFER_PLUGIN+ */+void update_compiler_type_if_perf_count(FilteredConfig& config,+ const ov::SoPtr<IEngineBackend>& backend,+ const std::string_view device_name) {+ if (config.has<PERF_COUNT>() && config.get<PERF_COUNT>() &&+ config.get<COMPILER_TYPE>() == ov::intel_npu::CompilerType::PREFER_PLUGIN) {+ ov::intel_npu::CompilerType compilerType = config.get<COMPILER_TYPE>();+ CompilerAdapterFactory factory;+ (void)factory.getCompiler(backend, compilerType, device_name);++ config.update({{ov::intel_npu::compiler_type.name(), COMPILER_TYPE::toString(compilerType)}});+ }+}++/**+ * @brief Uses the provided decryption callback to decrypt the given payload.+ */+void decrypt_payload(ov::Tensor& payload, const ov::EncryptionCallbacks& encryption_callbacks, const Logger& logger) {+ std::string decryptedBlobStr;+ {+ std::string encryptedBlobStr(payload.data<const char>(), payload.get_byte_size()); // +1x blob size+ decryptedBlobStr = encryption_callbacks.decrypt(encryptedBlobStr); // +1x blob size+ } // -1x blob size when deallocating temporary encrypted blob string+ ov::Allocator customAllocator{utils::AlignedAllocator{utils::STANDARD_PAGE_SIZE}};+ size_t alignedSize = utils::align_size_to_standard_page_size(decryptedBlobStr.size());+ size_t paddingSize = alignedSize - decryptedBlobStr.size();+ payload = ov::Tensor(ov::element::u8, ov::Shape{alignedSize},+ customAllocator); // +1x blob size+ std::memcpy(payload.data<char>(), decryptedBlobStr.c_str(), decryptedBlobStr.size());+ if (paddingSize > 0) {+ // The blob obtained after decryption is expected to be the same as the blob we had before encryption.+ // That means blobs compiled with the current plugin version are expected to be already aligned.+ // However, the alignment might not be mandatory in a future plugin version. For this scenario, the+ // padding is added here in order to make use of this "non-copy optimization".+ logger.warning("Decrypted blob size was not page aligned, additional %zu bytes padding will be added",+ paddingSize);+ std::memset(payload.data<char>() + decryptedBlobStr.size(), 0, paddingSize);+ }+} // -1x blob size when deallocating decrypted blob string++/**+ * @brief Creates an "ov::Model" object which contains only the given "parameter" and "result" nodes.+ * @details Using an "ov::Model" object to create the "CompiledModel" is the preferred way of using the OV API.+ * This path allows making use of the already written functions/attributes for handling the I/O information.+ *+ * Note that a stored compiled model does not hold the original IR model within it. The only related information+ * which may be extracted is the original model's "parameter"/"result" nodes. Thus, we need to build a dummy model+ * starting from these fields in order to satisfy the API.+ *+ * @param inputDescriptors Describes the input nodes.+ * @param outputDescriptors Describes the output nodes.+ * @returns The dummy "ov::Model" composed of "parameter" and "result" nodes built using the given descriptors.+ */+std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& inputDescriptors,+ const std::vector<IODescriptor>& outputDescriptors,+ const std::optional<int> batchSize,+ const std::optional<std::vector<ov::Layout>>& inputLayouts,+ const std::optional<std::vector<ov::Layout>>& outputLayouts) {+ ov::ParameterVector parameters;+ ov::ResultVector results;++ for (size_t inputIndex = 0; inputIndex < inputDescriptors.size(); ++inputIndex) {+ const IODescriptor& inputDescriptor = inputDescriptors.at(inputIndex);+ if (inputDescriptor.isStateInput || inputDescriptor.isStateOutput || inputDescriptor.isShapeTensor ||+ inputDescriptor.isInitInputWeights || inputDescriptor.isMainInputWeights) {+ continue;+ }++ auto shape = inputDescriptor.shapeFromIRModel.has_value() ? *inputDescriptor.shapeFromIRModel+ : inputDescriptor.shapeFromCompiler;++ if (batchSize.has_value()) {+ shape[utils::BATCH_AXIS] = ov::Dimension(batchSize.value());+ }++ std::shared_ptr<ov::op::v0::Parameter> parameter =+ std::make_shared<ov::op::v0::Parameter>(inputDescriptor.precision, shape);++ parameter->set_friendly_name(inputDescriptor.nodeFriendlyName);+ parameter->output(0).get_tensor().set_names(inputDescriptor.outputTensorNames);+ if (inputLayouts.has_value()) {+ parameter->set_layout(inputLayouts->at(inputIndex));+ }+ parameters.push_back(std::move(parameter));+ }++ // The "result" nodes require a parent node in order to satisfy the API conventions. Additionally, a dummy shape for+ // the "Constant" node was required since the specific constructor does not accept "ov::PartialShape" values (a+ // constant can't have dynamic shape). The dummy tensor was also brought in order to register the correct,+ // potentially dynamic, output shape.+ for (size_t outputIndex = 0; outputIndex < outputDescriptors.size(); ++outputIndex) {+ const IODescriptor& outputDescriptor = outputDescriptors.at(outputIndex);+ if (outputDescriptor.isStateInput || outputDescriptor.isStateOutput || outputDescriptor.isShapeTensor ||+ outputDescriptor.isInitOutputWeights) {+ continue;+ }++ std::shared_ptr<ov::Node> constantDummy =+ std::make_shared<ov::op::v0::Constant>(outputDescriptor.precision, CONSTANT_NODE_DUMMY_SHAPE);++ auto shape = outputDescriptor.shapeFromIRModel.has_value() ? *outputDescriptor.shapeFromIRModel+ : outputDescriptor.shapeFromCompiler;++ if (batchSize.has_value()) {+ shape[utils::BATCH_AXIS] = ov::Dimension(batchSize.value());+ }++ const std::shared_ptr<ov::descriptor::Tensor>& tensorDummy =+ std::make_shared<ov::descriptor::Tensor>(outputDescriptor.precision,+ shape,+ outputDescriptor.outputTensorNames);++ auto& result = results.emplace_back(std::make_shared<ov::op::v0::Result>(constantDummy));+ result->output(0).set_tensor_ptr(tensorDummy);+ if (outputLayouts.has_value()) {+ result->set_layout(outputLayouts->at(outputIndex));+ }+ result->set_friendly_name(outputDescriptor.nodeFriendlyName);+ }++ return std::make_shared<ov::Model>(results, parameters);+}++/**+ * @brief Class used to import a blob that contains only the compiler main schedule.+ */+class RawBlobImporter : public IBlobFormatImporter {+public:+ explicit RawBlobImporter(std::istream& 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::getFileSize(compiler_main_schedule);+ 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));+ }++ 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_main_schedule = ov::Tensor(compiler_main_schedule, ov::Coordinate{0}, ov::Coordinate{blob_size});+ }++private:+ /**+ * @brief Decrypts the compiler main schedule if a decryption callback was received.+ */+ void decrypt_schedules() override {+ const bool is_null_decryption = !(m_config.has(CACHE_ENCRYPTION_CALLBACKS::key().data()) &&+ m_config.get<CACHE_ENCRYPTION_CALLBACKS>().decrypt != nullptr);+ if (is_null_decryption) {+ m_logger.debug("No decryption callback found");+ return;+ }++ m_logger.warning(+ "Received decryption callback, but metadata parsing is skipped and cannot determine if blob was "+ "encrypted or not.");++ m_logger.debug(DECRYPTING_PAYLOAD_MESSAGE.data());+ decrypt_payload(m_main_schedule, m_config.get<CACHE_ENCRYPTION_CALLBACKS>(), m_logger);+ }++ ov::Tensor extract_main_schedule() const override {+ return m_main_schedule;+ }++ /**+ * @note N/A+ * @return Always std::nullopt+ */+ std::optional<std::vector<ov::Tensor>> extract_init_schedules() const override {+ return std::nullopt;+ }++ /**+ * @note N/A+ * @return Always std::nullopt+ */+ std::optional<int> extract_batch_size() const override {+ return std::nullopt;+ }++ /**+ * @note N/A+ * @return Always std::nullopt+ */+ std::optional<std::pair<std::vector<ov::Layout>, std::vector<ov::Layout>>> extract_layouts() const override {+ return std::nullopt;+ }++ /**+ * @note N/A+ * @return Always std::nullopt+ */+ std::optional<std::string> extract_compiler_compatibility_descriptor() const override {+ return std::nullopt;+ }++ /**+ * @brief The compiler main schedule, that is also the whole blob received to be imported.+ */+ ov::Tensor m_main_schedule;+};++/**+ * @brief Class used to import a blob that follows the "V1" format: compiler payload + some (non-TLV) metadata+ */+class BlobFormatV1Importer : public IBlobFormatImporter {+public:+ explicit BlobFormatV1Importer(std::istream& 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+ // 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);++ m_compiler_payload = allocate_aligned_tensor(blob_size);+ npu_formatted_blob.read(m_compiler_payload.data<char>(), static_cast<std::streamsize>(blob_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});++ register_compiler_version();+ }++private:+ /**+ * @brief Decrypts the whole compiler payload (main schedule + init schedules if applicable) if:+ * 1. A decryption callback was provided and+ * 2. The metadata indicates the blob was encrypted.+ * @throws ov::AssertFailure if the blob was encrypted but no decryption callback was provided.+ */+ void decrypt_schedules() override {+ const bool is_payload_encrypted = m_metadata->is_encrypted_blob().value_or(false);+ const bool is_null_decryption = !(m_config.has(CACHE_ENCRYPTION_CALLBACKS::key().data()) &&+ m_config.get<CACHE_ENCRYPTION_CALLBACKS>().decrypt != nullptr);+ if (!is_payload_encrypted) {+ m_logger.debug("The compiler payload is NOT encrypted");+ return;+ }+ OPENVINO_ASSERT(!is_null_decryption, "Blob is encrypted, but no decryption callback was provided!");++ m_logger.debug(DECRYPTING_PAYLOAD_MESSAGE.data());+ decrypt_payload(m_compiler_payload, m_config.get<CACHE_ENCRYPTION_CALLBACKS>(), m_logger);+ }++ ov::Tensor extract_main_schedule() const override {+ const uint64_t main_size = m_metadata->get_main_schedule_size();++ return ov::Tensor(m_compiler_payload, ov::Coordinate{0}, ov::Coordinate{main_size});+ }++ std::optional<std::vector<ov::Tensor>> extract_init_schedules() const override {+ const std::optional<std::vector<uint64_t>> init_sizes = m_metadata->get_init_sizes();+ if (!init_sizes.has_value()) {+ return std::nullopt;+ }++ std::vector<ov::Tensor> init_schedules;+ size_t cursor_position = m_metadata->get_main_schedule_size();++ m_logger.debug("Extracting %zu init schedules", init_sizes->size());++ for (const uint64_t init_size : init_sizes.value()) {+ m_logger.debug("Init size: %llu", init_size);++ init_schedules.push_back(ov::Tensor(m_compiler_payload,+ ov::Coordinate{cursor_position},+ ov::Coordinate{cursor_position + init_size}));+ cursor_position += init_size;+ }++ return init_schedules;+ }++ std::optional<int> extract_batch_size() const override {+ const std::optional<int64_t> batch_size = m_metadata->get_batch_size();+ if (batch_size.has_value()) {+ m_logger.debug("Extracted batch size: %d", batch_size.value());+ return std::make_optional<int>(static_cast<int>(batch_size.value()));+ }+ return std::nullopt;+ }++ std::optional<std::pair<std::vector<ov::Layout>, std::vector<ov::Layout>>> extract_layouts() const override {+ std::optional<std::vector<ov::Layout>> input_layouts = m_metadata->get_input_layouts();+ if (!input_layouts.has_value()) {+ return std::nullopt;+ }+ std::optional<std::vector<ov::Layout>> output_layouts = m_metadata->get_output_layouts();+ OPENVINO_ASSERT(output_layouts.has_value(),+ "The metadata version received at import supports input layouts, but it doesn't support output "+ "layouts. Either both or none should be supported");++ return std::make_pair<>(input_layouts.value(), output_layouts.value());+ }++ std::optional<std::string> extract_compiler_compatibility_descriptor() const override {+ const std::optional<std::string_view> compatibility_descriptor = m_metadata->get_compatibility_descriptor();+ // Convert the descriptor to an owning string before the metadata is potentially destroyed+ return compatibility_descriptor.has_value()+ ? std::make_optional<>(std::string(compatibility_descriptor.value()))+ : std::nullopt;+ }++ /**+ * @brief Registers the compiler version inside the configuration attribute if the version is found within the+ * metadata.+ */+ void register_compiler_version() {+ std::optional<uint32_t> compiler_version = m_metadata->get_compiler_version();+ if (compiler_version.has_value()) {+ m_config.update({{ov::intel_npu::compiler_version.name(), std::to_string(compiler_version.value())}});+ m_logger.debug("Imported model was compiled with compiler version: %u.%u",+ ONEAPI_VERSION_MAJOR(compiler_version.value()),+ ONEAPI_VERSION_MINOR(compiler_version.value()));+ }+ }++ /**+ * @brief The whole compiler payload. Init schedules include if weights separation was used.+ */+ ov::Tensor m_compiler_payload;+ std::unique_ptr<MetadataBase> m_metadata;+};++} // namespace++namespace intel_npu {++IBlobFormatImporter::IBlobFormatImporter(const std::shared_ptr<const ov::Model>& original_model,+ const FilteredConfig& config,+ const Logger& logger)+ : m_config(config),+ m_logger(logger),+ m_original_model(original_model) {}++std::shared_ptr<IGraph> IBlobFormatImporter::create_graph(const ov::SoPtr<IEngineBackend>& backend,+ const std::string_view network_name,+ const std::string_view device_name,+ const std::shared_ptr<ov::ICore>& core) {+ OV_ITT_TASK_CHAIN(PARSE_AND_CREATE_GRAPH, itt::domains::NPUPlugin, "IBlobFormatImporter", "create_graph");+ m_logger.debug("Creating a graph");++ OV_ITT_TASK_NEXT(PARSE_AND_CREATE_GRAPH, "decrypt_schedules");+ decrypt_schedules();++ OV_ITT_TASK_NEXT(PARSE_AND_CREATE_GRAPH, "extract_main_schedule");+ const ov::Tensor main_schedule = extract_main_schedule();++ OV_ITT_TASK_NEXT(PARSE_AND_CREATE_GRAPH, "extract_init_schedules");+ const std::optional<std::vector<ov::Tensor>> init_schedules = extract_init_schedules();+ m_batch_size = extract_batch_size();++ update_compiler_type_if_perf_count(m_config, backend, device_name);++ OV_ITT_TASK_NEXT(PARSE_AND_CREATE_GRAPH, "get_parser");+ m_logger.trace("Creating the parser");+ ParserFactory parserFactory;+ auto parser = parserFactory.getParser(backend->getInitStructs());++ std::variant<std::monostate, std::shared_ptr<const ov::Model>, std::pair<std::string, std::shared_ptr<ov::ICore>>>+ weights_source;+ if (init_schedules.has_value()) {+ if (m_original_model) {+ weights_source = std::move(m_original_model);+ } else if (!m_config.get<WEIGHTS_PATH>().empty()) {+ weights_source = std::make_pair<>(m_config.get<WEIGHTS_PATH>(), core);+ } else {+ OPENVINO_THROW("Attempted to load a weightless compiled model, but no weights have been provided");+ }+ }++ OV_ITT_TASK_NEXT(PARSE_AND_CREATE_GRAPH, "parse");+ m_logger.trace("Calling the parser");+ m_graph = parser->parse(main_schedule,+ m_config,+ std::move(weights_source),+ init_schedules,+ extract_compiler_compatibility_descriptor());++ m_graph->update_network_name(network_name);+ if (m_batch_size.has_value() && m_batch_size.value() > 0) {+ // Initial batch setup for static cases+ m_graph->set_batch_size(m_batch_size.value());+ }++ return m_graph;+}++std::shared_ptr<ov::Model> IBlobFormatImporter::create_dummy_model() const {+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "IBlobFormatImporter::create_dummy_model");+ m_logger.debug("Creating a dummy ov::Model");++ OPENVINO_ASSERT(m_graph != nullptr, "Invalid state");++ const std::optional<std::pair<std::vector<ov::Layout>, std::vector<ov::Layout>>> layouts = extract_layouts();+ return ::create_dummy_model(m_graph->get_metadata().inputs,+ m_graph->get_metadata().outputs,+ m_batch_size,+ layouts.has_value() ? std::make_optional<>(layouts->first) : std::nullopt,+ layouts.has_value() ? std::make_optional<>(layouts->second) : std::nullopt);+}++FilteredConfig IBlobFormatImporter::get_config() const {+ return m_config;+}++namespace blob_format_importer_factory {++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) {+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "blob_format_importer_factory::create(std::istream)");+ const size_t input_size = MetadataBase::getFileSize(npu_formatted_blob);+ OPENVINO_ASSERT(input_size > 0, EMPTY_BLOB_MESSAGE);++ 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 stream 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);+ }++ size_t magic_bytes_size = MAGIC_BYTES.size();+ std::string_view blob_magic_bytes(+ npu_formatted_blob.data<const char>() + npu_formatted_blob.get_byte_size() - magic_bytes_size,+ magic_bytes_size);++ OPENVINO_ASSERT(MAGIC_BYTES == blob_magic_bytes, MISSING_METADATA_MESSAGE);++ logger.debug("Creating a blob format v1 import handler from a tensor using the factory");+ return std::make_unique<BlobFormatV1Importer>(npu_formatted_blob, original_model, config);+}++} // namespace blob_format_importer_factory++} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/src/compiled_model.cppindex 6b5ebd17136..f6db2af0828 100644--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp@@ -102,12 +102,6 @@ void CompiledModel::export_model(std::ostream& stream) const {encryptedBlobStr =_propertiesManager->getConfig().get<CACHE_ENCRYPTION_CALLBACKS>().encrypt(tmpBlobStr); // +2x blob sizeblobSizeAfterEncryption = encryptedBlobStr.size();- if (blobSizeAfterEncryption.value() % utils::STANDARD_PAGE_SIZE != 0) {- _logger.warning("Encrypted blob size %" PRIu64- " is not page aligned, memory optimization when reading this blob "- "won't be applied",- blobSizeAfterEncryption.value());- }} // -1x blob size when deallocating temporary blob stringstream.write(encryptedBlobStr.c_str(), encryptedBlobStr.size());} // -1x blob size when deallocating encrypted blob stringdiff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cppindex d7472df7a13..731c3ceaae6 100644--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp@@ -15,6 +15,16 @@namespace {+// Metadata version + compiler payload size + magic bytes+constexpr size_t MINIMUM_BLOB_SIZE = sizeof(uint32_t) + sizeof(uint64_t) + intel_npu::MAGIC_BYTES.size();++constexpr std::string_view MISSING_METADATA_MESSAGE = "The blob is missing the NPU metadata!";+constexpr std::string_view BLOB_TOO_SMALL_MESSAGE =+ "The blob received for parsing is too small to contain all mandatory information. Blob size: ";+constexpr std::string_view INVALID_PAYLOAD_SIZE_MESSAGE =+ "The size of the compiler payload parsed from the blob is greater "+ "than the size of the blob. Compiler payload size: ";+template <typename T>void write_text_field(std::ostream& stream, std::string_view key, const T& value) {if (stream.tellp() != std::streampos(0)) {@@ -540,7 +550,7 @@ std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSiz}}-std::streampos MetadataBase::getFileSize(std::istream& stream) {+size_t MetadataBase::getFileSize(std::istream& stream) {auto log = Logger::global().clone("getFileSize");if (!stream) {OPENVINO_THROW("Stream is in bad status! Please check the passed stream status!");@@ -568,28 +578,30 @@ std::streampos MetadataBase::getFileSize(std::istream& stream) {}std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream) {- size_t magicBytesSize = MAGIC_BYTES.size();+ std::streampos currentStreamPos = stream.tellg();+ const size_t streamSize = MetadataBase::getFileSize(stream);++ OPENVINO_ASSERT(streamSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, streamSize);+std::string blobMagicBytes;- blobMagicBytes.resize(magicBytesSize);+ blobMagicBytes.resize(MAGIC_BYTES.size());+ stream.seekg(-std::streampos(MAGIC_BYTES.size()), std::ios::end);+ stream.read(blobMagicBytes.data(), MAGIC_BYTES.size());+ OPENVINO_ASSERT(MAGIC_BYTES == blobMagicBytes, MISSING_METADATA_MESSAGE);- std::streampos currentStreamPos = stream.tellg(), streamSize = MetadataBase::getFileSize(stream);- stream.seekg(streamSize - std::streampos(magicBytesSize), std::ios::cur);- stream.read(blobMagicBytes.data(), magicBytesSize);- if (MAGIC_BYTES != blobMagicBytes) {- OPENVINO_THROW("Blob is missing NPU metadata!");- }+ uint64_t payloadSize;+ stream.seekg(-std::streampos(MAGIC_BYTES.size()) - sizeof(payloadSize), std::ios::end);+ stream.read(reinterpret_cast<char*>(&payloadSize), sizeof(payloadSize));- uint64_t blobDataSize;- stream.seekg(-std::streampos(magicBytesSize) - sizeof(blobDataSize), std::ios::cur);- stream.read(reinterpret_cast<char*>(&blobDataSize), sizeof(blobDataSize));- stream.seekg(-stream.tellg() + currentStreamPos + blobDataSize, std::ios::cur);+ OPENVINO_ASSERT(streamSize >= MINIMUM_BLOB_SIZE + payloadSize, INVALID_PAYLOAD_SIZE_MESSAGE, payloadSize);+ stream.seekg(-stream.tellg() + currentStreamPos + payloadSize, std::ios::cur);uint32_t metaVersion;stream.read(reinterpret_cast<char*>(&metaVersion), sizeof(metaVersion));std::unique_ptr<MetadataBase> storedMeta;try {- storedMeta = create_metadata(metaVersion, blobDataSize);+ storedMeta = create_metadata(metaVersion, payloadSize);storedMeta->read(stream);} catch (const std::exception& ex) {OPENVINO_THROW("Can't read NPU metadata: ", ex.what());@@ -603,27 +615,26 @@ std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream) {}std::unique_ptr<MetadataBase> read_metadata_from(const ov::Tensor& tensor) {- size_t magicBytesSize = MAGIC_BYTES.size();- std::string_view blobMagicBytes(tensor.data<const char>() + tensor.get_byte_size() - magicBytesSize,- magicBytesSize);+ const size_t blobSize = tensor.get_byte_size();+ OPENVINO_ASSERT(blobSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, blobSize);- if (MAGIC_BYTES != blobMagicBytes) {- OPENVINO_THROW("Blob is missing NPU metadata!");- }+ 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));- uint64_t blobDataSize;- blobDataSize = *reinterpret_cast<const decltype(blobDataSize)*>(tensor.data<const char>() + tensor.get_byte_size() -- magicBytesSize - sizeof(blobDataSize));+ OPENVINO_ASSERT(blobSize >= MINIMUM_BLOB_SIZE + payloadSize, INVALID_PAYLOAD_SIZE_MESSAGE, payloadSize);uint32_t metaVersion;- metaVersion = *reinterpret_cast<const decltype(metaVersion)*>(tensor.data<const char>() + blobDataSize);+ metaVersion = *reinterpret_cast<const decltype(metaVersion)*>(tensor.data<const char>() + payloadSize);std::unique_ptr<MetadataBase> storedMeta;try {- const ov::Tensor roiTensor(tensor,- ov::Coordinate{blobDataSize + sizeof(metaVersion)},- ov::Coordinate{tensor.get_byte_size()});- storedMeta = create_metadata(metaVersion, blobDataSize);+ 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());@@ -668,6 +679,13 @@ uint64_t MetadataBase::get_blob_size() const {return _blobDataSize;}+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();+}+std::optional<std::vector<uint64_t>> MetadataBase::get_init_sizes() const {return std::nullopt;}diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex 438c70791e0..827a37a422a 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -14,7 +14,6 @@#include "intel_npu/common/icompiler_adapter.hpp"#include "intel_npu/common/igraph.hpp"#include "intel_npu/common/itt.hpp"-#include "intel_npu/common/parser_factory.hpp"#include "intel_npu/config/npuw.hpp"#include "intel_npu/config/options.hpp"#include "intel_npu/utils/utils.hpp"@@ -25,7 +24,6 @@#include "npuw/serialization.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/op/constant.hpp"-#include "openvino/op/parameter.hpp"#include "openvino/runtime/intel_npu/properties.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/shared_buffer.hpp"@@ -37,94 +35,9 @@namespace {using namespace intel_npu;-const std::vector<size_t> CONSTANT_NODE_DUMMY_SHAPE{1};--const char* NPU_PLUGIN_LIB_NAME = "openvino_intel_npu_plugin";-constexpr std::string_view WEIGHTS_IR_EXTENSION = ".bin";-constexpr std::string_view ONNX_EXTENSION = ".onnx";--/**- * @brief Creates an "ov::Model" object which contains only the given "parameter" and "result" nodes.- * @details Using an "ov::Model" object to create the "CompiledModel" is the preferred way of using the OV API.- * This path allows making use of the already written functions/attributes for handling the I/O information.- *- * Note that a stored compiled model does not hold the original IR model within it. The only related information- * which may be extracted is the original model's "parameter"/"result" nodes. Thus, we need to build a dummy model- * starting from these fields in order to satisfy the API.- *- * @param inputDescriptors Describes the input nodes.- * @param outputDescriptors Describes the output nodes.- * @returns The dummy "ov::Model" composed of "parameter" and "result" nodes built using the given descriptors.- */-std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& inputDescriptors,- const std::vector<IODescriptor>& outputDescriptors,- const std::optional<int64_t> batchSize,- const std::optional<std::vector<ov::Layout>>& inputLayouts,- const std::optional<std::vector<ov::Layout>>& outputLayouts) {- ov::ParameterVector parameters;- ov::ResultVector results;-- for (size_t inputIndex = 0; inputIndex < inputDescriptors.size(); ++inputIndex) {- const IODescriptor& inputDescriptor = inputDescriptors.at(inputIndex);- if (inputDescriptor.isStateInput || inputDescriptor.isStateOutput || inputDescriptor.isShapeTensor ||- inputDescriptor.isInitInputWeights || inputDescriptor.isMainInputWeights) {- continue;- }-- auto shape = inputDescriptor.shapeFromIRModel.has_value() ? *inputDescriptor.shapeFromIRModel- : inputDescriptor.shapeFromCompiler;-- if (batchSize.has_value()) {- shape[intel_npu::utils::BATCH_AXIS] = ov::Dimension(batchSize.value());- }-- std::shared_ptr<ov::op::v0::Parameter> parameter =- std::make_shared<ov::op::v0::Parameter>(inputDescriptor.precision, shape);-- parameter->set_friendly_name(inputDescriptor.nodeFriendlyName);- parameter->output(0).get_tensor().set_names(inputDescriptor.outputTensorNames);- if (inputLayouts.has_value()) {- parameter->set_layout(inputLayouts->at(inputIndex));- }- parameters.push_back(std::move(parameter));- }-- // The "result" nodes require a parent node in order to satisfy the API conventions. Additionally, a dummy shape for- // the "Constant" node was required since the specific constructor does not accept "ov::PartialShape" values (a- // constant can't have dynamic shape). The dummy tensor was also brought in order to register the correct,- // potentially dynamic, output shape.- for (size_t outputIndex = 0; outputIndex < outputDescriptors.size(); ++outputIndex) {- const IODescriptor& outputDescriptor = outputDescriptors.at(outputIndex);- if (outputDescriptor.isStateInput || outputDescriptor.isStateOutput || outputDescriptor.isShapeTensor ||- outputDescriptor.isInitOutputWeights) {- continue;- }-- std::shared_ptr<ov::Node> constantDummy =- std::make_shared<ov::op::v0::Constant>(outputDescriptor.precision, CONSTANT_NODE_DUMMY_SHAPE);-- auto shape = outputDescriptor.shapeFromIRModel.has_value() ? *outputDescriptor.shapeFromIRModel- : outputDescriptor.shapeFromCompiler;-- if (batchSize.has_value()) {- shape[intel_npu::utils::BATCH_AXIS] = ov::Dimension(batchSize.value());- }-- const std::shared_ptr<ov::descriptor::Tensor>& tensorDummy =- std::make_shared<ov::descriptor::Tensor>(outputDescriptor.precision,- shape,- outputDescriptor.outputTensorNames);-- auto& result = results.emplace_back(std::make_shared<ov::op::v0::Result>(constantDummy));- result->output(0).set_tensor_ptr(tensorDummy);- if (outputLayouts.has_value()) {- result->set_layout(outputLayouts->at(outputIndex));- }- result->set_friendly_name(outputDescriptor.nodeFriendlyName);- }-- return std::make_shared<ov::Model>(results, parameters);-}+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";/*** @brief Just checks if there is any "WeightlessCacheAttribute" present in the model. In the negative case, an error is@@ -185,7 +98,7 @@ std::shared_ptr<ov::ICompiledModel> import_model_npuw(std::istream& stream,stream.seekg(stream_start_pos);// Drop NPUW properties if there are any- for (auto it = properties.begin(); it != properties.end(); ) {+ for (auto it = properties.begin(); it != properties.end();) {if (it->first.find("NPUW") != it->first.npos) {it = properties.erase(it);} else {@@ -195,7 +108,7 @@ std::shared_ptr<ov::ICompiledModel> import_model_npuw(std::istream& stream,return nullptr;}-std::shared_ptr<const ov::Model> get_model_ptr_from_map(ov::AnyMap& properties) {+std::shared_ptr<const ov::Model> get_model_ptr_from_map(const ov::AnyMap& properties) {if (properties.count(ov::hint::model.name())) {try {return properties.at(ov::hint::model.name()).as<std::shared_ptr<const ov::Model>>();@@ -627,8 +540,24 @@ ov::SoPtr<ov::IRemoteContext> Plugin::get_default_context(const ov::AnyMap&) conreturn std::make_shared<RemoteContextImpl>(_backend);}+bool Plugin::should_import_raw_blob(const ov::AnyMap& properties) const {+ const bool skipCompatibility = (properties.find(DISABLE_VERSION_CHECK::key().data()) != properties.end())+ ? properties.at(DISABLE_VERSION_CHECK::key().data()).as<bool>()+ : _propertiesManager->getConfig().get<DISABLE_VERSION_CHECK>();+ if (skipCompatibility) {+ return true;+ }++ const bool importRawBlob = (properties.find(IMPORT_RAW_BLOB::key().data()) != properties.end())+ ? properties.at(IMPORT_RAW_BLOB::key().data()).as<bool>()+ : _propertiesManager->getConfig().get<IMPORT_RAW_BLOB>();+ return importRawBlob;+}+std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, const ov::AnyMap& properties) const {- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model");+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model(std::istream)");+ _logger.debug("Importing a compiled model from the given stream");+update_log_level(properties);if (properties.find(ov::hint::compiled_blob.name()) != properties.end()) {@@ -638,43 +567,25 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, cauto npuPluginProperties = properties;// NPUW properties from npuPluginProperties will be erased if import_model_npuw returns nullptr- auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this());- if (compiledModel) {+ if (auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this())) {+ _logger.debug(NPUW_MODEL_IMPORTED_MESSAGE.data());return compiledModel;}- if (_backend != nullptr) {- _backend->updateInfo(npuPluginProperties);- }+ 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);try {- const bool skipCompatibility =- (npuPluginProperties.find(DISABLE_VERSION_CHECK::key().data()) != npuPluginProperties.end())- ? npuPluginProperties[DISABLE_VERSION_CHECK::key().data()].as<bool>()- : _propertiesManager->getConfig().get<DISABLE_VERSION_CHECK>();- const bool importRawBlob =- (npuPluginProperties.find(IMPORT_RAW_BLOB::key().data()) != npuPluginProperties.end())- ? npuPluginProperties[IMPORT_RAW_BLOB::key().data()].as<bool>()- : _propertiesManager->getConfig().get<IMPORT_RAW_BLOB>();- std::unique_ptr<MetadataBase> metadata = nullptr;- size_t blobSize = MetadataBase::getFileSize(stream);-- if (!importRawBlob && !skipCompatibility) {- // Read only metadata from the stream and check if blob is compatible. Load blob into memory only in case it- // passes compatibility checks.- metadata = read_metadata_from(stream);- blobSize = metadata->get_blob_size();- } else {- _logger.info("Blob compatibility check skipped.");- }- OPENVINO_ASSERT(blobSize > 0, "Parsed blob size is empty from the given stream!");- ov::Allocator customAllocator{utils::AlignedAllocator{utils::STANDARD_PAGE_SIZE}};- ov::Tensor tensor(ov::element::u8, ov::Shape{blobSize}, customAllocator);- 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!");- }- stream.read(tensor.data<char>(), static_cast<std::streamsize>(blobSize));- return parse(tensor, std::move(metadata), npuPluginProperties);+ 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);} catch (const std::exception& ex) {OPENVINO_THROW("Can't import network: ", ex.what());} catch (...) {@@ -682,20 +593,11 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, c}}-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");- }-- return import_model(stream, properties);-}-std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compiledBlob,const ov::AnyMap& properties) const {- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model");+ OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::import_model(ov::Tensor)");+ _logger.debug("Importing a compiled model from the given tensor");+update_log_level(properties);// Need to create intermediate istream for NPUW@@ -704,38 +606,25 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compiauto npuPluginProperties = properties;// NPUW properties from npuPluginProperties will be erased if import_model_npuw returns nullptr- auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this());- if (compiledModel) {+ if (auto compiledModel = import_model_npuw(stream, npuPluginProperties, shared_from_this())) {+ _logger.debug(NPUW_MODEL_IMPORTED_MESSAGE.data());return compiledModel;}- if (_backend != nullptr) {- _backend->updateInfo(npuPluginProperties);- }+ 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);try {- const bool skipCompatibility =- (npuPluginProperties.find(DISABLE_VERSION_CHECK::key().data()) != npuPluginProperties.end())- ? npuPluginProperties[DISABLE_VERSION_CHECK::key().data()].as<bool>()- : _propertiesManager->getConfig().get<DISABLE_VERSION_CHECK>();- const bool importRawBlob =- (npuPluginProperties.find(IMPORT_RAW_BLOB::key().data()) != npuPluginProperties.end())- ? npuPluginProperties[IMPORT_RAW_BLOB::key().data()].as<bool>()- : _propertiesManager->getConfig().get<IMPORT_RAW_BLOB>();- std::unique_ptr<MetadataBase> metadata = nullptr;- size_t blobSize = compiledBlob.get_byte_size();-- if (!importRawBlob && !skipCompatibility) {- metadata = read_metadata_from(compiledBlob);- blobSize = metadata->get_blob_size();- } else {- _logger.info("Blob compatibility check skipped.");- }- OPENVINO_ASSERT(blobSize > 0, "Parsed blob size is empty from the given buffer!");- const ov::Tensor roiTensor(compiledBlob,- ov::Coordinate{0},- ov::Coordinate{blobSize}); // ROI tensor to skip NPU plugin metadata- return parse(roiTensor, std::move(metadata), npuPluginProperties);+ 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);} catch (const std::exception& ex) {OPENVINO_THROW("Can't import network: ", ex.what());} catch (...) {@@ -743,6 +632,45 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compi}}+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<IDevice> device =+ utils::getDeviceById(_backend, _propertiesManager->determineDeviceId(localProperties));+ OPENVINO_ASSERT(device != nullptr, "Device not found.");++ if (!localConfig.get<LOADED_FROM_CACHE>()) {+ _logger.warning("The usage of a compiled model can lead to undefined behavior. Please use OpenVINO IR instead");+ }++ const std::shared_ptr<IGraph> graph =+ blobFormatImporter->create_graph(_backend,+ "net" + std::to_string(_compiledModelLoadCounter++),+ device->getName(),+ get_core());++ return std::make_shared<CompiledModel>(blobFormatImporter->create_dummy_model(),+ shared_from_this(),+ device,+ graph,+ blobFormatImporter->get_config(),+ graph->get_batch_size());+}++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");+ }++ return import_model(stream, properties);+}+std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& compiledBlob,const ov::SoPtr<ov::IRemoteContext>& context,const ov::AnyMap& properties) const {@@ -795,184 +723,6 @@ ov::SupportedOpsMap Plugin::query_model(const std::shared_ptr<const ov::Model>&return supportedOpsMap;}-std::shared_ptr<ov::ICompiledModel> Plugin::parse(const ov::Tensor& tensorBig,- std::unique_ptr<MetadataBase> metadata,- const ov::AnyMap& properties) const {- OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::parse");-- auto localProperties = properties;-- auto originalModel = get_model_ptr_from_map(localProperties);-- std::shared_ptr<IDevice> device =- utils::getDeviceById(_backend, _propertiesManager->determineDeviceId(localProperties));-- if (_backend == nullptr || device == nullptr) {- OPENVINO_THROW("Device not found.");- }-- OV_ITT_TASK_CHAIN(PLUGIN_PARSE_MODEL, itt::domains::NPUPlugin, "Plugin::parse", "fork_local_config");- FilteredConfig localConfig = _propertiesManager->getConfigWithCompilerPropertiesDisabled(localProperties);-- const auto loadedFromCache = localConfig.get<LOADED_FROM_CACHE>();- if (!loadedFromCache) {- _logger.warning(- "The usage of a compiled model can lead to undefined behavior. Please use OpenVINO IR instead!");- }-- const bool isNotNullDecryption = localConfig.has(CACHE_ENCRYPTION_CALLBACKS::key().data()) &&- localConfig.get<CACHE_ENCRYPTION_CALLBACKS>().decrypt != nullptr;- if (!metadata && isNotNullDecryption) {- _logger.warning(- "Received decryption callback, but metadata parsing is skipped and cannot determine if blob was "- "encrypted or not.");- }-- ov::Tensor tensor = tensorBig;- if (isNotNullDecryption &&- (metadata == nullptr || (metadata != nullptr && metadata->is_encrypted_blob().value_or(false)))) {- {- std::string decryptedBlobStr;- {- std::string encryptedBlobStr(tensor.data<const char>(), tensor.get_byte_size()); // +1x blob size- decryptedBlobStr =- localConfig.get<CACHE_ENCRYPTION_CALLBACKS>().decrypt(encryptedBlobStr); // +2x blob size- } // -1x blob size when deallocating temporary encrypted blob string- ov::Allocator customAllocator{utils::AlignedAllocator{utils::STANDARD_PAGE_SIZE}};- size_t alignedSize = utils::align_size_to_standard_page_size(decryptedBlobStr.size());- size_t paddingSize = alignedSize - decryptedBlobStr.size();- tensor = ov::Tensor(ov::element::u8, ov::Shape{alignedSize},- customAllocator); // +1x blob size- std::memcpy(tensor.data<char>(), decryptedBlobStr.c_str(), decryptedBlobStr.size());- if (paddingSize > 0) {- // If user altered in some way initial blob during encryption, check if its size is still paged aligned- _logger.warning("Decrypted blob size was not page aligned, additional %zu bytes padding will be added",- paddingSize);- std::memset(tensor.data<char>() + decryptedBlobStr.size(), 0, paddingSize);- }- } // -1x blob size when deallocating decrypted blob string- }-- uint64_t mainSize = tensor.get_byte_size();- std::optional<std::vector<uint64_t>> initSizes;- std::optional<int64_t> batchSize = std::nullopt;-- if (metadata) {- if (metadata->is_encrypted_blob().value_or(false) && !isNotNullDecryption) {- OPENVINO_THROW("Blob is encrypted, but no decryption callback was provided!");- }-- size_t accumulator = 0;- initSizes = metadata->get_init_sizes();- mainSize = initSizes.has_value()- ? metadata->get_blob_size() - std::accumulate(initSizes->begin(), initSizes->end(), accumulator)- : metadata->get_blob_size();- batchSize = metadata->get_batch_size();-- std::optional<uint32_t> compilerVersion = metadata->get_compiler_version();- if (compilerVersion.has_value()) {- localConfig.update({{ov::intel_npu::compiler_version.name(), std::to_string(compilerVersion.value())}});- _logger.debug("Imported model was compiled with compiler version: %u.%u",- ONEAPI_VERSION_MAJOR(compilerVersion.value()),- ONEAPI_VERSION_MINOR(compilerVersion.value()));- }- } else {- _logger.warning(- "Metadata parsing is skipped, if this is a weightless blob, init schedules cannot be parsed from it!");- }-- const ov::Tensor tensorMain(tensor,- ov::Coordinate{0},- ov::Coordinate{mainSize}); // ROI tensor to skip NPU plugin metadata-- std::vector<ov::Tensor> tensorsInits;- const bool weightsSeparationEnabled = initSizes.has_value();-- if (weightsSeparationEnabled) {- // Read the init compiled models as well- size_t cursorPosition = mainSize;- for (uint64_t initSize : initSizes.value()) {- const ov::Tensor tensorInit(tensor,- ov::Coordinate{cursorPosition},- ov::Coordinate{cursorPosition + initSize});- tensorsInits.push_back(tensorInit);- cursorPosition += initSize;- }-- // Retrieve the ov::Model used for compilation. This is required for extracting and matching the weights- if (!originalModel) {- if (!localConfig.get<WEIGHTS_PATH>().empty()) {- const std::string weightsPath = localConfig.get<WEIGHTS_PATH>();- auto ext = ov::util::path_to_string(ov::util::make_path(weightsPath).extension());- if (ext == ONNX_EXTENSION) {- originalModel = get_core()->read_model(weightsPath, weightsPath, properties);- } else if (ext == WEIGHTS_IR_EXTENSION) {- // constants will be populated in parser- } else {- OPENVINO_THROW("Invalid path to the weights: ",- weightsPath,- ". A \".bin\" or \".onnx\" extension was expected.");- }- } else {- OPENVINO_THROW("Attempted to load a weightless compiled model, but no weights have been provided");- }- }-- check_weightless_cache_attribute_occurrence(originalModel);- }-- const std::optional<std::vector<ov::Tensor>> initBlobs =- weightsSeparationEnabled ? std::make_optional(std::move(tensorsInits)) : std::nullopt;-- // Special case for PERF_COUNT as it requires compiler_type detection in case it is still set to PREFER_PLUGIN- if (localConfig.has<PERF_COUNT>() && localConfig.get<PERF_COUNT>() &&- localConfig.get<COMPILER_TYPE>() == ov::intel_npu::CompilerType::PREFER_PLUGIN) {- ov::intel_npu::CompilerType compilerType = localConfig.get<COMPILER_TYPE>();- CompilerAdapterFactory factory;- (void)factory.getCompiler(_backend, compilerType, device->getName());-- localConfig.update({{ov::intel_npu::compiler_type.name(), COMPILER_TYPE::toString(compilerType)}});- }-- ParserFactory parserFactory;- auto parser = parserFactory.getParser(_backend->getInitStructs());-- // Convert descriptor to an owning string before metadata is potentially destroyed.- std::optional<std::string> compatibilityDescriptor = std::nullopt;- if (metadata) {- if (const auto descriptorView = metadata->get_compatibility_descriptor(); descriptorView.has_value()) {- compatibilityDescriptor = std::string(descriptorView.value());- }- }-- auto graph = parser->parse(tensorMain,- localConfig,- initBlobs,- weightsSeparationEnabled && originalModel != nullptr- ? std::make_optional(std::move(originalModel))- : std::nullopt,- compatibilityDescriptor);-- graph->update_network_name("net" + std::to_string(_compiledModelLoadCounter++));- const std::shared_ptr<ov::Model> modelDummy =- create_dummy_model(graph->get_metadata().inputs,- graph->get_metadata().outputs,- batchSize,- metadata ? metadata->get_input_layouts() : std::nullopt,- metadata ? metadata->get_output_layouts() : std::nullopt);-- if (batchSize.has_value()) {- if (batchSize.value() > 0) {- // Initial batch setup for static cases- graph->set_batch_size(batchSize.value());- }- }-- OV_ITT_TASK_NEXT(PLUGIN_PARSE_MODEL, "parse");-- return std::make_shared<CompiledModel>(modelDummy, shared_from_this(), device, graph, localConfig, batchSize);-}-void Plugin::update_log_level(const ov::AnyMap& properties) const {if (properties.count(ov::log::level.name()) != 0) {Logger::global().setLevel(properties.at(ov::log::level.name()).as<ov::log::Level>());@@ -982,7 +732,7 @@ void Plugin::update_log_level(const ov::AnyMap& properties) const {std::atomic<int> Plugin::_compiledModelLoadCounter{1};-static const ov::Version version = {CI_BUILD_NUMBER, NPU_PLUGIN_LIB_NAME};+static const ov::Version version = {CI_BUILD_NUMBER, NPU_PLUGIN_LIB_NAME.data()};OV_DEFINE_PLUGIN_CREATE_FUNCTION(Plugin, version)} // namespace intel_npudiff --git a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.hpp b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.hppindex 6d890fcb699..47bbe294e55 100644--- a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/import_export.hpp@@ -65,6 +65,7 @@ TEST_P(OVCompiledGraphImportExportTestNPU, CanImportModelWithApplicationHeaderAnOV_ASSERT_NO_THROW(auto compiledModel = core.import_model(sstream, target_device, configuration));configuration.erase(ov::intel_npu::disable_version_check.name());OV_ASSERT_NO_THROW(auto compiledModel = core.import_model(tensor, target_device, configuration));+ sstream.seekg(headerView.size(), std::ios::beg);OV_EXPECT_THROW(auto compiledModel = core.import_model(sstream, target_device, configuration),ov::Exception,testing::HasSubstr("metadata")); // OVNPU suffix cannot be parsed from metadatadiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 5a3e55febc9..f190e23153c 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -16,6 +16,7 @@ set(MANDATORY_UNIT_TESTS_LIBS"openvino_npu_common""openvino::npu_ops""openvino_npu_vm_utils"+ "openvino_npu_compiler_adapter")ov_add_test_target(@@ -43,6 +44,7 @@ ov_add_test_target(# plugin/src${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# npuw core${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cppdiff --git a/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cppnew file mode 100644index 00000000000..8b0e209e68c--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npu/blob_format_importers.cpp@@ -0,0 +1,125 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "blob_format_importers.hpp"++#include <gtest/gtest.h>++#include <sstream>+#include <string_view>++#include "common_test_utils/test_assertions.hpp"+#include "metadata.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"++using namespace intel_npu;++namespace {++constexpr std::string_view DUMMY_COMPILER_PAYLOAD = "1";+constexpr std::string_view RAW_BLOB = DUMMY_COMPILER_PAYLOAD;+constexpr size_t MINIMUM_BLOB_SIZE = sizeof(uint32_t) + sizeof(uint64_t) + MAGIC_BYTES.size();++std::string build_blob_format_v1_with_magic() {+ std::ostringstream stream;+ stream << DUMMY_COMPILER_PAYLOAD.data();+ Metadata<CURRENT_METADATA_VERSION> metadata(DUMMY_COMPILER_PAYLOAD.size());+ metadata.write(stream);++ const std::string blob = stream.str();+ OPENVINO_ASSERT(blob.size() >= MINIMUM_BLOB_SIZE);+ return blob;+}++std::string build_blob_format_v1_without_magic() {+ const std::string blob = build_blob_format_v1_with_magic();+ return blob.substr(0, blob.size() - MAGIC_BYTES.size());+}++std::shared_ptr<ov::Model> create_simple_model() {+ auto weights = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{5}, std::vector<float>{1.0f});+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1});+ auto add = std::make_shared<ov::op::v1::Add>(input, weights);++ return std::make_shared<ov::Model>(ov::OutputVector{add}, ov::ParameterVector{input}, "Simple with weights");+}++} // namespace++using testing::_;++struct BlobFormatImportersTest : public ::testing::Test {+ BlobFormatImportersTest() : config(std::make_shared<OptionsDesc>()) {}++ std::unique_ptr<IBlobFormatImporter> importer;+ FilteredConfig config;+};++/**+ * @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, _);+}++/**+ * @brief Non-raw blobs must contain the magic bytes+ */+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());++ 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, _);+}++/**+ * @brief Only raw blobs can be created when the magic bytes are missing+ */+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());++ 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));+}++/**+ * @brief If the magic bytes are present at the end of the input, then the factory can create "blob format v1" importers+ */+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());++ 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));++ 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));++ 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));+}++/**+ * @brief A dummy model cannot be created before the graph+ */+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());++ OV_ASSERT_NO_THROW(importer = blob_format_importer_factory::create(input_tensor, true, nullptr, config));+ OV_EXPECT_THROW(importer->create_dummy_model(), ov::Exception, _);+}