Skip to content

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

[NPUW] Make weights memory allocation sequential and ordered (#29039)

Alexey Smirnov8d83df6531df
diff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
index f0a7727cbb3..aba3d40bda1 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
@@ -57,10 +57,18 @@ ov::Tensor Const::eval() const {
return m_read_from_bin;
}
+LazyTensor::Meta Const::eval_meta() const {
+ if (m_node) {
+ return {m_node->get_shape(), m_node->get_element_type()};
+ }
+
+ NPUW_ASSERT(m_read_from_bin && "Underlying data should have been read first!");
+ return {m_read_from_bin.get_shape(), m_read_from_bin.get_element_type()};
+}
+
void Const::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
NPUW_ASSERT(!m_node &&
"LazyTensor can only read weight when it's being deserialized and not created from a Constant!");
-
if (ctx.weights) {
if (ctx.bf16_consts.find({m_offset, m_byte_size}) != ctx.bf16_consts.end()) {
NPUW_ASSERT(m_cached_type == ov::element::f16);
@@ -134,6 +142,15 @@ ov::Tensor Concat::eval() const {
return ov::npuw::util::concat(to_concat, axis);
}
+LazyTensor::Meta Concat::eval_meta() const {
+ auto meta = tensors[0].eval_meta();
+ ov::Shape shape = meta.shape;
+ for (std::size_t i = 1; i < tensors.size(); ++i) {
+ shape[axis] += tensors[i].eval_meta().shape[axis];
+ }
+ return {shape, meta.type};
+}
+
void Concat::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
for (auto& lt : tensors) {
lt.read_weight(ctx);
@@ -192,6 +209,10 @@ ov::Tensor Unpack::eval() const {
return dst;
}
+LazyTensor::Meta Unpack::eval_meta() const {
+ return {shape, type};
+}
+
void Unpack::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
w.read_weight(ctx);
if (z) { // could be empty
@@ -244,6 +265,16 @@ ov::Tensor Permute::eval() const {
return ov::npuw::util::permute(tensor.eval(), axes);
}
+LazyTensor::Meta Permute::eval_meta() const {
+ auto meta = tensor.eval_meta();
+ auto shape = meta.shape;
+ ov::Shape new_shape;
+ std::transform(axes.begin(), axes.end(), std::back_inserter(new_shape), [&](std::size_t i) {
+ return shape[i];
+ });
+ return {new_shape, meta.type};
+}
+
void Permute::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
tensor.read_weight(ctx);
}
@@ -281,6 +312,10 @@ ov::Tensor Convert::eval() const {
return ov::npuw::util::to_f16(tensor.eval());
}
+LazyTensor::Meta Convert::eval_meta() const {
+ return {tensor.eval_meta().shape, type};
+}
+
void Convert::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
tensor.read_weight(ctx);
}
@@ -314,6 +349,7 @@ struct LazyTensorImpl {
bool operator==(const LazyTensorImpl& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
std::size_t get_hash() const;
void get_transformations(std::vector<LazyTensor::Transform>& vec) const;
@@ -369,6 +405,13 @@ ov::Tensor LazyTensorImpl::eval() const {
m_transform);
}
+LazyTensor::Meta LazyTensorImpl::eval_meta() const {
+ return std::visit(overloaded{[](const auto& op) {
+ return op.eval_meta();
+ }},
+ m_transform);
+}
+
void LazyTensorImpl::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
std::visit(overloaded{[&ctx](auto& op) {
return op.read_weight(ctx);
@@ -517,6 +560,13 @@ ov::Tensor LazyTensor::eval() const {
return m_impl->eval();
}
+LazyTensor::Meta LazyTensor::eval_meta() const {
+ if (!m_impl) {
+ return {};
+ }
+ return m_impl->eval_meta();
+}
+
void LazyTensor::read_weight(const ov::npuw::s11n::WeightsContext& ctx) {
NPUW_ASSERT(m_impl && "Trying to read weights into uninitialized tensor!");
m_impl->read_weight(ctx);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
index cc12dec7258..5a62be1ecdb 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
@@ -61,6 +61,12 @@ public:
std::vector<Transform> get_transformations() const;
void detach();
+ struct Meta {
+ ov::Shape shape;
+ ov::element::Type type;
+ };
+ Meta eval_meta() const;
+
void serialize(std::ostream& stream) const;
static LazyTensor deserialize(std::istream& stream);
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
@@ -81,6 +87,7 @@ public:
std::size_t hash() const;
bool operator==(const Const& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
void serialize(std::ostream& stream) const;
@@ -106,6 +113,7 @@ public:
std::size_t hash() const;
bool operator==(const Concat& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
void serialize(std::ostream& stream) const;
@@ -131,6 +139,7 @@ public:
std::size_t hash() const;
bool operator==(const Unpack& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
void serialize(std::ostream& stream) const;
@@ -152,6 +161,7 @@ public:
std::size_t hash() const;
bool operator==(const Permute& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
void serialize(std::ostream& stream) const;
@@ -172,6 +182,7 @@ public:
std::size_t hash() const;
bool operator==(const Convert& other) const;
ov::Tensor eval() const;
+ LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
void serialize(std::ostream& stream) const;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
index 1c6dbd23755..09c4937df11 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
@@ -39,10 +39,9 @@ private:
int64_t 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);
+ std::unique_lock guard(m_mutex);
auto& device_bank = m_device_banks[device_for_alloc];
- std::unique_lock dev_guard(device_bank.mutex);
auto iter_registered = device_bank.registered_tensors.find(tensor);
if (iter_registered == device_bank.registered_tensors.end()) {
@@ -61,11 +60,9 @@ int64_t Bank::registerLT(const LazyTensor& tensor, const std::string& device) {
ov::Tensor Bank::get(int64_t uid, 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);
+ std::unique_lock guard(m_mutex);
- auto& device_bank = m_device_banks[device_for_alloc];
-
- std::unique_lock<std::mutex> dev_guard(device_bank.mutex);
+ auto& device_bank = m_device_banks.at(device_for_alloc);
auto iter_device = device_bank.storage.find(uid);
NPUW_ASSERT(iter_device != device_bank.storage.end() && iter_device->second.tensor &&
@@ -74,77 +71,109 @@ ov::Tensor Bank::get(int64_t uid, const std::string& device) {
return iter_device->second.tensor;
}
+struct TensorToAllocate {
+ LazyTensor::Meta meta;
+ ov::Tensor allocated_tensor;
+ int64_t uid;
+};
+
void Bank::evaluate_and_allocate() {
- std::lock_guard<std::mutex> guard(m_mutex);
+ std::unique_lock guard(m_mutex);
for (auto&& bank : m_device_banks) {
const auto& device_for_alloc = bank.first;
auto& device_bank = bank.second;
- std::vector<LazyTensor> vec;
-
- std::unique_lock storage_guard(device_bank.mutex);
- vec.reserve(device_bank.storage.size());
+ std::vector<LazyTensor> to_process;
+ to_process.reserve(device_bank.storage.size());
for (const auto& el : device_bank.storage) {
// Add non-allocated tensors for furter evaluation and allocation
if (!el.second.tensor) {
- vec.push_back(el.second.lt);
+ to_process.push_back(el.second.lt);
}
}
- storage_guard.unlock();
-
- ov::parallel_for(vec.size(), [&](std::size_t idx) {
- const auto& lt = vec[idx];
- std::unique_lock dev_guard(device_bank.mutex);
- auto iter_device_registered = device_bank.registered_tensors.find(lt);
- NPUW_ASSERT(iter_device_registered != device_bank.registered_tensors.end() &&
- "Tensor should be registered first!");
- if (device_bank.storage[iter_device_registered->second].tensor) {
- // Already allocated
- return;
- }
- dev_guard.unlock();
-
- // Allocation and/or evaluation needed
- // Evaluate concurrently, lock the device
- // mutex only to update the device bank (& allocate on-device memory, if needed)
- const auto& transformed_tensor = lt.eval();
-
- dev_guard.lock();
- if (device_for_alloc == "CPU") {
- // No allocation needed
- device_bank.storage[device_bank.registered_tensors.at(lt)].tensor = transformed_tensor;
- const_cast<LazyTensor&>(lt).detach();
- return;
- }
- ov::SoPtr<ov::ITensor> remote_tensor;
- ov::Tensor allocated_tensor;
-
- auto remote_ctx = m_core->get_default_context(device_for_alloc)._ptr;
- remote_tensor =
- remote_ctx->create_host_tensor(transformed_tensor.get_element_type(), transformed_tensor.get_shape());
- allocated_tensor = ov::make_tensor(remote_tensor);
- device_bank.storage[device_bank.registered_tensors.at(lt)].tensor = allocated_tensor;
- dev_guard.unlock(); // Unlock the guard, map update is done - copy can continue in parallel
+ if (device_for_alloc == "CPU") {
+ evaluate_cpu(device_bank, to_process);
+ } else {
+ evaluate_and_allocate_on_device(device_bank, to_process, device_for_alloc);
+ }
+ } // for (m_device_banks)
+}
- transformed_tensor.copy_to(allocated_tensor);
+void Bank::evaluate_cpu(Bank::DeviceBank& device_bank, const std::vector<LazyTensor>& to_process) {
+ // Note: not locking here. This is a private function, so Bank should handle the locks around it
+ // as we lock in evaluate_and_allocate() now.
+ ov::parallel_for(to_process.size(), [&](std::size_t idx) {
+ const auto& lt = to_process[idx];
+ auto iter_device_registered = device_bank.registered_tensors.find(lt);
+ NPUW_ASSERT(iter_device_registered != device_bank.registered_tensors.end() &&
+ "Tensor should be registered first!");
+ auto uid = iter_device_registered->second;
+ device_bank.storage.at(uid).tensor = lt.eval();
+ const_cast<LazyTensor&>(lt).detach();
+ });
+}
- // Detach the evaluated LazyTensor from its memory here - when it is 100%
- // not needed anymore (transformations, if any, and copies are done)
- // Note: this is the non-CPU path!
- const_cast<LazyTensor&>(lt).detach();
- });
+// Note: there are no locks in this function's parallel_for
+// At this point all the LazyTensor->Tensor pairs in the map are already
+// allocated and there are no conflicting reads/writes since all the tensors are unique.
+
+// FIXME: this whole flow could be improved for the same bank
+// processing from different threads. We could separate LazyTensors
+// evaluation and the bank access. But it requires additional rework.
+void Bank::evaluate_and_allocate_on_device(Bank::DeviceBank& device_bank,
+ const std::vector<LazyTensor>& to_process,
+ const std::string& device) {
+ // Note: not locking here. This is a private function, so Bank should handle the locks around it
+ // as we lock in evaluate_and_allocate() now.
+ std::vector<TensorToAllocate> uids_to_allocated;
+ uids_to_allocated.reserve(uid_count);
+
+ for (const auto& lt : to_process) {
+ auto iter_device_registered = device_bank.registered_tensors.find(lt);
+ NPUW_ASSERT(iter_device_registered != device_bank.registered_tensors.end() &&
+ "Tensor should be registered first!");
+ auto uid = iter_device_registered->second;
+ uids_to_allocated.push_back({lt.eval_meta(), ov::Tensor(), uid});
}
+ // Sort by UIDs, lowest first
+ std::sort(uids_to_allocated.begin(),
+ uids_to_allocated.end(),
+ [](const TensorToAllocate& a, const TensorToAllocate& b) {
+ return a.uid < b.uid;
+ });
+
+ // Allocate memory sequentially - in order of UID
+ auto remote_ctx = m_core->get_default_context(device)._ptr;
+ for (auto&& allocated : uids_to_allocated) {
+ ov::SoPtr<ov::ITensor> remote_tensor =
+ remote_ctx->create_host_tensor(allocated.meta.type, allocated.meta.shape);
+ allocated = {allocated.meta, ov::make_tensor(remote_tensor), allocated.uid};
+ }
+
+ // Evaluate and copy into the device memory
+ ov::parallel_for(uids_to_allocated.size(), [&](std::size_t idx) {
+ auto& allocated = uids_to_allocated[idx];
+ auto& stored_tensor = device_bank.storage.at(allocated.uid);
+
+ auto transformed = stored_tensor.lt.eval();
+ transformed.copy_to(allocated.allocated_tensor);
+ stored_tensor.tensor = std::move(allocated.allocated_tensor);
+
+ // Detach the evaluated LazyTensor from its memory here - when it is 100%
+ // not needed anymore (transformations, if any, and copies are done)
+ // Note: this is the non-CPU path!
+ const_cast<LazyTensor&>(stored_tensor.lt).detach();
+ });
}
bool Bank::is_remote(int64_t uid) const {
// FIXME: make generic
- std::lock_guard<std::mutex> guard(m_mutex);
+ std::unique_lock guard(m_mutex);
auto npu_bank = m_device_banks.find("NPU");
if (npu_bank != m_device_banks.end()) {
- std::lock_guard<std::mutex> dev_guard(npu_bank->second.mutex);
if (npu_bank->second.storage.find(uid) != npu_bank->second.storage.end()) {
// Found in NPU bank so considered remote (utterly wrong for the generic case)
return true;
@@ -159,19 +188,24 @@ void Bank::serialize(std::ostream& stream) const {
LOG_INFO("Serializing weights bank...");
LOG_BLOCK();
- std::lock_guard<std::mutex> guard(m_mutex);
+ std::unique_lock guard(m_mutex);
write(stream, m_device_banks.size());
for (const auto& elem : m_device_banks) {
const auto& device = elem.first;
const auto& device_bank = elem.second;
- std::lock_guard<std::mutex> dev_guard(device_bank.mutex);
write(stream, device);
write(stream, device_bank.storage.size());
+ // Write tensors sequentially according to sorted uids for better memory allocation and utilization
+ std::set<int64_t> uids;
for (const auto& t_pair : device_bank.storage) {
- write(stream, t_pair.first);
- write(stream, t_pair.second.tensor);
+ uids.insert(t_pair.first);
+ }
+
+ for (const auto& uid : uids) {
+ write(stream, uid);
+ write(stream, device_bank.storage.at(uid).tensor);
}
}
@@ -212,11 +246,9 @@ void Bank::read_and_add_tensor(std::istream& stream, int64_t uid, const std::str
using namespace ov::npuw::s11n;
// This method is supposed to be used only during deserialization
- std::lock_guard<std::mutex> guard(m_mutex);
+ std::unique_lock guard(m_mutex);
auto& device_bank = m_device_banks[device];
- std::lock_guard<std::mutex> dev_guard(device_bank.mutex);
-
auto iter_device = device_bank.storage.find(uid);
if (iter_device != device_bank.storage.end()) {
@@ -264,7 +296,7 @@ std::string Bank::get_name() const {
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);
+ std::unique_lock guard(m_mutex);
auto iter = m_bank_map.find(bank_name);
if (iter == m_bank_map.end() || iter->second.expired()) {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
index c276a54e772..994f3b0cec0 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
@@ -57,10 +57,14 @@ private:
struct DeviceBank {
std::unordered_map<int64_t, StoredTensor> storage;
std::unordered_map<LazyTensor, int64_t, LazyTensor::Hash> registered_tensors;
- mutable std::mutex mutex;
};
std::unordered_map<std::string, DeviceBank> m_device_banks;
+ void evaluate_cpu(DeviceBank& device_bank, const std::vector<LazyTensor>& to_process);
+ void evaluate_and_allocate_on_device(DeviceBank& device_bank,
+ const std::vector<LazyTensor>& to_process,
+ const std::string& device);
+
void serialize(std::ostream& stream) const;
static std::shared_ptr<Bank> deserialize(std::istream& stream,
const std::shared_ptr<const ov::ICore>& core,