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] Move serialize functions to ir_serializer (#32241)
Alexandru Enacheea3600ad8bba
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hppindex 140085cef7c..f1c1c302f22 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/driver_compiler_adapter.hpp@@ -6,9 +6,6 @@#pragma once-#include <type_traits>-#include <utility>-#include "intel_npu/common/icompiler_adapter.hpp"#include "intel_npu/config/config.hpp"#include "intel_npu/utils/logger/logger.hpp"@@ -40,28 +37,6 @@ public:uint32_t get_version() const override;private:- /**- * @brief Serialize input / output information to string format.- * @details Format:- * --inputs_precisions="0:<input1Precision> [1:<input2Precision>]"- * --inputs_layouts="0:<input1Layout> [1:<input2Layout>]"- * --outputs_precisions="0:<output1Precision>"- * --outputs_layouts="0:<output1Layout>"- *- * For older compiler versions, the name of the inputs/outputs may be used instead of their indices.- *- * Since the layout information is no longer an important part of the metadata values when using the 2.0 OV- * API, the layout fields shall be filled with default values in order to assure the backward compatibility- * with the driver.- */- std::string serializeIOInfo(const std::shared_ptr<const ov::Model>& model, const bool useIndices) const;-- SerializedIR serializeIR(const std::shared_ptr<const ov::Model>& model,- ze_graph_compiler_version_info_t compilerVersion,- const uint32_t supportedOpsetVersion) const;-- std::string serializeConfig(const Config& config, ze_graph_compiler_version_info_t compilerVersion) const;-std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;std::shared_ptr<ZeGraphExtWrappers> _zeGraphExt;diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hppindex fbb098a1238..e97c9b5aee2 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ir_serializer.hpp@@ -5,17 +5,20 @@#pragma once#include <iostream>#include <string>-#include <vector>-#include "custom_stream_buffer.hpp"+#include "intel_npu/config/config.hpp"#include "intel_npu/utils/logger/logger.hpp"-#include "openvino/pass/manager.hpp"+#include "ze_graph_ext.h"++namespace intel_npu {++using SerializedIR = std::pair<size_t, std::shared_ptr<uint8_t>>;/*** @brief Contain all required transformation on OpenVINO model in case for external compiler usage and* providing forward compatibility (OV model with opset N+M, external compiler with opset N)*/-namespace intel_npu::driver_compiler_utils {+namespace driver_compiler_utils {class IRSerializer {public:@@ -34,6 +37,30 @@ public:*/void serializeModelToBuffer(uint8_t* xml, uint8_t* weights);+ /**+ * @brief Serialize input / output information to string format.+ * @details Format:+ * --inputs_precisions="0:<input1Precision> [1:<input2Precision>]"+ * --inputs_layouts="0:<input1Layout> [1:<input2Layout>]"+ * --outputs_precisions="0:<output1Precision>"+ * --outputs_layouts="0:<output1Layout>"+ *+ * For older compiler versions, the name of the inputs/outputs may be used instead of their indices.+ *+ * Since the layout information is no longer an important part of the metadata values when using the 2.0 OV+ * API, the layout fields shall be filled with default values in order to assure the backward compatibility+ * with the driver.+ */+ SerializedIR serializeIR(const std::shared_ptr<const ov::Model>& model,+ ze_graph_compiler_version_info_t compilerVersion,+ const uint32_t supportedOpsetVersion);++ std::string serializeIOInfo(const std::shared_ptr<const ov::Model>& model, const bool useIndices);++ std::string serializeConfig(const Config& config,+ ze_graph_compiler_version_info_t compilerVersion,+ bool turboSupported = false);+private:/*** @brief Serialize OpenVINO model to target stream@@ -51,5 +78,5 @@ private:size_t _xmlSize = 0;size_t _weightsSize = 0;};--} // namespace intel_npu::driver_compiler_utils+} // namespace driver_compiler_utils+} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hppindex c7657e0213d..e0d42026dce 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/ze_graph_ext_wrappers.hpp@@ -7,18 +7,13 @@#include <ze_api.h>#include <ze_graph_ext.h>-#include <type_traits>-#include <utility>-#include "intel_npu/network_metadata.hpp"#include "intel_npu/utils/logger/logger.hpp"#include "intel_npu/utils/zero/zero_init.hpp"-#include "intel_npu/utils/zero/zero_types.hpp"+#include "ir_serializer.hpp"namespace intel_npu {-using SerializedIR = std::pair<size_t, std::shared_ptr<uint8_t>>;-struct GraphDescriptor {GraphDescriptor(ze_graph_handle_t handle = nullptr, bool memoryPersistent = false);@@ -36,10 +31,9 @@ public:ZeGraphExtWrappers& operator=(const ZeGraphExtWrappers&) = delete;~ZeGraphExtWrappers();- std::unordered_set<std::string> queryGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,- const std::string& buildFlags) const;+ std::unordered_set<std::string> queryGraph(SerializedIR serializedIR, const std::string& buildFlags) const;- GraphDescriptor getGraphDescriptor(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,+ GraphDescriptor getGraphDescriptor(SerializedIR serializedIR,const std::string& buildFlags,const uint32_t& flags) const;diff --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 808c6bd1fcb..9cd1320b1a5 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@@ -4,20 +4,13 @@#include "driver_compiler_adapter.hpp"-#include <fstream>-#include <regex>#include <string_view>#include "graph.hpp"#include "intel_npu/common/filtered_config.hpp"#include "intel_npu/common/itt.hpp"#include "intel_npu/config/options.hpp"-#include "intel_npu/prefix.hpp"#include "intel_npu/utils/logger/logger.hpp"-#include "intel_npu/utils/utils.hpp"-#include "intel_npu/utils/zero/zero_api.hpp"-#include "intel_npu/utils/zero/zero_result.hpp"-#include "intel_npu/utils/zero/zero_utils.hpp"#include "ir_serializer.hpp"#include "mem_usage.hpp"#include "openvino/core/model.hpp"@@ -25,127 +18,6 @@#include "weightless_graph.hpp"namespace {--constexpr std::string_view INPUTS_PRECISIONS_KEY = "--inputs_precisions";-constexpr std::string_view INPUTS_LAYOUTS_KEY = "--inputs_layouts";-constexpr std::string_view OUTPUTS_PRECISIONS_KEY = "--outputs_precisions";-constexpr std::string_view OUTPUTS_LAYOUTS_KEY = "--outputs_layouts";--// <option key>="<option value>"-constexpr std::string_view KEY_VALUE_SEPARATOR = "=";-constexpr std::string_view VALUE_DELIMITER = "\""; // marks beginning and end of value--// Format inside "<option value>"-// <name1>:<value (precision / layout)> [<name2>:<value>]-constexpr std::string_view NAME_VALUE_SEPARATOR = ":";-constexpr std::string_view VALUES_SEPARATOR = " ";--// Constants indicating the order indices needed to be applied as to perform conversions between legacy layout values-const std::vector<size_t> NC_TO_CN_LAYOUT_DIMENSIONS_ORDER = {1, 0};-const std::vector<size_t> NCHW_TO_NHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 1};-const std::vector<size_t> NCDHW_TO_NDHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 4, 1};--/**- * @brief A standard copy function concerning memory segments. Additional checks on the given arguments are performed- * before copying.- * @details This is meant as a replacement for the legacy "ie_memcpy" function coming from the OpenVINO API.- */-void checkedMemcpy(void* destination, size_t destinationSize, const void* source, size_t numberOfBytes) {- if (numberOfBytes == 0) {- return;- }-- OPENVINO_ASSERT(destination != nullptr, "Memcpy: received a null destination address");- OPENVINO_ASSERT(source != nullptr, "Memcpy: received a null source address");- OPENVINO_ASSERT(numberOfBytes <= destinationSize,- "Memcpy: the source buffer does not fit inside the destination one");- OPENVINO_ASSERT(numberOfBytes <= (destination > source ? ((uintptr_t)destination - (uintptr_t)source)- : ((uintptr_t)source - (uintptr_t)destination)),- "Memcpy: the offset between the two buffers does not allow a safe execution of the operation");-- memcpy(destination, source, numberOfBytes);-}--/**- * @brief For driver backward compatibility reasons, the given value shall be converted to a string corresponding to the- * adequate legacy precision.- */-std::string ovPrecisionToLegacyPrecisionString(const ov::element::Type& precision) {- switch (precision) {- case ov::element::Type_t::f16:- return "FP16";- case ov::element::Type_t::f32:- return "FP32";- case ov::element::Type_t::f64:- return "FP64";- case ov::element::Type_t::bf16:- return "BF16";- case ov::element::Type_t::f8e4m3:- return "FP8_E4M3";- case ov::element::Type_t::f8e5m2:- return "FP8_E5M2";- case ov::element::Type_t::f8e8m0:- return "FP8_E8M0";- case ov::element::Type_t::nf4:- return "NF4";- case ov::element::Type_t::i4:- return "I4";- case ov::element::Type_t::i8:- return "I8";- case ov::element::Type_t::i16:- return "I16";- case ov::element::Type_t::i32:- return "I32";- case ov::element::Type_t::i64:- return "I64";- case ov::element::Type_t::u4:- return "U4";- case ov::element::Type_t::u8:- return "U8";- case ov::element::Type_t::u16:- return "U16";- case ov::element::Type_t::u32:- return "U32";- case ov::element::Type_t::u64:- return "U64";- case ov::element::Type_t::u1:- return "BIN";- case ov::element::Type_t::u2:- return "U2";- case ov::element::Type_t::boolean:- return "BOOL";- case ov::element::Type_t::dynamic:- return "DYNAMIC";- default:- OPENVINO_THROW("Incorrect precision: ", precision);- }-}--/**- * @brief Gives the string representation of the default legacy layout value corresponding to the given rank.- * @details This is done in order to assure the backward compatibility with the driver. Giving a layout different from- * the default one may lead either to error or to accuracy failures since unwanted transposition layers may be- * introduced.- */-std::string rankToLegacyLayoutString(const size_t rank) {- switch (rank) {- case 0:- return "**SCALAR**";- case 1:- return "C";- case 2:- return "NC";- case 3:- return "CHW";- case 4:- return "NCHW";- case 5:- return "NCDHW";- default:- return "BLOCKED";- }-}-bool isInitMetadata(const intel_npu::NetworkMetadata& networkMetadata) {if (networkMetadata.inputs.size() == 0) {return false;@@ -216,15 +88,16 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compile(const std::shared_ptr<con_logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);_logger.debug("serialize IR");- auto serializedIR = serializeIR(model, compilerVersion, maxOpsetVersion);+ driver_compiler_utils::IRSerializer irSerializer(model, maxOpsetVersion);+ SerializedIR serializedIR = irSerializer.serializeIR(model, compilerVersion, maxOpsetVersion);std::string buildFlags;const bool useIndices = !((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 9));_logger.debug("build flags");- buildFlags += serializeIOInfo(model, useIndices);+ buildFlags += irSerializer.serializeIOInfo(model, useIndices);buildFlags += " ";- buildFlags += serializeConfig(config, compilerVersion);+ buildFlags += irSerializer.serializeConfig(config, compilerVersion, is_option_supported("NPU_TURBO"));_logger.debug("compileIR Build flags : %s", buildFlags.c_str());@@ -275,12 +148,13 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<o}_logger.debug("serialize IR");- auto serializedIR = serializeIR(model, compilerVersion, maxOpsetVersion);+ driver_compiler_utils::IRSerializer irSerializer(model, maxOpsetVersion);+ SerializedIR serializedIR = irSerializer.serializeIR(model, compilerVersion, maxOpsetVersion);std::string buildFlags;const bool useIndices = !((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 9));- const std::string serializedIOInfo = serializeIOInfo(model, useIndices);+ const std::string serializedIOInfo = irSerializer.serializeIOInfo(model, useIndices);const FilteredConfig* plgConfig = dynamic_cast<const FilteredConfig*>(&config);if (plgConfig == nullptr) {OPENVINO_THROW("config is not FilteredConfig");@@ -314,7 +188,7 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<o_logger.debug("build flags");buildFlags = serializedIOInfo;buildFlags += " ";- buildFlags += serializeConfig(updatedConfig, compilerVersion);+ buildFlags += irSerializer.serializeConfig(updatedConfig, compilerVersion);_logger.debug("compile start");auto graphDesc = _zeGraphExt->getGraphDescriptor(serializedIR, buildFlags, flags);@@ -421,10 +295,11 @@ ov::SupportedOpsMap DriverCompilerAdapter::query(const std::shared_ptr<const ov:_logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);_logger.debug("serialize IR");- auto serializedIR = serializeIR(model, compilerVersion, maxOpsetVersion);+ driver_compiler_utils::IRSerializer irSerializer(model, maxOpsetVersion);+ SerializedIR serializedIR = irSerializer.serializeIR(model, compilerVersion, maxOpsetVersion);std::string buildFlags;- buildFlags += serializeConfig(config, compilerVersion);+ buildFlags += irSerializer.serializeConfig(config, compilerVersion);_logger.debug("queryImpl build flags : %s", buildFlags.c_str());ov::SupportedOpsMap result;@@ -448,274 +323,6 @@ uint32_t DriverCompilerAdapter::get_version() const {return _zeroInitStruct->getCompilerVersion();}-/**- * @brief Place xml + weights in sequential memory- * @details Format of the memory:- */-SerializedIR DriverCompilerAdapter::serializeIR(const std::shared_ptr<const ov::Model>& model,- ze_graph_compiler_version_info_t compilerVersion,- const uint32_t supportedOpsetVersion) const {- driver_compiler_utils::IRSerializer irSerializer(model, supportedOpsetVersion);-- // Contract between adapter and compiler in driver- const uint32_t maxNumberOfElements = 10;- const uint64_t maxSizeOfXML = std::numeric_limits<uint64_t>::max() / 3;- const uint64_t maxSizeOfWeights = maxSizeOfXML * 2;-- const uint32_t numberOfInputData = 2;- const uint64_t xmlSize = static_cast<uint64_t>(irSerializer.getXmlSize());- const uint64_t weightsSize = static_cast<uint64_t>(irSerializer.getWeightsSize());-- OPENVINO_ASSERT(numberOfInputData < maxNumberOfElements);- if (xmlSize >= maxSizeOfXML) {- OPENVINO_THROW("Xml file is too big to process. xmlSize: ", xmlSize, " >= maxSizeOfXML: ", maxSizeOfXML);- }- if (weightsSize >= maxSizeOfWeights) {- OPENVINO_THROW("Bin file is too big to process. xmlSize: ",- weightsSize,- " >= maxSizeOfWeights: ",- maxSizeOfWeights);- }-- const uint64_t sizeOfSerializedIR = sizeof(compilerVersion) + sizeof(numberOfInputData) + sizeof(xmlSize) +- xmlSize + sizeof(weightsSize) + weightsSize;-- // use array to avoid vector's memory zeroing overhead- std::shared_ptr<uint8_t> buffer(new uint8_t[sizeOfSerializedIR], std::default_delete<uint8_t[]>());- uint8_t* serializedIR = buffer.get();-- uint64_t offset = 0;- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &compilerVersion, sizeof(compilerVersion));- offset += sizeof(compilerVersion);-- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &numberOfInputData, sizeof(numberOfInputData));- offset += sizeof(numberOfInputData);- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &xmlSize, sizeof(xmlSize));- offset += sizeof(xmlSize);- // xml data is filled in serializeModel()- uint64_t xmlOffset = offset;- offset += xmlSize;- checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &weightsSize, sizeof(weightsSize));- offset += sizeof(weightsSize);- // weights data is filled in serializeModel()- uint64_t weightsOffset = offset;- offset += weightsSize;-- irSerializer.serializeModelToBuffer(serializedIR + xmlOffset, serializedIR + weightsOffset);-- OPENVINO_ASSERT(offset == sizeOfSerializedIR);-- return std::make_pair(sizeOfSerializedIR, buffer);-}--std::string DriverCompilerAdapter::serializeIOInfo(const std::shared_ptr<const ov::Model>& model,- const bool useIndices) const {- const ov::ParameterVector& parameters = model->get_parameters();- const ov::ResultVector& results = model->get_results();-- std::stringstream inputsPrecisionSS;- std::stringstream inputsLayoutSS;- std::stringstream outputsPrecisionSS;- std::stringstream outputsLayoutSS;-- inputsPrecisionSS << INPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;- inputsLayoutSS << INPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;- const auto getRankOrThrow = [](const ov::PartialShape& shape) -> size_t {- if (shape.rank().is_dynamic()) {- OPENVINO_THROW("Dynamic rank is not supported for NPU plugin");- }- return shape.rank().get_length();- };-- if (!parameters.empty()) {- size_t parameterIndex = 0;-- for (const std::shared_ptr<ov::op::v0::Parameter>& parameter : parameters) {- const auto precision = parameter->get_element_type();- const auto rank = getRankOrThrow(parameter->get_partial_shape());-- if (parameterIndex != 0) {- inputsPrecisionSS << VALUES_SEPARATOR;- inputsLayoutSS << VALUES_SEPARATOR;- }-- if (useIndices) {- inputsPrecisionSS << parameterIndex;- inputsLayoutSS << parameterIndex;- } else {- const std::string& name = parameter->get_friendly_name();-- inputsPrecisionSS << name;- // Ticket: E-88902- inputsLayoutSS << name;- }-- inputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);- inputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);-- ++parameterIndex;- }- }-- inputsPrecisionSS << VALUE_DELIMITER;- inputsLayoutSS << VALUE_DELIMITER;-- outputsPrecisionSS << OUTPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;- outputsLayoutSS << OUTPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;-- size_t resultIndex = 0;- for (const std::shared_ptr<ov::op::v0::Result>& result : results) {- const auto precision = result->get_element_type();- const auto rank = getRankOrThrow(result->get_output_partial_shape(0));-- if (resultIndex != 0) {- outputsPrecisionSS << VALUES_SEPARATOR;- outputsLayoutSS << VALUES_SEPARATOR;- }-- if (useIndices) {- outputsPrecisionSS << resultIndex;- outputsLayoutSS << resultIndex;- } else {- const std::string& name = result->get_input_node_ptr(0)->get_friendly_name();-- outputsPrecisionSS << name;- outputsLayoutSS << name;- }-- outputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);- outputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);-- ++resultIndex;- }-- outputsPrecisionSS << VALUE_DELIMITER;- outputsLayoutSS << VALUE_DELIMITER;-- // One line without spaces to avoid parsing as config option inside CID- return inputsPrecisionSS.str() + VALUES_SEPARATOR.data() + inputsLayoutSS.str() + VALUES_SEPARATOR.data() +- outputsPrecisionSS.str() + VALUES_SEPARATOR.data() + outputsLayoutSS.str();-}--std::string DriverCompilerAdapter::serializeConfig(const Config& config,- ze_graph_compiler_version_info_t compilerVersion) const {- Logger logger("serializeConfig", Logger::global().level());-- std::string content = {};-- const FilteredConfig* plgConfig = dynamic_cast<const FilteredConfig*>(&config);- if (plgConfig != nullptr) {- content += plgConfig->toStringForCompiler();- content += plgConfig->toStringForCompilerInternal();- } else {- logger.warning("Failed to cast Config to FilteredConfig. Exporting all configs");- content += config.toString();- }-- logger.debug("Original content of config: %s", content.c_str());-- // Remove optimization-level and performance-hint-override for old driver which not support them- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 7)) {- std::string valueOfParams = config.get<COMPILATION_MODE_PARAMS>();- std::string keyOfOptL("optimization-level");- std::string keyOfPerfHO("performance-hint-override");- if (valueOfParams != "" && (valueOfParams.find(keyOfOptL) != std::string::npos ||- valueOfParams.find(keyOfPerfHO) != std::string::npos)) {- // Remove unsupported options from value- std::ostringstream optLevelStr;- optLevelStr << keyOfOptL << KEY_VALUE_SEPARATOR << "\\d+";- std::ostringstream perfHintStr;- perfHintStr << keyOfPerfHO << KEY_VALUE_SEPARATOR << "\\S+";- logger.warning("%s property is not supported by this compiler version. Removing from parameters",- keyOfOptL.c_str());- valueOfParams = std::regex_replace(valueOfParams, std::regex(optLevelStr.str()), "");- logger.warning("%s property is not supported by this compiler version. Removing from parameters",- keyOfPerfHO.c_str());- valueOfParams = std::regex_replace(valueOfParams, std::regex(perfHintStr.str()), "");-- // Trim space- valueOfParams = std::regex_replace(valueOfParams, std::regex(R"(^\s+|\s+$)"), "");-- // Replace the value in content with new value- std::ostringstream compilationParamsStr;- compilationParamsStr << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR- << VALUE_DELIMITER << ".*" << VALUE_DELIMITER;- if (valueOfParams == "") {- logger.warning("Clear empty NPU_COMPILATION_MODE_PARAMS. Removing from parameters");- content = std::regex_replace(content, std::regex(compilationParamsStr.str()), "");- } else {- std::ostringstream newValue;- newValue << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER- << valueOfParams << VALUE_DELIMITER;- logger.warning("Replace value of NPU_COMPILATION_MODE_PARAMS with new value %s",- newValue.str().c_str());- content = std::regex_replace(content, std::regex(compilationParamsStr.str()), newValue.str().c_str());- }- }- }-- // As a consequence of complying to the conventions established in the 2.0 OV API, the set of values corresponding- // to the "model priority" key has been modified cpu_pinning property is not supported in compilers < v5.2 - need to- // remove it- if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 2)) {- const auto& getTargetRegex = [](const ov::hint::Priority& priorityValue) -> std::regex {- std::ostringstream result;- result << ov::hint::model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << priorityValue- << VALUE_DELIMITER;- return std::regex(result.str());- };- const auto& getStringReplacement = [](const ov::intel_npu::LegacyPriority& priorityValue) -> std::string {- std::ostringstream result;- result << ov::intel_npu::legacy_model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER- << priorityValue << VALUE_DELIMITER;- return result.str();- };-- // E.g. (valid as of writing this): MODEL_PRIORITY="MEDIUM" -> MODEL_PRIORITY="MODEL_PRIORITY_MED"- content = std::regex_replace(content,- getTargetRegex(ov::hint::Priority::LOW),- getStringReplacement(ov::intel_npu::LegacyPriority::LOW));- content = std::regex_replace(content,- getTargetRegex(ov::hint::Priority::MEDIUM),- getStringReplacement(ov::intel_npu::LegacyPriority::MEDIUM));- content = std::regex_replace(content,- getTargetRegex(ov::hint::Priority::HIGH),- getStringReplacement(ov::intel_npu::LegacyPriority::HIGH));- }-- // Special case for compiler Turbo- // NPU_TURBO is a special option in the sense that by default it is a driver-setting, but certain compilers support- // and make use of it too If we have turbo in the config string, we check if compiler supports it. If it doesn't- // support it, we remove it- if (std::regex_search(content, std::regex("NPU_TURBO"))) {- bool is_supported = _zeGraphExt->isTurboOptionSupported(compilerVersion);-- if (!is_supported) {- std::ostringstream turbostr;- turbostr << ov::intel_npu::turbo.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"- << VALUE_DELIMITER;- logger.info("NPU_TURBO property is not supported by this compiler. Removing from "- "parameters");- content = std::regex_replace(content, std::regex(turbostr.str()), "");- }- }-- // FINAL step to convert prefixes of remaining params, to ensure backwards compatibility- // From 5.0.0, driver compiler start to use NPU_ prefix, the old version uses VPU_ prefix- if (compilerVersion.major < 5) {- std::regex reg("NPU_");- content = std::regex_replace(content, reg, "VPU_");- // From 4.0.0, driver compiler start to use VPU_ prefix, the old version uses VPUX_ prefix- if (compilerVersion.major < 4) {- // Replace VPU_ with VPUX_ for old driver compiler- std::regex reg("VPU_");- content = std::regex_replace(content, reg, "VPUX_");- }- }-- return "--config " + content;-}-std::vector<std::string> DriverCompilerAdapter::get_supported_options() const {std::string compilerOptionsStr;compilerOptionsStr = _zeGraphExt->getCompilerSupportedOptions();diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cppindex 5c0d82982c3..0d9866cc969 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/ir_serializer.cpp@@ -5,13 +5,139 @@#include "ir_serializer.hpp"#include <cstdint>-#include <istream>#include <mutex>-#include <streambuf>+#include <regex>+#include "custom_stream_buffer.hpp"+#include "intel_npu/common/filtered_config.hpp"+#include "intel_npu/config/options.hpp"+#include "openvino/pass/manager.hpp"#include "openvino/pass/serialize.hpp"#include "transformations/op_conversions/convert_interpolate11_downgrade.hpp"+namespace {+constexpr std::string_view INPUTS_PRECISIONS_KEY = "--inputs_precisions";+constexpr std::string_view INPUTS_LAYOUTS_KEY = "--inputs_layouts";+constexpr std::string_view OUTPUTS_PRECISIONS_KEY = "--outputs_precisions";+constexpr std::string_view OUTPUTS_LAYOUTS_KEY = "--outputs_layouts";++// <option key>="<option value>"+constexpr std::string_view KEY_VALUE_SEPARATOR = "=";+constexpr std::string_view VALUE_DELIMITER = "\""; // marks beginning and end of value++// Format inside "<option value>"+// <name1>:<value (precision / layout)> [<name2>:<value>]+constexpr std::string_view NAME_VALUE_SEPARATOR = ":";+constexpr std::string_view VALUES_SEPARATOR = " ";++// Constants indicating the order indices needed to be applied as to perform conversions between legacy layout values+const std::vector<size_t> NC_TO_CN_LAYOUT_DIMENSIONS_ORDER = {1, 0};+const std::vector<size_t> NCHW_TO_NHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 1};+const std::vector<size_t> NCDHW_TO_NDHWC_LAYOUT_DIMENSIONS_ORDER = {0, 2, 3, 4, 1};++/**+ * @brief A standard copy function concerning memory segments. Additional checks on the given arguments are performed+ * before copying.+ * @details This is meant as a replacement for the legacy "ie_memcpy" function coming from the OpenVINO API.+ */+void checkedMemcpy(void* destination, size_t destinationSize, const void* source, size_t numberOfBytes) {+ if (numberOfBytes == 0) {+ return;+ }++ OPENVINO_ASSERT(destination != nullptr, "Memcpy: received a null destination address");+ OPENVINO_ASSERT(source != nullptr, "Memcpy: received a null source address");+ OPENVINO_ASSERT(numberOfBytes <= destinationSize,+ "Memcpy: the source buffer does not fit inside the destination one");+ OPENVINO_ASSERT(numberOfBytes <= (destination > source ? ((uintptr_t)destination - (uintptr_t)source)+ : ((uintptr_t)source - (uintptr_t)destination)),+ "Memcpy: the offset between the two buffers does not allow a safe execution of the operation");++ memcpy(destination, source, numberOfBytes);+}++/**+ * @brief For driver backward compatibility reasons, the given value shall be converted to a string corresponding to the+ * adequate legacy precision.+ */+std::string ovPrecisionToLegacyPrecisionString(const ov::element::Type& precision) {+ switch (precision) {+ case ov::element::Type_t::f16:+ return "FP16";+ case ov::element::Type_t::f32:+ return "FP32";+ case ov::element::Type_t::f64:+ return "FP64";+ case ov::element::Type_t::bf16:+ return "BF16";+ case ov::element::Type_t::f8e4m3:+ return "FP8_E4M3";+ case ov::element::Type_t::f8e5m2:+ return "FP8_E5M2";+ case ov::element::Type_t::f8e8m0:+ return "FP8_E8M0";+ case ov::element::Type_t::nf4:+ return "NF4";+ case ov::element::Type_t::i4:+ return "I4";+ case ov::element::Type_t::i8:+ return "I8";+ case ov::element::Type_t::i16:+ return "I16";+ case ov::element::Type_t::i32:+ return "I32";+ case ov::element::Type_t::i64:+ return "I64";+ case ov::element::Type_t::u4:+ return "U4";+ case ov::element::Type_t::u8:+ return "U8";+ case ov::element::Type_t::u16:+ return "U16";+ case ov::element::Type_t::u32:+ return "U32";+ case ov::element::Type_t::u64:+ return "U64";+ case ov::element::Type_t::u1:+ return "BIN";+ case ov::element::Type_t::u2:+ return "U2";+ case ov::element::Type_t::boolean:+ return "BOOL";+ case ov::element::Type_t::dynamic:+ return "DYNAMIC";+ default:+ OPENVINO_THROW("Incorrect precision: ", precision);+ }+}++/**+ * @brief Gives the string representation of the default legacy layout value corresponding to the given rank.+ * @details This is done in order to assure the backward compatibility with the driver. Giving a layout different from+ * the default one may lead either to error or to accuracy failures since unwanted transposition layers may be+ * introduced.+ */+std::string rankToLegacyLayoutString(const size_t rank) {+ switch (rank) {+ case 0:+ return "**SCALAR**";+ case 1:+ return "C";+ case 2:+ return "NC";+ case 3:+ return "CHW";+ case 4:+ return "NCHW";+ case 5:+ return "NCDHW";+ default:+ return "BLOCKED";+ }+}++} // namespace+namespace intel_npu::driver_compiler_utils {IRSerializer::IRSerializer(const std::shared_ptr<const ov::Model>& origModel, const uint32_t supportedOpset)@@ -101,4 +227,271 @@ void IRSerializer::serializeModelToBuffer(uint8_t* xml, uint8_t* weights) {_logger.debug("serializeModelToBuffer end");}+SerializedIR IRSerializer::serializeIR(const std::shared_ptr<const ov::Model>& model,+ ze_graph_compiler_version_info_t compilerVersion,+ const uint32_t supportedOpsetVersion) {+ // Contract between adapter and compiler in driver+ const uint32_t maxNumberOfElements = 10;+ const uint64_t maxSizeOfXML = std::numeric_limits<uint64_t>::max() / 3;+ const uint64_t maxSizeOfWeights = maxSizeOfXML * 2;++ const uint32_t numberOfInputData = 2;+ const uint64_t xmlSize = static_cast<uint64_t>(getXmlSize());+ const uint64_t weightsSize = static_cast<uint64_t>(getWeightsSize());++ OPENVINO_ASSERT(numberOfInputData < maxNumberOfElements);+ if (xmlSize >= maxSizeOfXML) {+ OPENVINO_THROW("Xml file is too big to process. xmlSize: ", xmlSize, " >= maxSizeOfXML: ", maxSizeOfXML);+ }+ if (weightsSize >= maxSizeOfWeights) {+ OPENVINO_THROW("Bin file is too big to process. xmlSize: ",+ weightsSize,+ " >= maxSizeOfWeights: ",+ maxSizeOfWeights);+ }++ const uint64_t sizeOfSerializedIR = sizeof(compilerVersion) + sizeof(numberOfInputData) + sizeof(xmlSize) ++ xmlSize + sizeof(weightsSize) + weightsSize;++ // use array to avoid vector's memory zeroing overhead+ std::shared_ptr<uint8_t> buffer(new uint8_t[sizeOfSerializedIR], std::default_delete<uint8_t[]>());+ uint8_t* serializedIR = buffer.get();++ uint64_t offset = 0;+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &compilerVersion, sizeof(compilerVersion));+ offset += sizeof(compilerVersion);++ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &numberOfInputData, sizeof(numberOfInputData));+ offset += sizeof(numberOfInputData);+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &xmlSize, sizeof(xmlSize));+ offset += sizeof(xmlSize);+ // xml data is filled in serializeModel()+ uint64_t xmlOffset = offset;+ offset += xmlSize;+ checkedMemcpy(serializedIR + offset, sizeOfSerializedIR - offset, &weightsSize, sizeof(weightsSize));+ offset += sizeof(weightsSize);+ // weights data is filled in serializeModel()+ uint64_t weightsOffset = offset;+ offset += weightsSize;++ serializeModelToBuffer(serializedIR + xmlOffset, serializedIR + weightsOffset);++ OPENVINO_ASSERT(offset == sizeOfSerializedIR);++ return std::make_pair(sizeOfSerializedIR, buffer);+}++std::string IRSerializer::serializeIOInfo(const std::shared_ptr<const ov::Model>& model, const bool useIndices) {+ const ov::ParameterVector& parameters = model->get_parameters();+ const ov::ResultVector& results = model->get_results();++ std::stringstream inputsPrecisionSS;+ std::stringstream inputsLayoutSS;+ std::stringstream outputsPrecisionSS;+ std::stringstream outputsLayoutSS;++ inputsPrecisionSS << INPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;+ inputsLayoutSS << INPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;+ const auto getRankOrThrow = [](const ov::PartialShape& shape) -> size_t {+ if (shape.rank().is_dynamic()) {+ OPENVINO_THROW("Dynamic rank is not supported for NPU plugin");+ }+ return shape.rank().get_length();+ };++ if (!parameters.empty()) {+ size_t parameterIndex = 0;++ for (const std::shared_ptr<ov::op::v0::Parameter>& parameter : parameters) {+ const auto precision = parameter->get_element_type();+ const auto rank = getRankOrThrow(parameter->get_partial_shape());++ if (parameterIndex != 0) {+ inputsPrecisionSS << VALUES_SEPARATOR;+ inputsLayoutSS << VALUES_SEPARATOR;+ }++ if (useIndices) {+ inputsPrecisionSS << parameterIndex;+ inputsLayoutSS << parameterIndex;+ } else {+ const std::string& name = parameter->get_friendly_name();++ inputsPrecisionSS << name;+ // Ticket: E-88902+ inputsLayoutSS << name;+ }++ inputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);+ inputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);++ ++parameterIndex;+ }+ }++ inputsPrecisionSS << VALUE_DELIMITER;+ inputsLayoutSS << VALUE_DELIMITER;++ outputsPrecisionSS << OUTPUTS_PRECISIONS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;+ outputsLayoutSS << OUTPUTS_LAYOUTS_KEY << KEY_VALUE_SEPARATOR << VALUE_DELIMITER;++ size_t resultIndex = 0;+ for (const std::shared_ptr<ov::op::v0::Result>& result : results) {+ const auto precision = result->get_element_type();+ const auto rank = getRankOrThrow(result->get_output_partial_shape(0));++ if (resultIndex != 0) {+ outputsPrecisionSS << VALUES_SEPARATOR;+ outputsLayoutSS << VALUES_SEPARATOR;+ }++ if (useIndices) {+ outputsPrecisionSS << resultIndex;+ outputsLayoutSS << resultIndex;+ } else {+ const std::string& name = result->get_input_node_ptr(0)->get_friendly_name();++ outputsPrecisionSS << name;+ outputsLayoutSS << name;+ }++ outputsPrecisionSS << NAME_VALUE_SEPARATOR << ovPrecisionToLegacyPrecisionString(precision);+ outputsLayoutSS << NAME_VALUE_SEPARATOR << rankToLegacyLayoutString(rank);++ ++resultIndex;+ }++ outputsPrecisionSS << VALUE_DELIMITER;+ outputsLayoutSS << VALUE_DELIMITER;++ // One line without spaces to avoid parsing as config option inside CID+ return inputsPrecisionSS.str() + VALUES_SEPARATOR.data() + inputsLayoutSS.str() + VALUES_SEPARATOR.data() ++ outputsPrecisionSS.str() + VALUES_SEPARATOR.data() + outputsLayoutSS.str();+}++std::string IRSerializer::serializeConfig(const Config& config,+ ze_graph_compiler_version_info_t compilerVersion,+ bool turboSupported) {+ Logger logger("serializeConfig", Logger::global().level());++ std::string content = {};++ const FilteredConfig* plgConfig = dynamic_cast<const FilteredConfig*>(&config);+ if (plgConfig != nullptr) {+ content += plgConfig->toStringForCompiler();+ content += plgConfig->toStringForCompilerInternal();+ } else {+ logger.warning("Failed to cast Config to FilteredConfig. Exporting all configs");+ content += config.toString();+ }++ logger.debug("Original content of config: %s", content.c_str());++ // Remove optimization-level and performance-hint-override for old driver which not support them+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 7)) {+ std::string valueOfParams = config.get<COMPILATION_MODE_PARAMS>();+ std::string keyOfOptL("optimization-level");+ std::string keyOfPerfHO("performance-hint-override");+ if (valueOfParams != "" && (valueOfParams.find(keyOfOptL) != std::string::npos ||+ valueOfParams.find(keyOfPerfHO) != std::string::npos)) {+ // Remove unsupported options from value+ std::ostringstream optLevelStr;+ optLevelStr << keyOfOptL << KEY_VALUE_SEPARATOR << "\\d+";+ std::ostringstream perfHintStr;+ perfHintStr << keyOfPerfHO << KEY_VALUE_SEPARATOR << "\\S+";+ logger.warning("%s property is not supported by this compiler version. Removing from parameters",+ keyOfOptL.c_str());+ valueOfParams = std::regex_replace(valueOfParams, std::regex(optLevelStr.str()), "");+ logger.warning("%s property is not supported by this compiler version. Removing from parameters",+ keyOfPerfHO.c_str());+ valueOfParams = std::regex_replace(valueOfParams, std::regex(perfHintStr.str()), "");++ // Trim space+ valueOfParams = std::regex_replace(valueOfParams, std::regex(R"(^\s+|\s+$)"), "");++ // Replace the value in content with new value+ std::ostringstream compilationParamsStr;+ compilationParamsStr << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR+ << VALUE_DELIMITER << ".*" << VALUE_DELIMITER;+ if (valueOfParams == "") {+ logger.warning("Clear empty NPU_COMPILATION_MODE_PARAMS. Removing from parameters");+ content = std::regex_replace(content, std::regex(compilationParamsStr.str()), "");+ } else {+ std::ostringstream newValue;+ newValue << ov::intel_npu::compilation_mode_params.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER+ << valueOfParams << VALUE_DELIMITER;+ logger.warning("Replace value of NPU_COMPILATION_MODE_PARAMS with new value %s",+ newValue.str().c_str());+ content = std::regex_replace(content, std::regex(compilationParamsStr.str()), newValue.str().c_str());+ }+ }+ }++ // As a consequence of complying to the conventions established in the 2.0 OV API, the set of values corresponding+ // to the "model priority" key has been modified cpu_pinning property is not supported in compilers < v5.2 - need to+ // remove it+ if ((compilerVersion.major < 5) || (compilerVersion.major == 5 && compilerVersion.minor < 2)) {+ const auto& getTargetRegex = [](const ov::hint::Priority& priorityValue) -> std::regex {+ std::ostringstream result;+ result << ov::hint::model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << priorityValue+ << VALUE_DELIMITER;+ return std::regex(result.str());+ };+ const auto& getStringReplacement = [](const ov::intel_npu::LegacyPriority& priorityValue) -> std::string {+ std::ostringstream result;+ result << ov::intel_npu::legacy_model_priority.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER+ << priorityValue << VALUE_DELIMITER;+ return result.str();+ };++ // E.g. (valid as of writing this): MODEL_PRIORITY="MEDIUM" -> MODEL_PRIORITY="MODEL_PRIORITY_MED"+ content = std::regex_replace(content,+ getTargetRegex(ov::hint::Priority::LOW),+ getStringReplacement(ov::intel_npu::LegacyPriority::LOW));+ content = std::regex_replace(content,+ getTargetRegex(ov::hint::Priority::MEDIUM),+ getStringReplacement(ov::intel_npu::LegacyPriority::MEDIUM));+ content = std::regex_replace(content,+ getTargetRegex(ov::hint::Priority::HIGH),+ getStringReplacement(ov::intel_npu::LegacyPriority::HIGH));+ }++ // Special case for compiler Turbo+ // NPU_TURBO is a special option in the sense that by default it is a driver-setting, but certain compilers support+ // and make use of it too If we have turbo in the config string, we check if compiler supports it. If it doesn't+ // support it, we remove it+ if (std::regex_search(content, std::regex("NPU_TURBO"))) {+ bool is_supported = false;+ try {+ is_supported = turboSupported;+ } catch (...) {+ // mute it, not critical+ is_supported = false;+ }+ if (!is_supported) {+ std::ostringstream turbostr;+ turbostr << ov::intel_npu::turbo.name() << KEY_VALUE_SEPARATOR << VALUE_DELIMITER << "\\S+"+ << VALUE_DELIMITER;+ logger.info("NPU_TURBO property is not supported by this compiler. Removing from "+ "parameters");+ content = std::regex_replace(content, std::regex(turbostr.str()), "");+ }+ }++ // FINAL step to convert prefixes of remaining params, to ensure backwards compatibility+ // From 5.0.0, driver compiler start to use NPU_ prefix, the old version uses VPU_ prefix+ if (compilerVersion.major < 5) {+ std::regex reg("NPU_");+ content = std::regex_replace(content, reg, "VPU_");+ // From 4.0.0, driver compiler start to use VPU_ prefix, the old version uses VPUX_ prefix+ if (compilerVersion.major < 4) {+ // Replace VPU_ with VPUX_ for old driver compiler+ std::regex reg("VPU_");+ content = std::regex_replace(content, reg, "VPUX_");+ }+ }++ return "--config " + content;+}+} // namespace intel_npu::driver_compiler_utilsdiff --git a/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cppindex 87705a9f915..f4918614987 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/ze_graph_ext_wrappers.cpp@@ -6,10 +6,8 @@#include <ze_mem_import_system_memory_ext.h>-#include <regex>#include <string_view>-#include "intel_npu/config/options.hpp"#include "intel_npu/prefix.hpp"#include "intel_npu/utils/utils.hpp"#include "intel_npu/utils/zero/zero_api.hpp"@@ -17,7 +15,6 @@#include "intel_npu/utils/zero/zero_utils.hpp"#include "intel_npu/utils/zero/zero_wrappers.hpp"#include "openvino/core/dimension.hpp"-#include "openvino/core/model.hpp"#include "openvino/core/partial_shape.hpp"// A bug inside the driver makes the "pfnGraphGetArgumentMetadata" call not safe for use prior to@@ -210,7 +207,7 @@ std::unordered_set<std::string> ZeGraphExtWrappers::getQueryResultFromSupportedLreturn parseQueryResult(supportedLayers);}-std::unordered_set<std::string> ZeGraphExtWrappers::queryGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,+std::unordered_set<std::string> ZeGraphExtWrappers::queryGraph(SerializedIR serializedIR,const std::string& buildFlags) const {// For ext version >= 1.5ze_graph_query_network_handle_t hGraphQueryNetwork = nullptr;@@ -258,7 +255,7 @@ bool ZeGraphExtWrappers::canCpuVaBeImported(void* data, size_t size, const uint3return true;}-GraphDescriptor ZeGraphExtWrappers::getGraphDescriptor(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,+GraphDescriptor ZeGraphExtWrappers::getGraphDescriptor(SerializedIR serializedIR,const std::string& buildFlags,const uint32_t& flags) const {// For ext version >= 1.5, calling pfnCreate2 api in _zeroInitStruct->getGraphDdiTable()