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] Weights separation: reduce the size of the compiled model blob by removing most weights from it (#27084)
Razvan Apetroaiec4b92873a3c9
diff --git a/src/inference/include/openvino/runtime/properties.hpp b/src/inference/include/openvino/runtime/properties.hppindex d125fc40cfc..d914532fd9f 100644--- a/src/inference/include/openvino/runtime/properties.hpp+++ b/src/inference/include/openvino/runtime/properties.hpp@@ -812,9 +812,9 @@ inline std::istream& operator>>(std::istream& is, CacheMode& mode) {/*** @brief Read-write property to select the cache mode between optimize_size and optimize_speed.- * If optimize_speed is selected(default), loading time will decrease but the cache file size will increase.+ * If optimize_speed is selected (default), loading time will decrease but the cache file size will increase.* If optimize_size is selected, smaller cache files will be created.- * This is only supported from GPU.+ * Only the GPU and NPU plugins support this for now.* @ingroup ov_runtime_cpp_prop_api*/static constexpr Property<CacheMode, PropertyMutability::RW> cache_mode{"CACHE_MODE"};diff --git a/src/plugins/intel_npu/README.md b/src/plugins/intel_npu/README.mdindex f719a295b0c..ecf95b4e753 100644--- a/src/plugins/intel_npu/README.md+++ b/src/plugins/intel_npu/README.md@@ -180,7 +180,8 @@ The following properties are supported (may differ based on current system confi| `ov::hint::model_priority`/</br>`MODEL_PRIORITY` | RW | Assigns a priority for the model execution. | `LOW`/</br>`MEDIUM`/</br>`HIGH` | `MEDIUM` || `ov::hint::enable_cpu_pinning`/</br>`ENABLE_CPU_PINNING` | RW | Allows CPU threads pinning during inference. | `YES`/ `NO` /</br>`NO`| `ov::log::level`/</br>`LOG_LEVEL` | RW | Sets the log level for NPU Plugin. An environment variable is also made available to expose logs from early initialization phase: OV_NPU_LOG_LEVEL. | `LOG_NONE`/</br>`LOG_ERROR`/</br>`LOG_WARNING`/</br>`LOG_INFO`/</br>`LOG_DEBUG`/</br>`LOG_TRACE` | `LOG_NONE` |-| `ov::cache_dir`/</br>`CACHE_DIR` | RW | Folder path to be used by the OpenVINO cache. | `N/A` | empty |+| `ov::cache_dir`/</br>`CACHE_DIR` | RW | Folder path to be used by the OpenVINO cache. | Any string pointing towards a valid directory path | empty |+| `ov::cache_mode`/</br>`CACHE_MODE` | RW | If `CACHE_DIR` has been set, then this option indicates whether or not the size of the compiled model binary object will be reduced by decoupling a portion of the weights. | `OPTIMIZE_SIZE` /</br>`OPTIMIZE_SPEED` | `OPTIMIZE_SPEED` || `ov::available_devices`/</br>`AVAILABLE_DEVICES` | RO | Returns the list of enumerated NPU devices. </br> NPU plugin does not currently support multiple devices. | `N/A`| `N/A` || `ov::device::id`/</br>`DEVICE_ID` | RW | Device identifier. Empty means auto detection. | empty/</br> `3720`/</br> `4000` | empty || `ov::device::uuid`/</br> | RO | Returns the Universal Unique ID of the NPU device. | `N/A`| `N/A` |diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hppindex b0c897cf3c1..f5a60124672 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp@@ -14,10 +14,6 @@namespace intel_npu {-//-// PERFORMANCE_HINT-//-struct PERFORMANCE_HINT final : OptionBase<PERFORMANCE_HINT, ov::hint::PerformanceMode> {static std::string_view key() {return ov::hint::performance_mode.name();@@ -77,9 +73,6 @@ struct PERFORMANCE_HINT final : OptionBase<PERFORMANCE_HINT, ov::hint::Performan}};-// PERFORMANCE_HINT_NUM_REQUESTS-//-struct PERFORMANCE_HINT_NUM_REQUESTS final : OptionBase<PERFORMANCE_HINT_NUM_REQUESTS, uint32_t> {static std::string_view key() {return ov::hint::num_requests.name();@@ -128,10 +121,6 @@ struct PERFORMANCE_HINT_NUM_REQUESTS final : OptionBase<PERFORMANCE_HINT_NUM_REQ}};-//-// INFERENCE_PRECISION_HINT-//-struct INFERENCE_PRECISION_HINT final : OptionBase<INFERENCE_PRECISION_HINT, ov::element::Type> {static std::string_view key() {return ov::hint::inference_precision.name();@@ -176,10 +165,6 @@ struct INFERENCE_PRECISION_HINT final : OptionBase<INFERENCE_PRECISION_HINT, ov:};};-//-// PERF_COUNT-//-struct PERF_COUNT final : OptionBase<PERF_COUNT, bool> {static std::string_view key() {return ov::enable_profiling.name();@@ -202,10 +187,6 @@ struct PERF_COUNT final : OptionBase<PERF_COUNT, bool> {}};-//-// LOG_LEVEL-//-struct LOG_LEVEL final : OptionBase<LOG_LEVEL, ov::log::Level> {static std::string_view key() {return ov::log::level.name();@@ -236,10 +217,6 @@ struct LOG_LEVEL final : OptionBase<LOG_LEVEL, ov::log::Level> {}};-//-// PLATFORM-//-struct PLATFORM final : OptionBase<PLATFORM, std::string> {static std::string_view key() {return ov::intel_npu::platform.name();@@ -268,10 +245,6 @@ struct PLATFORM final : OptionBase<PLATFORM, std::string> {}};-//-// DEVICE_ID-//-struct DEVICE_ID final : OptionBase<DEVICE_ID, std::string> {static std::string_view key() {return ov::device::id.name();@@ -294,10 +267,6 @@ struct DEVICE_ID final : OptionBase<DEVICE_ID, std::string> {}};-//-// CACHE_DIR-//-struct CACHE_DIR final : OptionBase<CACHE_DIR, std::string> {static std::string_view key() {return ov::cache_dir.name();@@ -320,9 +289,80 @@ struct CACHE_DIR final : OptionBase<CACHE_DIR, std::string> {}};-//-// LOADED_FROM_CACHE-//+struct CACHE_MODE final : OptionBase<CACHE_MODE, ov::CacheMode> {+ static std::string_view key() {+ return ov::cache_mode.name();+ }++ static constexpr std::string_view getTypeName() {+ return "ov::CacheMode";+ }++ static ov::CacheMode defaultValue() {+ return ov::CacheMode::OPTIMIZE_SPEED;+ }++ static bool isPublic() {+ return true;+ }++ static ov::PropertyMutability mutability() {+ return ov::PropertyMutability::RW;+ }++ static OptionMode mode() {+ return OptionMode::CompileTime;+ }++ static uint32_t compilerSupportVersion() {+ return ONEAPI_MAKE_VERSION(7, 21);+ }++ static ov::CacheMode parse(std::string_view val) {+ std::istringstream stringStream = std::istringstream(std::string(val));+ ov::CacheMode cacheMode;+ stringStream >> cacheMode;+ return cacheMode;+ }++ static std::string toString(const ov::CacheMode& val) {+ std::stringstream strStream;+ strStream << val;+ return strStream.str();+ }+};++struct COMPILED_BLOB final : OptionBase<COMPILED_BLOB, ov::Tensor> {+ static std::string_view key() {+ return ov::hint::compiled_blob.name();+ }++ static constexpr std::string_view getTypeName() {+ return "ov::Tensor";+ }++ static ov::Tensor defaultValue() {+ return ov::Tensor();+ }++ static ov::PropertyMutability mutability() {+ return ov::PropertyMutability::RW;+ }++ static OptionMode mode() {+ return OptionMode::RunTime;+ }++ static ov::Tensor parse(std::string_view) {+ // Cannot/shouldn't parse this due to conversion and ownership reasons. The config option is added only to+ // comply with the OV API without inserting multiple workarounds.+ return defaultValue();+ }++ static std::string toString(const ov::Tensor&) {+ return "";+ }+};struct LOADED_FROM_CACHE final : OptionBase<LOADED_FROM_CACHE, bool> {static std::string_view key() {@@ -342,10 +382,6 @@ struct LOADED_FROM_CACHE final : OptionBase<LOADED_FROM_CACHE, bool> {}};-//-// CACHING PROPERTIES-//-struct CACHING_PROPERTIES final : OptionBase<CACHING_PROPERTIES, std::string> {static std::string_view key() {return ov::internal::caching_properties.name();@@ -364,10 +400,6 @@ struct CACHING_PROPERTIES final : OptionBase<CACHING_PROPERTIES, std::string> {}};-//-// INTERNAL SUPPORTED PROPERTIES-//-struct INTERNAL_SUPPORTED_PROPERTIES final : OptionBase<INTERNAL_SUPPORTED_PROPERTIES, std::string> {static std::string_view key() {return ov::internal::supported_properties.name();@@ -386,9 +418,6 @@ struct INTERNAL_SUPPORTED_PROPERTIES final : OptionBase<INTERNAL_SUPPORTED_PROPE}};-//-// BATCH_MODE-//struct BATCH_MODE final : OptionBase<BATCH_MODE, ov::intel_npu::BatchMode> {static std::string_view key() {return ov::intel_npu::batch_mode.name();@@ -435,10 +464,6 @@ struct BATCH_MODE final : OptionBase<BATCH_MODE, ov::intel_npu::BatchMode> {}};-//-// EXCLUSIVE_ASYNC_REQUESTS-//-struct EXCLUSIVE_ASYNC_REQUESTS final : OptionBase<EXCLUSIVE_ASYNC_REQUESTS, bool> {static std::string_view key() {return ov::internal::exclusive_async_requests.name();@@ -465,9 +490,6 @@ struct EXCLUSIVE_ASYNC_REQUESTS final : OptionBase<EXCLUSIVE_ASYNC_REQUESTS, boo}};-///-/// PROFILING TYPE-///struct PROFILING_TYPE final : OptionBase<PROFILING_TYPE, ov::intel_npu::ProfilingType> {static std::string_view key() {return ov::intel_npu::profiling_type.name();@@ -517,10 +539,6 @@ struct PROFILING_TYPE final : OptionBase<PROFILING_TYPE, ov::intel_npu::Profilin}};-//-// MODEL_PRIORITY-//-struct MODEL_PRIORITY final : OptionBase<MODEL_PRIORITY, ov::hint::Priority> {static std::string_view key() {return ov::hint::model_priority.name();@@ -564,10 +582,6 @@ struct MODEL_PRIORITY final : OptionBase<MODEL_PRIORITY, ov::hint::Priority> {}};-//-// CREATE_EXECUTOR-//-struct CREATE_EXECUTOR final : OptionBase<CREATE_EXECUTOR, int64_t> {static std::string_view key() {return ov::intel_npu::create_executor.name();@@ -596,9 +610,6 @@ struct CREATE_EXECUTOR final : OptionBase<CREATE_EXECUTOR, int64_t> {}};-//-// DEFER_WEIGHTS_LOAD-//struct DEFER_WEIGHTS_LOAD final : OptionBase<DEFER_WEIGHTS_LOAD, bool> {static std::string_view key() {return ov::intel_npu::defer_weights_load.name();@@ -622,9 +633,6 @@ struct DEFER_WEIGHTS_LOAD final : OptionBase<DEFER_WEIGHTS_LOAD, bool> {}};-//-// WEIGHTS_PATH-//struct WEIGHTS_PATH final : OptionBase<WEIGHTS_PATH, std::string> {static std::string_view key() {return ov::weights_path.name();@@ -651,9 +659,6 @@ struct WEIGHTS_PATH final : OptionBase<WEIGHTS_PATH, std::string> {}};-//-// NUM_STREAMS-//struct NUM_STREAMS final : OptionBase<NUM_STREAMS, ov::streams::Num> {static std::string_view key() {return ov::num_streams.name();@@ -705,9 +710,6 @@ struct NUM_STREAMS final : OptionBase<NUM_STREAMS, ov::streams::Num> {}};-//-// ENABLE_CPU_PINNING-//struct ENABLE_CPU_PINNING final : OptionBase<ENABLE_CPU_PINNING, bool> {static std::string_view key() {return ov::hint::enable_cpu_pinning.name();@@ -730,10 +732,6 @@ struct ENABLE_CPU_PINNING final : OptionBase<ENABLE_CPU_PINNING, bool> {}};-//-// WORKLOAD_TYPE-//-struct WORKLOAD_TYPE final : OptionBase<WORKLOAD_TYPE, ov::WorkloadType> {static std::string_view key() {return ov::workload_type.name();@@ -775,9 +773,6 @@ struct WORKLOAD_TYPE final : OptionBase<WORKLOAD_TYPE, ov::WorkloadType> {}};-//-// TURBO-//struct TURBO final : OptionBase<TURBO, bool> {static std::string_view key() {return ov::intel_npu::turbo.name();@@ -804,10 +799,6 @@ struct TURBO final : OptionBase<TURBO, bool> {}};-//-// COMPILER_TYPE-//-struct COMPILER_TYPE final : OptionBase<COMPILER_TYPE, ov::intel_npu::CompilerType> {static std::string_view key() {return ov::intel_npu::compiler_type.name();@@ -865,10 +856,6 @@ struct COMPILER_TYPE final : OptionBase<COMPILER_TYPE, ov::intel_npu::CompilerTy}};-//-// COMPILATION_MODE-//-struct COMPILATION_MODE final : OptionBase<COMPILATION_MODE, std::string> {static std::string_view key() {return ov::intel_npu::compilation_mode.name();@@ -897,10 +884,6 @@ struct COMPILATION_MODE final : OptionBase<COMPILATION_MODE, std::string> {}};-//-// EXECUTION_MODE_HINT-//-struct EXECUTION_MODE_HINT final : OptionBase<EXECUTION_MODE_HINT, ov::hint::ExecutionMode> {static std::string_view key() {return ov::hint::execution_mode.name();@@ -931,10 +914,6 @@ struct EXECUTION_MODE_HINT final : OptionBase<EXECUTION_MODE_HINT, ov::hint::Exe}};-//-// DYNAMIC_SHAPE_TO_STATIC-//-struct DYNAMIC_SHAPE_TO_STATIC final : OptionBase<DYNAMIC_SHAPE_TO_STATIC, bool> {static std::string_view key() {return ov::intel_npu::dynamic_shape_to_static.name();@@ -963,10 +942,6 @@ struct DYNAMIC_SHAPE_TO_STATIC final : OptionBase<DYNAMIC_SHAPE_TO_STATIC, bool>}};-//-// COMPILATION_MODE_PARAMS-//-struct COMPILATION_MODE_PARAMS final : OptionBase<COMPILATION_MODE_PARAMS, std::string> {static std::string_view key() {return ov::intel_npu::compilation_mode_params.name();@@ -989,10 +964,6 @@ struct COMPILATION_MODE_PARAMS final : OptionBase<COMPILATION_MODE_PARAMS, std::}};-//-// TILES-//-struct TILES final : OptionBase<TILES, int64_t> {static std::string_view key() {return ov::intel_npu::tiles.name();@@ -1029,10 +1000,6 @@ struct TILES final : OptionBase<TILES, int64_t> {#endif};-//-// STEPPING-//-struct STEPPING final : OptionBase<STEPPING, int64_t> {static std::string_view key() {return ov::intel_npu::stepping.name();@@ -1063,10 +1030,6 @@ struct STEPPING final : OptionBase<STEPPING, int64_t> {}};-//-// MAX_TILES-//-struct MAX_TILES final : OptionBase<MAX_TILES, int64_t> {static std::string_view key() {return ov::intel_npu::max_tiles.name();@@ -1097,10 +1060,6 @@ struct MAX_TILES final : OptionBase<MAX_TILES, int64_t> {}};-//-// DMA_ENGINES-//-struct DMA_ENGINES final : OptionBase<DMA_ENGINES, int64_t> {static std::string_view key() {return ov::intel_npu::dma_engines.name();@@ -1133,10 +1092,6 @@ struct DMA_ENGINES final : OptionBase<DMA_ENGINES, int64_t> {#endif};-//-// BACKEND_COMPILATION_PARAMS-//-struct BACKEND_COMPILATION_PARAMS final : OptionBase<BACKEND_COMPILATION_PARAMS, std::string> {static std::string_view key() {return ov::intel_npu::backend_compilation_params.name();@@ -1159,10 +1114,6 @@ struct BACKEND_COMPILATION_PARAMS final : OptionBase<BACKEND_COMPILATION_PARAMS,}};-//-// COMPILATION_NUM_THREADS-//-struct COMPILATION_NUM_THREADS final : OptionBase<COMPILATION_NUM_THREADS, int32_t> {static std::string_view key() {return ov::compilation_num_threads.name();@@ -1191,10 +1142,6 @@ struct COMPILATION_NUM_THREADS final : OptionBase<COMPILATION_NUM_THREADS, int32}};-//-// NPU_COMPILER_DYNAMIC_QUANTIZATION-//-struct COMPILER_DYNAMIC_QUANTIZATION final : OptionBase<COMPILER_DYNAMIC_QUANTIZATION, bool> {static std::string_view key() {return ov::intel_npu::compiler_dynamic_quantization.name();@@ -1217,9 +1164,6 @@ struct COMPILER_DYNAMIC_QUANTIZATION final : OptionBase<COMPILER_DYNAMIC_QUANTIZ}};-//-// BYPASS_UMD_CACHING-//struct BYPASS_UMD_CACHING final : OptionBase<BYPASS_UMD_CACHING, bool> {static std::string_view key() {return ov::intel_npu::bypass_umd_caching.name();@@ -1242,9 +1186,6 @@ struct BYPASS_UMD_CACHING final : OptionBase<BYPASS_UMD_CACHING, bool> {}};-//-// RUN_INFERENCES_SEQUENTIALLY-//struct RUN_INFERENCES_SEQUENTIALLY final : OptionBase<RUN_INFERENCES_SEQUENTIALLY, bool> {static std::string_view key() {return ov::intel_npu::run_inferences_sequentially.name();@@ -1263,10 +1204,6 @@ struct RUN_INFERENCES_SEQUENTIALLY final : OptionBase<RUN_INFERENCES_SEQUENTIALL}};-//-// NPU_QDQ_OPTIMIZATION-//-struct QDQ_OPTIMIZATION final : OptionBase<QDQ_OPTIMIZATION, bool> {static std::string_view key() {return ov::intel_npu::qdq_optimization.name();@@ -1289,10 +1226,6 @@ struct QDQ_OPTIMIZATION final : OptionBase<QDQ_OPTIMIZATION, bool> {}};-//-// DISABLE_VERSION_CHECK-//-struct DISABLE_VERSION_CHECK final : OptionBase<DISABLE_VERSION_CHECK, bool> {static std::string_view key() {return ov::intel_npu::disable_version_check.name();@@ -1313,10 +1246,6 @@ struct DISABLE_VERSION_CHECK final : OptionBase<DISABLE_VERSION_CHECK, bool> {}};-//-// BATCH_COMPILER_MODE_SETTINGS-//-struct BATCH_COMPILER_MODE_SETTINGS final : OptionBase<BATCH_COMPILER_MODE_SETTINGS, std::string> {static std::string_view key() {return ov::intel_npu::batch_compiler_mode_settings.name();@@ -1339,9 +1268,6 @@ struct BATCH_COMPILER_MODE_SETTINGS final : OptionBase<BATCH_COMPILER_MODE_SETTI}};-//-// MODEL_PTR-//struct MODEL_PTR final : OptionBase<MODEL_PTR, std::shared_ptr<const ov::Model>> {static std::string_view key() {return ov::hint::model.name();@@ -1356,7 +1282,9 @@ struct MODEL_PTR final : OptionBase<MODEL_PTR, std::shared_ptr<const ov::Model>>}static std::shared_ptr<const ov::Model> parse(std::string_view) {- return nullptr;+ // Cannot/shouldn't parse this due to conversion and ownership reasons. The config option is added only to+ // comply with the OV API without inserting multiple workarounds.+ return defaultValue();}static std::string toString(const std::shared_ptr<const ov::Model>& /* unused m*/) {return "";@@ -1375,4 +1303,85 @@ struct MODEL_PTR final : OptionBase<MODEL_PTR, std::shared_ptr<const ov::Model>>}};+struct WEIGHTLESS_BLOB final : OptionBase<WEIGHTLESS_BLOB, bool> {+ static std::string_view key() {+ return ov::intel_npu::weightless_blob.name();+ }++ static bool defaultValue() {+ return false;+ }++ static OptionMode mode() {+ return OptionMode::CompileTime;+ }++ static uint32_t compilerSupportVersion() {+ return ONEAPI_MAKE_VERSION(7, 21);+ }+};++struct SEPARATE_WEIGHTS_VERSION final : OptionBase<SEPARATE_WEIGHTS_VERSION, ov::intel_npu::WSVersion> {+ static std::string_view key() {+ return ov::intel_npu::separate_weights_version.name();+ }++ static constexpr std::string_view getTypeName() {+ return "ov::intel_npu::WSVersion";+ }++ static ov::intel_npu::WSVersion defaultValue() {+ return ov::intel_npu::WSVersion::ITERATIVE;+ }++ static ov::intel_npu::WSVersion parse(std::string_view val) {+ std::istringstream stringStream = std::istringstream(std::string(val));+ ov::intel_npu::WSVersion wsVersion;+ stringStream >> wsVersion;+ return wsVersion;+ }++ static std::string toString(const ov::intel_npu::WSVersion& val) {+ std::stringstream strStream;+ strStream << val;+ return strStream.str();+ }++ static OptionMode mode() {+ return OptionMode::CompileTime;+ }+};++struct WS_COMPILE_CALL_NUMBER final : OptionBase<WS_COMPILE_CALL_NUMBER, uint32_t> {+ static std::string_view key() {+ return ov::intel_npu::ws_compile_call_number.name();+ }++ static uint32_t defaultValue() {+ return 0;+ }++ static uint32_t parse(std::string_view val) {+ int val_i = -1;+ try {+ val_i = std::stoi(val.data());+ if (val_i >= 0) {+ return val_i;+ } else {+ throw std::logic_error("wrong val");+ }+ } catch (const std::exception&) {+ OPENVINO_THROW("Wrong value of ",+ val.data(),+ " for property key ",+ ov::intel_npu::ws_compile_call_number.name(),+ ". Expected only positive integer numbers");+ }+ }++ static OptionMode mode() {+ return OptionMode::CompileTime;+ }+};+} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hppindex 5751eec3c54..bfb8a141be6 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/icompiler.hpp@@ -56,6 +56,33 @@ public:*/virtual NetworkDescription compile(const std::shared_ptr<const ov::Model>& model, const Config& config) const = 0;+ /**+ * @brief Compiles the model, weights separation enabled. All init schedules along with the main one are compiled in+ * the same scope.+ * @return A "NetworkDescription" object for each init schedule, followed by another one corresponding to the main+ * part.+ */+ virtual std::vector<std::shared_ptr<NetworkDescription>> compileWsOneShot(const std::shared_ptr<ov::Model>& model,+ const Config& config) const = 0;++ /**+ * @brief Sequential compilation of Init(s) and Main+ *+ * "Stateless compiler" approach+ * We want to get multiple Inits in the case of a large number of weights.+ * This allows us to build pipeline:+ * Allocate W1 -> Init1+ * Allocate W2 -> Init2+ * Allocate W3 -> Init2+ *+ * This is why there is an additional parameter callNumber:+ * Compiler should somehow understand wich Init(or Main) to return+ * Plugin does not know total numbers of Init schedules+ */+ virtual NetworkDescription compileWsIterative(const std::shared_ptr<ov::Model>& model,+ const Config& config,+ size_t callNumber) const = 0;+/*** @brief Returns information about supported layers of the network passed* @param model The model to be querieddiff --git a/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hppindex 4999ef7cf72..8d418e1f0b7 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/network_metadata.hpp@@ -64,6 +64,25 @@ struct IODescriptor {*/bool isShapeTensor = false;+ /**+ * @brief If "true", the current object describes an input for an init schedule (weights separation).+ */+ bool isInitInputWeights = false;++ /**+ * @brief If "true", the current object describes an output for an init schedule (weights separation).+ */+ bool isInitOutputWeights = false;++ /**+ * @brief If "true", the current object describes a weights input for the main schedule (weights separation).+ *+ * @details If weights separation is enabled, a significant amount of weights are cut off from the compiled model+ * and then corresponding placeholders are created as inputs. These inputs are meant to be obtained by running the+ * init schedule(s).+ */+ bool isMainInputWeights = false;+/*** @brief Points towards a related descriptor.* @details The related descriptors are defined by (state input, state output) or (dynamic tensor, shape tensor)diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hppindex 33cb6d49013..24da138b51f 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npu_private_properties.hpp@@ -150,6 +150,44 @@ inline std::ostream& operator<<(std::ostream& out, const BatchMode& fmt) {return out;}+/**+ * @brief [Only for NPU Plugin]+ * Default is "ITERATIVE".+ * Switches between different implementations of the "weights separation" feature.+ */+enum class WSVersion {+ ONE_SHOT = 0,+ ITERATIVE = 1,+};++inline std::ostream& operator<<(std::ostream& out, const WSVersion& wsVersion) {+ switch (wsVersion) {+ case WSVersion::ONE_SHOT: {+ out << "ONE_SHOT";+ } break;+ case WSVersion::ITERATIVE: {+ out << "ITERATIVE";+ } break;+ default: {+ OPENVINO_THROW("Unsupported value for the weights separation version:", wsVersion);+ }+ }+ return out;+}++inline std::istream& operator>>(std::istream& is, WSVersion& wsVersion) {+ std::string str;+ is >> str;+ if (str == "ONE_SHOT") {+ wsVersion = WSVersion::ONE_SHOT;+ } else if (str == "ITERATIVE") {+ wsVersion = WSVersion::ITERATIVE;+ } else {+ OPENVINO_THROW("Unsupported value for the weights separation version:", str);+ }+ return is;+}+/*** @brief [Only for NPU Plugin]* Type: string, default is MODEL.@@ -291,6 +329,34 @@ static constexpr ov::Property<ProfilingType> profiling_type{"NPU_PROFILING_TYPE"*/static constexpr ov::Property<BatchMode> batch_mode{"NPU_BATCH_MODE"};+/**+ * @brief [Experimental, only for NPU Plugin]+ * Type: enum. Default is "ITERATIVE".+ *+ * The value stored in this entry indicates which implementation of the "weights separation" feature will be used.+ * Note: NPU_COMPILER_TYPE = DRIVER & NPU_SEPARATE_WEIGHTS_VERSION = ONE_SHOT are not compatible.+ */+static constexpr ov::Property<WSVersion> separate_weights_version{"NPU_SEPARATE_WEIGHTS_VERSION"};++/**+ * @brief [Only for NPU Plugin]+ * Type: bool. Default is "false".+ *+ * This option enables/disables the "weights separation" feature. If enabled, the result of compilation will be a binary+ * object stripped of a significant amount of weights. Before running the model, these weights need to be provided by+ * external means.+ */+static constexpr ov::Property<bool> weightless_blob{"NPU_WEIGHTLESS_BLOB"};++/**+ * @brief [Experimental, only for NPU Plugin]+ * Type: integer.+ *+ * Used for communicating a state to the compiler when compiling a model using the compiler-in-driver interfaces. This+ * takes effect only when weights separation is enabled and "NPU_SEPARATE_WEIGHTS_VERSION" is set to "ITERATIVE".+ */+static constexpr ov::Property<uint32_t> ws_compile_call_number{"WS_COMPILE_CALL_NUMBER"};+/*** @brief [Only for NPU Plugin]* Type: String. Default is "".diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/prefix.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/prefix.hppindex 3bfc57bbc0e..4535c24a23a 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/prefix.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/prefix.hpp@@ -5,24 +5,43 @@#pragma once#include <string>+#include <string_view>namespace intel_npu {//-// Prefix for ReadValue and Assign operations in compiler.+// Prefixes used to identify special inputs/outputs//+constexpr std::string_view READVALUE_PREFIX = "vpux_ie_read_value_";constexpr std::string_view ASSIGN_PREFIX = "vpux_ie_assign_";constexpr std::string_view SHAPE_TENSOR_PREFIX = "vpux_ie_shape_";+constexpr std::string_view INIT_INPUT_WEIGHTS_PREFIX = "vpux_ow_";+constexpr std::string_view INIT_OUTPUT_WEIGHTS_PREFIX = "vpux_tw_";+constexpr std::string_view MAIN_INPUT_WEIGHTS_PREFIX = "vpux_tw_";++inline bool nameHasPrefix(std::string_view name, std::string_view prefix) {+ return !name.compare(0, prefix.length(), prefix);+}++inline bool isStateInputName(std::string_view name) {+ return nameHasPrefix(name, READVALUE_PREFIX);+}+inline bool isStateOutputName(std::string_view name) {+ return nameHasPrefix(name, ASSIGN_PREFIX);+}+inline bool isShapeTensorName(std::string_view name) {+ return nameHasPrefix(name, SHAPE_TENSOR_PREFIX);+}-inline bool isStateInputName(const std::string& name) {- return !name.compare(0, READVALUE_PREFIX.length(), READVALUE_PREFIX);+inline bool isInitInputWeightsName(std::string_view name) {+ return nameHasPrefix(name, INIT_INPUT_WEIGHTS_PREFIX);}-inline bool isStateOutputName(const std::string& name) {- return !name.compare(0, ASSIGN_PREFIX.length(), ASSIGN_PREFIX);+inline bool isInitOutputWeightsName(std::string_view name) {+ return nameHasPrefix(name, INIT_OUTPUT_WEIGHTS_PREFIX);}-inline bool isShapeTensorName(const std::string& name) {- return !name.compare(0, SHAPE_TENSOR_PREFIX.length(), SHAPE_TENSOR_PREFIX);+inline bool isMainInputWeightsName(std::string_view name) {+ return nameHasPrefix(name, MAIN_INPUT_WEIGHTS_PREFIX);}} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cppindex 645a4c9f8c6..1035018c2b4 100644--- a/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_infer_request.cpp@@ -36,6 +36,12 @@ void check_level_zero_attributes_match(const IODescriptor& ioDescriptor, const AzeDescriptorName = zeDescriptorName.substr(ASSIGN_PREFIX.length());} else if (isShapeTensorName(zeDescriptorName)) {zeDescriptorName = zeDescriptorName.substr(SHAPE_TENSOR_PREFIX.length());+ } else if (isInitInputWeightsName(zeDescriptorName)) {+ zeDescriptorName = zeDescriptorName.substr(INIT_INPUT_WEIGHTS_PREFIX.length());+ } else if (isInitOutputWeightsName(zeDescriptorName)) {+ zeDescriptorName = zeDescriptorName.substr(INIT_OUTPUT_WEIGHTS_PREFIX.length());+ } else if (isMainInputWeightsName(zeDescriptorName)) {+ zeDescriptorName = zeDescriptorName.substr(MAIN_INPUT_WEIGHTS_PREFIX.length());}OPENVINO_ASSERT(ioDescriptor.nameFromCompiler == zeDescriptorName,@@ -553,6 +559,10 @@ void ZeroInferRequest::infer_async() {size_t inputIndex = 0;for (const auto& userTensor : _userInputTensors) {const IODescriptor inputDescriptor = _metadata.inputs.at(inputIndex);++ OPENVINO_ASSERT(!inputDescriptor.isInitInputWeights,+ "This path should not be used for running inferences for the \"init\" model");+if (inputDescriptor.isShapeTensor) {OPENVINO_ASSERT(inputDescriptor.relatedDescriptorIndex.has_value(),"The link between the dynamic tensor and its shape tensor is missing, entry name: ",@@ -609,6 +619,11 @@ void ZeroInferRequest::infer_async() {continue;}+ if (inputDescriptor.isMainInputWeights) {+ // These values were set while running the "WeightlessGraph::init" method+ continue;+ }+auto userRemoteTensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(userTensor.at(SINGLE_TENSOR)._ptr);void* userBuffer =!userRemoteTensor ? userTensor.at(SINGLE_TENSOR)->data() : userRemoteTensor->get_original_memory();diff --git a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cppindex bbd1c844e25..af417821114 100644--- a/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp+++ b/src/plugins/intel_npu/src/backend/src/zero_pipeline.cpp@@ -81,6 +81,11 @@ Pipeline::Pipeline(const Config& config,for (size_t i = 0; i < _number_of_command_lists; i++) {size_t io_index = 0;for (const auto& desc : graph->get_input_descriptors()) {+ if (isMainInputWeightsName(desc.info.name)) {+ // These values were set while running the "WeightlessGraph::init" method+ continue;+ }+if (input_tensors.at(io_index).size() > 1) {void* data = nullptr;auto remote_tensor = std::dynamic_pointer_cast<ZeroRemoteTensor>(input_tensors.at(io_index).at(i));diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiler_adapter.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiler_adapter.hppindex 4c71d75f1e3..108e3baee99 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiler_adapter.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/icompiler_adapter.hpp@@ -12,7 +12,45 @@ class ICompilerAdapter {public:virtual std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model,const Config& config) const = 0;- virtual std::shared_ptr<IGraph> parse(ov::Tensor blob, bool blobAllocatedByPlugin, const Config& config) const = 0;++ /**+ * @brief Compiles the model, weights separation enabled.+ * @details The result of compilation will be a binary object that does not contain a significant portion of+ * weights. The binary object will include two types of schedules: weights initialization and the operations of the+ * main graph. In order to run inference on this weightless blob, the original weights will need to be provided as+ * inputs to the weights initialization schedule. Running this will output the processed weights, that can then be+ * fed to the main schedule and therefore enable it to run predictions.+ *+ * @param model The model that will be compiled.+ * @param config Will be passed to the compiler. Additionally, the "SEPARATE_WEIGHTS_VERSION" option will determine+ * which weights separation implementation will be used. See the weights separation specific methods within+ * "icompiler.hpp".+ * @return A "WeightlessGraph" type of object.+ */+ virtual std::shared_ptr<IGraph> compileWS(const std::shared_ptr<ov::Model>& model, const Config& config) const = 0;++ /**+ * @brief Parses the provided binary objects and returns a wrapper over the resulted L0 handles. The model may also+ * be loaded on the device depending on the provided configuration (if "NPU_DEFER_WEIGHTS_LOAD" is off).+ *+ * @param mainBlob The core binary object to be parsed and used to build the "Graph" object.+ * @param blobAllocatedByPlugin Information required for managing the memory region allocated for the compiled+ * model.+ * @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.+ * @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(+ ov::Tensor mainBlob,+ const bool blobAllocatedByPlugin,+ const Config& config,+ std::optional<std::vector<ov::Tensor>> initBlobs = std::nullopt,+ const std::optional<std::shared_ptr<const ov::Model>>& model = std::nullopt) const = 0;+virtual ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const = 0;virtual uint32_t get_version() const = 0;virtual std::vector<std::string> get_supported_options() const = 0;diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hppindex 61910a817ff..0d548ea015b 100644--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/igraph.hpp@@ -19,7 +19,15 @@ class IGraph : public std::enable_shared_from_this<IGraph> {public:IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob);- virtual size_t export_blob(std::ostream& stream) const = 0;+ /**+ * @brief Writes the compiled model along with some metadata to the provided stream. The content of the stream can+ * later be used for importing the model.+ *+ * @param stream Where the content is placed+ * @return A pair made of the size of the main binary object and an optional variable. The optional variable+ * constitues the size of each init binary object if weights separation is enabled.+ */+ virtual std::pair<uint64_t, std::optional<std::vector<uint64_t>>> export_blob(std::ostream& stream) const = 0;virtual std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,const Config& config) const = 0;diff --git a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp b/src/plugins/intel_npu/src/common/src/sync_infer_request.cppindex e8d27652083..7fc6af21836 100644--- a/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/common/src/sync_infer_request.cpp@@ -312,6 +312,11 @@ std::shared_ptr<ov::ITensor> SyncInferRequest::allocate_tensor(const IODescriptoconst bool isInput,const ov::Allocator& allocator,const std::optional<std::size_t> batchSize) const {+ if (descriptor.isMainInputWeights) {+ // These values were set while running the "WeightlessGraph::init" method+ return nullptr;+ }+check_network_precision(descriptor.precision);std::shared_ptr<ov::ITensor> tensor;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 9316a43e001..b58630217a4 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@@ -23,7 +23,14 @@ public:std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;- std::shared_ptr<IGraph> parse(ov::Tensor blob, bool blobAllocatedByPlugin, const Config& config) const override;+ std::shared_ptr<IGraph> compileWS(const std::shared_ptr<ov::Model>& model, const Config& config) const override;++ std::shared_ptr<IGraph> parse(+ ov::Tensor mainBlob,+ const bool blobAllocatedByPlugin,+ const Config& config,+ std::optional<std::vector<ov::Tensor>> initBlobs = std::nullopt,+ const std::optional<std::shared_ptr<const ov::Model>>& model = std::nullopt) const override;ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hppindex 8a31af4b466..fad630c4766 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp@@ -16,7 +16,7 @@namespace intel_npu {-class Graph final : public IGraph {+class Graph : public IGraph {public:Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,@@ -25,9 +25,10 @@ public:std::optional<ov::Tensor> blob,bool blobAllocatedByPlugin,const Config& config,- const ov::SoPtr<ICompiler>& compiler = {nullptr});+ const ov::SoPtr<ICompiler>& compiler = {nullptr},+ const bool calledFromWeightlessGraph = false);- size_t export_blob(std::ostream& stream) const override;+ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> export_blob(std::ostream& stream) const override;std::vector<ov::ProfilingInfo> process_profiling_output(const std::vector<uint8_t>& profData,const Config& config) const override;@@ -38,10 +39,11 @@ public:~Graph() override;-private:+protected:bool release_blob(const Config& config);std::shared_ptr<ZeGraphExtWrappers> _zeGraphExt;+std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;// In the case of the import path, the blob is released after graph initialization so it can not be any longerdiff --git a/src/plugins/intel_npu/src/compiler_adapter/include/mem_usage.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/mem_usage.hppnew file mode 100644index 00000000000..55171659164--- /dev/null+++ b/src/plugins/intel_npu/src/compiler_adapter/include/mem_usage.hpp@@ -0,0 +1,11 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>++namespace intel_npu {+int64_t get_peak_memory_usage();+}diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hppindex c5bd4be79a7..534332fec76 100644--- a/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp+++ b/src/plugins/intel_npu/src/compiler_adapter/include/plugin_compiler_adapter.hpp@@ -21,7 +21,14 @@ public:std::shared_ptr<IGraph> compile(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;- std::shared_ptr<IGraph> parse(ov::Tensor blob, bool blobAllocatedByPlugin, const Config& config) const override;+ std::shared_ptr<IGraph> compileWS(const std::shared_ptr<ov::Model>& model, const Config& config) const override;++ std::shared_ptr<IGraph> parse(+ ov::Tensor mainBlob,+ const bool blobAllocatedByPlugin,+ const Config& config,+ std::optional<std::vector<ov::Tensor>> initBlobs = std::nullopt,+ const std::optional<std::shared_ptr<const ov::Model>>& model = std::nullopt) const override;ov::SupportedOpsMap query(const std::shared_ptr<const ov::Model>& model, const Config& config) const override;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.hppnew file mode 100644index 00000000000..4e772fa9e22--- /dev/null+++ b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp@@ -0,0 +1,132 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Compiler Interface++#pragma once++#include "graph.hpp"+#include "intel_npu/utils/zero/zero_host_tensor.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/runtime/iremote_context.hpp"++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.+ */+class WeightlessGraph final : public Graph {+public:+ WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,+ const bool blobAllocatedByPlugin,+ ze_graph_handle_t mainGraphHandle,+ NetworkMetadata mainMetadata,+ std::optional<ov::Tensor> mainBlob,+ const std::vector<ze_graph_handle_t>& initGraphHandles,+ std::vector<NetworkMetadata> initMetadata,+ std::optional<std::vector<ov::Tensor>> initBlobs,+ const std::shared_ptr<const ov::Model>& model,+ const Config& config,+ const ov::SoPtr<ICompiler>& compiler = {nullptr});++ /**+ * @brief The main schedule along with the weights initialization ones are exported.+ */+ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> export_blob(std::ostream& stream) const override;++ /**+ * @brief The same operations performed within "Graph::initialize", but for all handles. In addition to this, the+ * init schedules are run and the result of this is set as inputs to the main compiled model.+ */+ void initialize(const Config& config) override;++ // TODO: public for multi-threaded execution+ struct InputData {+ std::vector<std::shared_ptr<ov::ITensor>> tensors;+ ov::SoPtr<ZeroHostTensor> hostTensor;+ };++ struct OutputData {+ std::vector<std::shared_ptr<ov::ITensor>> tensors;+ ov::SoPtr<ZeroHostTensor> hostTensor;+ std::unordered_map<std::string, std::shared_ptr<ov::ITensor>> tensorsMap;+ };++ ~WeightlessGraph();++private:+ /**+ * @brief Allocates the inputs of the init schedule using a single L0 buffer and copies the original weights there.+ *+ * @param initIndex Identifies the init schedule.+ * @param constants The original weights extracted from the ov::Model object.+ * @return The allocated L0 tensor along with view tensors corresponding to the init inputs.+ */+ InputData allocate_inputs(const size_t initIndex,+ const std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>>& constants);++ /**+ * @brief Allocates the outputs of the init schedule using a single L0 buffer.+ *+ * @param initIndex Identifies the init schedule.+ * @return The allocated L0 tensor along with view tensors corresponding to the init outputs.+ */+ OutputData allocate_outputs(const size_t initIndex);++ /**+ * @brief Creates a pipeline for a single init schedule. This pipeline can be used for running inferences.+ */+ void create_pipeline(const size_t initIndex,+ const std::vector<std::shared_ptr<ov::ITensor>>& inputTensors,+ const std::vector<std::shared_ptr<ov::ITensor>>& outputTensors);++ /**+ * @brief Runs the pipeline corresponding to a single init schedule.+ * @details This should produce the processed weights that can be used as inputs of the main schedule.+ */+ void run_pipeline(const size_t initIndex);++ void run_init_single_threaded();++ void run_init_multi_threaded();++ /**+ * @brief Sets the processed weights as inputs of the main schedule.+ */+ void set_weights_inputs();++ void release_init_blob(const size_t initIndex, const Config& config);++ std::vector<ze_graph_handle_t> _initsHandles;+ std::optional<std::vector<ov::Tensor>> _initBlobs;+ std::vector<NetworkMetadata> _initsMetadata;+ std::shared_ptr<const ov::Model> _model;++ std::vector<std::vector<ArgumentDescriptor>> _initsInputDescriptors;+ std::vector<std::vector<ArgumentDescriptor>> _initsOutputDescriptors;++ std::vector<uint32_t> _initsCommandQueueOrdinals;+ std::vector<std::unique_ptr<CommandList>> _initsCommandLists;+ std::vector<std::unique_ptr<Fence>> _initsFences;+ std::shared_ptr<CommandQueue> _initsCommandQueue;+ uint32_t _initsCommandQueueGroupOrdinal = 0;++ /**+ * @brief Tensors holding the L0 buffers corresponding to the inputs of the main schedule.+ * @details Each vector entry corresponds to the output of one init schedule. The allocations have been performed+ * per init compiled model and not per init schedule output for performance reasons.+ */+ mutable std::vector<ov::SoPtr<ZeroHostTensor>> _mainInputsAllocatedTensors;+ /**+ * @brief Tensors pointing towards the buffers found in "_mainInputsAllocatedTensors".+ * @details Each map entry corresponds to one input of the main schedule.+ */+ mutable std::unordered_map<std::string, std::shared_ptr<ov::ITensor>> _mainInputsViewTensors;+};++} // 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 d4237bc2aa5..6ef6717a95c 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,6 +4,7 @@#include "driver_compiler_adapter.hpp"+#include <fstream>#include <regex>#include <string_view>@@ -17,7 +18,10 @@#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"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "weightless_graph.hpp"namespace {@@ -141,6 +145,45 @@ std::string rankToLegacyLayoutString(const size_t rank) {}}+bool isInitMetadata(const intel_npu::NetworkMetadata& networkMetadata) {+ if (networkMetadata.inputs.size() == 0) {+ return false;+ }+ return networkMetadata.inputs.at(0).isInitInputWeights;+}++/**+ * @brief Stores the information within the "WeightlessCacheAttribute" as runtime fields that persist upon+ * serialization.+ * @details Constant nodes (weights) may contain as medatadata the "WeightlessCacheAttribute", that is information+ * regarding the offset of the weights within the binary file, as well as the original size and precision. This+ * information is required within the "weights separation" flow, therefore this function is here to store it.+ * @note Not calling this function in the weights separation flow would lead to this information being lost upon+ * serialization. The "WeightlessCacheAttribute" information that is populated upon de-serialization would represent+ * metadata corresponding to the serialized stream, not the original weights file. Therefore the compiler would be+ * misinformed and lookups of weights offsets could fail.+ *+ * @param model Both source and target.+ */+void storeWeightlessCacheAttribute(const std::shared_ptr<ov::Model>& model) {+ size_t constantId = 0;+ for (auto&& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v0::Constant>(node)) {+ ov::RTMap& runtimeInfoMap = node->get_rt_info();+ const auto& weightlessCacheAttrIt =+ runtimeInfoMap.find(ov::WeightlessCacheAttribute::get_type_info_static());++ const std::string constantIdString = std::to_string(constantId++);+ if (weightlessCacheAttrIt != runtimeInfoMap.end()) {+ auto& weightlessCacheAttr = weightlessCacheAttrIt->second.as<ov::WeightlessCacheAttribute>();+ model->set_rt_info(weightlessCacheAttr.bin_offset, "ws_bin_offset_" + constantIdString);+ model->set_rt_info(weightlessCacheAttr.original_size, "ws_original_size_" + constantIdString);+ model->set_rt_info(weightlessCacheAttr.original_dtype, "ws_original_dtype_" + constantIdString);+ }+ }+ }+}+} // namespacenamespace intel_npu {@@ -208,26 +251,161 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compile(const std::shared_ptr<conconfig);}-std::shared_ptr<IGraph> DriverCompilerAdapter::parse(ov::Tensor blob,- bool blobAllocatedByPlugin,- const Config& config) const {+std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<ov::Model>& model,+ const Config& config) const {+ OV_ITT_TASK_CHAIN(COMPILE_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "compileWS");++ storeWeightlessCacheAttribute(model);++ const ze_graph_compiler_version_info_t& compilerVersion = _compilerProperties.compilerVersion;+ if ((compilerVersion.major < 6) || (compilerVersion.major == 6 && compilerVersion.minor < 3)) {+ OPENVINO_THROW("Minimum compiler version required for weights separation: 6.3. Found: ",+ compilerVersion.major,+ ".",+ compilerVersion.minor);+ }++ const auto maxOpsetVersion = _compilerProperties.maxOVOpsetVersionSupported;+ _logger.info("getSupportedOpsetVersion Max supported version of opset in CiD: %d", maxOpsetVersion);++ if (config.get<SEPARATE_WEIGHTS_VERSION>() != ov::intel_npu::WSVersion::ITERATIVE) {+ OPENVINO_THROW("Invalid \"SEPARATE_WEIGHTS_VERSION\" value found within the \"compileWS\" call:",+ config.get<SEPARATE_WEIGHTS_VERSION>(),+ ". \"WSVersion::ITERATIVE\" is the only supported value for the compiler-in-driver path.");+ }++ _logger.debug("serialize IR");+ auto serializedIR = 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 FilteredConfig* plgConfig = dynamic_cast<const FilteredConfig*>(&config);+ if (plgConfig == nullptr) {+ OPENVINO_THROW("config is not FilteredConfig");+ }+ FilteredConfig updatedConfig = *plgConfig;++ // If UMD Caching is requested to be bypassed or if OV cache is enabled, disable driver caching+ uint32_t flags = ZE_GRAPH_FLAG_NONE;+ const auto set_cache_dir = config.get<CACHE_DIR>();+ if (!set_cache_dir.empty() || config.get<BYPASS_UMD_CACHING>()) {+ flags = flags | ZE_GRAPH_FLAG_DISABLE_CACHING;+ }++ // WS v3 is based on a stateless compiler. We'll use a separate config entry for informing the compiler the index of+ // the current call iteration.+ std::vector<NetworkMetadata> initNetworkMetadata;+ NetworkMetadata mainNetworkMetadata;+ std::vector<ze_graph_handle_t> initGraphHandles;+ ze_graph_handle_t mainGraphHandle;+ size_t callNumber = 0;++ // Convention: run until the main schedule has been returned.+ int64_t compile_model_mem_start = 0;+ if (_logger.level() >= ov::log::Level::INFO) {+ compile_model_mem_start = get_peak_memory_usage();+ }+ while (true) {+ _logger.debug("compileWS iteration %d", callNumber);+ updatedConfig.update({{ov::intel_npu::ws_compile_call_number.name(), std::to_string(callNumber++)}});++ _logger.debug("build flags");+ buildFlags = serializedIOInfo;+ buildFlags += " ";+ buildFlags += serializeConfig(updatedConfig, compilerVersion);++ _logger.debug("compile start");+ ze_graph_handle_t graphHandle = _zeGraphExt->getGraphHandle(serializedIR, buildFlags, flags);+ _logger.debug("compile end");++ OV_ITT_TASK_NEXT(COMPILE_BLOB, "getNetworkMeta");+ NetworkMetadata networkMetadata = _zeGraphExt->getNetworkMeta(graphHandle);++ if (isInitMetadata(networkMetadata)) {+ networkMetadata.name = model->get_friendly_name() + "_init";+ initNetworkMetadata.push_back(std::move(networkMetadata));+ initGraphHandles.push_back(graphHandle);+ } else {+ networkMetadata.name = model->get_friendly_name() + "_main";+ mainNetworkMetadata = std::move(networkMetadata);+ mainGraphHandle = graphHandle;+ serializedIR = SerializedIR();+ // By convention, the main schedule is the last result produced by the compiler+ break;+ }+ }++ if (_logger.level() >= ov::log::Level::INFO) {+ auto compile_model_mem_end = get_peak_memory_usage();+ _logger.debug("Start of compilation memory usage: Peak %lld KB", compile_model_mem_start);+ _logger.debug("End of compilation memory usage: Peak %lld KB", compile_model_mem_end);+ // Note: Following log is parsed by CI. Take care when modifying it.+ _logger.info("Compilation memory usage: Peak %lld KB", compile_model_mem_end - compile_model_mem_start);+ }++ return std::make_shared<WeightlessGraph>(_zeGraphExt,+ _zeroInitStruct,+ /* blobAllocatedByPlugin = */ false,+ mainGraphHandle,+ std::move(mainNetworkMetadata),+ /* mainBlob = */ std::nullopt,+ initGraphHandles,+ std::move(initNetworkMetadata),+ /* initBlobs = */ std::nullopt,+ model,+ config);+}++std::shared_ptr<IGraph> DriverCompilerAdapter::parse(+ ov::Tensor mainBlob,+ const bool blobAllocatedByPlugin,+ const Config& config,+ std::optional<std::vector<ov::Tensor>> initBlobs,+ const std::optional<std::shared_ptr<const ov::Model>>& model) const {OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "parse");_logger.debug("parse start");ze_graph_handle_t graphHandle =- _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(blob.data()), blob.get_byte_size());+ _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(mainBlob.data()), mainBlob.get_byte_size());_logger.debug("parse end");OV_ITT_TASK_NEXT(PARSE_BLOB, "getNetworkMeta");auto networkMeta = _zeGraphExt->getNetworkMeta(graphHandle);- return std::make_shared<Graph>(_zeGraphExt,- _zeroInitStruct,- graphHandle,- std::move(networkMeta),- std::move(blob),- blobAllocatedByPlugin,- config);+ if (!initBlobs.has_value()) {+ return std::make_shared<Graph>(_zeGraphExt,+ _zeroInitStruct,+ graphHandle,+ std::move(networkMeta),+ std::move(mainBlob),+ blobAllocatedByPlugin,+ config);+ }++ // The presence of init schedules means weights separation has been enabled at compilation time. Use a specific+ // "Graph" object as wrapper over all L0 handles.+ std::vector<ze_graph_handle_t> initGraphHandles;+ std::vector<NetworkMetadata> initMetadata;+ for (const auto& initBlob : initBlobs.value()) {+ ze_graph_handle_t initGraphHandle =+ _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(initBlob.data()), initBlob.get_byte_size());+ initGraphHandles.push_back(initGraphHandle);+ initMetadata.push_back(_zeGraphExt->getNetworkMeta(initGraphHandle));+ }++ return std::make_shared<WeightlessGraph>(_zeGraphExt,+ _zeroInitStruct,+ blobAllocatedByPlugin,+ graphHandle,+ std::move(networkMeta),+ std::move(mainBlob),+ initGraphHandles,+ std::move(initMetadata),+ std::move(initBlobs),+ model.value(),+ config);}ov::SupportedOpsMap DriverCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cppindex a150c1357ca..5ba44dd5408 100644--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp@@ -17,7 +17,8 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,std::optional<ov::Tensor> blob,bool blobAllocatedByPlugin,const Config& config,- const ov::SoPtr<ICompiler>& compiler)+ const ov::SoPtr<ICompiler>& compiler,+ const bool calledFromWeightlessGraph): IGraph(graphHandle, std::move(metadata), config, std::move(blob)),_zeGraphExt(zeGraphExt),_zeroInitStruct(zeroInitStruct),@@ -29,10 +30,13 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,return;}- initialize(config);+ if (!calledFromWeightlessGraph) {+ // Will be called at a later stage from WeightlessGraph::initialize() in order to save some memory+ initialize(config);+ }}-size_t Graph::export_blob(std::ostream& stream) const {+std::pair<uint64_t, std::optional<std::vector<uint64_t>>> Graph::export_blob(std::ostream& stream) const {const uint8_t* blobPtr = nullptr;size_t blobSize;std::vector<uint8_t> blobVec; // plugin needs to keep a copy of the blob for older drivers@@ -57,7 +61,7 @@ size_t Graph::export_blob(std::ostream& stream) const {if (!stream) {_logger.error("Write blob to stream failed. Blob is broken!");- return 0;+ return std::make_pair(0, std::nullopt);}if (_logger.level() >= ov::log::Level::INFO) {@@ -71,7 +75,7 @@ size_t Graph::export_blob(std::ostream& stream) const {_logger.info(str.str().c_str());}_logger.info("Write blob to stream successfully.");- return blobSize;+ return std::make_pair(blobSize, std::nullopt);}std::vector<ov::ProfilingInfo> Graph::process_profiling_output(const std::vector<uint8_t>& profData,@@ -152,14 +156,12 @@ void Graph::initialize(const Config& config) {}_zeGraphExt->initializeGraph(_handle, _command_queue_group_ordinal);-_logger.debug("Graph initialize finish");// We are allowed to release the original blob because weights were loaded in NPU memory during// _zeGraphExt->initializeGraph(). The driver will not access the original blob from this moment on, so we are// releasing it here to avoid unnecessary memory usage._blobIsReleased = release_blob(config);-_batch_size = get_batch_size(_metadata);if (_zeroInitStruct->getCommandQueueDdiTable().version() < ZE_MAKE_VERSION(1, 1) &&diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/mem_usage.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/mem_usage.cppnew file mode 100644index 00000000000..99e466a3a33--- /dev/null+++ b/src/plugins/intel_npu/src/compiler_adapter/src/mem_usage.cpp@@ -0,0 +1,70 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// clang-format off++#include "mem_usage.hpp"++#if defined _WIN32++# include <windows.h>+# include <psapi.h>++# include <cmath>+# include <stdexcept>++int64_t intel_npu::get_peak_memory_usage() {+ PROCESS_MEMORY_COUNTERS mem_counters;+ if (!GetProcessMemoryInfo(GetCurrentProcess(), &mem_counters, sizeof(mem_counters))) {+ throw std::runtime_error("Can't get system memory values");+ }++ // Linux tracks memory usage in pages and then converts them to kB.+ // Thus, there is always some room for inaccuracy as pages are not guaranteed to be fully used.+ // In Windows, the situation is different: the system returns the memory usage in bytes, not in pages.+ // To align the output between the two operating systems as closely as possible, we have two options:+ // 1. Use rounding to the nearest integer.+ // 2. Try to estimate the number of pages used in Windows. However,+ // this approach is likely to be inaccurate as well, so option 1 was chosen.+ static constexpr double bytes_in_kilobyte = 1024.0;++ // please note then we calculate difference+ // to get peak memory increment value, so we return int64, not size_t+ return static_cast<int64_t>(std::round(mem_counters.PeakWorkingSetSize / bytes_in_kilobyte));+}++#else++# include <fstream>+# include <regex>+# include <sstream>++// clang-format on++int64_t intel_npu::get_peak_memory_usage() {+ std::size_t peak_mem_usage_kB = 0;++ std::ifstream status_file("/proc/self/status");+ std::string line;+ std::regex vm_peak_regex("VmPeak:");+ std::smatch vm_match;+ bool mem_values_found = false;+ while (std::getline(status_file, line)) {+ if (std::regex_search(line, vm_match, vm_peak_regex)) {+ std::istringstream iss(vm_match.suffix());+ iss >> peak_mem_usage_kB;+ mem_values_found = true;+ }+ }++ if (!mem_values_found) {+ throw std::runtime_error("Can't get system memory values");+ }++ // please note then we calculate difference+ // to get peak memory increment value, so we return int64, not size_t+ return static_cast<int64_t>(peak_mem_usage_kB);+}++#endifdiff --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 a47b31a4ea8..8a194457f21 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@@ -15,12 +15,16 @@#include "intel_npu/utils/logger/logger.hpp"#include "intel_npu/utils/zero/zero_api.hpp"#include "intel_npu/utils/zero/zero_result.hpp"+#include "mem_usage.hpp"+#include "openvino/core/model.hpp"#include "openvino/runtime/make_tensor.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/shared_object.hpp"+#include "weightless_graph.hpp"namespace {-std::shared_ptr<void> loadLibrary(const std::string& libpath) {++std::shared_ptr<void> load_library(const std::string& libpath) {#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)return ov::util::load_shared_object(ov::util::string_to_wstring(libpath).c_str());#else@@ -28,7 +32,7 @@ std::shared_ptr<void> loadLibrary(const std::string& libpath) {#endif}-std::shared_ptr<intel_npu::ICompiler> getCompiler(std::shared_ptr<void> so) {+std::shared_ptr<intel_npu::ICompiler> get_compiler(std::shared_ptr<void> so) {static constexpr auto CreateFuncName = "CreateNPUCompiler";auto symbol = ov::util::get_symbol(so, CreateFuncName);@@ -40,12 +44,22 @@ std::shared_ptr<intel_npu::ICompiler> getCompiler(std::shared_ptr<void> so) {return compilerPtr;}-ov::SoPtr<intel_npu::ICompiler> loadCompiler(const std::string& libpath) {- auto compilerSO = loadLibrary(libpath);- auto compiler = getCompiler(compilerSO);+ov::SoPtr<intel_npu::ICompiler> load_compiler(const std::string& libpath) {+ auto compilerSO = load_library(libpath);+ auto compiler = get_compiler(compilerSO);return ov::SoPtr<intel_npu::ICompiler>(compiler, compilerSO);}++ov::Tensor make_tensor_from_vector(std::vector<uint8_t>& vector) {+ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{vector.size()}, vector.data());+ auto impl = ov::get_tensor_impl(std::move(tensor));+ std::shared_ptr<std::vector<uint8_t>> sharedCompiledNetwork =+ std::make_shared<std::vector<uint8_t>>(std::move(vector));+ impl._so = std::move(sharedCompiledNetwork);+ return ov::make_tensor(impl);+}+} // namespacenamespace intel_npu {@@ -58,7 +72,7 @@ PluginCompilerAdapter::PluginCompilerAdapter(const std::shared_ptr<ZeroInitStruc_logger.info("MLIR compiler will be used.");std::string baseName = "npu_mlir_compiler";auto libPath = ov::util::make_plugin_library_name(ov::util::get_ov_lib_path(), baseName + OV_BUILD_POSTFIX);- _compiler = loadCompiler(libPath);+ _compiler = load_compiler(libPath);if (_zeroInitStruct == nullptr) {return;@@ -83,14 +97,7 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<conauto networkDesc = _compiler->compile(model, config);_logger.debug("compile end");- auto tensor =- ov::Tensor(ov::element::u8, ov::Shape{networkDesc.compiledNetwork.size()}, networkDesc.compiledNetwork.data());- auto impl = ov::get_tensor_impl(tensor);- std::shared_ptr<std::vector<uint8_t>> sharedCompiledNetwork =- std::make_shared<std::vector<uint8_t>>(std::move(networkDesc.compiledNetwork));- impl._so = std::move(sharedCompiledNetwork);- tensor = ov::make_tensor(impl);-+ ov::Tensor tensor = make_tensor_from_vector(networkDesc.compiledNetwork);ze_graph_handle_t graphHandle = nullptr;if (_zeGraphExt) {@@ -115,34 +122,200 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<con_compiler);}-std::shared_ptr<IGraph> PluginCompilerAdapter::parse(ov::Tensor blob,- bool blobAllocatedByPlugin,- const Config& config) const {+std::shared_ptr<IGraph> PluginCompilerAdapter::compileWS(const std::shared_ptr<ov::Model>& model,+ const Config& config) const {+ OV_ITT_TASK_CHAIN(COMPILE_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "compileWS");++ std::vector<std::shared_ptr<NetworkDescription>> initNetworkDescriptions;+ std::shared_ptr<NetworkDescription> mainNetworkDescription;++ _logger.debug("compile start");++ const auto starts_with = [](const std::string& str, const std::string& prefix) {+ return str.substr(0, prefix.size()) == prefix;+ };+ const auto isInit = [&](std::string name) {+ return starts_with(name, "init");+ };++ const auto isMain = [&](std::string name) {+ return starts_with(name, "main");+ };++ _logger.info("SEPARATE_WEIGHTS_VERSION: ", config.get<SEPARATE_WEIGHTS_VERSION>());++ int64_t compile_model_mem_start = 0;+ if (_logger.level() >= ov::log::Level::INFO) {+ compile_model_mem_start = get_peak_memory_usage();+ }+ switch (config.get<SEPARATE_WEIGHTS_VERSION>()) {+ case ov::intel_npu::WSVersion::ONE_SHOT: {+ std::vector<std::shared_ptr<NetworkDescription>> initMainNetworkDescriptions =+ _compiler->compileWsOneShot(model, config);++#if 0 // TODO: it is not clear whether we should change the name+ OPENVINO_ASSERT(isMain(initMainNetworkDescriptions.back()->metadata.name),+ "Unexpected network name for main:",+ initMainNetworkDescriptions.back()->metadata.name);+#endif++ mainNetworkDescription = initMainNetworkDescriptions.back();+ initMainNetworkDescriptions.pop_back();+ initNetworkDescriptions = std::move(initMainNetworkDescriptions);+ } break;+ case ov::intel_npu::WSVersion::ITERATIVE: {+ const std::shared_ptr<ov::Model> originalModel = model->clone();+ std::shared_ptr<ov::Model> targetModel = model;+ size_t i = 0;++ while (auto networkDescription =+ std::make_shared<NetworkDescription>(_compiler->compileWsIterative(targetModel, config, i++))) {+ if (isInit(networkDescription->metadata.name)) {+ initNetworkDescriptions.push_back(networkDescription);+ targetModel = originalModel->clone();+ continue;+ }+ OPENVINO_ASSERT(isMain(networkDescription->metadata.name),+ "Unexpected network name: ",+ networkDescription->metadata.name);++ mainNetworkDescription = std::move(networkDescription);+ break;+ }+ } break;+ default:+ OPENVINO_THROW("Invalid \"SEPARATE_WEIGHTS_VERSION\" value found within the \"compileWS\" call:",+ config.get<SEPARATE_WEIGHTS_VERSION>());+ break;+ }++ if (_logger.level() >= ov::log::Level::INFO) {+ auto compile_model_mem_end = get_peak_memory_usage();+ _logger.debug("Start of compilation memory usage: Peak %lld KB", compile_model_mem_start);+ _logger.debug("End of compilation memory usage: Peak %lld KB", compile_model_mem_end);+ // Note: Following log is parsed by CI. Take care when modifying it.+ _logger.info("Compilation memory usage: Peak %lld KB", compile_model_mem_end - compile_model_mem_start);+ }++ _logger.debug("compile end");++ ov::Tensor tensorMain = make_tensor_from_vector(mainNetworkDescription->compiledNetwork);+ ze_graph_handle_t mainGraphHandle = nullptr;+ if (_zeGraphExt) {+ // Depending on the config, we may get an error when trying to+ // get the graph handle from the compiled network+ try {+ mainGraphHandle = _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(tensorMain.data()),+ tensorMain.get_byte_size());+ } catch (...) {+ _logger.info("Failed to obtain the level zero graph handle. Inference requests for this model are not "+ "allowed. Only exports are available");+ }+ }++ std::vector<ze_graph_handle_t> initGraphHandles;+ std::vector<ov::Tensor> tensorsInits;+ std::vector<NetworkMetadata> initNetworkMetadata;+ initGraphHandles.reserve(initNetworkDescriptions.size());+ tensorsInits.reserve(initNetworkDescriptions.size());+ initNetworkMetadata.reserve(initNetworkDescriptions.size());+ for (auto& networkDesc : initNetworkDescriptions) {+ ov::Tensor tensor = make_tensor_from_vector(networkDesc->compiledNetwork);+ ze_graph_handle_t graphHandle = nullptr;+ if (_zeGraphExt) {+ try {+ graphHandle = _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(tensor.data()),+ tensor.get_byte_size());+ } catch (...) {+ }+ }++ initGraphHandles.push_back(graphHandle);+ tensorsInits.push_back(std::move(tensor));+ initNetworkMetadata.push_back(std::move(networkDesc->metadata));+ }++ return std::make_shared<WeightlessGraph>(_zeGraphExt,+ _zeroInitStruct,+ /* blobAllocatedByPlugin = */ false,+ mainGraphHandle,+ std::move(mainNetworkDescription->metadata),+ std::move(tensorMain),+ initGraphHandles,+ std::move(initNetworkMetadata),+ tensorsInits,+ model,+ config,+ _compiler);+}++std::shared_ptr<IGraph> PluginCompilerAdapter::parse(+ ov::Tensor mainBlob,+ const bool blobAllocatedByPlugin,+ const Config& config,+ std::optional<std::vector<ov::Tensor>> initBlobs,+ const std::optional<std::shared_ptr<const ov::Model>>& model) const {OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "PluginCompilerAdapter", "parse");_logger.debug("parse start");- std::vector<uint8_t> network(blob.get_byte_size());- network.assign(reinterpret_cast<const uint8_t*>(blob.data()),- reinterpret_cast<const uint8_t*>(blob.data()) + blob.get_byte_size());+ std::vector<uint8_t> network(mainBlob.get_byte_size());+ network.assign(reinterpret_cast<const uint8_t*>(mainBlob.data()),+ reinterpret_cast<const uint8_t*>(mainBlob.data()) + mainBlob.get_byte_size());auto networkMeta = _compiler->parse(network, config);network.clear();network.shrink_to_fit();- _logger.debug("parse end");ze_graph_handle_t graphHandle = nullptr;if (_zeGraphExt) {- graphHandle = _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(blob.data()), blob.get_byte_size());+ graphHandle =+ _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(mainBlob.data()), mainBlob.get_byte_size());}- return std::make_shared<Graph>(_zeGraphExt,- _zeroInitStruct,- graphHandle,- std::move(networkMeta),- std::move(blob),- blobAllocatedByPlugin,- config,- _compiler);+ _logger.debug("main schedule parse end");++ if (!initBlobs.has_value()) {+ return std::make_shared<Graph>(_zeGraphExt,+ _zeroInitStruct,+ graphHandle,+ std::move(networkMeta),+ std::move(mainBlob),+ blobAllocatedByPlugin,+ config,+ _compiler);+ }++ // The presence of init schedules means weights separation has been enabled at compilation time. Use a specific+ // "Graph" object as wrapper over all L0 handles.+ std::vector<ze_graph_handle_t> initGraphHandles;+ std::vector<NetworkMetadata> initMetadata;+ for (const auto& initBlob : initBlobs.value()) {+ network.reserve(initBlob.get_byte_size());+ network.assign(reinterpret_cast<const uint8_t*>(initBlob.data()),+ reinterpret_cast<const uint8_t*>(initBlob.data()) + initBlob.get_byte_size());+ initMetadata.push_back(_compiler->parse(network, config));+ network.clear();+ network.shrink_to_fit();++ if (_zeGraphExt) {+ initGraphHandles.push_back(_zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(initBlob.data()),+ initBlob.get_byte_size()));+ }+ }++ _logger.debug("init schedules parse end");+ return std::make_shared<WeightlessGraph>(_zeGraphExt,+ _zeroInitStruct,+ blobAllocatedByPlugin,+ graphHandle,+ std::move(networkMeta),+ std::move(mainBlob),+ initGraphHandles,+ std::move(initMetadata),+ std::move(initBlobs),+ model.value(),+ config,+ _compiler);}ov::SupportedOpsMap PluginCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,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.cppnew file mode 100644index 00000000000..e9103f9a20c--- /dev/null+++ b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp@@ -0,0 +1,603 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "weightless_graph.hpp"++#include <condition_variable>+#include <mutex>+#include <queue>++#include "intel_npu/config/options.hpp"+#include "intel_npu/prefix.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/core/type/element_iterator.hpp"+#include "openvino/runtime/make_tensor.hpp"++#define USE_SINGLE_THREADED_RUN_INIT 0++namespace intel_npu {++namespace {++constexpr uint8_t MAIN_SCHEDULE_INDEX = 0;++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,+ const Logger& logger) {+ std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> constants;++ // 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>();+ constants[weightlessCacheAttr.bin_offset] = constantNode;+ }+ }++ return constants;+}++struct QueueData {+ int64_t initIndex = -1;+ WeightlessGraph::InputData inputs;+ WeightlessGraph::OutputData outputs;++ bool isTerminator() const {+ return initIndex == -1;+ }+};++// very simple multi-threaded executor for 2 kinds of tasks where task 1 "calls"+// task 2+template <typename Task1Callable, typename Task2Callable>+class Parallelizer {+ std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>> _modelConstants;++ std::mutex _mutex;+ std::queue<QueueData> _payloads;+ std::atomic_bool _progressTask1 = true;++ Task1Callable _task1;+ Task2Callable _task2;++public:+ Parallelizer(const std::shared_ptr<const ov::Model>& model,+ Task1Callable&& task1,+ Task2Callable&& task2,+ const Logger& logger)+ : _modelConstants(get_all_constants_in_topological_order(model, logger)),+ _task1(std::forward<Task1Callable>(task1)),+ _task2(std::forward<Task2Callable>(task2)) {}++ void callForAllAndWait(const int64_t numberOfInits) {+ std::condition_variable task1SyncPoint;+ std::condition_variable task2SyncPoint;++ std::thread task2Thread([&]() {+ while (true) {+ std::unique_lock lock(_mutex);+ task2SyncPoint.wait(lock, [&]() {+ return !_payloads.empty();+ });++ auto payload = std::move(_payloads.front());+ _payloads.pop();+ if (payload.isTerminator()) {+ return; // Note: exit condition+ }+ lock.unlock();++ _task2(std::move(payload), task1SyncPoint,+ _progressTask1); // TODO: putting sync point inside is meh+ }+ });++ std::mutex task1Mutex;+ for (int64_t i = 0; i < numberOfInits; ++i) {+ {+ // TODO: task1Mutex is *only* used here. this is a poor man's+ // spinlock on an atomic boolean (without busy wait)+ std::unique_lock lock(task1Mutex);+ task1SyncPoint.wait(lock, [&]() {+ return _progressTask1.load();+ });+ }++ // TODO: should we run task1 under mutex?+ auto payload = _task1(_modelConstants, i);+ _progressTask1.store(false);+ {+ std::lock_guard guard(_mutex);+ _payloads.push(std::move(payload));+ }+ task2SyncPoint.notify_one();+ }+ {+ std::lock_guard guard(_mutex);+ _payloads.push({}); // isTerminator()+ }+ task2SyncPoint.notify_one();++ task2Thread.join();+ _modelConstants = {};+ }+};++// c++17 deduction guide+template <typename Task1Callable, typename Task2Callable>+Parallelizer(const std::shared_ptr<const ov::Model>&, Task1Callable&&, Task2Callable&&, const Logger&)+ -> Parallelizer<Task1Callable, Task2Callable>;++void merge_two_maps(std::unordered_map<std::string, std::shared_ptr<ov::ITensor>>& dst,+ std::unordered_map<std::string, std::shared_ptr<ov::ITensor>>& src) {+ dst.merge(src);+ OPENVINO_ASSERT(src.empty(), "Found weights inputs collision between different inits");+}++} // namespace++WeightlessGraph::WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,+ const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,+ const bool blobAllocatedByPlugin,+ ze_graph_handle_t mainGraphHandle,+ NetworkMetadata mainMetadata,+ std::optional<ov::Tensor> mainBlob,+ const std::vector<ze_graph_handle_t>& initGraphHandles,+ std::vector<NetworkMetadata> initMetadata,+ std::optional<std::vector<ov::Tensor>> initBlobs,+ const std::shared_ptr<const ov::Model>& model,+ const Config& config,+ const ov::SoPtr<ICompiler>& compiler)+ : Graph(zeGraphExt,+ zeroInitStruct,+ mainGraphHandle,+ std::move(mainMetadata),+ std::move(mainBlob),+ blobAllocatedByPlugin,+ config,+ compiler,+ true),+ _initsHandles(initGraphHandles),+ _initBlobs(std::move(initBlobs)),+ _initsMetadata(std::move(initMetadata)),+ _model(model) {+ if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {+ _logger.info("Graph initialize is deferred from the \"WeightlessGraph\" constructor");+ return;+ }++ initialize(config);+}++std::pair<uint64_t, std::optional<std::vector<uint64_t>>> WeightlessGraph::export_blob(std::ostream& stream) const {+ if (_blobIsReleased) {+ OPENVINO_THROW("Model was optimized away. Try importing it using `ov::hint::compiled_blob` property to extend "+ "its lifetime.");+ }++ size_t blobIndex = 0;+ std::uint32_t totalResult = 1171117u;+ totalResult = ((totalResult << 7) + totalResult);++ const auto writeToStream = [&](ze_graph_handle_t handle, const std::optional<ov::Tensor>& blobTensor) -> uint64_t {+ uint64_t blobSize;+ const uint8_t* blobRawPtr = nullptr;+ std::vector<uint8_t> blob;++ if (blobTensor == std::nullopt) {+ // when compiling the model using Compiler in Driver, the blob is handled by the driver+ _zeGraphExt->getGraphBinary(handle, blob, blobRawPtr, blobSize);+ } else {+ // in all other cases, the blob is handled by the plugin+ blobRawPtr = static_cast<const uint8_t*>(blobTensor->data());+ blobSize = blobTensor->get_byte_size();+ }++ 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.write(reinterpret_cast<const char*>(blobRawPtr), static_cast<std::streamsize>(blobSize));++ if (!stream) {+ _logger.error("Write blob to stream failed. Blob is broken!");+ return 0;+ }++ if (_logger.level() >= ov::log::Level::INFO) {+ std::uint32_t result = 1171117u;+ for (const uint8_t* it = blobRawPtr; it != blobRawPtr + blobSize; ++it) {+ result = ((result << 7) + result) + static_cast<uint32_t>(*it);+ }++ totalResult += result;++ std::stringstream str;+ if (blobIndex == MAIN_SCHEDULE_INDEX) {+ str << "Main blob size " << blobSize << ", hash " << std::hex << result;+ } else {+ str << "Init part " << blobIndex << " blob size " << blobSize << ", hash " << std::hex << result;+ }+ _logger.info(str.str().c_str());+ }++ return blobSize;+ };++ // By convention, first write the main part+ uint64_t mainBlobSize = writeToStream(_handle, _blob);+ uint64_t totalBlobSize = mainBlobSize;+ ++blobIndex;++ // Then the init schedules+ std::vector<uint64_t> initSizes;+ for (size_t initIndex = 0; initIndex < _initsHandles.size(); ++initIndex) {+ uint64_t initBlobSize = writeToStream(_initsHandles.at(initIndex),+ _initBlobs.has_value() && _initBlobs->at(initIndex)+ ? std::make_optional(_initBlobs->at(initIndex))+ : std::nullopt);+ totalBlobSize += initBlobSize;+ initSizes.push_back(initBlobSize);+ ++blobIndex;+ }++ std::stringstream str;+ str << "Blob size: " << totalBlobSize << ", hash: " << std::hex << totalResult;+ _logger.info(str.str().c_str());++ _logger.info("Write blob to stream successfully.");+ return std::make_pair(totalBlobSize, initSizes);+}++void WeightlessGraph::initialize(const Config& config) {+ // Simplified version for init schedules+ const size_t numberOfInits = _initsHandles.size();+ _initsInputDescriptors.resize(numberOfInits);+ _initsOutputDescriptors.resize(numberOfInits);+ _initsCommandQueueOrdinals.resize(numberOfInits);+ _initsCommandLists.resize(numberOfInits);+ _initsFences.resize(numberOfInits);++ for (size_t initIndex = 0; initIndex < numberOfInits; ++initIndex) {+ _logger.debug("WeightlessGraph initialize start, init schedule ", initIndex);++ ze_graph_handle_t initHandle = _initsHandles.at(initIndex);+ std::vector<ArgumentDescriptor>& initInputDescriptors = _initsInputDescriptors.at(initIndex);+ std::vector<ArgumentDescriptor>& initOutputDescriptors = _initsOutputDescriptors.at(initIndex);+ uint32_t& initCommandQueueOrdinal = _initsCommandQueueOrdinals.at(initIndex);++ // Code similar to "Graph::initialize"+ _logger.debug("performing pfnGetProperties");+ ze_graph_properties_t props{};+ props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(initHandle, &props);+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetProperties", result, _zeroInitStruct->getGraphDdiTable());++ _logger.debug("performing pfnGetArgumentProperties3");+ for (uint32_t index = 0; index < props.numGraphArgs; ++index) {+ ze_graph_argument_properties_3_t arg3{};+ arg3.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES;+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(initHandle, index, &arg3);+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());++ if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {+ initInputDescriptors.push_back(ArgumentDescriptor{arg3, index});+ } else {+ initOutputDescriptors.push_back(ArgumentDescriptor{arg3, index});+ }+ }++ initInputDescriptors.shrink_to_fit();+ initOutputDescriptors.shrink_to_fit();++ initCommandQueueOrdinal = zeroUtils::findCommandQueueGroupOrdinal(_zeroInitStruct->getDevice(),+ ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);++ _zeGraphExt->initializeGraph(initHandle, initCommandQueueOrdinal);+ _logger.debug("WeightlessGraph initialize finish, init schedule ", initIndex);++ // We are allowed to release the original blob because weights were loaded in NPU memory during+ // _zeGraphExt->initializeGraph(). The driver will not access the original blob from this moment on, so we are+ // releasing it here to avoid unnecessary memory usage.+ release_init_blob(initIndex, config);+ }++ // Create a single command queue for all weights initialization schedules+ _initsCommandQueueGroupOrdinal =+ zeroUtils::findCommandQueueGroupOrdinal(_zeroInitStruct->getDevice(),+ ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);++ uint32_t commandQueueOptions = 0;+ if (config.has<TURBO>() && config.get<TURBO>()) {+ _logger.debug("Set ZE_NPU_COMMAND_QUEUE_OPTION_TURBO in init command queue options");+ commandQueueOptions = commandQueueOptions | ZE_NPU_COMMAND_QUEUE_OPTION_TURBO;+ }++ _initsCommandQueue = std::make_shared<CommandQueue>(_zeroInitStruct,+ zeroUtils::toZeQueuePriority(config.get<MODEL_PRIORITY>()),+ _initsCommandQueueGroupOrdinal,+ commandQueueOptions);++ if (config.has<WORKLOAD_TYPE>()) {+ switch (config.get<WORKLOAD_TYPE>()) {+ case ov::WorkloadType::DEFAULT:+ _initsCommandQueue->setWorkloadType(ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_DEFAULT);+ break;+ case ov::WorkloadType::EFFICIENT:+ _initsCommandQueue->setWorkloadType(ze_command_queue_workload_type_t::ZE_WORKLOAD_TYPE_BACKGROUND);+ break;+ default:+ OPENVINO_THROW("Unknown value for WorkloadType!");+ }+ }++#if USE_SINGLE_THREADED_RUN_INIT+ run_init_single_threaded();+#else+ run_init_multi_threaded();+#endif++ _initsInputDescriptors.clear();+ _initsOutputDescriptors.clear();+ _initsCommandQueueOrdinals.clear();+ _initsCommandLists.clear();+ _initsFences.clear();+ _initsMetadata.clear();+ _initsCommandQueue.reset();++ // The main schedule is initialized after the weights initialization ones in order to save some memory+ Graph::initialize(config);++ set_weights_inputs();+}++WeightlessGraph::InputData WeightlessGraph::allocate_inputs(+ const size_t initIndex,+ const std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>>& constants) {+ std::vector<std::shared_ptr<ov::ITensor>> initInputsViewTensors;+ size_t initInputsByteSize = 0;++ for (const IODescriptor& descriptor : _initsMetadata.at(initIndex).inputs) {+ initInputsByteSize +=+ ov::element::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));+ }++ // Due to the large number of init inputs, allocating a single buffer for all of them is more efficient. "View+ // tensors" are used for separating them.+ const ov::SoPtr<ZeroHostTensor> initInputsAllocatedTensor = {+ std::make_shared<ZeroHostTensor>(nullptr,+ _zeroInitStruct,+ ov::element::Type_t::u8,+ ov::Shape({initInputsByteSize}),+ ov::intel_npu::TensorType::INPUT)};++ size_t offset = 0;+ for (const IODescriptor& descriptor : _initsMetadata.at(initIndex).inputs) {+ auto currentInputBufferLocation =+ static_cast<unsigned char*>(const_cast<void*>(initInputsAllocatedTensor->data(ov::element::Type_t::u8))) ++ offset;+ const size_t currentInputSize =+ ov::element::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));++ std::shared_ptr<ov::op::v0::Constant> constant;+ const size_t id = std::stoi(descriptor.nameFromCompiler);+ OPENVINO_ASSERT(constants.count(id) > 0,+ "Weights ID ",+ id,+ " not found in the model constants. This may indicate a mismatch between the model and the "+ "metadata of the compiled model.");++ constant = constants.at(id);++ std::memcpy(currentInputBufferLocation, constant->get_data_ptr(), currentInputSize);++ initInputsViewTensors.push_back(+ ov::make_tensor(constant->get_element_type(), constant->get_shape(), currentInputBufferLocation));+ offset += currentInputSize;+ }++ return {initInputsViewTensors, initInputsAllocatedTensor};+}++WeightlessGraph::OutputData WeightlessGraph::allocate_outputs(const size_t initIndex) {+ std::vector<std::shared_ptr<ov::ITensor>> initOutputsViewTensorsVector;+ std::unordered_map<std::string, std::shared_ptr<ov::ITensor>> initOutputsViewTensorsMap;+ size_t initOutputsByteSize = 0;++ for (const IODescriptor& descriptor : _initsMetadata.at(initIndex).outputs) {+ initOutputsByteSize +=+ ov::element::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));+ }++ const ov::SoPtr<ZeroHostTensor> initOutputsAllocatedTensor = {+ std::make_shared<ZeroHostTensor>(nullptr,+ _zeroInitStruct,+ ov::element::Type_t::u8,+ ov::Shape({initOutputsByteSize}),+ ov::intel_npu::TensorType::BINDED)};++ size_t offset = 0;+ for (const IODescriptor& descriptor : _initsMetadata.at(initIndex).outputs) {+ const auto currentOutputBufferLocation =+ static_cast<unsigned char*>(const_cast<void*>(initOutputsAllocatedTensor->data(ov::element::Type_t::u8))) ++ offset;++ const ov::SoPtr<ov::ITensor> hostTensor =+ ov::make_tensor(descriptor.precision, descriptor.shapeFromCompiler.to_shape(), currentOutputBufferLocation);++ initOutputsViewTensorsVector.push_back(hostTensor._ptr);+ initOutputsViewTensorsMap.emplace(descriptor.nameFromCompiler, hostTensor._ptr);+ offset +=+ ov::element::get_memory_size(descriptor.precision, shape_size(descriptor.shapeFromCompiler.to_shape()));+ }++ return {initOutputsViewTensorsVector, initOutputsAllocatedTensor, initOutputsViewTensorsMap};+}++void WeightlessGraph::run_init_single_threaded() {+ auto constants = get_all_constants_in_topological_order(_model, _logger);++ for (size_t initIndex = 0; initIndex < _initsHandles.size(); ++initIndex) {+ auto [initInputsViewTensors, initInputsAllocatedTensor] = allocate_inputs(initIndex, constants);++ // We don't need these anymore, potentially save some memory+ _model = nullptr;+ constants = {};+ auto [initOutputsViewTensors, initOutputsAllocatedTensor, initOutputsViewTensorsMap] =+ allocate_outputs(initIndex);++ // Create zero-pipeline and run it (infer init schedule)+ create_pipeline(initIndex, initInputsViewTensors, initOutputsViewTensors);+ run_pipeline(initIndex);++ merge_two_maps(_mainInputsViewTensors, initOutputsViewTensorsMap);+ _mainInputsAllocatedTensors.push_back(std::move(initOutputsAllocatedTensor));+ }+}++void WeightlessGraph::run_init_multi_threaded() {+ if (_initsHandles.size() == 1) {+ _logger.info("::run_init_multi_threaded() for single init - fallback to ::runInit()");+ run_init_single_threaded();+ return;+ }++ std::unordered_map<std::string, std::shared_ptr<ZeroHostTensor>> weightsInputs;+ std::vector<ov::SoPtr<ZeroHostTensor>> initTensors;++ // the pipeline:+ // allocate I/O -> create Pipeline -> run Pipeline+ // allocate I/O -> create Pipeline -> run Pipeline+ Parallelizer multiThreadedRunner(+ _model,+ [&](const std::unordered_map<size_t, std::shared_ptr<ov::op::v0::Constant>>& constants,+ int64_t initIndex) -> QueueData {+ QueueData data{};+ data.initIndex = initIndex;+ data.inputs = allocate_inputs(initIndex, constants);+ data.outputs = allocate_outputs(initIndex);+ return data;+ },+ [&](QueueData&& data, std::condition_variable& cv, std::atomic_bool& flag) {+ // Create zero-pipeline and run it (infer init schedule)+ ze_device_properties_t properties = {};+ properties.stype = ZE_STRUCTURE_TYPE_DEVICE_PROPERTIES;+ THROW_ON_FAIL_FOR_LEVELZERO("zeDeviceGetProperties",+ zeDeviceGetProperties(_zeroInitStruct->getDevice(), &properties));++ create_pipeline(data.initIndex, data.inputs.tensors, data.outputs.tensors);++ // progress task 1:+ flag.store(true);+ cv.notify_one();++ run_pipeline(data.initIndex);++ // TODO: pre-allocate those well in advance? (outside of this loop)+ merge_two_maps(_mainInputsViewTensors, data.outputs.tensorsMap);+ _mainInputsAllocatedTensors.push_back(data.outputs.hostTensor);+ },+ _logger);++ multiThreadedRunner.callForAllAndWait(_initsHandles.size());+ _model = nullptr;+}++void WeightlessGraph::create_pipeline(const size_t initIndex,+ const std::vector<std::shared_ptr<ov::ITensor>>& inputTensors,+ const std::vector<std::shared_ptr<ov::ITensor>>& outputTensors) {+ _logger.debug("Init Pipeline - initialize started");++ if (_zeGraphExt == nullptr) {+ OPENVINO_THROW("Zero compiler adapter wasn't initialized");+ }++ _initsCommandLists.at(initIndex) =+ std::make_unique<CommandList>(_zeroInitStruct, _initsCommandQueueOrdinals.at(initIndex));+ _initsFences.at(initIndex) = std::make_unique<Fence>(_initsCommandQueue);++ size_t io_index = 0;+ for (const auto& desc : _initsInputDescriptors.at(initIndex)) {+ void* data = inputTensors.at(io_index++)->data();+ _zeGraphExt->setGraphArgumentValue(_initsHandles.at(initIndex), desc.idx, static_cast<unsigned char*>(data));+ }++ io_index = 0;+ for (const auto& desc : _initsOutputDescriptors.at(initIndex)) {+ void* data = outputTensors.at(io_index++)->data();+ _zeGraphExt->setGraphArgumentValue(_initsHandles.at(initIndex), desc.idx, static_cast<unsigned char*>(data));+ }++ _initsCommandLists.at(initIndex)->appendGraphExecute(static_cast<ze_graph_handle_t>(_initsHandles.at(initIndex)),+ nullptr);++ _logger.debug("Init Pipeline - initialize completed");+}++void WeightlessGraph::run_pipeline(const size_t initIndex) {+ _logger.debug("Init Pipeline - push() started");+ _initsCommandLists.at(initIndex)->close();++ _initsCommandQueue->executeCommandList(*_initsCommandLists.at(initIndex), *_initsFences.at(initIndex));+ _logger.debug("Init Pipeline - push() completed");++ _logger.debug("Init Pipeline - pull() started");+ _initsFences.at(initIndex)->hostSynchronize();+ _logger.debug("Init Pipeline - pull() completed");+}++void WeightlessGraph::set_weights_inputs() {+ for (const auto& desc : _input_descriptors) {+ if (!isMainInputWeightsName(desc.info.name)) {+ continue;+ }++ const std::string weightsInputName = std::string(desc.info.name).substr(MAIN_INPUT_WEIGHTS_PREFIX.size());+ OPENVINO_ASSERT(_mainInputsViewTensors.count(weightsInputName),+ "Mismatch between main inputs and init outputs. The input of the main schedule \"",+ weightsInputName,+ "\" has no correspondent within the init outputs.");+ std::shared_ptr<ov::ITensor> weightsTensor = _mainInputsViewTensors.at(weightsInputName);+ set_argument_value(desc.idx, static_cast<unsigned char*>(weightsTensor->data()));+ }+}++void WeightlessGraph::release_init_blob(const size_t initIndex, const Config& config) {+ if (!_blobAllocatedByPlugin || _initBlobs == std::nullopt || config.get<PERF_COUNT>()) {+ return;+ }++ ze_graph_properties_2_t properties = {};+ properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(_initsHandles.at(initIndex), &properties);++ if (~properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {+ return;+ }++ _initBlobs->at(initIndex) = ov::Tensor();+ _logger.debug("Blob is released");+}++WeightlessGraph::~WeightlessGraph() {+ // make sure all the context-dependent components are destroyed before the zero context is destroyed+ for (auto& initHandle : _initsHandles) {+ if (initHandle != nullptr) {+ auto result = _zeGraphExt->destroyGraph(initHandle);++ if (ZE_RESULT_SUCCESS == result) {+ initHandle = nullptr;+ }+ }+ }+}++} // namespace intel_npudiff --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 17d6014b485..e155e29cc6f 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@@ -376,18 +376,31 @@ static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,// Flags will be used instead of indices for informing the type of the current entrystd::string nameFromCompiler = arg.name;+ const bool isInput = (arg.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT);bool isStateInput = false;bool isStateOutput = false;bool isShapeTensor = false;- if (isStateInputName(nameFromCompiler)) {+ bool isInitInputWeights = false;+ bool isInitOutputWeights = false;+ bool isMainInputWeights = false;+ if (isInput && isStateInputName(nameFromCompiler)) {nameFromCompiler = nameFromCompiler.substr(READVALUE_PREFIX.length());isStateInput = true;- } else if (isStateOutputName(nameFromCompiler)) {+ } else if (!isInput && isStateOutputName(nameFromCompiler)) {nameFromCompiler = nameFromCompiler.substr(ASSIGN_PREFIX.length());isStateOutput = true;} else if (isShapeTensorName(nameFromCompiler)) {nameFromCompiler = nameFromCompiler.substr(SHAPE_TENSOR_PREFIX.length());isShapeTensor = true;+ } else if (isInput && isInitInputWeightsName(nameFromCompiler)) {+ nameFromCompiler = nameFromCompiler.substr(INIT_INPUT_WEIGHTS_PREFIX.length());+ isInitInputWeights = true;+ } else if (!isInput && isInitOutputWeightsName(nameFromCompiler)) {+ nameFromCompiler = nameFromCompiler.substr(INIT_OUTPUT_WEIGHTS_PREFIX.length());+ isInitOutputWeights = true;+ } else if (isInput && isMainInputWeightsName(nameFromCompiler)) {+ nameFromCompiler = nameFromCompiler.substr(MAIN_INPUT_WEIGHTS_PREFIX.length());+ isMainInputWeights = true;}return {std::move(nameFromCompiler),@@ -396,6 +409,9 @@ static IODescriptor getIODescriptor(const ze_graph_argument_properties_3_t& arg,isStateInput,isStateOutput,isShapeTensor,+ isInitInputWeights,+ isInitOutputWeights,+ isMainInputWeights,std::nullopt,arg.debug_friendly_name,std::move(outputTensorNames),@@ -432,7 +448,9 @@ void ZeGraphExtWrappers::getMetadata(ze_graph_handle_t graphHandle,std::optional<ze_graph_argument_metadata_t> optionalMetadata = std::nullopt;- if (!isStateInputName(arg.name) && !isStateOutputName(arg.name) && !isShapeTensorName(arg.name)) {+ if (!isStateInputName(arg.name) && !isStateOutputName(arg.name) && !isShapeTensorName(arg.name) &&+ !isInitInputWeightsName(arg.name) && !isInitOutputWeightsName(arg.name) &&+ !isMainInputWeightsName(arg.name)) {_logger.debug("getMetadata - perform pfnGetArgumentMetadata");ze_graph_argument_metadata_t metadata = {};result = _zeroInitStruct->getGraphDdiTable().pfnGraphGetArgumentMetadata(graphHandle, index, &metadata);diff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hppindex 52e202d8812..52b6ea00e97 100644--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp@@ -8,17 +8,15 @@#include <memory>#include <optional>#include <string>+#include <vector>#include "openvino/core/version.hpp"namespace intel_npu {-struct MetadataBase {-protected:- uint32_t _version;-+class MetadataBase {public:- MetadataBase(uint32_t version) : _version(version) {}+ MetadataBase(uint32_t version, uint64_t blobDataSize);/*** @brief Reads metadata from a stream.@@ -30,9 +28,23 @@ public:*/virtual void write(std::ostream& stream) = 0;+ /**+ * @brief Adds the size of the binary object and the magic string to the end of the stream.+ * @details This should be called after the "write" method in order to conclude writing the metadata into the given+ * stream.+ * @note This operation was detached from "write" since "write" writes at the beginning of the stream, while this+ * method writes at the end. This change allows better extension of class hierarchy.+ */+ void append_blob_size_and_magic(std::ostream& stream);+virtual bool is_compatible() = 0;- virtual uint64_t get_blob_size() const = 0;+ virtual uint64_t get_blob_size() const;++ /**+ * @returns The sizes of the init schedules. Populated only if "weights separation" has been enabled.+ */+ virtual std::optional<std::vector<uint64_t>> get_init_sizes() const = 0;virtual ~MetadataBase() = default;@@ -65,6 +77,10 @@ public:static constexpr uint16_t get_minor(uint32_t version) {return static_cast<uint16_t>(version);}++protected:+ uint32_t _version;+ uint64_t _blobDataSize;};/**@@ -76,21 +92,17 @@ constexpr std::string_view MAGIC_BYTES = "OVNPU";* @brief List of supported version formats.*/constexpr uint32_t METADATA_VERSION_2_0{MetadataBase::make_version(2, 0)};+constexpr uint32_t METADATA_VERSION_2_1{MetadataBase::make_version(2, 1)};/*** @brief Current metadata version.*/-constexpr uint32_t CURRENT_METADATA_VERSION{METADATA_VERSION_2_0};+constexpr uint32_t CURRENT_METADATA_VERSION{METADATA_VERSION_2_1};constexpr uint16_t CURRENT_METADATA_MAJOR_VERSION{MetadataBase::get_major(CURRENT_METADATA_VERSION)};constexpr uint16_t CURRENT_METADATA_MINOR_VERSION{MetadataBase::get_minor(CURRENT_METADATA_VERSION)};-struct OpenvinoVersion final {-private:- uint16_t _major;- uint16_t _minor;- uint16_t _patch;-+class OpenvinoVersion final {public:constexpr OpenvinoVersion(uint16_t major, uint16_t minor, uint16_t patch): _major(major),@@ -128,6 +140,11 @@ public:uint16_t get_patch() const;bool operator!=(const OpenvinoVersion& version);++private:+ uint16_t _major;+ uint16_t _minor;+ uint16_t _patch;};constexpr OpenvinoVersion CURRENT_OPENVINO_VERSION(OPENVINO_VERSION_MAJOR,@@ -144,11 +161,7 @@ struct Metadata : public MetadataBase {};* @brief Template specialization for metadata version 1.0.*/template <>-struct Metadata<METADATA_VERSION_2_0> : public MetadataBase {-protected:- OpenvinoVersion _ovVersion;- uint64_t _blobDataSize;-+class Metadata<METADATA_VERSION_2_0> : public MetadataBase {public:Metadata(uint64_t blobSize, std::optional<OpenvinoVersion> ovVersion = std::nullopt);@@ -177,7 +190,38 @@ public:*/bool is_compatible() override;- uint64_t get_blob_size() const override;+ std::optional<std::vector<uint64_t>> get_init_sizes() const override;++protected:+ OpenvinoVersion _ovVersion;+};++/**+ * @brief The version that adds support for init schedules (weights separation).+ */+template <>+class Metadata<METADATA_VERSION_2_1> : public Metadata<METADATA_VERSION_2_0> {+public:+ Metadata(uint64_t blobSize,+ std::optional<OpenvinoVersion> ovVersion = std::nullopt,+ const std::optional<std::vector<uint64_t>> initSizes = std::nullopt);++ /**+ * @details The number of init schedules, along with the size of each init binary object are read in addition to the+ * information provided by the previous metadata versions.+ */+ void read(std::istream& stream) override;++ /**+ * @details The number of init schedules, along with the size of each init binary object are written in addition to+ * the information registered by the previous metadata versions.+ */+ void write(std::ostream& stream) override;++ std::optional<std::vector<uint64_t>> get_init_sizes() const override;++private:+ std::optional<std::vector<uint64_t>> _initSizes;};/**diff --git a/src/plugins/intel_npu/src/plugin/include/plugin.hpp b/src/plugins/intel_npu/src/plugin/include/plugin.hppindex 66e4e8dc953..fd0ca1da73d 100644--- a/src/plugins/intel_npu/src/plugin/include/plugin.hpp+++ b/src/plugins/intel_npu/src/plugin/include/plugin.hpp@@ -68,6 +68,30 @@ private:const std::unique_ptr<ICompilerAdapter>& compiler,OptionMode mode = OptionMode::Both) 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 stream Contains the whole binary object.+ * @param tensorBig Contains the whole binary object.+ * @param compiler Instance used for parsing the compiled model.+ * @param tensorFromProperty Indicates whether or not the compiled model has been provided to the plugin as a tensor+ * object.+ * @param localConfig Propagated to the compiler. Multiple entries are also extracted by this method.+ * @param properties Configuration taking the form of an "ov::AnyMap".+ * @return A wrapper over the L0 handle that can be used for running predictions. The inherited type will depend on+ * the active flow (e.g. may be a "WeightlessGraph" if "weights separation" has been enabled).+ */+ std::shared_ptr<IGraph> parse(std::istream& stream,+ const ov::Tensor& tensorBig,+ const std::unique_ptr<ICompilerAdapter>& compiler,+ const bool tensorFromProperty,+ const Config& localConfig,+ const ov::AnyMap& properties) const;+std::unique_ptr<BackendsRegistry> _backendsRegistry;// _backend might not be set by the plugin; certain actions, such as offline compilation, might be supported.diff --git a/src/plugins/intel_npu/src/plugin/include/properties.hpp b/src/plugins/intel_npu/src/plugin/include/properties.hppindex 4b1acdd032b..d6f0b5f04fa 100644--- a/src/plugins/intel_npu/src/plugin/include/properties.hpp+++ b/src/plugins/intel_npu/src/plugin/include/properties.hpp@@ -77,8 +77,8 @@ private:ov::intel_npu::compiler_type.name(),ov::intel_npu::batch_mode.name(),ov::hint::execution_mode.name(),- // NPUW caching propertiesov::cache_mode.name(),+ // NPUW caching propertiesov::intel_npu::use_npuw.name(),ov::intel_npu::npuw::devices.name(),ov::intel_npu::npuw::submodel_device.name(),diff --git a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/src/compiled_model.cppindex ad025297a42..0ca9c625abd 100644--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp@@ -13,7 +13,6 @@#include "intel_npu/config/options.hpp"#include "metadata.hpp"#include "openvino/pass/constant_folding.hpp"-#include "openvino/pass/manager.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/system_conf.hpp"#include "openvino/runtime/threading/executor_manager.hpp"@@ -88,10 +87,12 @@ std::shared_ptr<ov::ISyncInferRequest> CompiledModel::create_sync_infer_request(void CompiledModel::export_model(std::ostream& stream) const {_logger.debug("CompiledModel::export_model");- size_t blobSizeBeforeVersioning = _graph->export_blob(stream);- auto meta = Metadata<CURRENT_METADATA_VERSION>(blobSizeBeforeVersioning, CURRENT_OPENVINO_VERSION);+ auto [blobSizesBeforeVersioning, initBlobSizes] = _graph->export_blob(stream);++ auto meta = Metadata<CURRENT_METADATA_VERSION>(blobSizesBeforeVersioning, CURRENT_OPENVINO_VERSION, initBlobSizes);meta.write(stream);+ meta.append_blob_size_and_magic(stream);}std::shared_ptr<const ov::Model> CompiledModel::get_runtime_model() const {diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cppindex a6a5f43d641..a2fe2c31ab0 100644--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp@@ -45,20 +45,59 @@ void OpenvinoVersion::write(std::ostream& stream) {stream.write(reinterpret_cast<const char*>(&_patch), sizeof(_patch));}+MetadataBase::MetadataBase(uint32_t version, uint64_t blobDataSize) : _version(version), _blobDataSize(blobDataSize) {}+Metadata<METADATA_VERSION_2_0>::Metadata(uint64_t blobSize, std::optional<OpenvinoVersion> ovVersion)- : MetadataBase{METADATA_VERSION_2_0},- _ovVersion{ovVersion.value_or(CURRENT_OPENVINO_VERSION)},- _blobDataSize{blobSize} {}+ : MetadataBase{METADATA_VERSION_2_0, blobSize},+ _ovVersion{ovVersion.value_or(CURRENT_OPENVINO_VERSION)} {}++Metadata<METADATA_VERSION_2_1>::Metadata(uint64_t blobSize,+ std::optional<OpenvinoVersion> ovVersion,+ const std::optional<std::vector<uint64_t>> initSizes)+ : Metadata<METADATA_VERSION_2_0>{blobSize, ovVersion},+ _initSizes{initSizes} {+ _version = METADATA_VERSION_2_1;+}void Metadata<METADATA_VERSION_2_0>::read(std::istream& stream) {_ovVersion.read(stream);}+void Metadata<METADATA_VERSION_2_1>::read(std::istream& stream) {+ Metadata<METADATA_VERSION_2_0>::read(stream);++ uint64_t numberOfInits;+ stream.read(reinterpret_cast<char*>(&numberOfInits), sizeof(numberOfInits));++ if (numberOfInits) {+ _initSizes = std::vector<uint64_t>(numberOfInits);+ for (uint64_t initIndex = 0; initIndex < numberOfInits; ++initIndex) {+ stream.read(reinterpret_cast<char*>(&_initSizes->at(initIndex)), sizeof(_initSizes->at(initIndex)));+ }+ }+}++void MetadataBase::append_blob_size_and_magic(std::ostream& stream) {+ stream.write(reinterpret_cast<const char*>(&_blobDataSize), sizeof(_blobDataSize));+ stream.write(MAGIC_BYTES.data(), MAGIC_BYTES.size());+}+void Metadata<METADATA_VERSION_2_0>::write(std::ostream& stream) {stream.write(reinterpret_cast<const char*>(&_version), sizeof(_version));_ovVersion.write(stream);- stream.write(reinterpret_cast<const char*>(&_blobDataSize), sizeof(_blobDataSize));- stream.write(MAGIC_BYTES.data(), MAGIC_BYTES.size());+}++void Metadata<METADATA_VERSION_2_1>::write(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_0>::write(stream);++ uint64_t numberOfInits = _initSizes.has_value() ? _initSizes->size() : 0;+ stream.write(reinterpret_cast<const char*>(&numberOfInits), sizeof(numberOfInits));++ if (_initSizes.has_value()) {+ for (uint64_t initSize : _initSizes.value()) {+ stream.write(reinterpret_cast<const char*>(&initSize), sizeof(initSize));+ }+ }}std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSize) {@@ -70,7 +109,8 @@ std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSizswitch (version) {case METADATA_VERSION_2_0:return std::make_unique<Metadata<METADATA_VERSION_2_0>>(blobSize, std::nullopt);-+ case METADATA_VERSION_2_1:+ return std::make_unique<Metadata<METADATA_VERSION_2_1>>(blobSize, std::nullopt);default:OPENVINO_THROW("Metadata version is not supported!");}@@ -161,8 +201,15 @@ std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream) {return storedMeta;}-uint64_t Metadata<METADATA_VERSION_2_0>::get_blob_size() const {+uint64_t MetadataBase::get_blob_size() const {return _blobDataSize;}+std::optional<std::vector<uint64_t>> Metadata<METADATA_VERSION_2_0>::get_init_sizes() const {+ return std::nullopt;+}+std::optional<std::vector<uint64_t>> Metadata<METADATA_VERSION_2_1>::get_init_sizes() const {+ return _initSizes;+}+} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex cfe544c6719..42c2f2f97ec 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -20,6 +20,7 @@#include "npuw/compiled_model.hpp"#include "npuw/llm_compiled_model.hpp"#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"@@ -34,6 +35,9 @@ namespace {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_EXTENSION = ".bin";+constexpr std::string_view XML_EXTENSION = ".xml";+constexpr std::string_view ONNX_EXTENSION = ".onnx";/*** @brief Creates an "ov::Model" object which contains only the given "parameter" and "result" nodes.@@ -54,7 +58,8 @@ std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& iov::ResultVector results;for (const IODescriptor& inputDescriptor : inputDescriptors) {- if (inputDescriptor.isStateInput || inputDescriptor.isStateOutput || inputDescriptor.isShapeTensor) {+ if (inputDescriptor.isStateInput || inputDescriptor.isStateOutput || inputDescriptor.isShapeTensor ||+ inputDescriptor.isInitInputWeights || inputDescriptor.isMainInputWeights) {continue;}@@ -73,7 +78,8 @@ std::shared_ptr<ov::Model> create_dummy_model(const std::vector<IODescriptor>& i// constant can't have dynamic shape). The dummy tensor was also brought in order to register the correct,// potentially dynamic, output shape.for (const IODescriptor& outputDescriptor : outputDescriptors) {- if (outputDescriptor.isStateInput || outputDescriptor.isStateOutput || outputDescriptor.isShapeTensor) {+ if (outputDescriptor.isStateInput || outputDescriptor.isStateOutput || outputDescriptor.isShapeTensor ||+ outputDescriptor.isInitOutputWeights) {continue;}@@ -127,6 +133,26 @@ static ov::intel_npu::CompilerType resolveCompilerType(const FilteredConfig& basreturn base_conf.get<COMPILER_TYPE>();}+/**+ * @brief Just checks if there is any "WeightlessCacheAttribute" present in the model. In the negative case, an error is+ * thrown. The weights separation flow in its current state cannot work without this attribuite.+ */+void check_weightless_cache_attribute_occurrence(const std::shared_ptr<const ov::Model>& model) {+ for (const auto& ov_node : model->get_ordered_ops()) {+ if (!ov::is_type<ov::op::v0::Constant>(ov_node)) {+ continue;+ }++ if (auto it = ov_node->get_rt_info().find(ov::WeightlessCacheAttribute::get_type_info_static());+ it != ov_node->get_rt_info().end()) {+ return;+ }+ }++ OPENVINO_THROW("No \"WeightlessCacheAttribute\" has been found in any of the model's Constant nodes. This "+ "attribute is required for running the \"weights separation\" flow.");+}+} // namespacenamespace intel_npu {@@ -180,6 +206,8 @@ void Plugin::init_options() {REGISTER_OPTION(LOG_LEVEL);REGISTER_OPTION(CACHE_DIR);+ REGISTER_OPTION(CACHE_MODE);+ REGISTER_OPTION(COMPILED_BLOB);REGISTER_OPTION(DEVICE_ID);REGISTER_OPTION(NUM_STREAMS);REGISTER_OPTION(PERF_COUNT);@@ -215,6 +243,10 @@ void Plugin::init_options() {REGISTER_OPTION(MODEL_PTR);REGISTER_OPTION(BATCH_COMPILER_MODE_SETTINGS);REGISTER_OPTION(TURBO);+ REGISTER_OPTION(WEIGHTLESS_BLOB);+ REGISTER_OPTION(SEPARATE_WEIGHTS_VERSION);+ REGISTER_OPTION(WS_COMPILE_CALL_NUMBER);+if (_backend) {if (_backend->isCommandQueueExtSupported()) {REGISTER_OPTION(WORKLOAD_TYPE);@@ -229,9 +261,8 @@ void Plugin::init_options() {// filter out unsupported optionsfilter_config_by_compiler_support(_globalConfig);- // NPUW properties are requested by OV Core during caching and have no effect on the NPU plugin. But we still need to enable those for OV Core to query.- // Note: do this last to not filter them out.- // register npuw caching properties+ // NPUW properties are requested by OV Core during caching and have no effect on the NPU plugin. But we still need+ // to enable those for OV Core to query. Note: do this last to not filter them out. register npuw caching propertiesREGISTER_OPTION(NPU_USE_NPUW);REGISTER_OPTION(NPUW_DEVICES);REGISTER_OPTION(NPUW_SUBMODEL_DEVICE);@@ -527,13 +558,34 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<}}- auto originalModel = model->clone();-OV_ITT_TASK_NEXT(PLUGIN_COMPILE_MODEL, "compile");++ if (localConfig.isAvailable(ov::intel_npu::weightless_blob.name()) && !localConfig.get<CACHE_DIR>().empty()) {+ // If OV caching is enabled, then weights separation is performed only if the user opted for optimizing the+ // size of the binary object+ const bool cacheModeOptimizeSize = (localConfig.get<CACHE_MODE>() == ov::CacheMode::OPTIMIZE_SIZE);+ if (localConfig.get<WEIGHTLESS_BLOB>() && !cacheModeOptimizeSize) {+ _logger.warning("The cache mode was not set to \"optimize size\" but the \"WEIGHTLESS_BLOB\" configuration "+ "option was set to true. Weights separation WILL NOT be performed in this case.");+ } else if (!localConfig.get<WEIGHTLESS_BLOB>() && cacheModeOptimizeSize) {+ _logger.warning("The cache mode was set to \"optimize size\" but the \"WEIGHTLESS_BLOB\" configuration "+ "option was set to false. Weights separation WILL be performed in this case.");+ }++ localConfig.update({{ov::intel_npu::weightless_blob.name(), cacheModeOptimizeSize ? "YES" : "NO"}});+ }+std::shared_ptr<intel_npu::IGraph> graph;+try {_logger.debug("performing compile");- graph = compiler->compile(model->clone(), localConfig);++ if (!localConfig.get<WEIGHTLESS_BLOB>()) {+ graph = compiler->compile(model->clone(), localConfig);+ } else {+ check_weightless_cache_attribute_occurrence(model);+ graph = compiler->compileWS(model->clone(), localConfig);+ }} catch (const std::exception& ex) {OPENVINO_THROW(ex.what());} catch (...) {@@ -585,8 +637,6 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& origStreastd::istream stream{origStream.rdbuf()};ov::SharedStreamBuffer buffer{nullptr, 0}; // used only if blob is given by tensor, but it is not OV cached blob- // ov::hint::compiled_blob has no corresponding "Config" implementation thus we need to remove it from the- // list of propertiesif (auto blob_it = npu_plugin_properties.find(ov::hint::compiled_blob.name());blob_it != npu_plugin_properties.end()) {tensor = blob_it->second.as<ov::Tensor>();@@ -601,7 +651,6 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& origStreabuffer = ov::SharedStreamBuffer(reinterpret_cast<char*>(tensor.data()), tensor.get_byte_size());stream.rdbuf(&buffer);}- npu_plugin_properties.erase(blob_it);}// If was exported via NPUW@@ -657,32 +706,11 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& origStreastd::shared_ptr<ov::ICompiledModel> compiledModel;try {- const bool skipCompatibility = localConfig.get<DISABLE_VERSION_CHECK>();- size_t blobSize = MetadataBase::getFileSize(stream);- if (!skipCompatibility) {- auto storedMeta = read_metadata_from(stream);- if (!storedMeta->is_compatible()) {- OPENVINO_THROW("Incompatible blob version!");- }- blobSize = storedMeta->get_blob_size();- }- if (tensorFromProperty == false) { // tensor was not received from ov::compiled_blob property, copy from stream- tensor = ov::Tensor(ov::element::u8, ov::Shape{blobSize});- if (blobSize > static_cast<decltype(blobSize)>(std::numeric_limits<std::streamsize>::max())) {- OPENVINO_THROW("Blob size is too large to be represented on a std::streamsize!");- }- stream.read(tensor.data<char>(), static_cast<std::streamsize>(blobSize));- } else {- tensor = ov::Tensor(tensor,- ov::Coordinate{0},- ov::Coordinate{blobSize}); // ROI tensor to skip NPU plugin metadata- }- auto graph = compiler->parse(std::move(tensor), !tensorFromProperty, localConfig);- graph->update_network_name("net" + std::to_string(_compiledModelLoadCounter++));+ const std::shared_ptr<IGraph> graph =+ parse(stream, tensor, compiler, tensorFromProperty, localConfig, properties);const std::shared_ptr<ov::Model> modelDummy =create_dummy_model(graph->get_metadata().inputs, graph->get_metadata().outputs);-compiledModel = std::make_shared<CompiledModel>(modelDummy, shared_from_this(), device, graph, localConfig);} catch (const std::exception& ex) {OPENVINO_THROW("Can't import network: ", ex.what());@@ -695,6 +723,113 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& origStreareturn compiledModel;}+std::shared_ptr<IGraph> Plugin::parse(std::istream& stream,+ const ov::Tensor& tensorBig,+ const std::unique_ptr<ICompilerAdapter>& compiler,+ const bool tensorFromProperty,+ const Config& config,+ const ov::AnyMap& properties) const {+ uint64_t mainSize;+ std::optional<std::vector<uint64_t>> initSizes;++ const bool skipCompatibility = config.get<DISABLE_VERSION_CHECK>();+ if (!skipCompatibility) {+ auto storedMeta = read_metadata_from(stream);+ if (!storedMeta->is_compatible()) {+ OPENVINO_THROW("Incompatible blob version!");+ }++ size_t accumulator = 0;+ initSizes = storedMeta->get_init_sizes();+ mainSize = initSizes.has_value() ? storedMeta->get_blob_size() -+ std::accumulate(initSizes->begin(), initSizes->end(), accumulator)+ : storedMeta->get_blob_size();+ } else {+ _logger.info("Blob compatibility check skipped.");+ mainSize = MetadataBase::getFileSize(stream);+ }++ ov::Tensor tensorMain;+ if (tensorFromProperty == false) { // tensor was not received from ov::compiled_blob property, copy from stream+ tensorMain = ov::Tensor(ov::element::u8, ov::Shape{mainSize});+ stream.read(tensorMain.data<char>(), mainSize);+ } else {+ tensorMain = ov::Tensor(tensorBig,+ ov::Coordinate{0},+ ov::Coordinate{mainSize}); // ROI tensor to skip NPU plugin metadata+ }++ std::shared_ptr<const ov::Model> originalModel;+ std::vector<ov::Tensor> tensorsInits;+ const bool weightsSeparationEnabled = initSizes.has_value();++ if (weightsSeparationEnabled) {+ // Read the init compiled models as well+ size_t cursorPosition = mainSize;+ ov::Tensor tensorInit;+ for (uint64_t initSize : initSizes.value()) {+ if (tensorFromProperty == false) {+ tensorInit = ov::Tensor(ov::element::u8, ov::Shape{initSize});+ stream.read(tensorInit.data<char>(), initSize);+ } else {+ tensorInit =+ ov::Tensor(tensorBig, 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 (properties.count(ov::hint::model.name())) {+ try {+ originalModel = properties.at(ov::hint::model.name()).as<std::shared_ptr<const ov::Model>>();+ } catch (const ov::AssertFailure&) {+ try {+ originalModel = std::const_pointer_cast<const ov::Model>(+ properties.at(ov::hint::model.name()).as<std::shared_ptr<ov::Model>>());+ } catch (const ov::Exception&) {+ OPENVINO_THROW("The value of the \"ov::hint::model\" configuration option (\"MODEL_PTR\") has the "+ "wrong data type. Expected: std::shared_ptr<const ov::Model>.");+ }+ }+ } else if (!config.get<WEIGHTS_PATH>().empty()) {+ const std::string weightsPath = config.get<WEIGHTS_PATH>();+ const size_t weightsPathLength = weightsPath.length();+ std::string xmlPath = weightsPath;++ if (weightsPathLength > WEIGHTS_EXTENSION.length() &&+ weightsPath.compare(weightsPathLength - WEIGHTS_EXTENSION.length(),+ WEIGHTS_EXTENSION.length(),+ WEIGHTS_EXTENSION) == 0) {+ xmlPath.replace(weightsPathLength - WEIGHTS_EXTENSION.length(),+ WEIGHTS_EXTENSION.length(),+ XML_EXTENSION);+ } else if (weightsPathLength <= ONNX_EXTENSION.length() ||+ weightsPath.compare(weightsPathLength - ONNX_EXTENSION.length(),+ ONNX_EXTENSION.length(),+ ONNX_EXTENSION)) {+ OPENVINO_THROW("Invalid path to the weights: ",+ weightsPath,+ ". A \".bin\" or \".onnx\" extension was expected.");+ }++ originalModel = get_core()->read_model(xmlPath, weightsPath, properties);+ } else {+ OPENVINO_THROW("Attempted to load a weightless compiled model, but no weights have been provided");+ }++ check_weightless_cache_attribute_occurrence(originalModel);+ }++ auto graph = compiler->parse(std::move(tensorMain),+ !tensorFromProperty,+ config,+ weightsSeparationEnabled ? std::make_optional(std::move(tensorsInits)) : std::nullopt,+ weightsSeparationEnabled ? std::make_optional(originalModel) : std::nullopt);+ graph->update_network_name("net" + std::to_string(_compiledModelLoadCounter++));+ return graph;+}+std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream,const ov::SoPtr<ov::IRemoteContext>& context,const ov::AnyMap& properties) const {@@ -706,8 +841,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream,return import_model(stream, properties);}-std::shared_ptr<ov::ICompiledModel> Plugin::import_model(ov::Tensor& model,- const ov::AnyMap& properties) const{+std::shared_ptr<ov::ICompiledModel> Plugin::import_model(ov::Tensor& model, const ov::AnyMap& properties) const {ov::SharedStreamBuffer buffer{reinterpret_cast<char*>(model.data()), model.get_byte_size()};std::istream stream{&buffer};return import_model(stream, properties);@@ -715,13 +849,12 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(ov::Tensor& model,std::shared_ptr<ov::ICompiledModel> Plugin::import_model(ov::Tensor& model,const ov::SoPtr<ov::IRemoteContext>& context,- const ov::AnyMap& properties) const{+ const ov::AnyMap& properties) const {ov::SharedStreamBuffer buffer{reinterpret_cast<char*>(model.data()), model.get_byte_size()};std::istream stream{&buffer};return import_model(stream, context, properties);}-ov::SupportedOpsMap Plugin::query_model(const std::shared_ptr<const ov::Model>& model,const ov::AnyMap& properties) const {OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "Plugin::query_model");diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cppindex 89d4eb3713a..13957d98941 100644--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp@@ -353,6 +353,8 @@ void Properties::registerPluginProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::hint::inference_precision, INFERENCE_PRECISION_HINT);TRY_REGISTER_SIMPLE_PROPERTY(ov::log::level, LOG_LEVEL);TRY_REGISTER_SIMPLE_PROPERTY(ov::cache_dir, CACHE_DIR);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::cache_mode, CACHE_MODE);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::hint::compiled_blob, COMPILED_BLOB);TRY_REGISTER_SIMPLE_PROPERTY(ov::device::id, DEVICE_ID);TRY_REGISTER_SIMPLE_PROPERTY(ov::num_streams, NUM_STREAMS);TRY_REGISTER_SIMPLE_PROPERTY(ov::weights_path, WEIGHTS_PATH);@@ -378,6 +380,8 @@ void Properties::registerPluginProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::batch_compiler_mode_settings, BATCH_COMPILER_MODE_SETTINGS);TRY_REGISTER_SIMPLE_PROPERTY(ov::hint::enable_cpu_pinning, ENABLE_CPU_PINNING);TRY_REGISTER_SIMPLE_PROPERTY(ov::workload_type, WORKLOAD_TYPE);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::weightless_blob, WEIGHTLESS_BLOB);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::separate_weights_version, SEPARATE_WEIGHTS_VERSION);TRY_REGISTER_CUSTOMFUNC_PROPERTY(ov::intel_npu::stepping, STEPPING, [&](const Config& config) {if (!config.has<STEPPING>()) {@@ -556,6 +560,7 @@ void Properties::registerCompiledModelProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::hint::num_requests, PERFORMANCE_HINT_NUM_REQUESTS);TRY_REGISTER_SIMPLE_PROPERTY(ov::compilation_num_threads, COMPILATION_NUM_THREADS);TRY_REGISTER_SIMPLE_PROPERTY(ov::hint::inference_precision, INFERENCE_PRECISION_HINT);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::cache_mode, CACHE_MODE);// Properties we shall only enable if they were set prior-to-compilationTRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::hint::model, MODEL_PTR);@@ -581,6 +586,8 @@ void Properties::registerCompiledModelProperties() {TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::batch_compiler_mode_settings,BATCH_COMPILER_MODE_SETTINGS);TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::run_inferences_sequentially, RUN_INFERENCES_SEQUENTIALLY);+ TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::weightless_blob, WEIGHTLESS_BLOB);+ TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::separate_weights_version, SEPARATE_WEIGHTS_VERSION);TRY_REGISTER_VARPUB_PROPERTY(ov::intel_npu::batch_mode, BATCH_MODE, false);diff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cppindex eb3d10a801e..d680c456abe 100644--- a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp@@ -108,6 +108,7 @@ void ZeroRemoteTensor::update_strides() {}const std::string& ZeroRemoteTensor::get_device_name() const {+ OPENVINO_ASSERT(_context != nullptr);return _context->get_device_name();}diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xmlindex 57fc5875bcc..a480db88e9a 100644--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml@@ -867,14 +867,32 @@ Example:</filters></skip_config>- <!-- CACHE_MODE is not supported on NPU, update test with correct property to make weightless compiled model -->- <skip_config>- <message>compiled_blob test use `CACHE_MOD` which is not supported on NPU</message>- <filters>- <filter>.*OVCompiledModelBaseTest.*import_from_.*_blob.*</filter>- <filter>.*OVCompiledModelBaseTest.*compile_from_.*_blob.*</filter>- <filter>.*OVCompiledModelBaseTest.*compile_from_cached_weightless_blob.*</filter>- <filter>.*OVCompiledModelBaseTest.*use_blob_hint_.*</filter>+ <!-- EISW-162037 -->+ <skip_config>+ <message>compiled_blob test use `CACHE_MODE` which is not supported on NPU</message>+ <filters>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_regular_blob/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_weightless_blob_but_no_weights/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_use_weight_hint/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache_but_weights_bind_from_model_hint/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache_but_weights_from_model_path/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_but_no_weights/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache_but_weights_bind_from_model_hint/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_has_priority_over_cache_but_weights_from_model_path/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_but_no_weights/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.import_from_weightless_blob/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_weightless_blob/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_no_hint/.*</filter>+ <filter>.*smoke_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_which_fails_load_from_cache/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_use_weight_hint/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.use_blob_hint_which_fails_load_from_cache/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.import_from_weightless_blob/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_regular_blob/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_weightless_blob/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_weightless_blob_but_no_weights/.*</filter>+ <filter>.*smoke_Hetero_BehaviorTests/OVCompiledModelBaseTest.compile_from_cached_weightless_blob_no_hint/.*</filter></filters></skip_config>diff --git a/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp b/src/plugins/intel_npu/tests/unit/npu/metadata_version.cppindex 9fe017e8440..5a6f423cc9a 100644--- a/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp+++ b/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp@@ -34,6 +34,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {auto meta = MetadataTest(blobSize, CURRENT_OPENVINO_VERSION);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));std::unique_ptr<MetadataBase> storedMeta;OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));@@ -47,6 +48,7 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidOpenvinoVersion) {auto meta = MetadataTest(blobSize, wrongOvVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));std::unique_ptr<MetadataBase> storedMeta;OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));@@ -62,6 +64,7 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));ASSERT_ANY_THROW(auto storedMeta = read_metadata_from(stream));}@@ -75,6 +78,7 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));std::unique_ptr<MetadataBase> storedMeta;OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));storedMeta->is_compatible();@@ -146,6 +150,7 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtEnd) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));// inserting a new field at the end of the blob, between last metadata field and blobDataSizestd::string temp = stream.str();@@ -170,6 +175,7 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));// inserting a new field at the middle of the blob, between metadata version and OV version sizestd::string temp = stream.str();@@ -193,6 +199,7 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));+ OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));// removing fields between metadata version and blob data sizestd::string temp = stream.str();diff --git a/src/tests/functional/base_func_tests/include/behavior/compiled_model/compiled_model_base.hpp b/src/tests/functional/base_func_tests/include/behavior/compiled_model/compiled_model_base.hppindex aeee463c700..e4f4a30eff8 100644--- a/src/tests/functional/base_func_tests/include/behavior/compiled_model/compiled_model_base.hpp+++ b/src/tests/functional/base_func_tests/include/behavior/compiled_model/compiled_model_base.hpp@@ -6,7 +6,6 @@#include <openvino/core/preprocess/pre_post_process.hpp>#include <openvino/pass/serialize.hpp>-#include "shared_test_classes/base/ov_behavior_test_utils.hpp"#include "common_test_utils/file_utils.hpp"#include "common_test_utils/ov_tensor_utils.hpp"#include "common_test_utils/ov_test_utils.hpp"@@ -24,6 +23,7 @@#include "openvino/runtime/exec_model_info.hpp"#include "openvino/runtime/tensor.hpp"#include "openvino/util/file_util.hpp"+#include "shared_test_classes/base/ov_behavior_test_utils.hpp"namespace ov::test::behavior {namespace {@@ -1170,7 +1170,7 @@ TEST_P(OVCompiledModelBaseTest, compile_from_cached_weightless_blob_but_no_weigh// Model loaded from cache since weightless cache with ov::Model is supported.auto compiled_model = core->compile_model(model, target_device, configuration);ASSERT_TRUE(compiled_model);- if (target_device == utils::DEVICE_GPU) {+ if (target_device == utils::DEVICE_GPU || target_device == utils::DEVICE_NPU) {EXPECT_TRUE(compiled_model.get_property(ov::loaded_from_cache));} else {EXPECT_FALSE(compiled_model.get_property(ov::loaded_from_cache));