Skip to content

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

NPUW: Serialization refactoring (#35441)

Dmitry Matveev5ef1deb27055
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
index d8fc99affb5..f4c2f9c2140 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -41,6 +41,20 @@
#include "transformations/convert_precision.hpp"
namespace {
+std::string canonical_device_name(const std::string& device_name) {
+ const auto dot_pos = device_name.find('.');
+ return dot_pos == std::string::npos ? device_name : device_name.substr(0, dot_pos);
+}
+
+std::size_t find_device_index(const std::vector<std::string>& devices, const std::string& device_name) {
+ const auto canonical_name = canonical_device_name(device_name);
+ const auto it = std::find_if(devices.begin(), devices.end(), [&](const std::string& candidate) {
+ return canonical_device_name(candidate) == canonical_name;
+ });
+ NPUW_ASSERT(it != devices.end());
+ return static_cast<std::size_t>(it - devices.begin());
+}
+
void split_properties(const ov::AnyMap& properties,
ov::AnyMap& npu_plugin_properties,
ov::AnyMap& npuw_path_properties) {
@@ -729,311 +743,228 @@ bool ov::npuw::CompiledModel::should_use_quantized_host_gather(const std::shared
return false;
}
-void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
- const ov::npuw::s11n::WeightsContext& ctx) const {
+void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Stream& stream,
+ const ov::npuw::s11n::WeightsContext& ctx,
+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx) {
using namespace ov::npuw::s11n;
- LOG_DEBUG("Serializing CompiledModelDesc...");
- LOG_BLOCK();
-
- write(stream, replaced_by);
-
- write(stream, param_base);
- write(stream, forced_to_fcall);
-
- write(stream, host_gather.dst_idx);
- write(stream, host_gather.src_idx);
- write(stream, host_gather.idx_idx);
-
- write(stream, quant_unpack_gather.dst_idx);
- write(stream, quant_unpack_gather.src_w_idx);
- write(stream, quant_unpack_gather.src_z_idx);
- write(stream, quant_unpack_gather.src_s_idx);
- write(stream, quant_unpack_gather.idx_idx);
-
- write(stream, spatial);
- write(stream, attention);
-
- // Serialize compiled submodels for pyramid attention, except the last one
- write(stream, pyramid_attention);
- if (pyramid_attention.has_value()) {
- size_t num_models = pyramid_attention.value()._compiled_models.size();
- write(stream, num_models);
-
- for (size_t i = 0; i < num_models - 1; ++i) {
- std::stringstream ss;
- auto compiled_model = pyramid_attention.value()._compiled_models[i];
- compiled_model->export_model(ss);
- write(stream, ss.str());
- }
- }
-
- // Serialize MoE experts
- write(stream, moe_experts);
- if (moe_experts.has_value()) {
- const auto& moe = moe_experts.value();
- size_t num_compiled_models = moe._compiled_models.size();
- write(stream, num_compiled_models);
-
- for (const auto& [chunk_size, compiled_model] : moe._compiled_models) {
- write(stream, chunk_size);
- if (compiled_model) {
- write(stream, true);
- std::stringstream ss;
- compiled_model->export_model(ss);
- write(stream, ss.str());
- } else {
- write(stream, false);
- }
- }
- }
-
- // Serialize MoE experts downstream
- write(stream, moe_experts_downstream);
- if (moe_experts_downstream.has_value()) {
- const auto& moe_downstream = moe_experts_downstream.value();
- if (moe_downstream._compiled_model) {
- write(stream, true);
- std::stringstream ss;
- moe_downstream._compiled_model->export_model(ss);
- write(stream, ss.str());
- } else {
- write(stream, false);
- }
- }
-
- // Serialize host flash attention
- write(stream, host_flash_attention);
- if (host_flash_attention.has_value()) {
- // Serialize compiled tile model
- if (host_flash_attention.value()._compiled_tile_model) {
- write(stream, true);
- std::stringstream ss;
- host_flash_attention.value()._compiled_tile_model->export_model(ss);
- write(stream, ss.str());
- } else {
- write(stream, false);
- }
- }
-
- auto& closure_desc = closure.get();
-
- write(stream, closure_desc.is_remote);
- write(stream, closure_desc.closure_uid);
-
- if (ctx.is_weightless) {
- write_weightless(stream, scales, ctx);
- write_weightless(stream, zerops, ctx);
-
- write(stream, closure_desc.closure.size());
- std::vector<ov::Tensor> cpu_closures;
- std::vector<std::size_t> cpu_closure_ids;
- std::vector<ov::npuw::weights::LazyTensor> non_cpu_tensors;
- std::vector<std::size_t> non_cpu_tensors_ids;
- for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
- if (closure_desc.closure_uid[cidx] == -1) { // CPU closure
- cpu_closure_ids.push_back(cidx);
- cpu_closures.push_back(closure_desc.closure[cidx]);
- } else {
- non_cpu_tensors_ids.push_back(cidx);
- non_cpu_tensors.push_back(lazy_closure[cidx]); // must be there
- }
- }
-
- write(stream, cpu_closure_ids);
- write_weightless(stream, cpu_closures, ctx);
- write(stream, non_cpu_tensors_ids);
- write(stream, non_cpu_tensors);
+ if (stream.output()) {
+ LOG_DEBUG("Serializing CompiledModelDesc...");
} else {
- write(stream, scales);
- write(stream, zerops);
-
- write(stream, closure_desc.closure.size());
- std::vector<ov::Tensor> cpu_closures;
- std::vector<std::size_t> cpu_closure_ids;
- for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
- if (closure_desc.closure_uid[cidx] == -1) { // CPU closure, not in the bank
- cpu_closure_ids.push_back(cidx);
- cpu_closures.push_back(closure_desc.closure[cidx]);
- }
- }
-
- write(stream, cpu_closure_ids);
-
- for (const auto& tensor : cpu_closures) {
- write(stream, tensor);
- }
+ LOG_DEBUG("Deserializing CompiledModelDesc...");
}
-
- LOG_DEBUG("DONE.");
-}
-
-void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(
- std::istream& stream,
- const ov::npuw::s11n::WeightsContext& ctx,
- const ov::npuw::s11n::SubmodelDeserializeCtx& submodel_ctx) {
- using namespace ov::npuw::s11n;
-
- LOG_DEBUG("Deserializing CompiledModelDesc...");
LOG_BLOCK();
- read(stream, replaced_by);
-
- read(stream, param_base);
- read(stream, forced_to_fcall);
-
- read(stream, host_gather.dst_idx);
- read(stream, host_gather.src_idx);
- read(stream, host_gather.idx_idx);
+ stream & replaced_by & param_base & forced_to_fcall & host_gather.dst_idx & host_gather.src_idx &
+ host_gather.idx_idx & quant_unpack_gather.dst_idx & quant_unpack_gather.src_w_idx &
+ quant_unpack_gather.src_z_idx & quant_unpack_gather.src_s_idx & quant_unpack_gather.idx_idx & spatial &
+ attention & pyramid_attention;
- read(stream, quant_unpack_gather.dst_idx);
- read(stream, quant_unpack_gather.src_w_idx);
- read(stream, quant_unpack_gather.src_z_idx);
- read(stream, quant_unpack_gather.src_s_idx);
- read(stream, quant_unpack_gather.idx_idx);
-
- read(stream, spatial);
- read(stream, attention);
-
- read(stream, pyramid_attention);
if (pyramid_attention.has_value()) {
size_t num_models = 0;
- read(stream, num_models);
- pyramid_attention.value()._compiled_models.resize(num_models);
+ if (stream.output()) {
+ num_models = pyramid_attention.value()._compiled_models.size();
+ }
+ stream & num_models;
- if (num_models > 0) {
- // Import all pyramid models except the last one
+ if (stream.output()) {
+ for (size_t i = 0; i < num_models - 1; ++i) {
+ std::stringstream ss;
+ pyramid_attention.value()._compiled_models[i]->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ }
+ } else if (num_models > 0) {
+ pyramid_attention.value()._compiled_models.resize(num_models);
+ NPUW_ASSERT(submodel_ctx != nullptr);
for (size_t i = 0; i < num_models - 1; ++i) {
std::string model_str;
- read(stream, model_str);
+ stream & model_str;
std::stringstream ss(model_str);
pyramid_attention->_compiled_models[i] =
- submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device, submodel_ctx.import_config);
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
}
-
- // Reuse the already compiled model for the last pyramid attention model
- if (submodel_ctx.compiled_model) {
- pyramid_attention->_compiled_models[num_models - 1] = submodel_ctx.compiled_model;
+ if (submodel_ctx->compiled_model) {
+ pyramid_attention->_compiled_models[num_models - 1] = submodel_ctx->compiled_model;
LOG_DEBUG("Reused compiled_model for the last pyramid attention model");
}
}
}
- // Deserialize MoE experts
- read(stream, moe_experts);
+ stream & moe_experts;
if (moe_experts.has_value()) {
size_t num_compiled_models = 0;
- read(stream, num_compiled_models);
-
- for (size_t i = 0; i < num_compiled_models; ++i) {
- size_t chunk_size = 0;
- read(stream, chunk_size);
-
- bool has_model = false;
- read(stream, has_model);
-
- if (has_model) {
- std::string model_str;
- read(stream, model_str);
- std::stringstream ss(model_str);
- auto compiled_model =
- submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device, submodel_ctx.import_config);
- moe_experts->_compiled_models[chunk_size] = compiled_model;
- LOG_DEBUG("Imported MoE compiled model for chunk_size=" << chunk_size);
+ if (stream.output()) {
+ num_compiled_models = moe_experts.value()._compiled_models.size();
+ }
+ stream & num_compiled_models;
+
+ if (stream.output()) {
+ for (const auto& [chunk_size, compiled_model] : moe_experts.value()._compiled_models) {
+ stream & chunk_size;
+ bool has_model = compiled_model != nullptr;
+ stream & has_model;
+ if (has_model) {
+ std::stringstream ss;
+ compiled_model->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ }
+ }
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ for (size_t i = 0; i < num_compiled_models; ++i) {
+ size_t chunk_size = 0;
+ stream & chunk_size;
+ bool has_model = false;
+ stream & has_model;
+ if (has_model) {
+ std::string model_str;
+ stream & model_str;
+ std::stringstream ss(model_str);
+ moe_experts->_compiled_models[chunk_size] =
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
+ LOG_DEBUG("Imported MoE compiled model for chunk_size=" << chunk_size);
+ }
}
+ LOG_DEBUG("Deserialized " << moe_experts->_compiled_models.size() << " MoE expert models");
}
-
- LOG_DEBUG("Deserialized " << moe_experts->_compiled_models.size() << " MoE expert models");
}
- // Deserialize MoE experts downstream
- read(stream, moe_experts_downstream);
+ stream & moe_experts_downstream;
if (moe_experts_downstream.has_value()) {
bool has_model = false;
- read(stream, has_model);
-
+ if (stream.output()) {
+ has_model = moe_experts_downstream.value()._compiled_model != nullptr;
+ }
+ stream & has_model;
if (has_model) {
- std::string model_str;
- read(stream, model_str);
- std::stringstream ss(model_str);
- auto compiled_model =
- submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device, submodel_ctx.import_config);
- moe_experts_downstream->_compiled_model = compiled_model;
- LOG_DEBUG("Imported MoE downstream compiled model");
+ if (stream.output()) {
+ std::stringstream ss;
+ moe_experts_downstream.value()._compiled_model->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ std::string model_str;
+ stream & model_str;
+ std::stringstream ss(model_str);
+ moe_experts_downstream->_compiled_model =
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
+ LOG_DEBUG("Imported MoE downstream compiled model");
+ }
}
}
- // Deserialize host flash attention
- read(stream, host_flash_attention);
+ stream & host_flash_attention;
if (host_flash_attention.has_value()) {
bool has_compiled_model = false;
- read(stream, has_compiled_model);
+ if (stream.output()) {
+ has_compiled_model = host_flash_attention.value()._compiled_tile_model != nullptr;
+ }
+ stream & has_compiled_model;
if (has_compiled_model) {
- std::string model_str;
- read(stream, model_str);
- std::stringstream ss(model_str);
- host_flash_attention->_compiled_tile_model =
- submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device, submodel_ctx.import_config);
- LOG_DEBUG("Imported compiled tile model for host flash attention");
+ if (stream.output()) {
+ std::stringstream ss;
+ host_flash_attention.value()._compiled_tile_model->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ std::string model_str;
+ stream & model_str;
+ std::stringstream ss(model_str);
+ host_flash_attention->_compiled_tile_model =
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
+ LOG_DEBUG("Imported compiled tile model for host flash attention");
+ }
+ }
+ if (stream.input()) {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ host_flash_attention->_compiled_final_tile_model = submodel_ctx->compiled_model;
+ LOG_DEBUG("Set compiled final tile model reference for host flash attention");
}
-
- // Set reference to the final tile model (which is the main compiled_model for HFA)
- host_flash_attention->_compiled_final_tile_model = submodel_ctx.compiled_model;
- LOG_DEBUG("Set compiled final tile model reference for host flash attention");
}
auto& closure_desc = closure.get();
- read(stream, closure_desc.is_remote);
- read(stream, closure_desc.closure_uid);
+ stream & closure_desc.is_remote & closure_desc.closure_uid;
- if (ctx.weights || !ctx.consts_cache.empty()) {
- read_weightless(stream, scales, ctx);
- read_weightless(stream, zerops, ctx);
-
- std::size_t closure_size = 0;
- read(stream, closure_size);
- closure_desc.closure.resize(closure_size);
- lazy_closure.resize(closure_size);
-
- std::vector<std::size_t> cpu_closure_ids;
- read(stream, cpu_closure_ids);
+ if (ctx.is_weightless) {
+ serialize_weightless(stream, scales, ctx);
+ serialize_weightless(stream, zerops, ctx);
+ std::size_t closure_size = closure_desc.closure.size();
+ stream & closure_size;
std::vector<ov::Tensor> cpu_closures;
- read_weightless(stream, cpu_closures, ctx);
- std::size_t tidx = 0;
- for (const auto& idx : cpu_closure_ids) {
- closure_desc.closure[idx] = std::move(cpu_closures[tidx++]);
- }
-
- std::vector<std::size_t> non_cpu_tensors_ids;
- read(stream, non_cpu_tensors_ids);
-
+ std::vector<std::size_t> cpu_closure_ids;
std::vector<ov::npuw::weights::LazyTensor> non_cpu_tensors;
- read(stream, non_cpu_tensors);
- std::size_t ltidx = 0;
- for (const auto& idx : non_cpu_tensors_ids) {
- lazy_closure[idx] = std::move(non_cpu_tensors[ltidx++]);
- }
-
- // Also read weights into LazyTensors
- for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
- if (closure_desc.closure_uid[cidx] != -1 &&
- lazy_closure[cidx]) { // previously registered before serialization
- lazy_closure[cidx].read_weight(ctx);
+ std::vector<std::size_t> non_cpu_tensors_ids;
+ if (stream.output()) {
+ for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
+ if (closure_desc.closure_uid[cidx] == -1) {
+ cpu_closure_ids.push_back(cidx);
+ cpu_closures.push_back(closure_desc.closure[cidx]);
+ } else {
+ non_cpu_tensors_ids.push_back(cidx);
+ non_cpu_tensors.push_back(lazy_closure[cidx]);
+ }
+ }
+ stream & cpu_closure_ids;
+ serialize_weightless(stream, cpu_closures, ctx);
+ stream & non_cpu_tensors_ids & non_cpu_tensors;
+ } else {
+ closure_desc.closure.resize(closure_size);
+ lazy_closure.resize(closure_size);
+ stream & cpu_closure_ids;
+ serialize_weightless(stream, cpu_closures, ctx);
+ std::size_t tidx = 0;
+ for (const auto& idx : cpu_closure_ids) {
+ closure_desc.closure[idx] = std::move(cpu_closures[tidx++]);
+ }
+ stream & non_cpu_tensors_ids & non_cpu_tensors;
+ std::size_t ltidx = 0;
+ for (const auto& idx : non_cpu_tensors_ids) {
+ lazy_closure[idx] = std::move(non_cpu_tensors[ltidx++]);
+ }
+ for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
+ if (closure_desc.closure_uid[cidx] != -1 && lazy_closure[cidx]) {
+ lazy_closure[cidx].read_weight(ctx);
+ }
}
}
} else {
- read(stream, scales);
- read(stream, zerops);
+ stream & scales & zerops;
- std::size_t closure_size = 0;
- read(stream, closure_size);
+ std::size_t closure_size = closure_desc.closure.size();
+ stream & closure_size;
std::vector<std::size_t> cpu_closure_ids;
- read(stream, cpu_closure_ids);
- closure_desc.closure.resize(closure_size);
- for (const auto& cidx : cpu_closure_ids) {
- read(stream, closure_desc.closure[cidx]);
+ if (stream.output()) {
+ std::vector<ov::Tensor> cpu_closures;
+ for (std::size_t cidx = 0; cidx < closure_desc.closure.size(); ++cidx) {
+ if (closure_desc.closure_uid[cidx] == -1) {
+ cpu_closure_ids.push_back(cidx);
+ cpu_closures.push_back(closure_desc.closure[cidx]);
+ }
+ }
+ stream & cpu_closure_ids;
+ for (auto& tensor : cpu_closures) {
+ stream & tensor;
+ }
+ } else {
+ stream & cpu_closure_ids;
+ closure_desc.closure.resize(closure_size);
+ for (const auto& cidx : cpu_closure_ids) {
+ stream & closure_desc.closure[cidx];
+ }
}
}
@@ -1046,7 +977,7 @@ ov::npuw::CompiledModel::~CompiledModel() {
}
}
-void ov::npuw::CompiledModel::export_model(std::ostream& stream) const {
+void ov::npuw::CompiledModel::export_model(std::ostream& raw_stream) const {
using namespace ov::npuw::s11n;
// Identify encryption flow
@@ -1067,28 +998,28 @@ void ov::npuw::CompiledModel::export_model(std::ostream& stream) const {
// Write header regardless of encryption requirement - to identify NPUW serializated blobs
// Serialize magic number first
- write(stream, NPUW_SERIALIZATION_INDICATOR);
+ write(raw_stream, NPUW_SERIALIZATION_INDICATOR);
// Serilize CompiledModel identifier
- write(stream, NPUW_COMPILED_MODEL_INDICATOR);
+ write(raw_stream, NPUW_COMPILED_MODEL_INDICATOR);
// Serialize general meta info
- write(stream, OPENVINO_VERSION_MAJOR);
- write(stream, OPENVINO_VERSION_MINOR);
- write(stream, OPENVINO_VERSION_PATCH);
- write(stream, std::string(NPUW_SERIALIZATION_VERSION));
+ write(raw_stream, OPENVINO_VERSION_MAJOR);
+ write(raw_stream, OPENVINO_VERSION_MINOR);
+ write(raw_stream, OPENVINO_VERSION_PATCH);
+ write(raw_stream, std::string(NPUW_SERIALIZATION_VERSION));
// Serialize encrypted flag
- write(stream, encryption_required);
+ write(raw_stream, encryption_required);
// Write flow identifier
- write(stream, is_weightless);
+ write(raw_stream, is_weightless);
if (!encryption_required) {
CompiledContext ctx(false, nullptr, nullptr, m_bf16_consts);
- serialize(stream, ctx);
+ serialize(raw_stream, ctx);
- write(stream, m_weights_bank->get_name());
+ auto stream = Stream::writer(raw_stream);
+ auto bank_name = m_weights_bank->get_name();
+ stream & bank_name;
if (!is_weightless) {
- // Serialize weights bank
- // Note: no need to encrypt weights in full flow
- m_weights_bank->serialize(stream);
+ ov::npuw::s11n::serialize(stream, *m_weights_bank);
}
return;
}
@@ -1096,22 +1027,22 @@ void ov::npuw::CompiledModel::export_model(std::ostream& stream) const {
// In case of weightless flow the whole blob will be encrypted on NPUW side.
std::stringstream non_encrypted_stream;
if (is_weightless) {
- non_encrypted_stream.copyfmt(stream);
+ non_encrypted_stream.copyfmt(raw_stream);
CompiledContext ctx(false, nullptr, nullptr, m_bf16_consts);
serialize(non_encrypted_stream, ctx);
std::string encrypted = enc_callbacks.encrypt(non_encrypted_stream.str());
- write(stream, encrypted);
+ write(raw_stream, encrypted);
} else {
// In case of blob with weights only encrypt XML part of the model
CompiledContext ctx(true, enc_callbacks.encrypt, nullptr, m_bf16_consts);
- serialize(stream, ctx);
+ serialize(raw_stream, ctx);
}
- write(stream, m_weights_bank->get_name());
+ auto stream = Stream::writer(raw_stream);
+ auto bank_name = m_weights_bank->get_name();
+ stream & bank_name;
if (!is_weightless) {
- // Serialize weights bank
- // Note: no need to encrypt weights in full flow
- m_weights_bank->serialize(stream);
+ ov::npuw::s11n::serialize(stream, *m_weights_bank);
}
}
@@ -1170,16 +1101,16 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::import_model(
auto read_and_finalize_bank = [&](std::istream& model_stream,
const std::shared_ptr<ov::npuw::CompiledModel>& compiled) {
- // Deserialize weights bank name
+ auto stream = Stream::reader(model_stream);
std::string bank_name;
- read(model_stream, bank_name);
+ stream & bank_name;
if (is_weightless) {
compiled->m_weights_bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
compiled->finalize_weights_bank();
} else {
- compiled->m_weights_bank =
- ov::npuw::weights::Bank::deserialize(model_stream, compiled->get_plugin()->get_core(), bank_name);
+ compiled->m_weights_bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
+ ov::npuw::s11n::serialize(stream, *compiled->m_weights_bank);
compiled->reconstruct_closure();
}
};
@@ -1229,73 +1160,76 @@ void ov::npuw::CompiledModel::serialize(std::ostream& stream, const ov::npuw::s1
using namespace ov::npuw::s11n;
auto write_model = [&](std::ostream& model_stream) {
+ auto stream = Stream::writer(model_stream);
// Serialize name
- write(model_stream, m_name);
+ stream & m_name;
// Serialize inputs and outputs
- write(model_stream, inputs());
- write(model_stream, outputs());
+ stream& inputs() & outputs();
// Serialize meta
- write(model_stream, m_inputs_to_submodels_inputs);
- write(model_stream, m_outputs_to_submodels_outputs);
- write(model_stream, m_param_subscribers);
- write(model_stream, m_submodels_input_to_prev_output);
+ stream & m_inputs_to_submodels_inputs & m_outputs_to_submodels_outputs & m_param_subscribers &
+ m_submodels_input_to_prev_output;
// Write device list
- write(model_stream, m_dev_list);
+ stream & m_dev_list;
// Write config
- write(model_stream, m_cfg);
+ stream & m_cfg;
// FIXME: utilize overload instead
- write(model_stream, m_non_npuw_props.size());
+ auto props_size = m_non_npuw_props.size();
+ stream & props_size;
for (const auto& p : m_non_npuw_props) {
// Skip properties which don't need to/can't be serialized
// FIXME: extend the logic
if (p.first == ov::cache_encryption_callbacks.name()) {
- write(model_stream, false);
+ bool should_write = false;
+ stream & should_write;
continue;
}
- write(model_stream, true);
- write(model_stream, p.first);
+ bool should_write = true;
+ stream & should_write & p.first;
write_any(model_stream, p.second);
}
// Write flow identifier
bool is_weightless = should_use_weightless_flow(m_non_npuw_props, m_cfg, m_const_to_offset);
- write(model_stream, is_weightless);
+ stream & is_weightless;
// Write bf16 consts cache
- write(model_stream, enc_ctx.bf16_consts);
+ stream & enc_ctx.bf16_consts;
// Create weightless context
WeightsContext ctx(is_weightless, m_const_to_offset);
// Serialize compiled submodels
- write(model_stream, m_compiled_submodels.size());
+ auto submodel_count = m_compiled_submodels.size();
+ stream & submodel_count;
for (std::size_t i = 0; i < m_compiled_submodels.size(); ++i) {
- auto& subm = m_compiled_submodels[i];
+ auto& subm = const_cast<CompiledModelDesc&>(m_compiled_submodels[i]);
auto real_idx = subm.replaced_by.value_or(i);
// Write device idx
// FIXME: if there is no compiled submodel, device_it is not set.
auto dev_idx = [&]() {
- auto it = std::find(m_dev_list.begin(), m_dev_list.end(), submodel_device(real_idx));
- NPUW_ASSERT(it != m_dev_list.end());
- return it - m_dev_list.begin();
+ return find_device_index(m_dev_list, submodel_device(real_idx));
};
- write(model_stream, real_idx == i ? dev_idx() : 0);
+ auto device_index = real_idx == i ? dev_idx() : 0;
+ stream & device_index;
// Write ICompiledModel if it's there
if (subm.compiled_model) {
- write(model_stream, true);
+ bool has_compiled_model = true;
+ stream & has_compiled_model;
// FIXME: workaround for import/export model since import model seem to reset the file pointer
std::stringstream ss;
subm.compiled_model->export_model(ss);
- write(model_stream, ss.str());
+ auto exported_model = ss.str();
+ stream & exported_model;
} else {
- write(model_stream, false);
+ bool has_compiled_model = false;
+ stream & has_compiled_model;
}
// Write the rest of the submodel desc
- subm.serialize(model_stream, ctx);
+ subm.serialize(stream, ctx);
}
};
@@ -1324,17 +1258,17 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
using namespace ov::npuw::s11n;
auto read_model = [&](std::istream& model_stream) {
+ auto stream = Stream::reader(model_stream);
// Deserialize model name first
std::string model_name;
- read(stream, model_name);
+ stream & model_name;
// Create a dummy CompiledModel with an empty ov::Model - this will skip the constructor flow
// to continue deserialization
ov::ParameterVector parameters;
ov::NodeVector results;
- read(stream, parameters);
- read(stream, results);
+ stream & parameters & results;
auto ov_model = std::make_shared<ov::Model>(ov::as_output_vector(results), parameters, model_name);
@@ -1342,42 +1276,40 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
// Deserialize meta
compiled->m_name = model_name;
- read(stream, compiled->m_inputs_to_submodels_inputs);
- read(stream, compiled->m_outputs_to_submodels_outputs);
- read(stream, compiled->m_param_subscribers);
- read(stream, compiled->m_submodels_input_to_prev_output);
+ stream & compiled->m_inputs_to_submodels_inputs & compiled->m_outputs_to_submodels_outputs &
+ compiled->m_param_subscribers & compiled->m_submodels_input_to_prev_output;
// Deserialize device list
- read(stream, compiled->m_dev_list);
+ stream & compiled->m_dev_list;
// Deserialize config
- read(stream, compiled->m_cfg);
+ stream & compiled->m_cfg;
compiled->m_cfg.parseEnvVars();
// FIXME: utilize overload instead
std::size_t props_size;
- read(stream, props_size);
+ stream & props_size;
for (std::size_t i = 0; i < props_size; ++i) {
bool should_read = true;
- read(stream, should_read);
+ stream & should_read;
// Skip properties which don't need to/can't be deserialized
// FIXME: extend the logic
if (!should_read) {
continue;
}
std::string key;
- read(stream, key);
+ stream & key;
ov::Any val;
- read_any(stream, val);
+ read_any(model_stream, val);
compiled->m_non_npuw_props[key] = std::move(val);
}
compiled->implement_properties();
// Read flow identifier
bool is_weightless = false;
- read(stream, is_weightless);
+ stream & is_weightless;
// Read bf16 consts cache
- read(stream, compiled->m_bf16_consts);
+ stream & compiled->m_bf16_consts;
// Initialize weights stream if weightless flow
std::string weights_path;
@@ -1453,14 +1385,14 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
// Deserialize compiled submodels
std::size_t subm_size = 0;
- read(stream, subm_size);
+ stream & subm_size;
compiled->m_compiled_submodels.resize(subm_size);
for (std::size_t i = 0; i < subm_size; ++i) {
std::size_t device_idx = 0;
- read(stream, device_idx);
+ stream & device_idx;
bool has_compiled_model = false;
- read(stream, has_compiled_model);
+ stream & has_compiled_model;
// Build import config for NPU device
ov::AnyMap import_config;
@@ -1476,7 +1408,7 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
// Import model from the plugin
// FIXME: workaround for import/export model since import model seems to reset the file pointer
std::string buf;
- read(stream, buf);
+ stream & buf;
std::stringstream buffer(buf);
compiled->m_compiled_submodels[i].compiled_model =
plugin->get_core()->import_model(buffer, device, import_config);
@@ -1488,7 +1420,7 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
device,
compiled->m_compiled_submodels[i].compiled_model,
import_config);
- compiled->m_compiled_submodels[i].deserialize(stream, compiled->m_import_weights_ctx, submodel_ctx);
+ compiled->m_compiled_submodels[i].serialize(stream, compiled->m_import_weights_ctx, &submodel_ctx);
}
compiled->implement_properties();
@@ -1839,6 +1771,26 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::vec
auto make_wrapped = [&](const std::shared_ptr<ov::Model>& model,
const std::string& profile_suffix,
const std::vector<std::string>& devs) -> ov::SoPtr<ov::ICompiledModel> {
+ if (!m_cfg.get<::intel_npu::NPUW_FALLBACK_EXEC>()) {
+ std::exception_ptr last_failure;
+ auto factory = make_factory(model, profile_suffix);
+ for (const auto& device : devs) {
+ try {
+ auto compiled = factory(device);
+ OPENVINO_ASSERT(compiled._ptr != nullptr,
+ "Failsafe factory returned null compiled model for device ",
+ device);
+ return compiled;
+ } catch (...) {
+ last_failure = std::current_exception();
+ }
+ }
+ if (last_failure) {
+ std::rethrow_exception(last_failure);
+ }
+ OPENVINO_THROW("No candidate devices available for compilation");
+ }
+
return ov::npuw::failsafe::CompiledModel::create(model,
get_plugin(),
devs,
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
index 3ec230f5207..3a2f042f5cc 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -286,10 +286,9 @@ private:
// Metrics
execution_stats stat;
- void serialize(std::ostream& stream, const ov::npuw::s11n::WeightsContext& ctx) const;
- void deserialize(std::istream& stream,
- const ov::npuw::s11n::WeightsContext& ctx,
- const ov::npuw::s11n::SubmodelDeserializeCtx& submodel_ctx);
+ void serialize(ov::npuw::s11n::Stream& stream,
+ const ov::npuw::s11n::WeightsContext& ctx,
+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx = nullptr);
};
std::vector<CompiledModelDesc> m_compiled_submodels;
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 cd59bfe04b7..502ce66e589 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
@@ -144,51 +144,6 @@ void Const::detach() {
m_mmaped_weights.reset();
}
-void Const::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, m_cached_type.to_string());
- write(stream, m_cached_shape);
- write(stream, m_offset);
- write(stream, m_byte_size);
-
- // FIXME: handle a special case:
- // 1) We added a Constant to the model before compilation (e.g. int RoPE patterns)
- // 2) This Constant became a parameter during folding
- // 3) Thus it became a LazyTensor, but there is no original data in weights file,
- // so it will fail in read_weight() during weightless deserialization.
- // In this case we need to include Constant's data into the blob.
- if (m_copied_if_not_in_model) {
- LOG_WARN("Some pattern introduced a new Constant node not present in the original weights file. This will "
- "increase the blob size by "
- << m_byte_size << " bytes.");
- write(stream, true);
- write(stream, m_copied_if_not_in_model);
- // detach the tensor
- m_copied_if_not_in_model = ov::Tensor();
- } else {
- write(stream, false);
- }
-}
-
-Const Const::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Const c;
- std::string type_str;
- read(stream, type_str);
- c.m_cached_type = ov::element::Type(type_str);
- read(stream, c.m_cached_shape);
- read(stream, c.m_offset);
- read(stream, c.m_byte_size);
-
- bool contains_weight = false;
- read(stream, contains_weight);
- if (contains_weight) {
- read(stream, c.m_read_from_bin);
- }
-
- return c;
-}
-
std::size_t Concat::hash() const {
std::size_t seed = std::hash<std::size_t>()(axis) + 0x9e3779b9;
for (auto& lt : tensors) {
@@ -230,20 +185,6 @@ void Concat::detach() {
}
}
-void Concat::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, axis);
- write(stream, tensors);
-}
-
-Concat Concat::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Concat c;
- read(stream, c.axis);
- read(stream, c.tensors);
- return c;
-}
-
std::size_t Unpack::hash() const {
std::size_t seed = w.get_hash() + 0x9e3779b9;
seed ^= z.get_hash() + 0x9e3779b9;
@@ -294,28 +235,6 @@ void Unpack::detach() {
s.detach();
}
-void Unpack::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, type.to_string());
- write(stream, shape);
- write(stream, w);
- write(stream, z);
- write(stream, s);
-}
-
-Unpack Unpack::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Unpack u;
- std::string type_str;
- read(stream, type_str);
- u.type = ov::element::Type(type_str);
- read(stream, u.shape);
- read(stream, u.w);
- read(stream, u.z);
- read(stream, u.s);
- return u;
-}
-
std::size_t Permute::hash() const {
std::size_t seed = tensor.get_hash() + 0x9e3779b9;
for (const auto& axis : axes) {
@@ -350,20 +269,6 @@ void Permute::detach() {
tensor.detach();
}
-void Permute::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, axes);
- write(stream, tensor);
-}
-
-Permute Permute::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Permute p;
- read(stream, p.axes);
- read(stream, p.tensor);
- return p;
-}
-
std::size_t Convert::hash() const {
std::size_t seed = type.hash() + 0x9e3779b9;
seed ^= tensor.get_hash() + 0x9e3779b9;
@@ -391,22 +296,6 @@ void Convert::detach() {
tensor.detach();
}
-void Convert::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, type.to_string());
- write(stream, tensor);
-}
-
-Convert Convert::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Convert c;
- std::string type_str;
- read(stream, type_str);
- c.type = ov::element::Type(type_str);
- read(stream, c.tensor);
- return c;
-}
-
std::size_t Gather::hash() const {
std::size_t seed = w.get_hash() + 0x9e3779b9;
seed ^= t.get_element_type().hash() + 0x9e3779b9;
@@ -466,25 +355,6 @@ void Gather::detach() {
w.detach();
}
-void Gather::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, dst_type.to_string());
- write(stream, dst_shape);
- write(stream, w);
- write(stream, t);
-}
-
-Gather Gather::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- Gather g;
- std::string type_str;
- read(stream, type_str);
- g.dst_type = ov::element::Type(type_str);
- read(stream, g.dst_shape);
- read(stream, g.w);
- read(stream, g.t);
- return g;
-}
} // namespace op
enum class TransformType : int { CONST = 0, CONCAT, UNPACK, PERMUTE, CONVERT, GATHER };
@@ -501,9 +371,8 @@ struct LazyTensorImpl {
void detach();
- void serialize(std::ostream& stream) const;
- static std::shared_ptr<LazyTensorImpl> deserialize(std::istream& stream);
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
+ void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor::Transform m_transform;
std::size_t m_hash = 0;
@@ -524,6 +393,180 @@ struct overloaded : Ts... {
template <class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
+namespace {
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Const&) {
+ return ov::npuw::weights::TransformType::CONST;
+}
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Concat&) {
+ return ov::npuw::weights::TransformType::CONCAT;
+}
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Unpack&) {
+ return ov::npuw::weights::TransformType::UNPACK;
+}
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Permute&) {
+ return ov::npuw::weights::TransformType::PERMUTE;
+}
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Convert&) {
+ return ov::npuw::weights::TransformType::CONVERT;
+}
+
+ov::npuw::weights::TransformType get_transform_type(const ov::npuw::weights::op::Gather&) {
+ return ov::npuw::weights::TransformType::GATHER;
+}
+
+} // namespace
+
+namespace ov {
+namespace npuw {
+namespace weights {
+namespace op {
+
+void Const::serialize(ov::npuw::s11n::Stream& stream) {
+ std::string type_str;
+ if (stream.output()) {
+ type_str = m_cached_type.to_string();
+ }
+ stream & type_str & m_cached_shape & m_offset & m_byte_size;
+ if (stream.input()) {
+ m_cached_type = ov::element::Type(type_str);
+ }
+
+ bool contains_weight = static_cast<bool>(m_copied_if_not_in_model);
+ stream & contains_weight;
+ if (contains_weight) {
+ if (stream.output()) {
+ stream & m_copied_if_not_in_model;
+ m_copied_if_not_in_model = ov::Tensor();
+ } else {
+ stream & m_read_from_bin;
+ }
+ }
+}
+
+void Concat::serialize(ov::npuw::s11n::Stream& stream) {
+ stream & axis & tensors;
+}
+
+void Unpack::serialize(ov::npuw::s11n::Stream& stream) {
+ std::string type_str;
+ if (stream.output()) {
+ type_str = type.to_string();
+ }
+ stream & type_str & shape & w & z & s;
+ if (stream.input()) {
+ type = ov::element::Type(type_str);
+ }
+}
+
+void Permute::serialize(ov::npuw::s11n::Stream& stream) {
+ stream & axes & tensor;
+}
+
+void Convert::serialize(ov::npuw::s11n::Stream& stream) {
+ std::string type_str;
+ if (stream.output()) {
+ type_str = type.to_string();
+ }
+ stream & type_str & tensor;
+ if (stream.input()) {
+ type = ov::element::Type(type_str);
+ }
+}
+
+void Gather::serialize(ov::npuw::s11n::Stream& stream) {
+ std::string type_str;
+ if (stream.output()) {
+ type_str = dst_type.to_string();
+ }
+ stream & type_str & dst_shape & w & t;
+ if (stream.input()) {
+ dst_type = ov::element::Type(type_str);
+ }
+}
+
+} // namespace op
+
+void LazyTensorImpl::serialize(ov::npuw::s11n::Stream& stream) {
+ stream & m_hash;
+
+ int op_type = 0;
+ if (stream.output()) {
+ std::visit(
+ [&](auto& op) {
+ op_type = static_cast<int>(get_transform_type(op));
+ stream & op_type;
+ op.serialize(stream);
+ },
+ m_transform);
+ return;
+ }
+
+ stream & op_type;
+ switch (TransformType(op_type)) {
+ case TransformType::CONCAT:
+ m_transform.emplace<op::Concat>();
+ std::get<op::Concat>(m_transform).serialize(stream);
+ break;
+ case TransformType::CONST:
+ m_transform.emplace<op::Const>();
+ std::get<op::Const>(m_transform).serialize(stream);
+ break;
+ case TransformType::CONVERT:
+ m_transform.emplace<op::Convert>();
+ std::get<op::Convert>(m_transform).serialize(stream);
+ break;
+ case TransformType::PERMUTE:
+ m_transform.emplace<op::Permute>();
+ std::get<op::Permute>(m_transform).serialize(stream);
+ break;
+ case TransformType::UNPACK:
+ m_transform.emplace<op::Unpack>();
+ std::get<op::Unpack>(m_transform).serialize(stream);
+ break;
+ case TransformType::GATHER:
+ m_transform.emplace<op::Gather>();
+ std::get<op::Gather>(m_transform).serialize(stream);
+ break;
+ default:
+ NPUW_ASSERT(false && "Unsupported type");
+ break;
+ }
+}
+
+void LazyTensor::serialize(ov::npuw::s11n::Stream& stream) {
+ bool is_initialized = static_cast<bool>(m_impl);
+ stream & is_initialized;
+ if (!is_initialized) {
+ if (stream.input()) {
+ m_impl.reset();
+ }
+ return;
+ }
+
+ if (stream.output()) {
+ m_impl->serialize(stream);
+ } else {
+ m_impl = std::make_shared<LazyTensorImpl>();
+ m_impl->serialize(stream);
+ }
+}
+
+} // namespace weights
+
+namespace s11n {
+void serialize(ov::npuw::s11n::Stream& stream, ov::npuw::weights::LazyTensor& var) {
+ var.serialize(stream);
+}
+} // namespace s11n
+
+} // namespace npuw
+} // namespace ov
+
LazyTensorImpl::LazyTensorImpl(LazyTensor::Transform&& t)
: m_transform(std::move(t)),
m_hash(std::visit(overloaded{[](const auto& op) {
@@ -612,71 +655,6 @@ void LazyTensorImpl::detach() {
m_transform);
}
-void LazyTensorImpl::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- write(stream, m_hash);
- // FIXME: create proper op identificators instead of int
- std::visit(overloaded{
- [&stream](const op::Concat& op) {
- write(stream, static_cast<int>(TransformType::CONCAT));
- op.serialize(stream);
- },
- [&stream](const op::Const& op) {
- write(stream, static_cast<int>(TransformType::CONST));
- op.serialize(stream);
- },
- [&stream](const op::Convert& op) {
- write(stream, static_cast<int>(TransformType::CONVERT));
- op.serialize(stream);
- },
- [&stream](const op::Permute& op) {
- write(stream, static_cast<int>(TransformType::PERMUTE));
- op.serialize(stream);
- },
- [&stream](const op::Unpack& op) {
- write(stream, static_cast<int>(TransformType::UNPACK));
- op.serialize(stream);
- },
- [&stream](const op::Gather& op) {
- write(stream, static_cast<int>(TransformType::GATHER));
- op.serialize(stream);
- },
- },
- m_transform);
-}
-
-std::shared_ptr<LazyTensorImpl> LazyTensorImpl::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- auto lt_impl = std::make_shared<LazyTensorImpl>();
- read(stream, lt_impl->m_hash);
- int op_type;
- read(stream, op_type);
- switch (TransformType(op_type)) {
- case TransformType::CONCAT:
- lt_impl->m_transform = op::Concat::deserialize(stream);
- break;
- case TransformType::CONST:
- lt_impl->m_transform = op::Const::deserialize(stream);
- break;
- case TransformType::CONVERT:
- lt_impl->m_transform = op::Convert::deserialize(stream);
- break;
- case TransformType::PERMUTE:
- lt_impl->m_transform = op::Permute::deserialize(stream);
- break;
- case TransformType::UNPACK:
- lt_impl->m_transform = op::Unpack::deserialize(stream);
- break;
- case TransformType::GATHER:
- lt_impl->m_transform = op::Gather::deserialize(stream);
- break;
- default:
- NPUW_ASSERT(false && "Unsupported type");
- break;
- }
- return lt_impl;
-}
-
LazyTensor::LazyTensor(const std::shared_ptr<ov::op::v0::Constant>& const_ptr)
: m_impl(std::make_shared<LazyTensorImpl>(op::Const(const_ptr))) {}
LazyTensor::LazyTensor(const std::vector<LazyTensor>& to_concat, const std::size_t axis)
@@ -765,28 +743,6 @@ void LazyTensor::detach() {
}
}
-void LazyTensor::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
- if (!m_impl) {
- write(stream, false);
- return;
- }
- write(stream, true);
- m_impl->serialize(stream);
-}
-
-LazyTensor LazyTensor::deserialize(std::istream& stream) {
- using namespace ov::npuw::s11n;
- bool is_initialized;
- read(stream, is_initialized);
- LazyTensor lt;
- if (!is_initialized) {
- return lt;
- }
- lt.m_impl = LazyTensorImpl::deserialize(stream);
- return lt;
-}
-
std::size_t LazyTensor::Hash::operator()(const LazyTensor& lt) const {
return lt.get_hash();
}
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 66ab1bef45b..e7b71cfc2cd 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
@@ -73,12 +73,12 @@ public:
};
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);
operator bool() const;
private:
+ friend void ov::npuw::s11n::serialize(ov::npuw::s11n::Stream& stream, LazyTensor& var);
+ void serialize(ov::npuw::s11n::Stream& stream);
std::shared_ptr<LazyTensorImpl> m_impl = nullptr;
};
@@ -96,10 +96,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Const deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
std::shared_ptr<ov::op::v0::Constant> m_node = nullptr;
ov::element::Type m_cached_type;
ov::Shape m_cached_shape;
@@ -129,10 +128,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Concat deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
std::vector<LazyTensor> tensors;
std::size_t axis = 0;
};
@@ -155,10 +153,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Unpack deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor w, z, s;
ov::element::Type type;
ov::Shape shape;
@@ -177,10 +174,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Permute deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor tensor;
std::vector<std::size_t> axes;
};
@@ -198,10 +194,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Convert deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor tensor;
ov::element::Type type;
};
@@ -223,10 +218,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
- void serialize(std::ostream& stream) const;
- static Gather deserialize(std::istream& stream);
private:
+ void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor w;
ov::Tensor t;
ov::element::Type dst_type;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 92ef105aea2..d819a653042 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
@@ -1143,7 +1143,7 @@ void ov::npuw::LLMCompiledModel::export_model(std::ostream& stream) const {
}
}
-void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw::s11n::CompiledContext& ctx) const {
+void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::npuw::s11n::CompiledContext& ctx) const {
LOG_INFO("Serializing LLMCompiledModel...");
LOG_BLOCK();
@@ -1158,38 +1158,26 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:
}
auto write_model_meta = [&](std::ostream& model_stream) {
+ auto stream = Stream::writer(model_stream);
// Serialize name
- write(model_stream, m_name);
+ stream & m_name;
// Serialize inputs and outputs
- write(model_stream, inputs());
- write(model_stream, outputs());
+ stream& inputs() & outputs();
// Serialize LLMCompiledModel-specific data
- write(model_stream, m_kvcache_desc.max_prompt_size);
- write(model_stream, m_kvcache_desc.total_size);
- write(model_stream, m_kvcache_desc.num_stored_tokens);
- write(model_stream, m_kvcache_desc.dim);
- write(model_stream, m_kvcache_desc.max_generation_token_len);
- write(model_stream, m_kvcache_desc.v_tensors_transposed_pre);
- write(model_stream, m_kvcache_desc.v_tensors_transposed_gen);
- write(model_stream, m_prefill_chunk_size);
- write(model_stream, m_use_chunk_prefill);
- write(model_stream, m_max_lora_rank);
- write(model_stream, m_enable_prefix_caching);
- write(model_stream, m_prefix_caching_block_size);
- write(model_stream, m_prefix_caching_max_num_blocks);
- write(model_stream, m_is_whisper);
- write(model_stream, m_eos_token_id);
- write(model_stream, m_is_eagle);
- write(model_stream, m_is_embedding);
+ stream & m_kvcache_desc.max_prompt_size & m_kvcache_desc.total_size & m_kvcache_desc.num_stored_tokens &
+ m_kvcache_desc.dim & m_kvcache_desc.max_generation_token_len & m_kvcache_desc.v_tensors_transposed_pre &
+ m_kvcache_desc.v_tensors_transposed_gen & m_prefill_chunk_size & m_use_chunk_prefill & m_max_lora_rank &
+ m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks & m_is_whisper &
+ m_eos_token_id & m_is_eagle & m_is_embedding;
// Write config
- write(model_stream, m_cfg);
+ stream & m_cfg;
// Serialize KV cache model variants
- write(model_stream, m_kvcache_sizes);
- write(model_stream, static_cast<uint32_t>(m_generate_compiled_variants.size()));
+ auto variant_count = static_cast<uint32_t>(m_generate_compiled_variants.size());
+ stream & m_kvcache_sizes & variant_count;
// Serialize CompiledModels
// Note: no need to pass any encryption here as it's done in export_model()
@@ -1202,7 +1190,7 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:
m_prefill_compiled->serialize(model_stream, enc_ctx);
const bool is_shared_lm_head = m_lm_head_compiled != nullptr;
- write(model_stream, is_shared_lm_head);
+ stream & is_shared_lm_head;
if (is_shared_lm_head) {
m_lm_head_compiled->serialize(model_stream, enc_ctx);
}
@@ -1211,24 +1199,24 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:
std::stringstream non_encrypted_stream;
if (ctx.encrypted) {
NPUW_ASSERT(ctx.encrypt && "Encryption function isn't provided!");
- non_encrypted_stream.copyfmt(stream);
+ non_encrypted_stream.copyfmt(raw_stream);
write_model_meta(non_encrypted_stream);
std::string encrypted_str = ctx.encrypt(non_encrypted_stream.str());
- write(stream, encrypted_str);
+ write(raw_stream, encrypted_str);
} else {
- write_model_meta(stream);
+ write_model_meta(raw_stream);
}
// Serialize bank name
const auto& kv_bank = m_kvcache_compiled->get_weights_bank();
const auto& p_bank = m_prefill_compiled->get_weights_bank();
NPUW_ASSERT(kv_bank && p_bank && kv_bank == p_bank && "Prefill and KVCache models' weight bank should be shared!");
- write(stream, kv_bank->get_name());
+ auto stream = Stream::writer(raw_stream);
+ auto bank_name = kv_bank->get_name();
+ stream & bank_name;
if (!is_weightless) {
- // Serialize weights bank
- // Note: no need to encrypt weights in full flow
- kv_bank->serialize(stream);
+ ov::npuw::s11n::serialize(stream, *kv_bank);
}
LOG_INFO("Done.");
@@ -1289,9 +1277,9 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_m
auto read_and_finalize_banks = [&](std::istream& model_stream,
const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {
- // Deserialize weights bank name
+ auto stream = Stream::reader(model_stream);
std::string bank_name;
- read(model_stream, bank_name);
+ stream & bank_name;
if (is_weightless) {
auto bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
@@ -1309,8 +1297,8 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_m
compiled->m_lm_head_compiled->finalize_weights_bank();
}
} else {
- auto bank =
- ov::npuw::weights::Bank::deserialize(model_stream, compiled->get_plugin()->get_core(), bank_name);
+ auto bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
+ ov::npuw::s11n::serialize(stream, *bank);
compiled->m_kvcache_compiled->set_weights_bank(bank);
for (const auto& compiled_variant : compiled->m_generate_compiled_variants) {
@@ -1375,49 +1363,39 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
using namespace ov::npuw::s11n;
auto read_model_meta = [&](std::istream& model_stream) {
+ auto stream = Stream::reader(model_stream);
// Deserialize model name first
std::string model_name;
- read(model_stream, model_name);
+ stream & model_name;
// Create a dummy CompiledModel with an empty ov::Model - this will skip the constructor flow
// to continue deserialization
ov::ParameterVector parameters;
ov::NodeVector results;
- read(model_stream, parameters);
- read(model_stream, results);
+ stream & parameters & results;
auto ov_model = std::make_shared<ov::Model>(ov::as_output_vector(results), parameters, model_name);
auto compiled = std::make_shared<ov::npuw::LLMCompiledModel>(ov_model, plugin, true);
// Deserialize LLMCompiledModel-specific data
- read(model_stream, compiled->m_kvcache_desc.max_prompt_size);
- read(model_stream, compiled->m_kvcache_desc.total_size);
- read(model_stream, compiled->m_kvcache_desc.num_stored_tokens);
- read(model_stream, compiled->m_kvcache_desc.dim);
- read(model_stream, compiled->m_kvcache_desc.max_generation_token_len);
- read(model_stream, compiled->m_kvcache_desc.v_tensors_transposed_pre);
- read(model_stream, compiled->m_kvcache_desc.v_tensors_transposed_gen);
- read(model_stream, compiled->m_prefill_chunk_size);
- read(model_stream, compiled->m_use_chunk_prefill);
- read(model_stream, compiled->m_max_lora_rank);
- read(model_stream, compiled->m_enable_prefix_caching);
- read(model_stream, compiled->m_prefix_caching_block_size);
- read(model_stream, compiled->m_prefix_caching_max_num_blocks);
- read(model_stream, compiled->m_is_whisper);
- read(model_stream, compiled->m_eos_token_id);
- read(model_stream, compiled->m_is_eagle);
- read(model_stream, compiled->m_is_embedding);
+ stream & compiled->m_kvcache_desc.max_prompt_size & compiled->m_kvcache_desc.total_size &
+ compiled->m_kvcache_desc.num_stored_tokens & compiled->m_kvcache_desc.dim &
+ compiled->m_kvcache_desc.max_generation_token_len & compiled->m_kvcache_desc.v_tensors_transposed_pre &
+ compiled->m_kvcache_desc.v_tensors_transposed_gen & compiled->m_prefill_chunk_size &
+ compiled->m_use_chunk_prefill & compiled->m_max_lora_rank & compiled->m_enable_prefix_caching &
+ compiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks & compiled->m_is_whisper &
+ compiled->m_eos_token_id & compiled->m_is_eagle & compiled->m_is_embedding;
// Deserialize config
- read(model_stream, compiled->m_cfg);
+ stream & compiled->m_cfg;
compiled->implement_properties();
// Deserialize KV cache model variants
- read(model_stream, compiled->m_kvcache_sizes);
+ stream & compiled->m_kvcache_sizes;
uint32_t num_variants = 0;
- read(model_stream, num_variants);
+ stream & num_variants;
compiled->m_generate_compiled_variants.reserve(num_variants);
@@ -1438,7 +1416,7 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserial
compiled->m_prefill_compiled = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
bool is_shared_lm_head = false;
- read(model_stream, is_shared_lm_head);
+ stream & is_shared_lm_head;
if (is_shared_lm_head) {
compiled->m_lm_head_compiled =
ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
index e194b568394..39cc31bfdfa 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
@@ -21,6 +21,17 @@
#include "spatial.hpp"
#include "util.hpp"
+namespace {
+
+std::streamsize checked_stream_size(const std::size_t size) {
+ if (size > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
+ OPENVINO_THROW("Blob size is too large to be represented on a std::streamsize!");
+ }
+ return static_cast<std::streamsize>(size);
+}
+
+} // namespace
+
// NOTE: This construtor should only be used when exporting blobs
ov::npuw::s11n::WeightsContext::WeightsContext(bool _is_weightless,
const std::unordered_map<const void*, std::size_t>& _const_to_offset)
@@ -60,539 +71,295 @@ ov::npuw::s11n::BF16Cache ov::npuw::s11n::get_bf16_consts(const std::shared_ptr<
return bf16_cache;
}
-void ov::npuw::s11n::write(std::ostream& stream, const std::streampos& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, std::streampos& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::write(std::ostream& stream, const std::string& var) {
- auto var_size = var.size();
- stream.write(reinterpret_cast<const char*>(&var_size), sizeof var_size);
- stream.write(&var[0], var.size());
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const bool& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const float& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Spatial& var) {
- using ov::npuw::s11n::write;
-
- write(stream, var.params.size());
- for (const auto& p : var.params) {
- write(stream, p.idx);
- write(stream, p.dim);
- }
- write(stream, var.range);
- write(stream, var.nway);
- write(stream, var.out_dim);
- write(stream, var.nway_iters);
- write(stream, var.tail_size);
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Attention& var) {
- using ov::npuw::s11n::write;
-
- write(stream, var.query_size);
- write(stream, var.context_size);
-
- // NB: This should've been done through a generic vector<T> write!
- write(stream, var.params.size());
- for (const auto& p : var.params) {
- write(stream, p.idx);
- write(stream, p.dim);
- }
-
- write(stream, var.mask_idx);
- write(stream, var.attend_all);
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::PyramidAttention& var) {
- using ov::npuw::s11n::write;
-
- write(stream, var.query_size);
- write(stream, var.full_context_size);
- write(stream, var._context_lengths);
-
- // Serialize attention infos
- write(stream, var._attention_infos.size());
- for (const auto& info : var._attention_infos) {
- write(stream, info.params.size());
- for (const auto& p : info.params) {
- write(stream, p.idx);
- write(stream, p.dim);
+void ov::npuw::s11n::serialize(Stream& stream, std::string& var) {
+ if (stream.output()) {
+ auto var_size = var.size();
+ stream.bytes(&var_size, sizeof var_size);
+ if (!var.empty()) {
+ stream.bytes(var.data(), checked_stream_size(var.size()));
}
- write(stream, info.mask_idx);
- write(stream, info.query_size);
- write(stream, info.context_length);
- }
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::HostFlashAttention& var) {
- using ov::npuw::s11n::write;
-
- // Serialize basic info from _sdpa_attention_info
- write(stream, var._sdpa_attention_info._query_size);
- write(stream, var._sdpa_attention_info._context_size);
- write(stream, var._sdpa_attention_info._k_seq_dim);
- write(stream, var._sdpa_attention_info._v_seq_dim);
-
- // Serialize SDPA indices from _sdpa_attention_info
- write(stream, var._sdpa_attention_info._sdpa_indices.query);
- write(stream, var._sdpa_attention_info._sdpa_indices.past_key);
- write(stream, var._sdpa_attention_info._sdpa_indices.past_value);
- write(stream, var._sdpa_attention_info._sdpa_indices.present_key);
- write(stream, var._sdpa_attention_info._sdpa_indices.present_value);
- write(stream, var._sdpa_attention_info._sdpa_indices.attention_mask);
-
- // Serialize tile input indices from _sdpa_attention_info
- write(stream, var._sdpa_attention_info._tile_input_indices.q);
- write(stream, var._sdpa_attention_info._tile_input_indices.k);
- write(stream, var._sdpa_attention_info._tile_input_indices.v);
- write(stream, var._sdpa_attention_info._tile_input_indices.mask);
- write(stream, var._sdpa_attention_info._tile_input_indices.acc);
- write(stream, var._sdpa_attention_info._tile_input_indices.max);
- write(stream, var._sdpa_attention_info._tile_input_indices.d);
-
- // Serialize tile output indices from _sdpa_attention_info
- write(stream, var._sdpa_attention_info._tile_output_indices.acc);
- write(stream, var._sdpa_attention_info._tile_output_indices.max);
- write(stream, var._sdpa_attention_info._tile_output_indices.d);
-
- // Serialize tile_size
- write(stream, var._tile_size);
-
- // Serialize can_use_tensor_view
- write(stream, var._can_use_tensor_view);
-
- // Note: _tile_model_to_compile and _compiled_tile_model are not serialized here
- // They are handled separately in CompiledModelDesc::serialize()
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::MoEExperts& var) {
- using ov::npuw::s11n::write;
-
- // Serialize basic MoE metadata
- write(stream, var.num_experts);
- write(stream, var.expert_hidden_dim);
- write(stream, var.num_active_experts);
- write(stream, var.input_token_count);
-
- // Serialize router scores index
- write(stream, var._router_scores_idx.has_value());
- if (var._router_scores_idx.has_value()) {
- write(stream, var._router_scores_idx.value());
- }
-
- // Serialize expert input parameter index
- write(stream, var._expert_input_param_idx.has_value());
- if (var._expert_input_param_idx.has_value()) {
- write(stream, var._expert_input_param_idx.value());
- }
-
- // Serialize parameter mapping
- write(stream, var._param_mapping);
-
- // Note: _compiled_models and _models_to_compile are not serialized here
- // They are handled separately in CompiledModelDesc::serialize()
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::MoEDownstream& var) {
- using ov::npuw::s11n::write;
-
- // Serialize MoE downstream metadata
- write(stream, var.total_experts_num);
- write(stream, var.active_experts_num);
- write(stream, var.expert_output_param_idx);
-
- // Note: _compiled_model and _model_to_compile are not serialized here
- // They are handled separately in CompiledModelDesc::serialize()
-}
-
-void ov::npuw::s11n::write(std::ostream& stream, const ov::Tensor& var) {
- using ov::npuw::s11n::write;
-
- if (!var) {
- write(stream, false);
- return;
- }
- write(stream, true);
-
- auto type_str = var.get_element_type().to_string();
- write(stream, type_str);
- write(stream, var.get_shape());
- write(stream, var.get_byte_size());
-
- ov::Tensor tensor;
- if (var.is_continuous()) {
- tensor = var;
} else {
- // Just copy strided tensor to a non-strided one
- tensor = ov::Tensor(var.get_element_type(), var.get_shape());
- var.copy_to(tensor);
- }
- NPUW_ASSERT(tensor);
- size_t blob_size = var.get_byte_size();
- if (blob_size > static_cast<decltype(blob_size)>(std::numeric_limits<std::streamsize>::max())) {
- OPENVINO_THROW("Blob size is too large to be represented on a std::streamsize!");
+ std::size_t var_size = 0;
+ stream.bytes(&var_size, sizeof var_size);
+ var.resize(var_size);
+ if (var_size != 0) {
+ stream.bytes(var.data(), checked_stream_size(var_size));
+ }
}
- stream.write(reinterpret_cast<const char*>(var.data()), static_cast<std::streamsize>(blob_size));
}
-void ov::npuw::s11n::write(std::ostream& stream, const ::intel_npu::Config& var) {
- write(stream, var.toString());
+void ov::npuw::s11n::serialize(Stream& stream, bool& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::Output<const ov::Node>& var) {
- write(stream, var.get_element_type().to_string());
- write(stream, var.get_partial_shape().to_string());
- write(stream, var.get_names());
+void ov::npuw::s11n::serialize(Stream& stream, float& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::write_any(std::ostream& stream, const ov::Any& var) {
- auto str = ov::npuw::s11n::anyToString(var);
- write(stream, str);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Spatial& var) {
+ stream & var.params & var.range & var.nway & var.out_dim & var.nway_iters & var.tail_size;
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::weights::LazyTensor& var) {
- var.serialize(stream);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Spatial::Param& var) {
+ stream & var.idx & var.dim;
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::CacheMode& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Attention& var) {
+ stream & var.query_size & var.context_size & var.params & var.mask_idx & var.attend_all;
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::element::Type& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Attention::Param& var) {
+ stream & var.idx & var.dim;
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::hint::PerformanceMode& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::PyramidAttention& var) {
+ stream & var.query_size & var.full_context_size & var._context_lengths & var._attention_infos;
}
-void ov::npuw::s11n::write(std::ostream& stream, const ov::AnyMap& var) {
- auto str = ov::npuw::s11n::anyMapToString(var);
- write(stream, str);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo& var) {
+ stream & var.params & var.mask_idx & var.query_size & var.context_length;
}
-void ov::npuw::s11n::read(std::istream& stream, std::streampos& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo::Param& var) {
+ stream & var.idx & var.dim;
}
-void ov::npuw::s11n::read(std::istream& stream, std::string& var) {
- std::size_t var_size = 0;
- stream.read(reinterpret_cast<char*>(&var_size), sizeof var_size);
- var.resize(var_size);
- stream.read(&var[0], var_size);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::HostFlashAttention& var) {
+ auto& info = var._sdpa_attention_info;
+ stream & info._query_size & info._context_size & info._k_seq_dim & info._v_seq_dim & info._sdpa_indices.query &
+ info._sdpa_indices.past_key & info._sdpa_indices.past_value & info._sdpa_indices.present_key &
+ info._sdpa_indices.present_value & info._sdpa_indices.attention_mask & info._tile_input_indices.q &
+ info._tile_input_indices.k & info._tile_input_indices.v & info._tile_input_indices.mask &
+ info._tile_input_indices.acc & info._tile_input_indices.max & info._tile_input_indices.d &
+ info._tile_output_indices.acc & info._tile_output_indices.max & info._tile_output_indices.d & var._tile_size &
+ var._can_use_tensor_view;
}
-void ov::npuw::s11n::read(std::istream& stream, bool& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::MoEExperts& var) {
+ stream & var.num_experts & var.expert_hidden_dim & var.num_active_experts & var.input_token_count &
+ var._router_scores_idx & var._expert_input_param_idx & var._param_mapping;
}
-void ov::npuw::s11n::read(std::istream& stream, float& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::MoEDownstream& var) {
+ stream & var.total_experts_num & var.active_experts_num & var.expert_output_param_idx;
}
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::Spatial& var) {
- using ov::npuw::s11n::read;
-
- std::size_t params_size = 0;
- read(stream, params_size);
- for (std::size_t i = 0; i < params_size; ++i) {
- ov::npuw::compiled::Spatial::Param p;
- read(stream, p.idx);
- read(stream, p.dim);
- var.params.push_back(p);
- }
- read(stream, var.range);
- read(stream, var.nway);
- read(stream, var.out_dim);
- read(stream, var.nway_iters);
- read(stream, var.tail_size);
+void ov::npuw::s11n::serialize(Stream& stream, ov::Tensor& var) {
+ transfer_tensor(stream, var);
}
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::Attention& var) {
- using ov::npuw::s11n::read;
-
- read(stream, var.query_size);
- read(stream, var.context_size);
-
- std::size_t params_size = 0;
- read(stream, params_size);
- for (std::size_t i = 0; i < params_size; ++i) {
- ov::npuw::compiled::Attention::Param p;
- read(stream, p.idx);
- read(stream, p.dim);
- var.params.push_back(p);
+void ov::npuw::s11n::serialize(Stream& stream, ::intel_npu::Config& var) {
+ std::string str;
+ if (stream.output()) {
+ str = var.toString();
}
-
- read(stream, var.mask_idx);
- read(stream, var.attend_all);
-}
-
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::PyramidAttention& var) {
- using ov::npuw::s11n::read;
-
- read(stream, var.query_size);
- read(stream, var.full_context_size);
- read(stream, var._context_lengths);
-
- // Deserialize attention infos
- std::size_t attention_infos_size = 0;
- read(stream, attention_infos_size);
- var._attention_infos.resize(attention_infos_size);
-
- for (auto& info : var._attention_infos) {
- std::size_t params_size = 0;
- read(stream, params_size);
- info.params.resize(params_size);
- for (auto& p : info.params) {
- read(stream, p.idx);
- read(stream, p.dim);
- }
- read(stream, info.mask_idx);
- read(stream, info.query_size);
- read(stream, info.context_length);
+ stream & str;
+ if (stream.input()) {
+ var.fromString(str);
}
}
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::HostFlashAttention& var) {
- using ov::npuw::s11n::read;
-
- // Deserialize basic info into _sdpa_attention_info
- read(stream, var._sdpa_attention_info._query_size);
- read(stream, var._sdpa_attention_info._context_size);
- read(stream, var._sdpa_attention_info._k_seq_dim);
- read(stream, var._sdpa_attention_info._v_seq_dim);
-
- // Deserialize SDPA indices into _sdpa_attention_info
- read(stream, var._sdpa_attention_info._sdpa_indices.query);
- read(stream, var._sdpa_attention_info._sdpa_indices.past_key);
- read(stream, var._sdpa_attention_info._sdpa_indices.past_value);
- read(stream, var._sdpa_attention_info._sdpa_indices.present_key);
- read(stream, var._sdpa_attention_info._sdpa_indices.present_value);
- read(stream, var._sdpa_attention_info._sdpa_indices.attention_mask);
-
- // Deserialize tile input indices into _sdpa_attention_info
- read(stream, var._sdpa_attention_info._tile_input_indices.q);
- read(stream, var._sdpa_attention_info._tile_input_indices.k);
- read(stream, var._sdpa_attention_info._tile_input_indices.v);
- read(stream, var._sdpa_attention_info._tile_input_indices.mask);
- read(stream, var._sdpa_attention_info._tile_input_indices.acc);
- read(stream, var._sdpa_attention_info._tile_input_indices.max);
- read(stream, var._sdpa_attention_info._tile_input_indices.d);
-
- // Deserialize tile output indices into _sdpa_attention_info
- read(stream, var._sdpa_attention_info._tile_output_indices.acc);
- read(stream, var._sdpa_attention_info._tile_output_indices.max);
- read(stream, var._sdpa_attention_info._tile_output_indices.d);
-
- // Deserialize tile_size
- read(stream, var._tile_size);
-
- // Deserialize can_use_tensor_view
- read(stream, var._can_use_tensor_view);
-
- // Note: _tile_model_to_compile and _compiled_tile_model are not deserialized here
- // They are handled separately in CompiledModelDesc::deserialize()
-}
-
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::MoEExperts& var) {
- using ov::npuw::s11n::read;
-
- // Deserialize basic MoE metadata
- read(stream, var.num_experts);
- read(stream, var.expert_hidden_dim);
- read(stream, var.num_active_experts);
- read(stream, var.input_token_count);
-
- // Deserialize router scores index
- bool has_router_scores_idx = false;
- read(stream, has_router_scores_idx);
- if (has_router_scores_idx) {
- size_t value = 0;
- read(stream, value);
- var._router_scores_idx = value;
- }
-
- // Deserialize expert input parameter index
- bool has_expert_input_param_idx = false;
- read(stream, has_expert_input_param_idx);
- if (has_expert_input_param_idx) {
- size_t value = 0;
- read(stream, value);
- var._expert_input_param_idx = value;
+void ov::npuw::s11n::serialize(Stream& stream, ov::Output<const ov::Node>& var) {
+ if (stream.output()) {
+ auto elem_type = var.get_element_type().to_string();
+ auto shape = var.get_partial_shape().to_string();
+ auto names = var.get_names();
+ stream & elem_type & shape & names;
+ } else {
+ OPENVINO_THROW("ov::Output<const ov::Node> is write-only in NPUW serialization");
}
-
- // Deserialize parameter mapping
- read(stream, var._param_mapping);
-
- // Note: _compiled_models and _models_to_compile are not deserialized here
- // They are handled separately in CompiledModelDesc::deserialize()
}
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::MoEDownstream& var) {
- using ov::npuw::s11n::read;
+void ov::npuw::s11n::transfer_tensor(Stream& stream, ov::Tensor& var, const TensorAllocator& allocator) {
+ if (stream.output()) {
+ bool is_initialized = static_cast<bool>(var);
+ stream & is_initialized;
+ if (!is_initialized) {
+ return;
+ }
- // Deserialize MoE downstream metadata
- read(stream, var.total_experts_num);
- read(stream, var.active_experts_num);
- read(stream, var.expert_output_param_idx);
+ auto type_str = var.get_element_type().to_string();
+ auto shape = var.get_shape();
+ auto byte_size = var.get_byte_size();
+ stream & type_str & shape & byte_size;
- // Note: _compiled_model and _model_to_compile are not deserialized here
- // They are handled separately in CompiledModelDesc::deserialize()
-}
+ ov::Tensor tensor = var;
+ if (!var.is_continuous()) {
+ tensor = ov::Tensor(var.get_element_type(), var.get_shape());
+ var.copy_to(tensor);
+ }
+ NPUW_ASSERT(tensor);
+ stream.bytes(tensor.data(), tensor.get_byte_size());
+ return;
+ }
-void ov::npuw::s11n::read(std::istream& stream, ov::Tensor& var) {
bool is_initialized = false;
- read(stream, is_initialized);
-
+ stream & is_initialized;
if (!is_initialized) {
+ var = ov::Tensor();
return;
}
std::string type_str;
- read(stream, type_str);
+ stream & type_str;
ov::element::Type type(type_str);
ov::Shape shape;
- read(stream, shape);
+ stream & shape;
std::size_t byte_size = 0;
- read(stream, byte_size);
-
- var = ov::Tensor(type, shape);
-
- stream.read(reinterpret_cast<char*>(var.data()), byte_size);
-}
-
-void ov::npuw::s11n::read(std::istream& stream, ::intel_npu::Config& var) {
- std::string str;
- read(stream, str);
- var.fromString(str);
-}
+ stream & byte_size;
-void ov::npuw::s11n::read(std::istream& stream, std::shared_ptr<ov::op::v0::Parameter>& var) {
- std::string elem_type_str;
- std::string part_shape_str;
- std::unordered_set<std::string> names;
- read(stream, elem_type_str);
- read(stream, part_shape_str);
- read(stream, names);
- // NOTE: the code below is taken from NPU plugin's create_dummy_model()
- var = std::make_shared<op::v0::Parameter>(ov::element::Type(elem_type_str), ov::PartialShape(part_shape_str));
- if (!names.empty()) {
- var->set_friendly_name(*names.begin()); // FIXME: any_name ?
+ if (allocator) {
+ var = allocator(type, shape);
+ } else {
+ var = ov::Tensor(type, shape);
+ }
+ NPUW_ASSERT(var && "Tensor allocator returned an empty tensor");
+ NPUW_ASSERT(var.get_element_type() == type && var.get_shape() == shape &&
+ "Tensor allocator returned tensor with unexpected type or shape");
+ NPUW_ASSERT(var.get_byte_size() == byte_size && "Tensor allocator returned tensor with unexpected byte size");
+
+ stream.bytes(var.data(), byte_size);
+}
+
+void ov::npuw::s11n::serialize(Stream& stream, std::shared_ptr<ov::op::v0::Parameter>& var) {
+ if (stream.input()) {
+ std::string elem_type_str;
+ std::string part_shape_str;
+ std::unordered_set<std::string> names;
+ stream & elem_type_str & part_shape_str & names;
+ var = std::make_shared<op::v0::Parameter>(ov::element::Type(elem_type_str), ov::PartialShape(part_shape_str));
+ if (!names.empty()) {
+ var->set_friendly_name(*names.begin());
+ }
+ var->output(0).get_tensor().set_names(names);
+ } else {
+ OPENVINO_THROW("Parameter pointer is read-only in NPUW serialization");
}
- var->output(0).get_tensor().set_names(names);
}
-void ov::npuw::s11n::read(std::istream& stream, std::shared_ptr<ov::Node>& var) {
- std::string elem_type_str;
- std::string part_shape_str;
- std::unordered_set<std::string> names;
- read(stream, elem_type_str);
- read(stream, part_shape_str);
- read(stream, names);
- // NOTE: the code below is taken from NPU plugin's create_dummy_model()
- std::shared_ptr<ov::Node> res =
- std::make_shared<ov::op::v0::Constant>(ov::element::Type(elem_type_str), std::vector<size_t>{1});
- // FIXME: serialize names as well?
- const std::shared_ptr<ov::descriptor::Tensor>& tensor_dummy =
- std::make_shared<ov::descriptor::Tensor>(ov::element::Type(elem_type_str),
- ov::PartialShape(part_shape_str),
- names);
- var = std::make_shared<ov::op::v0::Result>(res);
- var->output(0).set_tensor_ptr(tensor_dummy);
- if (!names.empty()) {
- var->set_friendly_name(*names.begin()); // any_name ?
+void ov::npuw::s11n::serialize(Stream& stream, std::shared_ptr<ov::Node>& var) {
+ if (stream.input()) {
+ std::string elem_type_str;
+ std::string part_shape_str;
+ std::unordered_set<std::string> names;
+ stream & elem_type_str & part_shape_str & names;
+ std::shared_ptr<ov::Node> res =
+ std::make_shared<ov::op::v0::Constant>(ov::element::Type(elem_type_str), std::vector<size_t>{1});
+ const std::shared_ptr<ov::descriptor::Tensor>& tensor_dummy =
+ std::make_shared<ov::descriptor::Tensor>(ov::element::Type(elem_type_str),
+ ov::PartialShape(part_shape_str),
+ names);
+ var = std::make_shared<ov::op::v0::Result>(res);
+ var->output(0).set_tensor_ptr(tensor_dummy);
+ if (!names.empty()) {
+ var->set_friendly_name(*names.begin());
+ }
+ } else {
+ OPENVINO_THROW("Node pointer is read-only in NPUW serialization");
}
}
-void ov::npuw::s11n::read_any(std::istream& stream, ov::Any& var) {
+void ov::npuw::s11n::serialize(Stream& stream, ov::Any& var) {
std::string str;
- read(stream, str);
- var = ov::npuw::s11n::stringToAny(str);
-}
-
-void ov::npuw::s11n::read(std::istream& stream, ov::npuw::weights::LazyTensor& var) {
- var = ov::npuw::weights::LazyTensor::deserialize(stream);
+ if (stream.output()) {
+ str = ov::npuw::s11n::anyToString(var);
+ }
+ stream & str;
+ if (stream.input()) {
+ var = ov::npuw::s11n::stringToAny(str);
+ }
}
-void ov::npuw::s11n::read(std::istream& stream, ov::CacheMode& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::CacheMode& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::read(std::istream& stream, ov::element::Type& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::element::Type& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::read(std::istream& stream, ov::hint::PerformanceMode& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void ov::npuw::s11n::serialize(Stream& stream, ov::hint::PerformanceMode& var) {
+ stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::read(std::istream& stream, ov::AnyMap& var) {
+void ov::npuw::s11n::serialize(Stream& stream, ov::AnyMap& var) {
std::string str;
- read(stream, str);
- var = ov::npuw::s11n::stringToAnyMap(str);
+ if (stream.output()) {
+ str = ov::npuw::s11n::anyMapToString(var);
+ }
+ stream & str;
+ if (stream.input()) {
+ var = ov::npuw::s11n::stringToAnyMap(str);
+ }
}
// Weightless
// FIXME: all serialization needs a good rewriting
-void ov::npuw::s11n::write_weightless(std::ostream& stream,
- const std::vector<ov::Tensor>& var,
- const ov::npuw::s11n::WeightsContext& ctx) {
- write(stream, var.size());
- for (const auto& t : var) {
- if (!t) {
- write(stream, false);
- continue;
- }
- write(stream, true);
- auto data = t.data();
- auto iter = ctx.const_to_offset.find(data);
- if (iter == ctx.const_to_offset.end()) {
- write(stream, false);
- write(stream, t);
- } else {
- write(stream, true);
- write(stream, t.get_element_type().to_string());
- write(stream, t.get_shape());
- write(stream, t.get_byte_size());
- write(stream, iter->second); // offset in weights file
+void ov::npuw::s11n::serialize_weightless(Stream& stream,
+ std::vector<ov::Tensor>& var,
+ const ov::npuw::s11n::WeightsContext& ctx) {
+ if (stream.output()) {
+ auto size = var.size();
+ serialize(stream, size);
+ for (auto& t : var) {
+ if (!t) {
+ bool is_initialized = false;
+ serialize(stream, is_initialized);
+ continue;
+ }
+ bool is_initialized = true;
+ serialize(stream, is_initialized);
+ auto data = t.data();
+ auto iter = ctx.const_to_offset.find(data);
+ if (iter == ctx.const_to_offset.end()) {
+ bool is_weightless = false;
+ serialize(stream, is_weightless);
+ auto tensor = t;
+ serialize(stream, tensor);
+ } else {
+ bool is_weightless = true;
+ serialize(stream, is_weightless);
+ auto elem_type = t.get_element_type().to_string();
+ serialize(stream, elem_type);
+ auto shape = t.get_shape();
+ serialize(stream, shape);
+ auto byte_size = t.get_byte_size();
+ serialize(stream, byte_size);
+ auto offset = iter->second;
+ serialize(stream, offset);
+ }
}
+ return;
}
-}
-void ov::npuw::s11n::read_weightless(std::istream& stream,
- std::vector<ov::Tensor>& var,
- const ov::npuw::s11n::WeightsContext& ctx) {
var.clear();
std::size_t size;
- read(stream, size);
+ serialize(stream, size);
for (std::size_t i = 0; i < size; ++i) {
bool is_initialized = false;
- read(stream, is_initialized);
+ serialize(stream, is_initialized);
if (!is_initialized) {
var.push_back(ov::Tensor());
continue;
}
bool is_weightless = false;
- read(stream, is_weightless);
+ serialize(stream, is_weightless);
if (is_weightless) {
std::string type_str;
- read(stream, type_str);
+ serialize(stream, type_str);
ov::element::Type type(type_str);
ov::Shape shape;
- read(stream, shape);
+ serialize(stream, shape);
std::size_t byte_size = 0;
- read(stream, byte_size);
+ serialize(stream, byte_size);
std::size_t offset = 0;
- read(stream, offset);
+ serialize(stream, offset);
ov::Tensor t(type, shape);
if (ctx.weights) {
@@ -623,7 +390,7 @@ void ov::npuw::s11n::read_weightless(std::istream& stream,
var.push_back(t);
} else {
ov::Tensor t;
- read(stream, t);
+ serialize(stream, t);
var.push_back(t);
}
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index 99bd1003b87..0ffbc79c0ca 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -8,16 +8,23 @@
#include <cstdint>
#include <functional>
#include <iostream>
+#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
+#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
+#include "attention.hpp"
+#include "host_flash_attention.hpp"
+#include "openvino/core/shape.hpp"
#include "openvino/runtime/file_handle.hpp"
+#include "pyramid_attention.hpp"
+#include "spatial.hpp"
namespace ov {
namespace npuw {
@@ -36,7 +43,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =
const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR =
{char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};
-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.21";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.22";
// Forward declaration
namespace intel_npu {
@@ -87,6 +94,7 @@ struct MoEDownstream;
} // namespace compiled
namespace weights {
class LazyTensor;
+class Bank;
} // namespace weights
namespace s11n {
@@ -176,209 +184,261 @@ struct SubmodelDeserializeCtx {
BF16Cache get_bf16_consts(const std::shared_ptr<ov::Model>& model);
-// Specific type overloads
-void write(std::ostream& stream, const std::streampos& var);
-void write(std::ostream& stream, const std::string& var);
-void write(std::ostream& stream, const bool& var);
-void write(std::ostream& stream, const float& var);
-void write(std::ostream& stream, const ov::npuw::compiled::Spatial& var);
-void write(std::ostream& stream, const ov::npuw::compiled::Attention& var);
-void write(std::ostream& stream, const ov::npuw::compiled::PyramidAttention& var);
-void write(std::ostream& stream, const ov::npuw::compiled::HostFlashAttention& var);
-void write(std::ostream& stream, const ov::npuw::compiled::MoEExperts& var);
-void write(std::ostream& stream, const ov::npuw::compiled::MoEDownstream& var);
-void write(std::ostream& stream, const ov::Tensor& var);
-void write(std::ostream& stream, const ::intel_npu::Config& var);
-void write(std::ostream& stream, const ov::Output<const ov::Node>& var);
-void write_any(std::ostream& stream, const ov::Any& var);
-void write(std::ostream& stream, const ov::npuw::weights::LazyTensor& var);
-void write(std::ostream& stream, const ov::CacheMode& var);
-void write(std::ostream& stream, const ov::element::Type& var);
-void write(std::ostream& stream, const std::map<std::string, Any>& var);
-void write(std::ostream& stream, const ov::hint::PerformanceMode& var);
-
-void read(std::istream& stream, std::streampos& var);
-void read(std::istream& stream, std::string& var);
-void read(std::istream& stream, bool& var);
-void read(std::istream& stream, float& var);
-void read(std::istream& stream, ov::npuw::compiled::Spatial& var);
-void read(std::istream& stream, ov::npuw::compiled::Attention& var);
-void read(std::istream& stream, ov::npuw::compiled::PyramidAttention& var);
-void read(std::istream& stream, ov::npuw::compiled::HostFlashAttention& var);
-void read(std::istream& stream, ov::npuw::compiled::MoEExperts& var);
-void read(std::istream& stream, ov::npuw::compiled::MoEDownstream& var);
-void read(std::istream& stream, ov::Tensor& var);
-void read(std::istream& stream, ::intel_npu::Config& var);
-void read(std::istream& stream, std::shared_ptr<ov::op::v0::Parameter>& var);
-void read(std::istream& stream, std::shared_ptr<ov::Node>& var);
-void read_any(std::istream& stream, ov::Any& var);
-void read(std::istream& stream, ov::npuw::weights::LazyTensor& var);
-void read(std::istream& stream, ov::CacheMode& var);
-void read(std::istream& stream, ov::element::Type& var);
-void read(std::istream& stream, std::map<std::string, Any>& var);
-void read(std::istream& stream, ov::hint::PerformanceMode& var);
+class Stream {
+public:
+ static Stream reader(std::istream& stream) {
+ return Stream(&stream, nullptr);
+ }
+
+ static Stream writer(std::ostream& stream) {
+ return Stream(nullptr, &stream);
+ }
+
+ bool input() const {
+ return m_input != nullptr;
+ }
+
+ bool output() const {
+ return m_output != nullptr;
+ }
+
+ template <typename T>
+ Stream& operator&(T&& value) {
+ using plain_type = std::remove_const_t<std::remove_reference_t<T>>;
+ serialize(*this, const_cast<plain_type&>(value));
+ return *this;
+ }
+
+ void operator()() {}
+
+ template <typename T, typename... Ts>
+ void operator()(T&& value, Ts&&... values) {
+ (*this) & std::forward<T>(value);
+ (*this)(std::forward<Ts>(values)...);
+ }
+
+ void bytes(void* data, std::size_t size) {
+ const auto stream_size = to_streamsize(size);
+ if (output()) {
+ m_output->write(reinterpret_cast<const char*>(data), stream_size);
+ } else {
+ m_input->read(reinterpret_cast<char*>(data), stream_size);
+ }
+ }
+
+private:
+ static std::streamsize to_streamsize(std::size_t size) {
+ if (size > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
+ throw std::overflow_error("Stream::bytes() size exceeds std::streamsize range");
+ }
+ return static_cast<std::streamsize>(size);
+ }
+
+ Stream(std::istream* input, std::ostream* output) : m_input(input), m_output(output) {}
+
+ std::istream* m_input = nullptr;
+ std::ostream* m_output = nullptr;
+};
+
+void serialize(Stream& stream, std::streampos& var);
+void serialize(Stream& stream, std::string& var);
+void serialize(Stream& stream, bool& var);
+void serialize(Stream& stream, float& var);
+void serialize(Stream& stream, ov::npuw::compiled::Spatial& var);
+void serialize(Stream& stream, ov::npuw::compiled::Spatial::Param& var);
+void serialize(Stream& stream, ov::npuw::compiled::Attention& var);
+void serialize(Stream& stream, ov::npuw::compiled::Attention::Param& var);
+void serialize(Stream& stream, ov::npuw::compiled::PyramidAttention& var);
+void serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo& var);
+void serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo::Param& var);
+void serialize(Stream& stream, ov::npuw::compiled::HostFlashAttention& var);
+void serialize(Stream& stream, ov::npuw::compiled::MoEExperts& var);
+void serialize(Stream& stream, ov::npuw::compiled::MoEDownstream& var);
+void serialize(Stream& stream, ov::Tensor& var);
+void serialize(Stream& stream, ::intel_npu::Config& var);
+void serialize(Stream& stream, ov::Any& var);
+void serialize(Stream& stream, ov::npuw::weights::LazyTensor& var);
+void serialize(Stream& stream, ov::npuw::weights::Bank& var);
+void serialize(Stream& stream, ov::CacheMode& var);
+void serialize(Stream& stream, ov::element::Type& var);
+void serialize(Stream& stream, ov::hint::PerformanceMode& var);
+void serialize(Stream& stream, std::map<std::string, Any>& var);
+void serialize(Stream& stream, ov::Output<const ov::Node>& var);
+void serialize(Stream& stream, std::shared_ptr<ov::op::v0::Parameter>& var);
+void serialize(Stream& stream, std::shared_ptr<ov::Node>& var);
// Weightless utils
-void write_weightless(std::ostream& stream, const std::vector<ov::Tensor>& var, const WeightsContext& ctx);
-// No allocation needed
-void read_weightless(std::istream& stream, std::vector<ov::Tensor>& var, const WeightsContext& ctx);
+void serialize_weightless(Stream& stream, std::vector<ov::Tensor>& var, const WeightsContext& ctx);
// Forward declaration
template <typename T1, typename T2>
-void write(std::ostream& stream, const std::pair<T1, T2>& var);
+void serialize(Stream& stream, std::pair<T1, T2>& var);
template <typename T>
-void write(std::ostream& stream, const std::vector<T>& var);
+void serialize(Stream& stream, std::vector<T>& var);
template <typename T, size_t N>
-void write(std::ostream& stream, const std::array<T, N>& var);
-template <typename T1, typename T2>
-void read(std::istream& stream, std::pair<T1, T2>& var);
-template <typename T>
-void read(std::istream& stream, std::vector<T>& var);
-template <typename T, std::size_t N>
-void read(std::istream& stream, std::array<T, N>& var);
+void serialize(Stream& stream, std::array<T, N>& var);
-// Serialization
-template <typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>
+template <typename T>
void write(std::ostream& stream, const T& var) {
- stream.write(reinterpret_cast<const char*>(&var), sizeof var);
-}
-
-template <typename T1, typename T2>
-void write(std::ostream& stream, const std::pair<T1, T2>& var) {
- write(stream, var.first);
- write(stream, var.second);
+ auto stream_io = Stream::writer(stream);
+ auto& mutable_var = const_cast<std::remove_const_t<T>&>(var);
+ serialize(stream_io, mutable_var);
}
template <typename T>
-void write(std::ostream& stream, const std::vector<T>& var) {
- write(stream, var.size());
- for (const auto& el : var) {
- write(stream, el);
- }
-}
-
-template <typename T, size_t N>
-void write(std::ostream& stream, const std::array<T, N>& var) {
- for (const auto& el : var) {
- write(stream, el);
- }
+void read(std::istream& stream, T& var) {
+ auto stream_io = Stream::reader(stream);
+ serialize(stream_io, var);
}
-template <typename T>
-void write(std::ostream& stream, const std::unordered_set<T>& var) {
- write(stream, var.size());
- for (const auto& el : var) {
- write(stream, el);
- }
+inline void write_any(std::ostream& stream, const ov::Any& var) {
+ write(stream, var);
}
-template <typename T, typename H>
-void write(std::ostream& stream, const std::unordered_set<T, H>& var) {
- write(stream, var.size());
- for (const auto& el : var) {
- write(stream, el);
- }
+inline void read_any(std::istream& stream, ov::Any& var) {
+ read(stream, var);
}
-template <typename K, typename V>
-void write(std::ostream& stream, const std::map<K, V>& var) {
- write(stream, var.size());
- for (const auto& el : var) {
- write(stream, el);
- }
+inline void write_weightless(std::ostream& stream, const std::vector<ov::Tensor>& var, const WeightsContext& ctx) {
+ auto stream_io = Stream::writer(stream);
+ auto& mutable_var = const_cast<std::vector<ov::Tensor>&>(var);
+ serialize_weightless(stream_io, mutable_var, ctx);
}
-template <typename T>
-void write(std::ostream& stream, const std::optional<T>& var) {
- if (var) {
- write(stream, true);
- write(stream, var.value());
- } else {
- write(stream, false);
- }
+inline void read_weightless(std::istream& stream, std::vector<ov::Tensor>& var, const WeightsContext& ctx) {
+ auto stream_io = Stream::reader(stream);
+ serialize_weightless(stream_io, var, ctx);
}
-// Deserialization
+// Serialization
template <typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>
-void read(std::istream& stream, T& var) {
- stream.read(reinterpret_cast<char*>(&var), sizeof var);
+void serialize(Stream& stream, T& var) {
+ stream.bytes(&var, sizeof var);
}
template <typename T1, typename T2>
-void read(std::istream& stream, std::pair<T1, T2>& var) {
- read(stream, var.first);
- read(stream, var.second);
+void serialize(Stream& stream, std::pair<T1, T2>& var) {
+ stream & var.first & var.second;
}
template <typename T>
-void read(std::istream& stream, std::vector<T>& var) {
- var.clear();
- std::size_t var_size = 0;
- stream.read(reinterpret_cast<char*>(&var_size), sizeof var_size);
- var.reserve(var_size);
- for (std::size_t i = 0; i < var_size; ++i) {
- T elem;
- read(stream, elem);
- var.push_back(std::move(elem));
+void serialize(Stream& stream, std::vector<T>& var) {
+ if (stream.output()) {
+ auto size = var.size();
+ stream & size;
+ for (std::size_t i = 0; i < var.size(); ++i) {
+ if constexpr (std::is_same_v<T, bool>) {
+ bool el = var[i];
+ stream & el;
+ } else {
+ auto& el = var[i];
+ stream & el;
+ }
+ }
+ } else {
+ var.clear();
+ std::size_t var_size = 0;
+ stream & var_size;
+ var.reserve(var_size);
+ for (std::size_t i = 0; i < var_size; ++i) {
+ T elem;
+ stream & elem;
+ var.push_back(std::move(elem));
+ }
}
}
-template <typename T, std::size_t N>
-void read(std::istream& stream, std::array<T, N>& var) {
- for (std::size_t i = 0; i < N; ++i) {
- T elem;
- read(stream, elem);
- var[i] = elem;
+template <typename T, size_t N>
+void serialize(Stream& stream, std::array<T, N>& var) {
+ for (auto& el : var) {
+ stream & el;
}
}
template <typename T>
-void read(std::istream& stream, std::unordered_set<T>& var) {
- var.clear();
- std::size_t var_size = 0;
- stream.read(reinterpret_cast<char*>(&var_size), sizeof var_size);
- for (std::size_t i = 0; i < var_size; ++i) {
- T elem;
- read(stream, elem);
- var.insert(std::move(elem));
+void serialize(Stream& stream, std::unordered_set<T>& var) {
+ if (stream.output()) {
+ auto size = var.size();
+ stream & size;
+ for (const auto& el : var) {
+ auto value = el;
+ stream & value;
+ }
+ } else {
+ var.clear();
+ std::size_t var_size = 0;
+ stream & var_size;
+ for (std::size_t i = 0; i < var_size; ++i) {
+ T elem;
+ stream & elem;
+ var.insert(std::move(elem));
+ }
}
}
template <typename T, typename H>
-void read(std::istream& stream, std::unordered_set<T, H>& var) {
- var.clear();
- std::size_t var_size = 0;
- stream.read(reinterpret_cast<char*>(&var_size), sizeof var_size);
- for (std::size_t i = 0; i < var_size; ++i) {
- T elem;
- read(stream, elem);
- var.insert(std::move(elem));
+void serialize(Stream& stream, std::unordered_set<T, H>& var) {
+ if (stream.output()) {
+ auto size = var.size();
+ stream & size;
+ for (const auto& el : var) {
+ auto value = el;
+ stream & value;
+ }
+ } else {
+ var.clear();
+ std::size_t var_size = 0;
+ stream & var_size;
+ for (std::size_t i = 0; i < var_size; ++i) {
+ T elem;
+ stream & elem;
+ var.insert(std::move(elem));
+ }
}
}
template <typename K, typename V>
-void read(std::istream& stream, std::map<K, V>& var) {
- var.clear();
- std::size_t var_size = 0;
- stream.read(reinterpret_cast<char*>(&var_size), sizeof var_size);
- for (std::size_t i = 0; i < var_size; ++i) {
- std::pair<K, V> elem;
- read(stream, elem);
- var[elem.first] = elem.second;
+void serialize(Stream& stream, std::map<K, V>& var) {
+ if (stream.output()) {
+ auto size = var.size();
+ stream & size;
+ for (auto& el : var) {
+ auto pair = el;
+ stream & pair;
+ }
+ } else {
+ var.clear();
+ std::size_t var_size = 0;
+ stream & var_size;
+ for (std::size_t i = 0; i < var_size; ++i) {
+ std::pair<K, V> elem;
+ stream & elem;
+ var[elem.first] = elem.second;
+ }
}
}
template <typename T>
-void read(std::istream& stream, std::optional<T>& var) {
- bool has_value = false;
- read(stream, has_value);
+void serialize(Stream& stream, std::optional<T>& var) {
+ bool has_value = var.has_value();
+ stream & has_value;
if (has_value) {
- T val;
- read(stream, val);
- var = val;
+ if (stream.output()) {
+ auto& value = var.value();
+ stream & value;
+ } else {
+ T value;
+ stream & value;
+ var = std::move(value);
+ }
+ } else {
+ var.reset();
}
}
+using TensorAllocator = std::function<ov::Tensor(const ov::element::Type&, const ov::Shape&)>;
+void transfer_tensor(Stream& stream, ov::Tensor& var, const TensorAllocator& allocator = {});
+
} // namespace s11n
} // namespace npuw
} // namespace ov
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 b43753c360a..9823a467ae9 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
@@ -196,21 +196,20 @@ bool Bank::is_remote(int64_t uid) const {
return false;
}
-void Bank::serialize(std::ostream& stream) const {
- using namespace ov::npuw::s11n;
-
+void Bank::serialize(ov::npuw::s11n::Stream& stream) {
LOG_INFO("Serializing weights bank...");
LOG_BLOCK();
std::unique_lock guard(m_mutex);
- write(stream, m_device_banks.size());
+ std::size_t bank_size = m_device_banks.size();
+ stream & bank_size;
for (const auto& elem : m_device_banks) {
const auto& device = elem.first;
const auto& device_bank = elem.second;
- write(stream, device);
- write(stream, device_bank.storage.size());
+ auto storage_size = device_bank.storage.size();
+ stream & device & 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) {
@@ -218,47 +217,16 @@ void Bank::serialize(std::ostream& stream) const {
}
for (const auto& uid : uids) {
- write(stream, uid);
- write(stream, device_bank.storage.at(uid).tensor);
- }
- }
-
- LOG_INFO("DONE.");
-}
-
-std::shared_ptr<Bank> Bank::deserialize(std::istream& stream,
- const std::shared_ptr<const ov::ICore>& core,
- const std::string& name) {
- using namespace ov::npuw::s11n;
-
- LOG_INFO("Deserializing weights bank...");
- LOG_BLOCK();
-
- auto bank = ov::npuw::weights::bank(name, core, "");
-
- std::size_t bank_size = 0;
- read(stream, bank_size);
-
- for (std::size_t i = 0; i < bank_size; ++i) {
- std::string device;
- read(stream, device);
- std::size_t storage_size = 0;
- read(stream, storage_size);
- for (std::size_t j = 0; j < storage_size; ++j) {
- int64_t uid = -1;
- read(stream, uid);
- bank->read_and_add_tensor(stream, uid, device);
+ stream & uid;
+ auto tensor = device_bank.storage.at(uid).tensor;
+ transfer_tensor(stream, tensor);
}
}
LOG_INFO("DONE.");
-
- return bank;
}
-void Bank::read_and_add_tensor(std::istream& stream, int64_t uid, const std::string& device) {
- using namespace ov::npuw::s11n;
-
+void Bank::read_and_add_tensor(ov::npuw::s11n::Stream& stream, int64_t uid, const std::string& device) {
// This method is supposed to be used only during deserialization
std::unique_lock guard(m_mutex);
@@ -273,40 +241,52 @@ void Bank::read_and_add_tensor(std::istream& stream, int64_t uid, const std::str
if (device == "CPU") {
// Just read deserialized tensor into the bank
- read(stream, device_bank.storage[uid].tensor);
+ transfer_tensor(stream, device_bank.storage[uid].tensor);
return;
}
// Need to allocate on device and copy deserialized tensor to that memory
- ov::SoPtr<ov::ITensor> remote_tensor;
- ov::Tensor allocated_tensor;
-
- // FIXME: reading not via a dedicated function
- bool is_intialized = false;
- read(stream, is_intialized);
- NPUW_ASSERT(is_intialized);
-
- std::string type_str;
- read(stream, type_str);
- ov::element::Type type(type_str);
-
- ov::Shape shape;
- read(stream, shape);
-
- std::size_t byte_size = 0;
- read(stream, byte_size);
-
auto remote_ctx = m_core->get_default_context(device)._ptr;
- remote_tensor = remote_ctx->create_host_tensor(type, shape);
- allocated_tensor = ov::make_tensor(remote_tensor);
- device_bank.storage[uid] = {LazyTensor(), allocated_tensor};
- stream.read(reinterpret_cast<char*>(allocated_tensor.data()), byte_size);
+ transfer_tensor(stream,
+ device_bank.storage[uid].tensor,
+ [&remote_ctx](const ov::element::Type& type, const ov::Shape& shape) {
+ ov::SoPtr<ov::ITensor> remote_tensor = remote_ctx->create_host_tensor(type, shape);
+ return ov::make_tensor(remote_tensor);
+ });
+ NPUW_ASSERT(device_bank.storage[uid].tensor && "Remote tensor should be initialized during bank deserialize");
+ device_bank.storage[uid].lt = LazyTensor();
}
std::string Bank::get_name() const {
return m_bank_name;
}
+void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::weights::Bank& var) {
+ if (stream.output()) {
+ var.serialize(stream);
+ } else {
+ LOG_INFO("Deserializing weights bank...");
+ LOG_BLOCK();
+
+ std::size_t bank_size = 0;
+ stream & bank_size;
+
+ for (std::size_t i = 0; i < bank_size; ++i) {
+ std::string device;
+ stream & device;
+ std::size_t storage_size = 0;
+ stream & storage_size;
+ for (std::size_t j = 0; j < storage_size; ++j) {
+ int64_t uid = -1;
+ stream & uid;
+ var.read_and_add_tensor(stream, uid, device);
+ }
+ }
+
+ LOG_INFO("DONE.");
+ }
+}
+
std::shared_ptr<Bank> BankManager::getBank(const std::string& bank_name,
const std::shared_ptr<const ov::ICore>& core,
const std::string& 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.hpp
index 10efad349b2..2375b644565 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
@@ -43,6 +43,7 @@ public:
private:
friend class ov::npuw::LLMCompiledModel;
friend class ov::npuw::CompiledModel;
+ friend void ov::npuw::s11n::serialize(ov::npuw::s11n::Stream& stream, ov::npuw::weights::Bank& var);
struct StoredTensor {
LazyTensor lt;
@@ -60,12 +61,8 @@ private:
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,
- const std::string& name);
- // Used during deserialization
- void read_and_add_tensor(std::istream& stream, int64_t uid, const std::string& device);
+ void serialize(ov::npuw::s11n::Stream& stream);
+ void read_and_add_tensor(ov::npuw::s11n::Stream& stream, int64_t uid, const std::string& device);
mutable std::mutex m_mutex;
std::shared_ptr<const ov::ICore> m_core = nullptr;
diff --git a/src/plugins/intel_npu/tests/unit/npuw/import_non_llm_blob.cpp b/src/plugins/intel_npu/tests/unit/npuw/import_non_llm_blob.cpp
index e0bbd93a9cb..1a2b3544442 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/import_non_llm_blob.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/import_non_llm_blob.cpp
@@ -11,6 +11,7 @@
#include "intel_npu/config/npuw.hpp"
#include "model_builder.hpp"
#include "openvino/openvino.hpp"
+#include "serialization.hpp"
using ov::test::npuw::ModelBuilder;
@@ -23,6 +24,64 @@ public:
}
protected:
+ static ov::Tensor make_input_tensor(const ov::Output<const ov::Node>& input) {
+ ov::Tensor tensor(input.get_element_type(), input.get_shape());
+
+ if (input.get_element_type() == ov::element::i32) {
+ auto* data = tensor.data<int32_t>();
+ for (std::size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = static_cast<int32_t>(i % 17);
+ }
+ } else if (input.get_element_type() == ov::element::i64) {
+ auto* data = tensor.data<int64_t>();
+ for (std::size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = static_cast<int64_t>(i % 17);
+ }
+ } else if (input.get_element_type() == ov::element::f32) {
+ auto* data = tensor.data<float>();
+ for (std::size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = static_cast<float>(i) * 0.25f;
+ }
+ } else if (input.get_element_type() == ov::element::f16) {
+ auto* data = tensor.data<ov::float16>();
+ for (std::size_t i = 0; i < tensor.get_size(); ++i) {
+ data[i] = ov::float16(static_cast<float>(i) * 0.25f);
+ }
+ } else {
+ std::memset(tensor.data(), 0, tensor.get_byte_size());
+ }
+
+ return tensor;
+ }
+
+ static std::vector<ov::Tensor> infer_outputs(ov::CompiledModel& model) {
+ auto request = model.create_infer_request();
+ for (const auto& input : model.inputs()) {
+ request.set_tensor(input, make_input_tensor(input));
+ }
+ request.infer();
+
+ std::vector<ov::Tensor> outputs;
+ outputs.reserve(model.outputs().size());
+ for (const auto& output : model.outputs()) {
+ auto result = request.get_tensor(output);
+ ov::Tensor copy(result.get_element_type(), result.get_shape());
+ result.copy_to(copy);
+ outputs.push_back(copy);
+ }
+ return outputs;
+ }
+
+ static void expect_outputs_equal(const std::vector<ov::Tensor>& expected, const std::vector<ov::Tensor>& actual) {
+ ASSERT_EQ(expected.size(), actual.size());
+ for (std::size_t i = 0; i < expected.size(); ++i) {
+ EXPECT_EQ(expected[i].get_element_type(), actual[i].get_element_type());
+ EXPECT_EQ(expected[i].get_shape(), actual[i].get_shape());
+ ASSERT_EQ(expected[i].get_byte_size(), actual[i].get_byte_size());
+ EXPECT_EQ(std::memcmp(expected[i].data(), actual[i].data(), expected[i].get_byte_size()), 0);
+ }
+ }
+
ModelBuilder model_builder;
std::shared_ptr<ov::Model> m_ov_model;
ov::AnyMap m_props;
@@ -35,13 +94,15 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeed) {
m_props["CACHE_MODE"] = "OPTIMIZE_SPEED";
auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ auto compiled_outputs = infer_outputs(compiled);
std::stringstream blob;
compiled.export_model(blob);
EXPECT_NO_THROW({
auto imported = m_core.import_model(blob, "NPU", m_props);
- imported.create_infer_request();
+ auto imported_outputs = infer_outputs(imported);
+ expect_outputs_equal(compiled_outputs, imported_outputs);
});
}
@@ -51,6 +112,7 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtr) {
m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ auto compiled_outputs = infer_outputs(compiled);
std::stringstream blob;
compiled.export_model(blob);
@@ -59,7 +121,8 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtr) {
auto import_props = m_props;
import_props[ov::hint::model.name()] = std::static_pointer_cast<const ov::Model>(m_ov_model);
auto imported = m_core.import_model(blob, "NPU", import_props);
- imported.create_infer_request();
+ auto imported_outputs = infer_outputs(imported);
+ expect_outputs_equal(compiled_outputs, imported_outputs);
});
}
@@ -70,13 +133,15 @@ TEST_P(ImportNonLLMNonWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ auto compiled_outputs = infer_outputs(compiled);
std::stringstream blob;
compiled.export_model(blob);
EXPECT_NO_THROW({
auto imported = m_core.import_model(blob, "NPU", m_props);
- imported.create_infer_request();
+ auto imported_outputs = infer_outputs(imported);
+ expect_outputs_equal(compiled_outputs, imported_outputs);
});
}
diff --git a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp b/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp
index f5d06210607..82f63beb08c 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp
@@ -6,18 +6,158 @@
#include <gtest/gtest.h>
+#include <filesystem>
+#include <fstream>
#include <iostream>
+#include "attention.hpp"
+#include "common_test_utils/file_utils.hpp"
#include "compiled_model.hpp"
+#include "host_flash_attention.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/npuw.hpp"
+#include "lazy_tensor.hpp"
+#include "moe_transformations/moe_transformation.hpp"
#include "model_builder.hpp"
#include "openvino/core/parallel.hpp"
+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/openvino.hpp"
+#include "openvino/runtime/shared_buffer.hpp"
+#include "openvino/util/mmap_object.hpp"
+#include "pyramid_attention.hpp"
#include "spatial.hpp"
+#include "weights_bank.hpp"
using ov::test::npuw::ModelBuilder;
+namespace {
+
+void expect_tensors_equal(const ov::Tensor& expected, const ov::Tensor& actual) {
+ ASSERT_EQ(static_cast<bool>(expected), static_cast<bool>(actual));
+ if (!expected) {
+ return;
+ }
+
+ EXPECT_EQ(expected.get_element_type(), actual.get_element_type());
+ EXPECT_EQ(expected.get_shape(), actual.get_shape());
+ ASSERT_EQ(expected.get_byte_size(), actual.get_byte_size());
+ EXPECT_EQ(std::memcmp(expected.data(), actual.data(), expected.get_byte_size()), 0);
+}
+
+template <typename T>
+std::shared_ptr<ov::op::v0::Constant> make_weightless_constant(const ov::element::Type& type,
+ const ov::Shape& shape,
+ const std::vector<T>& data,
+ std::size_t offset) {
+ auto constant = std::make_shared<ov::op::v0::Constant>(type, shape, data);
+ constant->get_rt_info()[ov::WeightlessCacheAttribute::get_type_info_static()] =
+ ov::WeightlessCacheAttribute(constant->get_byte_size(), offset, type);
+ return constant;
+}
+
+ov::npuw::s11n::WeightsContext::ConstsCache make_consts_cache(
+ const std::vector<std::shared_ptr<ov::op::v0::Constant>>& constants) {
+ ov::npuw::s11n::WeightsContext::ConstsCache cache;
+ for (const auto& constant : constants) {
+ const auto attr =
+ constant->get_rt_info().at(ov::WeightlessCacheAttribute::get_type_info_static())
+ .as<ov::WeightlessCacheAttribute>();
+ cache[{attr.bin_offset, constant->get_byte_size()}] = constant;
+ }
+ return cache;
+}
+
+void expect_attention_equal(const ov::npuw::compiled::Attention& expected, const ov::npuw::compiled::Attention& actual) {
+ EXPECT_EQ(expected.query_size, actual.query_size);
+ EXPECT_EQ(expected.context_size, actual.context_size);
+ EXPECT_EQ(expected.params.size(), actual.params.size());
+ for (std::size_t i = 0; i < expected.params.size(); ++i) {
+ EXPECT_EQ(expected.params[i].idx, actual.params[i].idx);
+ EXPECT_EQ(expected.params[i].dim, actual.params[i].dim);
+ }
+ EXPECT_EQ(expected.mask_idx, actual.mask_idx);
+ expect_tensors_equal(expected.attend_all, actual.attend_all);
+}
+
+void expect_pyramid_attention_equal(const ov::npuw::compiled::PyramidAttention& expected,
+ const ov::npuw::compiled::PyramidAttention& actual) {
+ EXPECT_EQ(expected.query_size, actual.query_size);
+ EXPECT_EQ(expected.full_context_size, actual.full_context_size);
+ EXPECT_EQ(expected._context_lengths, actual._context_lengths);
+ ASSERT_EQ(expected._attention_infos.size(), actual._attention_infos.size());
+ for (std::size_t i = 0; i < expected._attention_infos.size(); ++i) {
+ const auto& lhs = expected._attention_infos[i];
+ const auto& rhs = actual._attention_infos[i];
+ EXPECT_EQ(lhs.mask_idx, rhs.mask_idx);
+ EXPECT_EQ(lhs.query_size, rhs.query_size);
+ EXPECT_EQ(lhs.context_length, rhs.context_length);
+ EXPECT_EQ(lhs.params.size(), rhs.params.size());
+ for (std::size_t j = 0; j < lhs.params.size(); ++j) {
+ EXPECT_EQ(lhs.params[j].idx, rhs.params[j].idx);
+ EXPECT_EQ(lhs.params[j].dim, rhs.params[j].dim);
+ }
+ }
+}
+
+void expect_host_flash_attention_equal(const ov::npuw::compiled::HostFlashAttention& expected,
+ const ov::npuw::compiled::HostFlashAttention& actual) {
+ const auto& lhs = expected._sdpa_attention_info;
+ const auto& rhs = actual._sdpa_attention_info;
+ EXPECT_EQ(lhs._query_size, rhs._query_size);
+ EXPECT_EQ(lhs._context_size, rhs._context_size);
+ EXPECT_EQ(lhs._k_seq_dim, rhs._k_seq_dim);
+ EXPECT_EQ(lhs._v_seq_dim, rhs._v_seq_dim);
+ EXPECT_EQ(lhs._sdpa_indices.query, rhs._sdpa_indices.query);
+ EXPECT_EQ(lhs._sdpa_indices.past_key, rhs._sdpa_indices.past_key);
+ EXPECT_EQ(lhs._sdpa_indices.past_value, rhs._sdpa_indices.past_value);
+ EXPECT_EQ(lhs._sdpa_indices.present_key, rhs._sdpa_indices.present_key);
+ EXPECT_EQ(lhs._sdpa_indices.present_value, rhs._sdpa_indices.present_value);
+ EXPECT_EQ(lhs._sdpa_indices.attention_mask, rhs._sdpa_indices.attention_mask);
+ EXPECT_EQ(lhs._tile_input_indices.q, rhs._tile_input_indices.q);
+ EXPECT_EQ(lhs._tile_input_indices.k, rhs._tile_input_indices.k);
+ EXPECT_EQ(lhs._tile_input_indices.v, rhs._tile_input_indices.v);
+ EXPECT_EQ(lhs._tile_input_indices.mask, rhs._tile_input_indices.mask);
+ EXPECT_EQ(lhs._tile_input_indices.acc, rhs._tile_input_indices.acc);
+ EXPECT_EQ(lhs._tile_input_indices.max, rhs._tile_input_indices.max);
+ EXPECT_EQ(lhs._tile_input_indices.d, rhs._tile_input_indices.d);
+ EXPECT_EQ(lhs._tile_output_indices.acc, rhs._tile_output_indices.acc);
+ EXPECT_EQ(lhs._tile_output_indices.max, rhs._tile_output_indices.max);
+ EXPECT_EQ(lhs._tile_output_indices.d, rhs._tile_output_indices.d);
+ EXPECT_EQ(expected._tile_size, actual._tile_size);
+ EXPECT_EQ(expected._can_use_tensor_view, actual._can_use_tensor_view);
+}
+
+void expect_moe_experts_equal(const ov::npuw::compiled::MoEExperts& expected,
+ const ov::npuw::compiled::MoEExperts& actual) {
+ EXPECT_EQ(expected.num_experts, actual.num_experts);
+ EXPECT_EQ(expected.expert_hidden_dim, actual.expert_hidden_dim);
+ EXPECT_EQ(expected.num_active_experts, actual.num_active_experts);
+ EXPECT_EQ(expected.input_token_count, actual.input_token_count);
+ EXPECT_EQ(expected._router_scores_idx, actual._router_scores_idx);
+ EXPECT_EQ(expected._expert_input_param_idx, actual._expert_input_param_idx);
+ EXPECT_EQ(expected._param_mapping, actual._param_mapping);
+}
+
+void expect_moe_downstream_equal(const ov::npuw::compiled::MoEDownstream& expected,
+ const ov::npuw::compiled::MoEDownstream& actual) {
+ EXPECT_EQ(expected.total_experts_num, actual.total_experts_num);
+ EXPECT_EQ(expected.active_experts_num, actual.active_experts_num);
+ EXPECT_EQ(expected.expert_output_param_idx, actual.expert_output_param_idx);
+}
+
+void expect_lazy_tensor_transform_types_equal(const ov::npuw::weights::LazyTensor& expected,
+ const ov::npuw::weights::LazyTensor& actual) {
+ const auto expected_transforms = expected.get_transformations();
+ const auto actual_transforms = actual.get_transformations();
+ ASSERT_EQ(expected_transforms.size(), actual_transforms.size());
+ for (std::size_t i = 0; i < expected_transforms.size(); ++i) {
+ EXPECT_EQ(expected_transforms[i].index(), actual_transforms[i].index());
+ }
+}
+
+} // namespace
+
// FIXME: parametrize all the tests below
TEST(SerializationTest, BasicTypes_string) {
@@ -210,6 +350,34 @@ TEST(SerializationTest, BasicTypes_vector) {
EXPECT_EQ(var, res);
}
+TEST(SerializationTest, BasicTypes_array) {
+ using namespace ov::npuw::s11n;
+
+ std::array<int, 4> var{1, 2, 3, 4};
+ std::array<int, 4> res{};
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_EQ(var, res);
+}
+
+TEST(SerializationTest, BasicTypes_vector_bool) {
+ using namespace ov::npuw::s11n;
+
+ std::vector<bool> var{true, false, true, true, false};
+ std::vector<bool> res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_EQ(var, res);
+}
+
TEST(SerializationTest, BasicTypes_map) {
using namespace ov::npuw::s11n;
@@ -258,6 +426,175 @@ TEST(SerializationTest, BasicTypes_optional) {
EXPECT_EQ(var2, res2);
}
+TEST(SerializationTest, OVTypes_AnyMap) {
+ using namespace ov::npuw::s11n;
+
+ ov::AnyMap var = {{"NPU_USE_NPUW", std::string("YES")},
+ {"NPUW_FUNCALL_FOR_ALL", true},
+ {"NPUW_ACC_THRESH", 0.125f},
+ {"NPUW_LLM_BATCH_DIM", 7}};
+ ov::AnyMap res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ ASSERT_EQ(var.size(), res.size());
+ EXPECT_EQ(res.at("NPU_USE_NPUW").as<std::string>(), "YES");
+ EXPECT_EQ(res.at("NPUW_FUNCALL_FOR_ALL").as<bool>(), true);
+ EXPECT_FLOAT_EQ(res.at("NPUW_ACC_THRESH").as<float>(), 0.125f);
+ EXPECT_EQ(res.at("NPUW_LLM_BATCH_DIM").as<int>(), 7);
+}
+
+TEST(SerializationTest, OVTypes_ElementType) {
+ using namespace ov::npuw::s11n;
+
+ ov::element::Type var = ov::element::f16;
+ ov::element::Type res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_EQ(var, res);
+}
+
+TEST(SerializationTest, OVTypes_CacheMode) {
+ using namespace ov::npuw::s11n;
+
+ ov::CacheMode var = ov::CacheMode::OPTIMIZE_SPEED;
+ ov::CacheMode res = ov::CacheMode::OPTIMIZE_SIZE;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_EQ(var, res);
+}
+
+TEST(SerializationTest, OVTypes_PerformanceMode) {
+ using namespace ov::npuw::s11n;
+
+ ov::hint::PerformanceMode var = ov::hint::PerformanceMode::LATENCY;
+ ov::hint::PerformanceMode res = ov::hint::PerformanceMode::THROUGHPUT;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_EQ(var, res);
+}
+
+TEST(SerializationTest, OVTypes_Attention) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::compiled::Attention var;
+ var.query_size = 3;
+ var.context_size = 5;
+ var.params = {{1, 2}, {3, 4}};
+ var.mask_idx = 7;
+ var.attend_all = ov::Tensor(ov::element::f32, ov::Shape{1, 1, 3, 5});
+ std::vector<float> mask_data(var.attend_all.get_size());
+ std::iota(mask_data.begin(), mask_data.end(), -2.0f);
+ std::memcpy(var.attend_all.data(), mask_data.data(), var.attend_all.get_byte_size());
+
+ ov::npuw::compiled::Attention res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_attention_equal(var, res);
+}
+
+TEST(SerializationTest, OVTypes_PyramidAttention) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::compiled::PyramidAttention var;
+ var.query_size = 16;
+ var.full_context_size = 128;
+ var._context_lengths = {16, 32, 64, 128};
+ var._attention_infos = {{{{0, 2}, {1, 3}}, 4, 16, 32}, {{{2, 1}}, 5, 16, 64}};
+
+ ov::npuw::compiled::PyramidAttention res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_pyramid_attention_equal(var, res);
+}
+
+TEST(SerializationTest, OVTypes_HostFlashAttention) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::compiled::HostFlashAttention var;
+ var._sdpa_attention_info._query_size = 8;
+ var._sdpa_attention_info._context_size = 32;
+ var._sdpa_attention_info._k_seq_dim = 1;
+ var._sdpa_attention_info._v_seq_dim = 2;
+ var._sdpa_attention_info._sdpa_indices = {3, 4, 5, 6, 7, 8};
+ var._sdpa_attention_info._tile_input_indices = {9, 10, 11, 12, 13, 14, 15};
+ var._sdpa_attention_info._tile_output_indices = {16, 17, 18};
+ var._tile_size = 64;
+ var._can_use_tensor_view = true;
+
+ ov::npuw::compiled::HostFlashAttention res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_host_flash_attention_equal(var, res);
+}
+
+TEST(SerializationTest, OVTypes_MoEExperts) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::compiled::MoEExperts var;
+ var.num_experts = 16;
+ var.expert_hidden_dim = 128;
+ var.num_active_experts = 2;
+ var.input_token_count = 64;
+ var._router_scores_idx = 5;
+ var._expert_input_param_idx = 3;
+ var._param_mapping = {{0, {1, 2}}, {4, {6, 7, 8}}};
+
+ ov::npuw::compiled::MoEExperts res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_moe_experts_equal(var, res);
+}
+
+TEST(SerializationTest, OVTypes_MoEDownstream) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::compiled::MoEDownstream var;
+ var.total_experts_num = 16;
+ var.active_experts_num = 2;
+ var.expert_output_param_idx = 9;
+
+ ov::npuw::compiled::MoEDownstream res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_moe_downstream_equal(var, res);
+}
+
// "with_weights" is an option for read/write_weightless() when Constant in our model is not present in the original
// it reads/writes the whole ov::Tensor
TEST(SerializationTest, OVTypes_Tensor_with_weights) {
@@ -289,4 +626,307 @@ TEST(SerializationTest, OVTypes_Tensor_with_weights) {
EXPECT_EQ(data, data_res);
}
+TEST(SerializationTest, OVTypes_Tensor_empty) {
+ using namespace ov::npuw::s11n;
+
+ ov::Tensor var;
+ ov::Tensor res(ov::element::u8, ov::Shape{1});
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_FALSE(res);
+}
+
+TEST(SerializationTest, OVTypes_Tensor_non_contiguous) {
+ using namespace ov::npuw::s11n;
+
+ std::vector<float> storage{1.f, 2.f, 100.f, 3.f, 4.f, 200.f};
+ ov::Strides strides{3 * sizeof(float), sizeof(float)};
+ ov::Tensor var(ov::element::f32, ov::Shape{2, 2}, storage.data(), strides);
+ ASSERT_FALSE(var.is_continuous());
+
+ ov::Tensor res;
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ ASSERT_TRUE(res.is_continuous());
+ std::vector<float> expected_values{1.f, 2.f, 3.f, 4.f};
+ ov::Tensor expected(ov::element::f32, ov::Shape{2, 2}, expected_values.data());
+ expect_tensors_equal(expected, res);
+}
+
+TEST(SerializationTest, OVTypes_Tensor_allocator) {
+ using namespace ov::npuw::s11n;
+
+ ov::Tensor var(ov::element::i32, ov::Shape{2, 2});
+ std::vector<int32_t> values{1, 2, 3, 4};
+ std::memcpy(var.data(), values.data(), var.get_byte_size());
+
+ std::stringstream ss;
+ auto output_stream = Stream::writer(ss);
+ transfer_tensor(output_stream, var);
+
+ bool allocator_called = false;
+ ov::Tensor res;
+ auto input_stream = Stream::reader(ss);
+ transfer_tensor(input_stream,
+ res,
+ [&](const ov::element::Type& type, const ov::Shape& shape) {
+ allocator_called = true;
+ return ov::Tensor(type, shape);
+ });
+
+ EXPECT_TRUE(allocator_called);
+ expect_tensors_equal(var, res);
+}
+
+TEST(SerializationTest, OVTypes_Tensor_weightless_bf16_to_f16) {
+ using namespace ov::npuw::s11n;
+
+ std::vector<ov::float16> expected_values = {ov::float16(1.0f), ov::float16(-2.5f), ov::float16(3.25f)};
+ ov::Tensor var(ov::element::f16, ov::Shape{3}, expected_values.data());
+
+ std::stringstream ss;
+ WeightsContext export_ctx(true, {{var.data(), 0}});
+ write_weightless(ss, {var}, export_ctx);
+
+ std::filesystem::path file_path = ov::test::utils::generateTestFilePrefix() + "_npuw_bf16_weights.bin";
+ {
+ std::ofstream os(file_path, std::ios::binary);
+ std::vector<ov::bfloat16> bf16_values = {ov::bfloat16(1.0f), ov::bfloat16(-2.5f), ov::bfloat16(3.25f)};
+ os.write(reinterpret_cast<const char*>(bf16_values.data()),
+ static_cast<std::streamsize>(bf16_values.size() * sizeof(ov::bfloat16)));
+ }
+
+ std::vector<ov::Tensor> res;
+ {
+ auto mapped = ov::load_mmap_object(file_path);
+ ASSERT_NE(mapped, nullptr);
+ auto weights = std::make_shared<Weights>(reinterpret_cast<char*>(mapped->data()), mapped->size(), mapped);
+
+ WeightsContext import_ctx(weights, file_path.string(), {}, {{0, var.get_byte_size()}});
+ read_weightless(ss, res, import_ctx);
+ } // mapped + weights released here, file handle closed on Windows
+
+ ASSERT_EQ(res.size(), 1);
+ expect_tensors_equal(var, res.front());
+ std::filesystem::remove(file_path);
+}
+
+TEST(SerializationTest, OVTypes_OutputPort_roundtrips_into_parameter_pointer) {
+ using namespace ov::npuw::s11n;
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 3});
+ param->set_friendly_name("input");
+ param->output(0).get_tensor().set_names({"input", "alias"});
+
+ std::shared_ptr<ov::op::v0::Parameter> res;
+ std::stringstream ss;
+ ov::Output<const ov::Node> output = param->output(0);
+
+ write(ss, output);
+ read(ss, res);
+
+ ASSERT_NE(res, nullptr);
+ EXPECT_EQ(res->get_element_type(), param->get_element_type());
+ EXPECT_EQ(res->get_partial_shape(), param->get_partial_shape());
+ EXPECT_EQ(res->output(0).get_tensor().get_names(), param->output(0).get_tensor().get_names());
+}
+
+TEST(SerializationTest, OVTypes_OutputPort_roundtrips_into_node_pointer) {
+ using namespace ov::npuw::s11n;
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{2, 4});
+ param->set_friendly_name("node_input");
+ param->output(0).get_tensor().set_names({"node_input"});
+
+ std::shared_ptr<ov::Node> res;
+ std::stringstream ss;
+ ov::Output<const ov::Node> output = param->output(0);
+
+ write(ss, output);
+ read(ss, res);
+
+ ASSERT_NE(res, nullptr);
+ EXPECT_EQ(res->get_friendly_name(), "node_input");
+ EXPECT_EQ(res->output(0).get_tensor().get_names(), param->output(0).get_tensor().get_names());
+}
+
+TEST(SerializationTest, OVTypes_OutputPort_throws_on_read) {
+ using namespace ov::npuw::s11n;
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1});
+ std::stringstream ss;
+ ov::Output<const ov::Node> output = param->output(0);
+ write(ss, output);
+
+ EXPECT_THROW(read(ss, output), ov::Exception);
+}
+
+TEST(SerializationTest, OVTypes_ParameterPointer_throws_on_write) {
+ using namespace ov::npuw::s11n;
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1});
+ std::stringstream ss;
+
+ EXPECT_THROW(write(ss, param), ov::Exception);
+}
+
+TEST(SerializationTest, OVTypes_NodePointer_throws_on_write) {
+ using namespace ov::npuw::s11n;
+
+ std::shared_ptr<ov::Node> node =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1});
+ std::stringstream ss;
+
+ EXPECT_THROW(write(ss, node), ov::Exception);
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_uninitialized) {
+ using namespace ov::npuw::s11n;
+
+ ov::npuw::weights::LazyTensor var;
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ EXPECT_FALSE(var);
+ EXPECT_FALSE(res);
+ EXPECT_EQ(var, res);
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_const_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto constant = make_weightless_constant<float>(ov::element::f32, ov::Shape{2}, {1.0f, 2.0f}, 0);
+ ov::npuw::weights::LazyTensor var(constant);
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+ write(ss, var);
+ read(ss, res);
+ res.read_weight(WeightsContext(nullptr, "", make_consts_cache({constant}), {}));
+
+ expect_lazy_tensor_transform_types_equal(var, res);
+ EXPECT_EQ(var.eval_meta().shape, res.eval_meta().shape);
+ EXPECT_EQ(var.eval_meta().type, res.eval_meta().type);
+ expect_tensors_equal(var.eval(), res.eval());
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_const_with_embedded_weight_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto constant = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{2}, std::vector<float>{1.0f, 2.0f});
+ ov::npuw::weights::LazyTensor var(constant);
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+ write(ss, var);
+ read(ss, res);
+
+ expect_lazy_tensor_transform_types_equal(var, res);
+ EXPECT_EQ(var.eval_meta().shape, res.eval_meta().shape);
+ EXPECT_EQ(var.eval_meta().type, res.eval_meta().type);
+ expect_tensors_equal(var.eval(), res.eval());
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_concat_permute_convert_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto first = make_weightless_constant<float>(ov::element::f32, ov::Shape{1, 2}, {1.0f, 2.0f}, 0);
+ auto second = make_weightless_constant<float>(ov::element::f32, ov::Shape{1, 2}, {3.0f, 4.0f}, first->get_byte_size());
+ ov::npuw::weights::LazyTensor concat(std::vector<ov::npuw::weights::LazyTensor>{
+ ov::npuw::weights::LazyTensor(first),
+ ov::npuw::weights::LazyTensor(second)},
+ 0);
+ auto var = concat.permute({1, 0}).convert(ov::element::f16);
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+ write(ss, var);
+ read(ss, res);
+ res.read_weight(WeightsContext(nullptr, "", make_consts_cache({first, second}), {}));
+
+ expect_lazy_tensor_transform_types_equal(var, res);
+ EXPECT_EQ(var.get_hash(), res.get_hash());
+ EXPECT_EQ(var.eval_meta().shape, res.eval_meta().shape);
+ EXPECT_EQ(var.eval_meta().type, res.eval_meta().type);
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_unpack_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto w = make_weightless_constant<uint8_t>(ov::element::u8, ov::Shape{8}, {1, 2, 3, 4, 5, 6, 7, 8}, 0);
+ auto s = make_weightless_constant<ov::float16>(ov::element::f16, ov::Shape{8}, {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, w->get_byte_size());
+ ov::npuw::weights::LazyTensor var(ov::npuw::weights::LazyTensor(w),
+ ov::npuw::weights::LazyTensor(),
+ ov::npuw::weights::LazyTensor(s),
+ ov::element::f16,
+ ov::Shape{8});
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+ write(ss, var);
+ read(ss, res);
+ res.read_weight(WeightsContext(nullptr, "", make_consts_cache({w, s}), {}));
+
+ expect_lazy_tensor_transform_types_equal(var, res);
+ EXPECT_EQ(var.eval_meta().shape, res.eval_meta().shape);
+ EXPECT_EQ(var.eval_meta().type, res.eval_meta().type);
+}
+
+TEST(SerializationTest, OVTypes_LazyTensor_gather_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto w = make_weightless_constant<uint8_t>(ov::element::u8, ov::Shape{16}, {0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 14, 15},
+ 0);
+ std::vector<uint8_t> indices{0, 1, 2, 3};
+ ov::Tensor lut(ov::element::f8e4m3, ov::Shape{4}, indices.data());
+ ov::npuw::weights::LazyTensor var(ov::npuw::weights::LazyTensor(w), lut, ov::element::f16, ov::Shape{8});
+ ov::npuw::weights::LazyTensor res;
+
+ std::stringstream ss;
+ write(ss, var);
+ read(ss, res);
+ res.read_weight(WeightsContext(nullptr, "", make_consts_cache({w}), {}));
+
+ expect_lazy_tensor_transform_types_equal(var, res);
+ EXPECT_EQ(var.eval_meta().shape, res.eval_meta().shape);
+ EXPECT_EQ(var.eval_meta().type, res.eval_meta().type);
+}
+
+TEST(SerializationTest, OVTypes_WeightsBank_cpu_roundtrip) {
+ using namespace ov::npuw::s11n;
+
+ auto first = make_weightless_constant<float>(ov::element::f32, ov::Shape{2}, {1.0f, 2.0f}, 0);
+ auto second = make_weightless_constant<float>(ov::element::f32, ov::Shape{2}, {3.0f, 4.0f}, first->get_byte_size());
+
+ ov::npuw::weights::Bank var(nullptr, "CPU", "test-bank");
+ const auto uid0 = var.registerLT(ov::npuw::weights::LazyTensor(first), "CPU");
+ const auto uid0_dup = var.registerLT(ov::npuw::weights::LazyTensor(first), "CPU");
+ const auto uid1 = var.registerLT(ov::npuw::weights::LazyTensor(second), "CPU");
+ EXPECT_EQ(uid0, uid0_dup);
+ EXPECT_NE(uid0, uid1);
+
+ var.evaluate_and_allocate();
+
+ ov::npuw::weights::Bank res(nullptr, "CPU", "restored-bank");
+ std::stringstream ss;
+
+ write(ss, var);
+ read(ss, res);
+
+ expect_tensors_equal(var.get(uid0, "CPU"), res.get(uid0, "CPU"));
+ expect_tensors_equal(var.get(uid1, "CPU"), res.get(uid1, "CPU"));
+}
+
// TODO: add tests on CompiledModel and LLMCompiledModel once tests have access to any model to test on