OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Update weights bank and closures to operate on top of DQ transformations (#26978)
Alexey Smirnovcbc29ee16f68
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/al/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/al/config/npuw.hppindex 2b22c50a00e..65ec475df6b 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/al/config/npuw.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/al/config/npuw.hpp@@ -51,6 +51,7 @@ DEFINE_OPT(NPUW_DCOFF_SCALE, bool, false, npuw::partitioning::dcoff_with_scale,DEFINE_OPT(NPUW_FUNCALL_FOR_ALL, bool, false, npuw::partitioning::funcall_for_all, CompileTime);DEFINE_OPT(NPUW_PARALLEL_COMPILE, bool, false, npuw::parallel_compilation, CompileTime);DEFINE_OPT(NPUW_WEIGHTS_BANK, std::string, "", npuw::weights_bank, CompileTime);+DEFINE_OPT(NPUW_WEIGHTS_BANK_ALLOC, std::string, "", npuw::weights_bank_alloc, CompileTime);DEFINE_OPT(NPUW_CACHE_DIR, std::string, "", npuw::cache_dir, CompileTime);DEFINE_OPT(NPUW_FUNCALL_ASYNC, bool, false, npuw::funcall_async, RunTime);DEFINE_OPT(NPUW_ACC_CHECK, bool, false, npuw::accuracy::check, RunTime);diff --git a/src/plugins/intel_npu/src/al/include/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/npuw_private_properties.hppindex 343d47af55a..31fa52c3878 100644--- a/src/plugins/intel_npu/src/al/include/npuw_private_properties.hpp+++ b/src/plugins/intel_npu/src/al/include/npuw_private_properties.hpp@@ -45,6 +45,14 @@ static constexpr ov::Property<std::string> submodel_device{"NPUW_SUBMODEL_DEVICE*/static constexpr ov::Property<std::string> weights_bank{"NPUW_WEIGHTS_BANK"};+/**+ * @brief+ * Type: std::string.+ * Specify device name for weights bank which is used to allocate memory.+ * Default value: "".+ */+static constexpr ov::Property<std::string> weights_bank_alloc{"NPUW_WEIGHTS_BANK_ALLOC"};+/*** @brief* Type: std::string.diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cppindex 695494072a2..4aa4a88b9b5 100644--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp@@ -37,6 +37,7 @@ void intel_npu::registerNPUWOptions(OptionsDesc& desc) {desc.add<NPUW_PARALLEL_COMPILE>();desc.add<NPUW_FUNCALL_ASYNC>();desc.add<NPUW_WEIGHTS_BANK>();+ desc.add<NPUW_WEIGHTS_BANK_ALLOC>();desc.add<NPUW_CACHE_DIR>();desc.add<NPUW_ACC_CHECK>();desc.add<NPUW_ACC_THRESH>();diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cppindex 3bbbbe6aca7..b52b61d44a2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp@@ -375,6 +375,19 @@ bool ov::npuw::IBaseInferRequest::needs_copy(std::size_t idx) const {return true;}+bool ov::npuw::IBaseInferRequest::needs_copy(std::size_t idx, std::size_t cidx) const {+ if (!needs_copy(idx)) {+ return false;+ }+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];+ if (comp_model_desc.is_remote[cidx]) {+ // FIXME: Test if the tensor device and the request device are+ // the same or compatible!+ return false;+ }+ return true;+}+std::size_t ov::npuw::IBaseInferRequest::next(std::size_t idx_base) const {// Answer the next valid subrequest which is possible to prepare// FIXME: this could be a predefined map, not a lookupdiff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hppindex 6d4b4c71ef3..6be64d676d6 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp@@ -127,6 +127,7 @@ protected:std::size_t m_run_iter = 0u;bool needs_copy(std::size_t idx) const;+ bool needs_copy(std::size_t idx, std::size_t cidx) const;std::size_t next(std::size_t idx_base) const;std::size_t real(std::size_t idx) const;diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex 9c3b6f8cdfa..dc326b22f3a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -115,7 +115,8 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,// Initialize weights bankconst std::string weights_bank_opt = m_cfg.get<::intel_npu::NPUW_WEIGHTS_BANK>();- m_weights_bank = ov::npuw::weights::bank(weights_bank_opt, plugin->get_core());+ const std::string wbank_alloc = m_cfg.get<::intel_npu::NPUW_WEIGHTS_BANK_ALLOC>();+ m_weights_bank = ov::npuw::weights::bank(weights_bank_opt, plugin->get_core(), wbank_alloc);LOG_VERB("*** Original model ***");const auto& orig_parameters = model->get_parameters();@@ -235,6 +236,8 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,} // for(ordered_subgraphs)// NOTE(dm): there's a better way to do it, like we do in G-API backends.+ m_update_required = m_cfg.get<::intel_npu::NPUW_FOLD>();+// Store mapping between manually splitted inputs/outputs// to connect tensors between compiled submodelsm_submodels_input_to_prev_output = partitioning.input_to_prev_output;@@ -302,10 +305,10 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_compiled_submodels[id].host_gather = subgraph._host_gather;m_compiled_submodels[id].param_base = fcn_template._param_offset;m_compiled_submodels[id].closure = subgraph._closure;+ m_compiled_submodels[id].lazy_closure = subgraph._lazy_closure;m_compiled_submodels[id].scales = subgraph._scales;m_compiled_submodels[id].zerops = subgraph._zerops;- m_compiled_submodels[id].update_required.resize(subgraph._closure.size(), false);- fill_weights_bank(id);+ m_compiled_submodels[id].is_remote.resize(subgraph._lazy_closure.size(), false);} // if(!funcall)if (!m_compiled_submodels[id].model && !m_compiled_submodels[id].replaced_by) {@@ -421,6 +424,9 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,}}+ // Finalize memory in closures and weight banks+ finalize_weights_bank();+// Print stats report when possible{LOG_INFO("Initial device distribution:");@@ -434,24 +440,54 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,reset_io();}-void ov::npuw::CompiledModel::fill_weights_bank(const std::size_t idx) {- LOG_VERB("Filling weights bank for Subgraph[" << idx << "]...");- LOG_BLOCK();+void ov::npuw::CompiledModel::finalize_weights_bank() {+ // Register lazy tensors+ for (std::size_t idx = 0; idx < m_compiled_submodels.size(); ++idx) {+ auto& comp_model_desc = m_compiled_submodels[idx];- NPUW_ASSERT(m_compiled_submodels[idx].replaced_by);+ // Skip optimized out and non-functions+ if (!comp_model_desc.compiled_model && !comp_model_desc.replaced_by) {+ return;+ }- auto& comp_model_desc = m_compiled_submodels[idx];+ const auto real_idx = comp_model_desc.replaced_by.value_or(idx);+ auto& func_desc = m_compiled_submodels[real_idx];- for (std::size_t cidx = 0u; cidx < comp_model_desc.closure.size(); cidx++) {- comp_model_desc.closure[cidx] = m_weights_bank->update(comp_model_desc.closure[cidx]);- if (m_cfg.get<::intel_npu::NPUW_FOLD>()) {- comp_model_desc.update_required[cidx] = true;- } else {- comp_model_desc.update_required[cidx] = false;+ for (std::size_t tidx = 0; tidx < comp_model_desc.lazy_closure.size(); ++tidx) {+ if (comp_model_desc.closure[tidx]) {+ continue; // host-side closure+ }+ m_weights_bank->registerLT(comp_model_desc.lazy_closure[tidx], *func_desc.device_it);}}- LOG_VERB("DONE");+ // Evaluate and allocate all LazyTensors inside the bank+ m_weights_bank->evaluate_and_allocate();++ // Set evaluated and allocated ov::Tensors to closures+ for (size_t idx = 0; idx < m_compiled_submodels.size(); ++idx) {+ auto& comp_model_desc = m_compiled_submodels[idx];++ // Skip optimized out and non-functions+ if (!comp_model_desc.compiled_model && !comp_model_desc.replaced_by) {+ continue;+ }++ const auto real_idx = comp_model_desc.replaced_by.value_or(idx);+ auto& func_desc = m_compiled_submodels[real_idx];++ for (std::size_t tidx = 0; tidx < comp_model_desc.lazy_closure.size(); ++tidx) {+ if (comp_model_desc.closure[tidx]) {+ // host-side closure - already set, do nothing+ comp_model_desc.is_remote[tidx] = false;+ continue;+ }+ const auto& lt = comp_model_desc.lazy_closure[tidx];+ comp_model_desc.closure[tidx] = m_weights_bank->get(lt, *func_desc.device_it);+ // FIXME: find a more reliable way to do so+ comp_model_desc.is_remote[tidx] = m_weights_bank->is_remote(lt);+ }+ }}void ov::npuw::CompiledModel::remove_long_output_names(const std::shared_ptr<ov::Model>& model) {@@ -856,6 +892,7 @@ void ov::npuw::CompiledModel::implement_properties() {BIND(npuw::parallel_compilation, NPUW_PARALLEL_COMPILE),BIND(npuw::funcall_async, NPUW_FUNCALL_ASYNC),BIND(npuw::weights_bank, NPUW_WEIGHTS_BANK),+ BIND(npuw::weights_bank_alloc, NPUW_WEIGHTS_BANK_ALLOC),BIND(npuw::cache_dir, NPUW_CACHE_DIR),BIND(npuw::accuracy::check, NPUW_ACC_CHECK),BIND(npuw::accuracy::threshold, NPUW_ACC_THRESH),diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hppindex ab517d6adc7..2a89230fefa 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp@@ -72,7 +72,7 @@ private:void implement_properties();- void fill_weights_bank(const std::size_t idx);+ void finalize_weights_bank();std::shared_ptr<::intel_npu::OptionsDesc> m_options_desc;::intel_npu::Config m_cfg;@@ -135,10 +135,14 @@ private:// FIXME: This is a 1:1 copy of the ov::npuw::Subgraph structure// w.r.t. function callsstd::size_t param_base = 0;+ // NB: closure and lazy_closure are of the same size - to preserve proper indexing.+ // closure is responsible for host-side tensors (DCOFF, Gather, etc) while+ // lazy_closure is used for weights sharing and allocating device memory.std::vector<ov::Tensor> closure;+ std::vector<weights::LazyTensor> lazy_closure;std::vector<ov::Tensor> scales;std::vector<ov::Tensor> zerops;- std::vector<bool> update_required;+ std::vector<bool> is_remote;// FIXME: Take it out of structureov::SoPtr<ov::ICompiledModel> ref_compiled_model;@@ -149,6 +153,8 @@ private:};std::vector<CompiledModelDesc> m_compiled_submodels;+ bool m_update_required;+std::function<bool(const ov::SoPtr<ov::ITensor>&, const ov::SoPtr<ov::ITensor>&)> m_acc_check;std::string m_ref_device;diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cppindex 9ad7016f3ef..a853a27b194 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp@@ -207,8 +207,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com}// }}}- // Sort out how to handle weights bank and unpack- auto& wbank = m_npuw_model->m_weights_bank;for (size_t i = 0; i < m_num_submodels; i++) {LOG_VERB("Trying to preemptively set tensors for Subgraph[" << i << "]...");LOG_BLOCK();@@ -230,8 +228,10 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Comconst auto& iport = func_desc.compiled_model->inputs()[closure_param_id];// No update required to this tensor in runtime - so it can be set only once- if (!comp_model_desc.update_required[cidx]) {- request->set_tensor(iport, ov::get_tensor_impl(wbank->get(closure, *func_desc.device_it)));+ // Will be utilized when there is no FOLDing+ if (!m_npuw_model->m_update_required) {+ // At this point closure already contains allocated and transformed tensor ready to be used+ request->set_tensor(iport, ov::get_tensor_impl(closure));}} // for(closure)LOG_VERB("DONE");@@ -578,8 +578,8 @@ void ov::npuw::JustInferRequest::unpack_closure(std::size_t idx, RqPtr request)if (closure.get_element_type() != clparam->get_element_type()) {// Remember where the unpack is requiredclosure_unpack_required.push_back(cidx);- } else if (comp_model_desc.update_required[cidx]) {- if (needs_copy(idx)) {+ } else if (m_npuw_model->m_update_required) {+ if (needs_copy(idx, cidx)) {// Remember where copy is requriedclosure_copy_required.push_back(cidx);} else {diff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cppnew file mode 100644index 00000000000..8a0317a9f71--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp@@ -0,0 +1,293 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "lazy_tensor.hpp"++using ov::npuw::weights::ConcatMeta;+using ov::npuw::weights::ConstPtr;+using ov::npuw::weights::LazyTensor;+using ov::npuw::weights::OrigData;+using ov::npuw::weights::Transform;+using ov::npuw::weights::TransformType;+using ov::npuw::weights::UnpackMeta;++namespace ov {+namespace npuw {+namespace weights {++struct LazyTensorImpl {+public:+ LazyTensorImpl() = default;+ LazyTensorImpl(const TransformType& type, const Transform& transform);++ bool operator==(const LazyTensorImpl& other) const;++ ov::Tensor eval() const;++ ov::Tensor get_orig_tensor() const;++ std::size_t get_hash() const;++ bool has_transformations() const;++ std::shared_ptr<LazyTensorImpl> m_parent = nullptr;+ std::pair<TransformType, Transform> m_transform;+ std::size_t m_hash = 0;++ void* m_orig_data = nullptr;+ ov::Shape m_orig_shape;+ ov::element::Type m_orig_type;+};++std::size_t LazyTensorImpl::get_hash() const {+ // Already calculated+ if (m_hash != 0) {+ return m_hash;+ }++ // Get parent's hash+ std::size_t seed = 0;+ if (m_parent) {+ seed = m_parent->get_hash();+ } else {+ seed = std::hash<void*>()(m_orig_data) + 0x9e3779b9;+ for (const auto& dim : m_orig_shape) {+ seed ^= std::hash<std::size_t>()(dim) + 0x9e3779b9;+ }+ seed ^= m_orig_type.hash() + 0x9e3779b9;+ }++ // Combine with this hash+ seed ^= std::hash<int>()(static_cast<int>(m_transform.first)) + 0x9e3779b9;+ if (m_transform.first == TransformType::PERMUTE) {+ const auto& axes = std::get<std::vector<std::size_t>>(m_transform.second);+ for (const auto& axis : axes) {+ seed ^= std::hash<std::size_t>()(axis) + 0x9e3779b9;+ }+ } else if (m_transform.first == TransformType::CONCAT) {+ const auto& axis = std::get<ConcatMeta>(m_transform.second).second;+ seed ^= std::hash<std::size_t>()(axis) + 0x9e3779b9;+ for (auto& lt : std::get<ConcatMeta>(m_transform.second).first) {+ seed ^= lt.get_hash() + 0x9e3779b9;+ }+ } else if (m_transform.first == TransformType::UNPACK) {+ const auto& unpack_meta = std::get<UnpackMeta>(m_transform.second);+ seed ^= std::get<0>(unpack_meta).get_hash() + 0x9e3779b9;+ seed ^= std::get<1>(unpack_meta).get_hash() + 0x9e3779b9;+ seed ^= std::get<2>(unpack_meta).get_hash() + 0x9e3779b9;+ for (const auto& dim : std::get<3>(unpack_meta)) {+ seed ^= std::hash<std::size_t>()(dim) + 0x9e3779b9;+ }+ seed ^= std::get<4>(unpack_meta).hash() + 0x9e3779b9;+ }++ return seed;+}+} // namespace weights+} // namespace npuw+} // namespace ov++using ov::npuw::weights::LazyTensorImpl;++LazyTensorImpl::LazyTensorImpl(const TransformType& type, const Transform& transform) {+ if (type == TransformType::THIS && std::holds_alternative<OrigData>(transform)) {+ m_transform = std::make_pair(type, transform);+ ov::Tensor tensor;+ if (std::holds_alternative<ConstPtr>(std::get<OrigData>(transform))) {+ tensor = ov::npuw::util::tensor_from_const(std::get<ConstPtr>(std::get<OrigData>(transform)));+ } else {+ tensor = std::get<ov::Tensor>(std::get<OrigData>(transform));+ if (!tensor) {+ // Don't set anything+ return;+ }+ }+ m_orig_data = tensor.data();+ m_orig_shape = tensor.get_shape();+ m_orig_type = tensor.get_element_type();+ } else if (type == TransformType::CONCAT && std::holds_alternative<ConcatMeta>(transform)) {+ m_transform = std::make_pair(type, transform);+ } else if (type == TransformType::UNPACK && std::holds_alternative<UnpackMeta>(transform)) {+ m_transform = std::make_pair(type, transform);+ } else {+ NPUW_ASSERT(false);+ }++ m_hash = get_hash();+}++bool LazyTensorImpl::operator==(const LazyTensorImpl& other) const {+ if (m_hash != other.m_hash || m_orig_data != other.m_orig_data || m_orig_shape != other.m_orig_shape ||+ m_orig_type != other.m_orig_type || m_transform.first != other.m_transform.first) {+ return false;+ }++ switch (m_transform.first) {+ case TransformType::THIS:+ // everything is already compared above - skip+ break;+ case TransformType::CONVERT:+ // everything is already compared above - skip+ break;+ case TransformType::PERMUTE:+ if (std::get<std::vector<std::size_t>>(m_transform.second) !=+ std::get<std::vector<std::size_t>>(other.m_transform.second)) {+ return false;+ }+ break;+ case TransformType::CONCAT:+ if (std::get<ConcatMeta>(m_transform.second) != std::get<ConcatMeta>(other.m_transform.second)) {+ return false;+ }+ break;+ case TransformType::UNPACK:+ if (std::get<UnpackMeta>(m_transform.second) != std::get<UnpackMeta>(other.m_transform.second)) {+ return false;+ }+ break;+ default:+ NPUW_ASSERT(false);+ break;+ }++ if ((m_parent && !other.m_parent) || (!m_parent && other.m_parent)) {+ return false;+ }++ if (m_parent && other.m_parent) {+ return *m_parent.get() == *other.m_parent.get();+ }++ return true;+}++ov::Tensor LazyTensorImpl::eval() const {+ /* FIXME:+ Consider case:+ model1: concat->permute->f16+ model2: permute->f16+ Due to different history of transformation new tensors will be allocated for model2.+ However, we could avoid it by introducing a proper slicing on top of known axes and+ some kind of indicator that the only difference is concat and we should look for an existing ov::Tensor.+ Perhaps it should be done after model compilation and not handled here.+ */++ // Process the initial tensor - either from Const or from Concat+ if (!m_parent) {+ if (m_transform.first == TransformType::THIS) {+ return get_orig_tensor();+ } else if (m_transform.first == TransformType::CONCAT) {+ std::vector<ov::Tensor> to_concat;+ for (const auto& lt : std::get<ConcatMeta>(m_transform.second).first) {+ // Sanity check+ NPUW_ASSERT(!lt.has_transformations());+ to_concat.push_back(lt.get_orig_tensor());+ }+ return ov::npuw::util::concat(to_concat, std::get<ConcatMeta>(m_transform.second).second);+ } else if (m_transform.first == TransformType::UNPACK) {+ const auto& unpack_meta = std::get<UnpackMeta>(m_transform.second);+ const auto& cw = std::get<0>(unpack_meta);+ const auto& cz = std::get<1>(unpack_meta);+ const auto& cs = std::get<2>(unpack_meta);+ const auto& shape = std::get<3>(unpack_meta);+ const auto& type = std::get<4>(unpack_meta);++ // Note: unpacking done in-place since the original tensor is empty at this point+ NPUW_ASSERT(!cw.has_transformations());+ NPUW_ASSERT(!cs.has_transformations());+ // FIXME: Ugly check concat case as well since cz might be not set+ if (cz.has_transformations()) {+ NPUW_ASSERT(false);+ }++ const auto& gti = ov::get_tensor_impl;+ const auto& tw = cw.get_orig_tensor();+ const auto& tz = cz.get_orig_tensor();+ const auto& ts = cs.get_orig_tensor();+ ov::Tensor dst(type, shape);+ if (tw && tz && ts) {+ ov::npuw::util::unpack(gti(tw), gti(tz), gti(ts), gti(dst));+ } else if (tw && ts) {+ ov::npuw::util::unpack(gti(tw), gti(ts), gti(dst));+ } else {+ NPUW_ASSERT(false && "Unsupported combination");+ }+ return dst;+ } else {+ NPUW_ASSERT(false);+ }+ }++ // Process transformation+ switch (m_transform.first) {+ case TransformType::PERMUTE:+ return ov::npuw::util::permute(m_parent->eval(), std::get<std::vector<std::size_t>>(m_transform.second));+ case TransformType::CONVERT:+ return ov::npuw::util::to_f16(m_parent->eval());+ default:+ NPUW_ASSERT(false);+ }++ NPUW_ASSERT(false);+ return ov::Tensor();+}++ov::Tensor LazyTensorImpl::get_orig_tensor() const {+ // Sanity check+ NPUW_ASSERT(!has_transformations());+ if (std::holds_alternative<ConstPtr>(std::get<OrigData>(m_transform.second))) {+ return ov::npuw::util::tensor_from_const(std::get<ConstPtr>(std::get<OrigData>(m_transform.second)));+ }+ return std::get<ov::Tensor>(std::get<OrigData>(m_transform.second));+}++bool LazyTensorImpl::has_transformations() const {+ return m_transform.first != TransformType::THIS;+}++LazyTensor::LazyTensor(const TransformType& type, const Transform& transform)+ : m_impl(std::make_shared<LazyTensorImpl>(type, transform)) {}++bool LazyTensor::operator==(const LazyTensor& other) const {+ return *m_impl.get() == *other.m_impl.get();+}++bool LazyTensor::operator!=(const LazyTensor& other) const {+ return !(*m_impl.get() == *other.m_impl.get());+}++void LazyTensor::update(const TransformType& type, const Transform& transform) {+ const auto& curr = m_impl;+ auto new_lt = std::make_shared<LazyTensorImpl>();++ new_lt->m_orig_data = curr->m_orig_data;+ new_lt->m_orig_shape = curr->m_orig_shape;+ new_lt->m_orig_type = curr->m_orig_type;++ new_lt->m_transform = std::make_pair(type, transform);+ new_lt->m_parent = curr;+ new_lt->m_hash = new_lt->get_hash();++ m_impl = new_lt;+}++ov::Tensor LazyTensor::eval() const {+ return m_impl->eval();+}++ov::Tensor LazyTensor::get_orig_tensor() const {+ return m_impl->get_orig_tensor();+}++std::size_t LazyTensor::get_hash() const {+ return m_impl->get_hash();+}++std::size_t LazyTensor::Hash::operator()(const LazyTensor& lt) const {+ return lt.get_hash();+}++bool LazyTensor::has_transformations() const {+ return m_impl->has_transformations();+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hppnew file mode 100644index 00000000000..5cdeeba058e--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp@@ -0,0 +1,61 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <mutex>+#include <tuple>+#include <unordered_map>+#include <variant>++#include "logging.hpp"+#include "openvino/runtime/make_tensor.hpp"+#include "openvino/runtime/tensor.hpp"+#include "util.hpp"++namespace ov {+namespace npuw {+namespace weights {++enum class TransformType : int { THIS, PERMUTE, CONVERT, CONCAT, UNPACK };++// Forward declaration+class LazyTensor;+struct LazyTensorImpl;++using ConcatMeta = std::pair<std::vector<LazyTensor>, std::size_t>;+using UnpackMeta = std::tuple<LazyTensor, LazyTensor, LazyTensor, ov::Shape, ov::element::Type>;+using ConstPtr = std::shared_ptr<ov::op::v0::Constant>;+using OrigData = std::variant<ConstPtr, ov::Tensor>;++using Transform = std::variant<OrigData, std::vector<std::size_t>, std::monostate, ConcatMeta, UnpackMeta>;++class LazyTensor {+public:+ class Hash {+ public:+ std::size_t operator()(const LazyTensor& lt) const;+ };++ LazyTensor() = default;+ LazyTensor(const TransformType& type, const Transform& transform);++ bool operator==(const LazyTensor& other) const;+ bool operator!=(const LazyTensor& other) const;++ void update(const TransformType& type, const Transform& transform);+ ov::Tensor eval() const;++ ov::Tensor get_orig_tensor() const;+ std::size_t get_hash() const;+ bool has_transformations() const;++private:+ std::shared_ptr<LazyTensorImpl> m_impl = nullptr;+};++} // namespace weights+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex 6663f7a4f09..cbe9463b265 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -284,12 +284,12 @@ public:Partitioner(const std::shared_ptr<ov::Model>& _model,ov::npuw::Ensemble& _ens,ov::npuw::Partitioning& _P,- ::intel_npu::Config& cfg)+ ::intel_npu::Config& _cfg): model(_model),ens(_ens),P(_P),func_pipeline_type(FunctionPipelineType::FOLD),- cfg(cfg) {}+ cfg(_cfg) {}////////////////////////////////////////////////////////// Partitioning execution pipeline@@ -1454,6 +1454,8 @@ void Partitioner::matchResults(const std::string& func_name) {}void Partitioner::createFunction(FunctionPipeline& func_ggg) {+ using namespace ov::npuw::weights;+ov::npuw::Subgraph& body_sg = func_ggg.refs.front();const std::string func_name = body_sg._repeated_id;@@ -1509,7 +1511,9 @@ void Partitioner::createFunction(FunctionPipeline& func_ggg) {new_param_idx++;LOG_DEBUG("Register " << prod_output << " in the function closure");- funcall._closure.push_back(ov::npuw::util::tensor_from_const(input_node)); // (n)/1/i/c+ funcall._lazy_closure.push_back(+ LazyTensor(TransformType::THIS,+ std::static_pointer_cast<ov::op::v0::Constant>(input_node))); // (n)/1/i/c} else if (ov::op::util::is_parameter(input_node)) {LOG_DEBUG("Handling a Parameter input " << prod_output);LOG_BLOCK();@@ -1529,6 +1533,7 @@ void Partitioner::createFunction(FunctionPipeline& func_ggg) {} // if(Const|Parameter)} // for(inputs)} // for(nodes)+ funcall._closure.resize(funcall._lazy_closure.size());function._num_params_total = new_param_idx;function._model->validate_nodes_and_infer_types();P.functions.insert({func_name, std::move(function)});@@ -1613,6 +1618,8 @@ void Partitioner::createFunction(const std::string& func_name) {}void Partitioner::matchRepeatedSubgraphs(const std::string& func_name) {+ using namespace ov::npuw::weights;+LOG_VERB("Process function " << func_name << " in model " << model->get_friendly_name() << "...");LOG_BLOCK();@@ -1652,6 +1659,7 @@ void Partitioner::matchRepeatedSubgraphs(const std::string& func_name) {LOG_BLOCK();const auto& function = func_iter->second;funcall._closure.resize(function._num_params_total - function._param_offset);+ funcall._lazy_closure.resize(function._num_params_total - function._param_offset);auto tmp_model = *mod_iter;for (auto&& node_ptr : tmp_model->get_ordered_ops()) {@@ -1672,8 +1680,9 @@ void Partitioner::matchRepeatedSubgraphs(const std::string& func_name) {std::make_pair(proto_layer_name, input_desc.get_index())); // (t)/1/bLOG_DEBUG("Register " << prod_output << " in the function closure[" << param_idx<< "] (via prototype " << proto_layer_name << ")");- funcall._closure[param_idx - function._param_offset] =- ov::npuw::util::tensor_from_const(input_node); // (t)/1/c+ funcall._lazy_closure[param_idx - function._param_offset] =+ LazyTensor(TransformType::THIS,+ std::static_pointer_cast<ov::op::v0::Constant>(input_node)); // (t)/1/c}} // for (inputs)} // for(nodes)@@ -1731,6 +1740,8 @@ void Partitioner::spatial(const std::string& func_name) {}void Partitioner::optimize(const std::string& func_name) {+ using namespace ov::npuw::weights;+ov::npuw::Function& f = P.functions.at(func_name);auto& func_group = all_functions.at(func_name);@@ -1740,7 +1751,7 @@ void Partitioner::optimize(const std::string& func_name) {auto closure_idx = param_idx - f._param_offset;ov::parallel_for(func_group.refs.size(), [&](std::size_t f_idx) {auto& funcall = func_group.refs[f_idx].get();- ov::npuw::util::permute(funcall._closure[closure_idx], p.second);+ funcall._lazy_closure[closure_idx].update(TransformType::PERMUTE, p.second);});}};@@ -1750,7 +1761,7 @@ void Partitioner::optimize(const std::string& func_name) {auto closure_idx = param_idx - f._param_offset;ov::parallel_for(func_group.refs.size(), [&](std::size_t f_idx) {auto& funcall = func_group.refs[f_idx].get();- ov::npuw::util::to_f16(funcall._closure[closure_idx]);+ funcall._lazy_closure[closure_idx].update(TransformType::CONVERT, std::monostate{});});}};@@ -1802,11 +1813,21 @@ void Partitioner::optimize(const std::string& func_name) {}ov::parallel_for(func_group.refs.size(), [&](std::size_t f_idx) {auto& funcall = func_group.refs[f_idx].get();- std::vector<ov::Tensor> to_concat;+ std::vector<LazyTensor> to_concat;+ // Fill tensor vectorfor (auto&& cidx : to_concat_idx) {- to_concat.push_back(funcall._closure[cidx]);+ // FIXME: Assuming here concat goes first and other transformations later.+ // This allows to store ov::Tensor and ignore their potential history of transformations+ NPUW_ASSERT(!funcall._lazy_closure[cidx].has_transformations());+ to_concat.push_back(funcall._lazy_closure[cidx]);+ }+ // Note: we can ignore updating funcall._lazy_closure[cidx] here since those LazyTensors will be gone+ // and the new one added into the vector+ if (!to_concat.empty()) {+ funcall._lazy_closure.push_back(LazyTensor(TransformType::CONCAT, std::make_pair(to_concat, axis)));+ // Some of the tensors might be in closure - preserve it's 1:1 idx mapping with _lazy_closure+ funcall._closure.push_back(ov::Tensor());}- funcall._closure.push_back(ov::npuw::util::concat(to_concat, axis));});}@@ -1830,20 +1851,19 @@ void Partitioner::optimize(const std::string& func_name) {ov::parallel_for(func_group.refs.size(), [&](std::size_t f_idx) {auto& funcall = func_group.refs[f_idx].get();- ov::Tensor cw = funcall._closure[w_idx - f._param_offset];- ov::Tensor cz = z_idx != -1 ? funcall._closure[z_idx - f._param_offset] : ov::Tensor{};- ov::Tensor cs = funcall._closure[s_idx - f._param_offset];- ov::Tensor dst(p.first->get_element_type(), p.first->get_shape());-- const auto& gti = ov::get_tensor_impl;- if (cw && cz && cs) {- ov::npuw::util::unpack(gti(cw), gti(cz), gti(cs), gti(dst));- } else if (cw && cs) {- ov::npuw::util::unpack(gti(cw), gti(cs), gti(dst));- } else {- NPUW_ASSERT(false && "Unsupported combination");- }- funcall._closure.push_back(std::move(dst));+ // FIXME: assuming no transformations were applied to the tensor - since we are utilizing the original+ // ov::Tensor below+ LazyTensor cw = funcall._lazy_closure[w_idx - f._param_offset];+ LazyTensor cz = z_idx != -1 ? funcall._lazy_closure[z_idx - f._param_offset]+ : LazyTensor(TransformType::THIS, ov::Tensor());+ LazyTensor cs = funcall._lazy_closure[s_idx - f._param_offset];++ // FIXME: currently there is an issue that we don't share such tensor between head and tail+ funcall._lazy_closure.push_back(+ LazyTensor(TransformType::UNPACK,+ std::make_tuple(cw, cz, cs, p.first->get_shape(), p.first->get_element_type())));+ // Some of the tensors might be in closure - preserve it's 1:1 idx mapping with _lazy_closure+ funcall._closure.push_back(ov::Tensor());});}@@ -1857,25 +1877,31 @@ void Partitioner::optimize(const std::string& func_name) {for (auto&& funcall : func_group.refs) {auto new_elem_type = params_to_gather.pnew->get_element_type();const auto& new_shape = params_to_gather.pnew->get_shape();+ // Note: no allocation needed for this tensor - set to _closure and dummy in _lazy_closurefuncall.get()._closure.push_back(ov::Tensor(new_elem_type, new_shape));+ funcall.get()._lazy_closure.push_back(LazyTensor(TransformType::THIS, ov::Tensor()));}}// Add all new parameters introduced by this changef._model->add_parameters(new_params);- // Remove parameters and closures that were concatenated- std::vector<ov::Tensor> new_closure;+ // Remove LazyTensors which will be concatenatedfor (auto&& fref : func_group.refs) {auto& funcall = fref.get();+ std::vector<LazyTensor> new_transforms;+ // Some of the tensors might be in closure (e.g. host-gather), thus need to preserve the _closure as wellstd::vector<ov::Tensor> new_closure;- for (std::size_t cidx = 0; cidx < funcall._closure.size(); cidx++) {- if (to_remove_idx.count(f._param_offset + cidx) == 0) {- new_closure.push_back(funcall._closure[cidx]);+ for (std::size_t tidx = 0; tidx < funcall._lazy_closure.size(); tidx++) {+ if (to_remove_idx.count(f._param_offset + tidx) == 0) {+ new_transforms.push_back(funcall._lazy_closure[tidx]);+ new_closure.push_back(funcall._closure[tidx]);}}+ funcall._lazy_closure = std::move(new_transforms);funcall._closure = std::move(new_closure);}+ // Remove parameters that were concatenatedfor (auto&& now_remove : to_remove) {f._model->remove_parameter(now_remove);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hppindex fec00f359a8..86394617927 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp@@ -9,6 +9,7 @@#include <variant>#include <vector>+#include "../lazy_tensor.hpp"#include "intel_npu/al/config/config.hpp"#include "openvino/openvino.hpp"@@ -42,6 +43,9 @@ struct Subgraph {std::vector<ov::Tensor> _scales; // Scale coeffs for manual unpackingstd::vector<ov::Tensor> _zerops; // Zero points for manual unpacking+ // Stores transformation history for weights which will be applied before inference+ std::vector<weights::LazyTensor> _lazy_closure;+struct Gather {// NB.: int64_t is strange but it is used by OV to refer to parametersint64_t dst_idx = -1;diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cppindex 4928be78331..887670ca1e6 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.cpp@@ -4,6 +4,7 @@#include "dcoff.hpp"+#include "../../lazy_tensor.hpp"#include "../../logging.hpp"#include "../../util.hpp"#include "../partitioning.hpp" // Subgraph@@ -93,6 +94,7 @@ ClosureRemap build_remap(const Function& fbody, const DCOFFParams& params_to) {} else if (ban_list.find(param) == ban_list.end()) {// If it's not in the ban list, it's an OK parameter and should be keptLOG_DEBUG("This is an OK parameter, will be kept");+ m.weights_to_unpack.insert(i - fbody._param_offset);m.closure_remap.push_back(i - fbody._param_offset);}@@ -115,25 +117,34 @@ ClosureRemap build_remap(const Function& fbody, const DCOFFParams& params_to) {void apply_remap(Subgraph& fcall, const ClosureRemap& m) {std::vector<ov::Tensor> new_closure;+ std::vector<ov::npuw::weights::LazyTensor> new_lazy_closure;std::vector<ov::Tensor> new_scales;std::vector<ov::Tensor> new_zerops;- // For a new_closure vector by rearranging the old one. Also+ // For a new_lazy_closure vector by rearranging the old one. Also// reserve a new_scales vector to have the same size, filled with// empty tensors by default.for (auto&& i : m.closure_remap) {- new_closure.push_back(fcall._closure[i]);+ new_lazy_closure.push_back(fcall._lazy_closure[i]);+ if (fcall._closure[i]) {+ new_closure.push_back(fcall._closure[i]);+ } else {+ new_closure.push_back(m.weights_to_unpack.count(i) ? fcall._lazy_closure[i].eval() : fcall._closure[i]);+ }auto scale_iter = m.scale_remap.find(i);- new_scales.push_back(scale_iter != m.scale_remap.end() ? fcall._closure[scale_iter->second] : ov::Tensor());- // Check for asymmetric zero points and add them to new_zeropsauto zerop_iter = m.zerop_remap.find(i);- const auto& zerop = zerop_iter != m.zerop_remap.end() ? fcall._closure[zerop_iter->second] : m.zero_points[i];- new_zerops.push_back(zerop);++ new_scales.push_back(scale_iter != m.scale_remap.end() ? fcall._lazy_closure[scale_iter->second].eval()+ : ov::Tensor());+ // Check for asymmetric zero points and add them to new_zerops+ new_zerops.push_back(zerop_iter != m.zerop_remap.end() ? fcall._lazy_closure[zerop_iter->second].eval()+ : m.zero_points[i]);}- fcall._closure = std::move(new_closure);fcall._scales = std::move(new_scales);fcall._zerops = std::move(new_zerops);+ fcall._closure = std::move(new_closure);+ fcall._lazy_closure = std::move(new_lazy_closure);}void finalize_remap(Function& fbody, const ClosureRemap& m) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hppindex 9bb3c132fa9..3c61526be71 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/dcoff.hpp@@ -40,6 +40,7 @@ struct ClosureRemap {std::map<std::size_t, std::size_t> scale_remap; // orig closure idx -> orig scale idxstd::map<std::size_t, std::size_t> zerop_remap; // orig closure idx -> orig asymm zero point idxov::ParameterVector params_to_remove;+ std::set<std::size_t> weights_to_unpack;std::vector<ov::Tensor> zero_points; // zero points for closures, if needed};diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 5a3c92bef01..59851b00a54 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -14,7 +14,6 @@#include <sstream>#include "logging.hpp"-#include "openvino/op/constant.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/runtime/make_tensor.hpp" // get_tensor_impl@@ -1667,7 +1666,7 @@ void ov::npuw::util::to_f32(const ov::Tensor& in, ov::Tensor& out) {}}-void ov::npuw::util::to_f16(ov::Tensor& t) {+ov::Tensor ov::npuw::util::to_f16(const ov::Tensor& t) {ov::Shape shape = t.get_shape();NPUW_ASSERT(t.get_element_type() == ov::element::f32);NPUW_ASSERT(t.get_size() % 8 == 0);@@ -1687,7 +1686,7 @@ void ov::npuw::util::to_f16(ov::Tensor& t) {pdst += (8 * 2); // offset in bytes}- t = std::move(tnew);+ return tnew;}inline uint8_t tread_4b(const ov::Tensor& t, std::size_t r, std::size_t c, std::size_t COLS) {@@ -1711,7 +1710,7 @@ inline void twrite_4b(ov::Tensor& t, uint8_t value, std::size_t r, std::size_t c}}-void ov::npuw::util::transpose(ov::Tensor& t) {+ov::Tensor ov::npuw::util::transpose(const ov::Tensor& t) {ov::Shape shape = t.get_shape();NPUW_ASSERT(shape.size() == 3); // Yes, so far only transpose 3D tensorsNPUW_ASSERT(t.get_element_type() == ov::element::i4);@@ -1727,7 +1726,7 @@ void ov::npuw::util::transpose(ov::Tensor& t) {twrite_4b(tnew, value, j, i, IN_ROWS);}}- t = std::move(tnew);+ return tnew;}template <typename T>@@ -1752,12 +1751,12 @@ void permute120(const ov::Tensor& src, ov::Tensor& dst) {}}-void ov::npuw::util::permute(ov::Tensor& t, const std::vector<std::size_t>& axes) {+ov::Tensor ov::npuw::util::permute(const ov::Tensor& t, const std::vector<std::size_t>& axes) {ov::Shape shape = t.get_shape();NPUW_ASSERT(shape.size() == 3); // Yes, so far only transpose 3D tensorsif (axes[0] == 2 && axes[1] == 0 && axes[2] == 1) {- transpose(t);+ return transpose(t);} else if (axes[0] == 0 && axes[1] == 2 && axes[2] == 1) {NPUW_ASSERT(t.get_element_type() == ov::element::i4); // 4bit only hereov::Shape tshape = {shape[0], shape[2], shape[1]};@@ -1771,7 +1770,7 @@ void ov::npuw::util::permute(ov::Tensor& t, const std::vector<std::size_t>& axes}}}- t = std::move(tnew);+ return tnew;} else if (axes[0] == 1 && axes[1] == 0 && axes[2] == 2) {NPUW_ASSERT(t.get_element_type() == ov::element::i4); // 4bit only here tooov::Shape tshape = {shape[1], shape[0], shape[2]};@@ -1786,7 +1785,7 @@ void ov::npuw::util::permute(ov::Tensor& t, const std::vector<std::size_t>& axes}}}- t = std::move(tnew);+ return tnew;} else if (axes[0] == 1 && axes[1] == 2 && axes[2] == 0) {ov::Shape tshape = {shape[1], shape[2], shape[0]};ov::Tensor tnew(t.get_element_type(), tshape);@@ -1800,7 +1799,7 @@ void ov::npuw::util::permute(ov::Tensor& t, const std::vector<std::size_t>& axesdefault:NPUW_ASSERT("Element type is not supported yet");}- t = std::move(tnew);+ return tnew;} else {NPUW_ASSERT(false && "Not supported yet");}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex 689bf8571dd..1704314aee7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -7,6 +7,7 @@#include <string>#include "logging.hpp"+#include "openvino/op/constant.hpp"#include "openvino/runtime/itensor.hpp"#include "openvino/runtime/so_ptr.hpp"@@ -58,9 +59,9 @@ ov::SoPtr<ov::ITensor> view(const ov::SoPtr<ov::ITensor>& src, const View& from,ov::SoPtr<ov::ITensor> view(const ov::SoPtr<ov::ITensor>& src, std::size_t dim, std::size_t offset, std::size_t len);void to_f32(const ov::Tensor& in, ov::Tensor& out);-void to_f16(ov::Tensor& t);-void transpose(ov::Tensor& t);-void permute(ov::Tensor& t, const std::vector<std::size_t>& axes);+ov::Tensor to_f16(const ov::Tensor& t);+ov::Tensor transpose(const ov::Tensor& t);+ov::Tensor permute(const ov::Tensor& t, const std::vector<std::size_t>& axes);ov::Tensor concat(const std::vector<ov::Tensor>& tt, std::size_t axis);namespace at {diff --git a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cppindex 08181f80e7f..d142f72f9b7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp@@ -4,7 +4,12 @@#include "weights_bank.hpp"+#include "logging.hpp"+#include "openvino/core/parallel.hpp"+#include "util.hpp"+using ov::npuw::weights::Bank;+using ov::npuw::weights::LazyTensor;class BankManager {public:@@ -20,7 +25,9 @@ private:public:// Public API- std::shared_ptr<Bank> getBank(const std::string& bank_name, const std::shared_ptr<const ov::ICore>& core);+ std::shared_ptr<Bank> getBank(const std::string& bank_name,+ const std::shared_ptr<const ov::ICore>& core,+ const std::string& alloc_device);private:// Data@@ -28,65 +35,96 @@ private:std::mutex m_mutex;};-ov::Tensor Bank::update(const ov::Tensor& tensor) {- if (!tensor) {- OPENVINO_THROW("Uninitialized tensor in weights bank allocation!");- }+ov::Tensor Bank::get(const LazyTensor& tensor, const std::string& device) {+ const std::string& device_for_alloc = m_alloc_device.empty() ? device : m_alloc_device;std::lock_guard<std::mutex> guard(m_mutex);- if (m_bank.find(tensor.data()) == m_bank.end()) {- // need to allocate first- m_bank[tensor.data()] = tensor;+ auto& device_bank = m_device_bank[device_for_alloc];+ auto iter_device = device_bank.find(tensor);++ if (iter_device != device_bank.end() && iter_device->second) {+ // Already allocated+ return iter_device->second;}- return tensor;+ // Allocation and evaluation needed+ return unsafe_eval_and_alloc(tensor, device_for_alloc);}-ov::Tensor Bank::get(const ov::Tensor& tensor, const std::string& device) {- if (!tensor) {- OPENVINO_THROW("Uninitialized tensor in weights bank allocation!");- }+void Bank::registerLT(const LazyTensor& tensor, const std::string& device) {+ const std::string& device_for_alloc = m_alloc_device.empty() ? device : m_alloc_device;++ std::lock_guard<std::mutex> guard(m_mutex);- if (device != "CPU" && device != "NPU") {- OPENVINO_THROW("Unsupported device in weights bank allocation: ", device);+ auto& device_bank = m_device_bank[device_for_alloc];+ if (device_bank.find(tensor) == device_bank.end()) {+ device_bank[tensor] = ov::Tensor();}+}+void Bank::evaluate_and_allocate() {std::lock_guard<std::mutex> guard(m_mutex);- auto iter_cpu = m_bank.find(tensor.data());- if (iter_cpu == m_bank.end()) {- OPENVINO_THROW("Unknown tensor in weights bank allocation!");+ for (auto&& bank : m_device_bank) {+ const auto& device_for_alloc = bank.first;+ auto& device_bank = bank.second;+ std::vector<LazyTensor> vec;+ for (const auto& el : device_bank) {+ vec.push_back(el.first);+ }+ ov::parallel_for(vec.size(), [&](std::size_t idx) {+ const auto& lt = vec[idx];+ auto iter_device = device_bank.find(lt);+ if (iter_device != device_bank.end() && iter_device->second) {+ // Already allocated+ return;+ }++ // Allocation and evaluation needed+ unsafe_eval_and_alloc(lt, device_for_alloc);+ });}+}- // If target device is CPU - just reuse the default bank- if (device == "CPU") {- return iter_cpu->second;+ov::Tensor Bank::unsafe_eval_and_alloc(const LazyTensor& tensor, const std::string& device_for_alloc) {+ // Note: private method used inside other methods with already locked mutex+ const auto& transformed_tensor = tensor.eval();+ if (device_for_alloc == "CPU") {+ m_device_bank[device_for_alloc][tensor] = transformed_tensor;+ return transformed_tensor;}- // Non-CPU - check if the tensor is already there- auto& device_bank = m_device_bank[device];- auto iter_device = device_bank.find(tensor.data());- if (iter_device != device_bank.end()) {- // Already allocated on the device - reuse- return iter_device->second;- }+ // FIXME: L0 allocation may crash when run in parallel+ std::lock_guard<std::mutex> guard(m_alloc_mutex);- // Allocation needed- m_remote_ctx = m_core->get_default_context(device)._ptr;- auto remote_tensor = m_remote_ctx->create_host_tensor(tensor.get_element_type(), tensor.get_shape());+ m_remote_ctx = m_core->get_default_context(device_for_alloc)._ptr;+ auto remote_tensor =+ m_remote_ctx->create_host_tensor(transformed_tensor.get_element_type(), transformed_tensor.get_shape());auto allocated_tensor = ov::make_tensor(remote_tensor);- tensor.copy_to(allocated_tensor);- device_bank[tensor.data()] = allocated_tensor;+ transformed_tensor.copy_to(allocated_tensor);+ m_device_bank[device_for_alloc][tensor] = allocated_tensor;return allocated_tensor;}-std::shared_ptr<Bank> BankManager::getBank(const std::string& bank_name, const std::shared_ptr<const ov::ICore>& core) {+bool Bank::is_remote(const LazyTensor& tensor) const {+ // FIXME: make generic+ auto npu_bank = m_device_bank.find("NPU");+ if (npu_bank != m_device_bank.end() && npu_bank->second.find(tensor) != npu_bank->second.end()) {+ // Found in NPU bank+ return true;+ }+ return false;+}++std::shared_ptr<Bank> BankManager::getBank(const std::string& bank_name,+ const std::shared_ptr<const ov::ICore>& core,+ const std::string& alloc_device) {std::lock_guard<std::mutex> guard(m_mutex);auto iter = m_bank_map.find(bank_name);if (iter == m_bank_map.end()) {- auto bank = std::make_shared<Bank>(core);+ auto bank = std::make_shared<Bank>(core, alloc_device);m_bank_map[bank_name] = bank;return bank;}@@ -94,12 +132,13 @@ std::shared_ptr<Bank> BankManager::getBank(const std::string& bank_name, const s}std::shared_ptr<Bank> ov::npuw::weights::bank(const std::string& bank_name,- const std::shared_ptr<const ov::ICore>& core) {+ const std::shared_ptr<const ov::ICore>& core,+ const std::string& alloc_device) {if (bank_name.empty()) {// Don't share this bank in manager- return std::make_shared<Bank>(core);+ return std::make_shared<Bank>(core, alloc_device);}auto& instance = BankManager::getInstance();- return instance.getBank(bank_name, core);+ return instance.getBank(bank_name, core, alloc_device);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hppindex c8efa46a301..b9d8d21143c 100644--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp@@ -9,6 +9,8 @@#include <tuple>#include <unordered_map>+#include "lazy_tensor.hpp"+#include "openvino/op/constant.hpp"#include "openvino/runtime/iplugin.hpp"#include "openvino/runtime/iremote_context.hpp"#include "openvino/runtime/make_tensor.hpp"@@ -20,25 +22,32 @@ namespace weights {class Bank {public:- explicit Bank(const std::shared_ptr<const ov::ICore>& core) : m_core(core) {}-- // Capture CPU version of the tensor- ov::Tensor update(const ov::Tensor& tensor);-- // Based on previously captured tensor allocate a new tensor (if needed) on a specified device- ov::Tensor get(const ov::Tensor& tensor, const std::string& device);+ explicit Bank(const std::shared_ptr<const ov::ICore>& core, const std::string& alloc_device)+ : m_core(core),+ m_alloc_device(alloc_device) {}++ // Allocate a new tensor (if needed) on a specified device. LazyTensor needs to be registered and evaluated first+ ov::Tensor get(const LazyTensor& tensor, const std::string& device);+ // Register LazyTensor in a bank if it's not there+ void registerLT(const LazyTensor& tensor, const std::string& device);+ // Evaluate and allocate all LazyTensors in the bank+ void evaluate_and_allocate();+ bool is_remote(const LazyTensor& tensor) const;private:- // Default CPU bank. Filled by update()- std::unordered_map<void*, ov::Tensor> m_bank;+ ov::Tensor unsafe_eval_and_alloc(const LazyTensor& tensor, const std::string& device);// Bank for specified device and their allocated memory- std::unordered_map<std::string, std::unordered_map<void*, ov::Tensor>> m_device_bank;+ std::unordered_map<std::string, std::unordered_map<LazyTensor, ov::Tensor, LazyTensor::Hash>> m_device_bank;std::mutex m_mutex;+ std::mutex m_alloc_mutex;std::shared_ptr<const ov::ICore> m_core = nullptr;std::shared_ptr<ov::IRemoteContext> m_remote_ctx = nullptr;+ std::string m_alloc_device;};-std::shared_ptr<Bank> bank(const std::string& bank_name, const std::shared_ptr<const ov::ICore>& core);+std::shared_ptr<Bank> bank(const std::string& bank_name,+ const std::shared_ptr<const ov::ICore>& core,+ const std::string& alloc_device);} // namespace weights} // namespace npuw