Skip to content

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

NPUW: Start transitioning on the new serialization format (#35692)

Dmitry Matveev2ecadcad587f
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
index ce53df2652c..8b3272672d1 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc
@@ -32,6 +32,7 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_DCOFF_TYPE, std::string, "", ov::intel_npu::npuw:
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_DCOFF_SCALE, bool, false, ov::intel_npu::npuw::partitioning, dcoff_with_scale, "NPUW_DCOFF_SCALE", ROOT, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_FUNCALL_FOR_ALL, bool, false, ov::intel_npu::npuw::partitioning, funcall_for_all, "NPUW_FUNCALL_FOR_ALL", ROOT, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_PARALLEL_COMPILE, bool, false, ov::intel_npu::npuw, parallel_compilation, "NPUW_PARALLEL_COMPILE", ROOT, HIDDEN, UNCACHED, ALL)
+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_ENSURE_COMPATIBILITY, bool, false, ov::intel_npu::npuw, ensure_compatibility, "NPUW_ENSURE_COMPATIBILITY", ROOT, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_WEIGHTS_BANK, std::string, "", ov::intel_npu::npuw, weights_bank, "NPUW_WEIGHTS_BANK", ROOT, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_WEIGHTS_BANK_ALLOC, std::string, "", ov::intel_npu::npuw, weights_bank_alloc, "NPUW_WEIGHTS_BANK_ALLOC", ROOT, EXPOSED, CACHED, ALL)
INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_CACHE_DIR, std::string, "", ov::intel_npu::npuw, cache_dir, "NPUW_CACHE_DIR", ROOT, HIDDEN, UNCACHED, ALL)
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp
index e5c0824a328..111f2f0080a 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp
@@ -16,8 +16,11 @@ struct Attention;
struct PyramidAttention;
struct HostFlashAttention;
} // namespace compiled
-namespace s11n {
+namespace orc {
class Stream;
+}
+namespace s11n {
+using Stream = ::ov::npuw::orc::Stream;
struct SubmodelDeserializeCtx;
} // namespace s11n
namespace attn {
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 51b4e039e74..cde62397084 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -4,6 +4,7 @@
#include "compiled_model.hpp"
#include <algorithm>
+#include <cstring>
#include <memory>
#include <set>
#include <string>
@@ -35,7 +36,9 @@
#include "intel_npu/config/npuw.hpp"
#include "intel_npu/npuw_private_properties.hpp"
#include "llm_compiled_model.hpp"
+#include "openvino/core/descriptor/tensor.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
+#include "openvino/op/result.hpp"
#include "openvino/runtime/device_id_parser.hpp"
#include "openvino/runtime/internal_properties.hpp"
#include "openvino/runtime/properties.hpp"
@@ -48,6 +51,8 @@ std::string canonical_device_name(const std::string& device_name) {
return dot_pos == std::string::npos ? device_name : device_name.substr(0, dot_pos);
}
+void pre_load_transform(const std::shared_ptr<ov::Model>& model, const ov::AnyMap& props);
+
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) {
@@ -104,6 +109,88 @@ bool should_use_weightless_flow(const ov::AnyMap& non_npuw_props,
return is_weightless;
}
+ov::npuw::s11n::WeightsContext make_import_weights_ctx(const ov::AnyMap& properties,
+ bool is_weightless,
+ const ov::npuw::s11n::BF16Cache& bf16_consts) {
+ using namespace ov::npuw::s11n;
+
+ std::string weights_path;
+ WeightsContext::ConstsCache consts_cache;
+ ov::FileHandleProvider handle_provider = nullptr;
+ if (is_weightless) {
+ if (const auto handle_it = properties.find(ov::intel_npu::npuw::weights_handle_provider.name());
+ handle_it != properties.end()) {
+ if (handle_it->second.is<ov::FileHandleProvider>()) {
+ handle_provider = handle_it->second.as<ov::FileHandleProvider>();
+ } else {
+ LOG_WARN("WEIGHTS_HANDLE_PROVIDER property is present but is not a FileHandleProvider; falling back to "
+ "other weightless import sources");
+ }
+ }
+ if (!handle_provider && properties.find(ov::weights_path.name()) != properties.end()) {
+ weights_path = properties.at(ov::weights_path.name()).as<std::string>();
+ NPUW_ASSERT(!weights_path.empty() &&
+ "Empty weights_path. Please provide WEIGHTS_PATH or MODEL_PTR in the configuration.");
+ } else if (!handle_provider && properties.find(ov::hint::model.name()) != properties.end()) {
+ auto model_ptr = std::const_pointer_cast<ov::Model>(
+ properties.at(ov::hint::model.name()).as<std::shared_ptr<const ov::Model>>())
+ ->clone();
+ NPUW_ASSERT(
+ model_ptr &&
+ "Empty model passed in MODEL_PTR. Please provide WEIGHTS_PATH or MODEL_PTR in the configuration.");
+ pre_load_transform(model_ptr, {});
+ for (const auto& node : model_ptr->get_ordered_ops()) {
+ if (!ov::op::util::is_constant(node)) {
+ continue;
+ }
+ const auto& c = std::static_pointer_cast<ov::op::v0::Constant>(node);
+ auto rt_info = c->get_rt_info();
+ auto weightless_cache_attr = rt_info.find(ov::WeightlessCacheAttribute::get_type_info_static());
+ if (weightless_cache_attr == rt_info.end()) {
+ continue;
+ }
+ std::size_t offset = weightless_cache_attr->second.as<ov::WeightlessCacheAttribute>().bin_offset;
+ std::size_t size = c->get_byte_size();
+ consts_cache[{offset, size}] = node;
+ }
+ } else if (!handle_provider) {
+ NPUW_ASSERT(false && "Blob is weightless but no WEIGHTS_PATH nor MODEL_PTR property is provided!");
+ }
+ }
+
+ WeightsPtr weights = nullptr;
+ if (is_weightless) {
+ std::shared_ptr<ov::MappedMemory> mapped_memory;
+ if (handle_provider) {
+ ov::FileHandle handle = handle_provider();
+ mapped_memory = ov::load_mmap_object(handle);
+ } else if (!weights_path.empty()) {
+ mapped_memory = ov::load_mmap_object(ov::util::make_path(weights_path));
+ }
+ if (mapped_memory) {
+ weights = std::make_shared<Weights>(mapped_memory->data(), mapped_memory->size(), mapped_memory);
+ }
+ }
+
+ return WeightsContext(weights, weights_path, consts_cache, bf16_consts, handle_provider);
+}
+
+std::function<std::string(const std::string&)> get_encrypt_callback(const ov::AnyMap& properties) {
+ if (auto it = properties.find(ov::cache_encryption_callbacks.name()); it != properties.end()) {
+ return it->second.as<ov::EncryptionCallbacks>().encrypt;
+ }
+ return {};
+}
+
+std::function<std::string(const std::string&)> get_decrypt_callback_or_throw(const ov::AnyMap& properties) {
+ if (auto it = properties.find(ov::cache_encryption_callbacks.name()); it != properties.end()) {
+ if (const auto decrypt = it->second.as<ov::EncryptionCallbacks>().decrypt) {
+ return decrypt;
+ }
+ }
+ OPENVINO_THROW("Blob is encrypted, but no decryption callback was provided");
+}
+
std::set<std::string> device_list_to_set(const std::string& device_list) {
std::set<std::string> result;
if (!device_list.empty()) {
@@ -120,6 +207,14 @@ namespace ov {
namespace npuw {
namespace {
+ov::AnyMap make_submodel_import_config(const std::string& device, const ::intel_npu::Config& cfg) {
+ ov::AnyMap import_config;
+ if (ov::npuw::util::starts_with(device, "NPU") && cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>()) {
+ import_config["NPU_RUN_INFERENCES_SEQUENTIALLY"] = "YES";
+ }
+ return import_config;
+}
+
ov::npuw::DeviceProperties get_properties_per_device(const std::shared_ptr<const ov::IPlugin>& plugin,
const std::string& device_priorities,
const ov::AnyMap& properties) {
@@ -745,6 +840,7 @@ bool ov::npuw::CompiledModel::should_use_quantized_host_gather(const std::shared
void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Stream& stream,
const ov::npuw::s11n::WeightsContext& ctx,
+ std::optional<std::size_t> orc_device_index,
const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx) {
using namespace ov::npuw::s11n;
@@ -755,6 +851,40 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Strea
}
LOG_BLOCK();
+ ov::SoPtr<ov::ICompiledModel> imported_compiled_model;
+ std::optional<ov::npuw::s11n::SubmodelDeserializeCtx> resolved_submodel_ctx;
+ if (orc_device_index.has_value() || (stream.input() && submodel_ctx != nullptr && submodel_ctx->device_by_index)) {
+ std::size_t device_index = orc_device_index.value_or(0u);
+ stream & device_index;
+
+ bool has_compiled_model = static_cast<bool>(compiled_model);
+ stream & has_compiled_model;
+
+ if (stream.output()) {
+ if (has_compiled_model) {
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ compiled_model->export_model(buffer);
+ auto model_blob = buffer.str();
+ stream & model_blob;
+ }
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr && "Submodel deserialization context must be provided for ORC import");
+ NPUW_ASSERT(submodel_ctx->device_by_index &&
+ "Submodel deserialization context must provide device_by_index for ORC import");
+ const auto device = submodel_ctx->device_by_index(device_index);
+ const auto import_config = submodel_ctx->import_config_for_device(device);
+ if (has_compiled_model) {
+ std::string model_blob;
+ stream & model_blob;
+ std::stringstream buffer(model_blob, std::ios::in | std::ios::out | std::ios::binary);
+ imported_compiled_model = submodel_ctx->plugin->get_core()->import_model(buffer, device, import_config);
+ }
+ compiled_model = imported_compiled_model;
+ resolved_submodel_ctx.emplace(submodel_ctx->plugin, device, compiled_model, import_config);
+ submodel_ctx = &(*resolved_submodel_ctx);
+ }
+ }
+
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;
@@ -856,273 +986,290 @@ ov::npuw::CompiledModel::~CompiledModel() {
}
void ov::npuw::CompiledModel::export_model(std::ostream& raw_stream) const {
- using namespace ov::npuw::s11n;
+ serialize_orc(raw_stream);
+}
- // Identify encryption flow
- bool encryption_required = false;
- EncryptionCallbacks enc_callbacks;
- if (auto it = m_non_npuw_props.find(ov::cache_encryption_callbacks.name());
- it != m_non_npuw_props.end() && it->second.as<EncryptionCallbacks>().encrypt) {
- LOG_INFO("Encryption will be done via the function provided.");
- encryption_required = true;
- enc_callbacks.encrypt = it->second.as<EncryptionCallbacks>().encrypt;
+std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::import_model(
+ std::istream& stream,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ const ov::AnyMap& properties) {
+ if (!ov::npuw::orc::is_orc(stream).has_value()) {
+ OPENVINO_THROW("Legacy flat NPUW CompiledModel blobs are no longer supported. Re-export the model with the "
+ "current OpenVINO package.");
}
+ return deserialize_orc(stream, plugin, properties);
+}
- // Identify either full flow or weightless
- bool is_weightless = should_use_weightless_flow(m_non_npuw_props, m_cfg, m_const_to_offset);
- if (!is_weightless) {
- LOG_INFO("Serialization will be done via flow with weights.");
- }
-
- // Write header regardless of encryption requirement - to identify NPUW serializated blobs
- // Serialize magic number first
- write(raw_stream, NPUW_SERIALIZATION_INDICATOR);
- // Serilize CompiledModel identifier
- write(raw_stream, NPUW_COMPILED_MODEL_INDICATOR);
- // Serialize general meta info
- 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(raw_stream, encryption_required);
- // Write flow identifier
- write(raw_stream, is_weightless);
-
- if (!encryption_required) {
- CompiledContext ctx(false, nullptr, nullptr, m_bf16_consts);
- serialize(raw_stream, ctx);
-
- auto stream = Stream::writer(raw_stream);
- auto bank_name = m_weights_bank->get_name();
- stream & bank_name;
- if (!is_weightless) {
- ov::npuw::s11n::serialize(stream, *m_weights_bank);
+void ov::npuw::CompiledModel::ensure_phase0_compatibility() const {
+ for (std::size_t idx = 0; idx < m_compiled_submodels.size(); ++idx) {
+ const auto& subm = m_compiled_submodels[idx];
+ const auto name = format_subgraph_name(idx, "");
+ const auto real_idx = subm.replaced_by.value_or(idx);
+ const auto device = submodel_device(real_idx);
+ auto fail = [&](const auto& feature) {
+ OPENVINO_THROW("Cannot produce ORC-compatible blob: subgraph ",
+ idx,
+ " (\"",
+ name,
+ "\") has ",
+ feature,
+ " - not yet versioned for NPUW phase 0. Recompile without NPUW_ENSURE_COMPATIBILITY or wait "
+ "for a later phase.");
+ };
+
+ if (!ov::npuw::util::starts_with(device, "NPU")) {
+ fail(std::string("device \"") + device + "\"");
+ }
+ if (subm.spatial.has_value()) {
+ fail("Spatial");
+ }
+ if (ov::npuw::attn::get_compiled_dynamic(subm.pipeline.context) != nullptr) {
+ fail("Attention");
+ }
+ if (ov::npuw::attn::get_compiled_pyramid(subm.pipeline.context) != nullptr) {
+ fail("PyramidAttention");
+ }
+ if (ov::npuw::attn::get_compiled_hfa(subm.pipeline.context) != nullptr) {
+ fail("HostFlashAttention");
+ }
+ if (ov::npuw::moe::get_compiled_experts(subm.pipeline.context) != nullptr) {
+ fail("MoEExperts");
+ }
+ if (ov::npuw::moe::get_compiled_downstream(subm.pipeline.context) != nullptr) {
+ fail("MoEDownstream");
+ }
+ if (subm.pipeline.runtime_behavior.has_value()) {
+ fail("runtime behavior");
}
- return;
}
+}
- // 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(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(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(raw_stream, ctx);
- }
+void ov::npuw::CompiledModel::serialize_orc(std::ostream& stream) const {
+ ov::npuw::orc::write_file_header(stream, ov::npuw::orc::schema_npuw::NPUW_ORC_PARTITIONED_SCHEMA);
+ serialize_orc_container(stream, true, get_encrypt_callback(m_non_npuw_props));
+}
+
+void ov::npuw::CompiledModel::serialize_orc_container(
+ std::ostream& stream,
+ bool include_weights_bank,
+ const std::function<std::string(const std::string&)>& encrypt) const {
+ using namespace ov::npuw;
- auto stream = Stream::writer(raw_stream);
- auto bank_name = m_weights_bank->get_name();
- stream & bank_name;
- if (!is_weightless) {
- ov::npuw::s11n::serialize(stream, *m_weights_bank);
+ if (m_cfg.get<::intel_npu::NPUW_ENSURE_COMPATIBILITY>()) {
+ if (encrypt) {
+ OPENVINO_THROW("Cannot produce ORC-compatible blob: encrypted export is not yet supported in "
+ "NPUW_ENSURE_COMPATIBILITY mode");
+ }
+ ensure_phase0_compatibility();
}
+
+ bool is_weightless = should_use_weightless_flow(m_non_npuw_props, m_cfg, m_const_to_offset);
+ LOG_INFO("Serialization will be done via " << (is_weightless ? "weightless" : "flow with weights") << ".");
+
+ ov::AnyMap serializable_props = m_non_npuw_props;
+ serializable_props.erase(ov::cache_encryption_callbacks.name());
+ s11n::WeightsContext weights_ctx(is_weightless, m_const_to_offset);
+
+ auto write_children = [&](std::ostream& body_stream) {
+ for (std::size_t idx = 0; idx < m_compiled_submodels.size(); ++idx) {
+ auto& subm = const_cast<CompiledModelDesc&>(m_compiled_submodels[idx]);
+ const auto real_idx = subm.replaced_by.value_or(idx);
+ const auto device_index = real_idx == idx ? find_device_index(m_dev_list, submodel_device(real_idx)) : 0u;
+ ov::npuw::orc::with_leaf_section(body_stream,
+ CompiledModelDesc::kOrcType,
+ CompiledModelDesc::kOrcVersion,
+ [&] {
+ auto desc_stream = ov::npuw::s11n::Stream::writer(body_stream);
+ subm.serialize(desc_stream, weights_ctx, device_index);
+ });
+ }
+
+ if (include_weights_bank) {
+ ov::npuw::orc::with_leaf_section(body_stream, weights::Bank::kOrcType, weights::Bank::kOrcVersion, [&] {
+ auto weights_stream = ov::npuw::s11n::Stream::writer(body_stream);
+ auto bank_name = m_weights_bank->get_name();
+ weights_stream & bank_name;
+ if (!is_weightless) {
+ weights_stream&* m_weights_bank;
+ }
+ });
+ }
+ };
+
+ const auto root_flags =
+ encrypt ? static_cast<ov::npuw::orc::SectionFlags>(ov::npuw::orc::SectionFlag::ENCRYPTED) : 0u;
+ ov::npuw::orc::with_section(stream, kOrcType, kOrcVersion, root_flags, [&] {
+ auto meta_stream = ov::npuw::s11n::Stream::writer(stream);
+ meta_stream & m_name;
+ meta_stream& inputs() & outputs();
+ meta_stream & m_inputs_to_submodels_inputs & m_outputs_to_submodels_outputs & m_param_subscribers &
+ m_submodels_input_to_prev_output;
+ meta_stream & m_dev_list;
+ meta_stream& const_cast<::intel_npu::Config&>(m_cfg);
+ meta_stream & serializable_props;
+ meta_stream & is_weightless;
+ meta_stream& const_cast<ov::npuw::s11n::BF16Cache&>(m_bf16_consts);
+ if (encrypt) {
+ std::stringstream payload_stream(std::ios::in | std::ios::out | std::ios::binary);
+ write_children(payload_stream);
+ auto encrypted_payload = encrypt(payload_stream.str());
+ meta_stream & encrypted_payload;
+ } else {
+ write_children(stream);
+ }
+ });
}
-std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::import_model(
+std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize_orc(
std::istream& stream,
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties) {
- LOG_INFO("Deserializing CompiledModel...");
- LOG_BLOCK();
+ const auto header = ov::npuw::orc::read_file_header(stream);
+ if (header.schema_uuid != ov::npuw::orc::schema_npuw::NPUW_ORC_PARTITIONED_SCHEMA) {
+ OPENVINO_THROW("Unsupported ORC schema for NPUW CompiledModel");
+ }
+ return deserialize_orc_container(stream, plugin, properties, true, {});
+}
- using namespace ov::npuw::s11n;
+std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize_orc_container(
+ std::istream& stream,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ const ov::AnyMap& properties,
+ bool require_weights_bank,
+ const std::function<std::string(const std::string&)>& decrypt) {
+ ov::npuw::orc::ScopedReadSection root(stream);
+ if (root.header().type != kOrcType || root.header().version > kOrcVersion ||
+ ov::npuw::orc::has_flag(root.header().flags, ov::npuw::orc::SectionFlag::LEAF)) {
+ OPENVINO_THROW("Unsupported ORC NPUW root section");
+ }
+
+ auto meta_stream = ov::npuw::s11n::Stream::reader(stream);
+
+ std::string model_name;
+ ov::ParameterVector parameters;
+ ov::NodeVector results;
+ bool is_weightless = false;
+ meta_stream & model_name & 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::CompiledModel>(ov_model, plugin, true);
+ compiled->m_name = std::move(model_name);
+ meta_stream & compiled->m_inputs_to_submodels_inputs & compiled->m_outputs_to_submodels_outputs &
+ compiled->m_param_subscribers & compiled->m_submodels_input_to_prev_output;
+ meta_stream & compiled->m_dev_list;
+ meta_stream & compiled->m_cfg;
+ compiled->m_cfg.parseEnvVars();
+ meta_stream & compiled->m_non_npuw_props;
+ meta_stream & is_weightless;
+ meta_stream & compiled->m_bf16_consts;
+ compiled->m_import_weights_ctx = make_import_weights_ctx(properties, is_weightless, compiled->m_bf16_consts);
+
+ const bool encrypted = ov::npuw::orc::has_flag(root.header().flags, ov::npuw::orc::SectionFlag::ENCRYPTED);
+ bool have_weights = false;
+ auto peek_child_header = [](std::istream& child_source) {
+ const auto saved = child_source.tellg();
+ auto peek_stream = ov::npuw::s11n::Stream::reader(child_source);
+ ov::npuw::orc::SectionHeader header;
+ peek_stream & header;
+ child_source.seekg(saved);
+ return header;
+ };
+ auto consume_submodel = [&](std::istream& child_source) {
+ ov::npuw::orc::ScopedReadSection child(child_source);
+ if (child.header().type != CompiledModelDesc::kOrcType) {
+ OPENVINO_THROW("Unexpected ORC child type ID ", child.header().type, " in NPUW CompiledModel container");
+ }
+ if (child.header().version != CompiledModelDesc::kOrcVersion) {
+ OPENVINO_THROW("Unsupported ORC NPUW subgraph version ", child.header().version);
+ }
+
+ compiled->m_compiled_submodels.emplace_back();
+ auto& submodel = compiled->m_compiled_submodels.back();
+ auto child_stream = ov::npuw::s11n::Stream::reader(child_source);
+ ov::npuw::s11n::SubmodelDeserializeCtx submodel_ctx(
+ plugin,
+ submodel.compiled_model,
+ [&](std::size_t device_index) {
+ return compiled->m_dev_list.at(device_index);
+ },
+ [&](const std::string& device) {
+ return make_submodel_import_config(device, compiled->m_cfg);
+ });
+ submodel.serialize(child_stream, compiled->m_import_weights_ctx, std::nullopt, &submodel_ctx);
+ child.expect_end();
+ };
- // Sanity check magic number
- ov::npuw::s11n::IndicatorType serialization_indicator;
- read(stream, serialization_indicator);
- NPUW_ASSERT(serialization_indicator == NPUW_SERIALIZATION_INDICATOR && "This blob wasn't serialized via NPUW!");
-
- ov::npuw::s11n::IndicatorType compiled_indicator;
- read(stream, compiled_indicator);
- NPUW_ASSERT(compiled_indicator == NPUW_COMPILED_MODEL_INDICATOR &&
- "This blob wasn't serialized via CompiledModel!");
-
- // Deserialize general meta info
- int vmajor, vminor, vpatch;
- std::string s11n_version;
- read(stream, vmajor);
- read(stream, vminor);
- read(stream, vpatch);
- read(stream, s11n_version);
-
- if (vmajor != OPENVINO_VERSION_MAJOR || vminor != OPENVINO_VERSION_MINOR || vpatch != OPENVINO_VERSION_PATCH ||
- s11n_version != std::string(NPUW_SERIALIZATION_VERSION)) {
- OPENVINO_THROW("This blobs was serialized with different OV version!",
- "\nSerialized by OV ",
- vmajor,
- '.',
- vminor,
- '.',
- vpatch,
- "\nCurrent OV version ",
- OPENVINO_VERSION_MAJOR,
- '.',
- OPENVINO_VERSION_MINOR,
- '.',
- OPENVINO_VERSION_PATCH,
- "\nNPUW serialized by version ",
- s11n_version,
- "\nNPUW current serialization version ",
- NPUW_SERIALIZATION_VERSION);
- }
-
- bool encrypted = false;
- read(stream, encrypted);
- bool is_weightless = true;
- read(stream, is_weightless);
+ auto consume_weights_bank = [&](std::istream& child_source) {
+ ov::npuw::orc::ScopedReadSection child(child_source);
+ if (child.header().type != weights::Bank::kOrcType) {
+ OPENVINO_THROW("Unexpected ORC child type ID ", child.header().type, " in NPUW CompiledModel container");
+ }
+ if (child.header().version != weights::Bank::kOrcVersion) {
+ OPENVINO_THROW("Unsupported ORC NPUW weights version ", child.header().version);
+ }
- auto read_and_finalize_bank = [&](std::istream& model_stream,
- const std::shared_ptr<ov::npuw::CompiledModel>& compiled) {
- auto stream = Stream::reader(model_stream);
+ auto child_stream = ov::npuw::s11n::Stream::reader(child_source);
std::string bank_name;
- stream & bank_name;
-
+ child_stream & bank_name;
+ compiled->m_weights_bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
if (is_weightless) {
- compiled->m_weights_bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
+ child.expect_end();
compiled->finalize_weights_bank();
} else {
- compiled->m_weights_bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
- ov::npuw::s11n::serialize(stream, *compiled->m_weights_bank);
+ child_stream& * compiled->m_weights_bank;
+ child.expect_end();
compiled->reconstruct_closure();
}
+ have_weights = true;
};
- if (!encrypted) {
- CompiledContext ctx(false, nullptr, nullptr);
- auto compiled_model = ov::npuw::CompiledModel::deserialize(stream, plugin, properties, ctx);
- NPUW_ASSERT(compiled_model && "Couldn't import NPUW compiled model!");
- read_and_finalize_bank(stream, compiled_model);
- LOG_INFO("Done.");
- return compiled_model;
- }
-
- EncryptionCallbacks enc_callbacks;
- NPUW_ASSERT(properties.count(ov::cache_encryption_callbacks.name()) &&
- properties.at(ov::cache_encryption_callbacks.name()).as<EncryptionCallbacks>().decrypt &&
- "Model is encrypted but no decrypt function was provided!");
- enc_callbacks.decrypt = properties.at(ov::cache_encryption_callbacks.name()).as<EncryptionCallbacks>().decrypt;
-
- LOG_INFO("Decryption will be done via the function provided.");
-
- std::shared_ptr<ov::npuw::CompiledModel> compiled_model = nullptr;
+ if (encrypted) {
+ std::string encrypted_payload;
+ meta_stream & encrypted_payload;
+ root.expect_end();
- // Model is encrypted
- if (is_weightless) {
- std::string encrypted_str;
- read(stream, encrypted_str);
- std::istringstream decrypted_stream(std::move(enc_callbacks.decrypt(encrypted_str)));
- CompiledContext ctx(false, nullptr, nullptr);
- compiled_model = ov::npuw::CompiledModel::deserialize(decrypted_stream, plugin, properties, ctx);
+ const auto decrypt_fn = decrypt ? decrypt : get_decrypt_callback_or_throw(properties);
+ std::istringstream decrypted_stream(std::move(decrypt_fn(encrypted_payload)));
+ while (decrypted_stream.peek() != std::char_traits<char>::eof() &&
+ peek_child_header(decrypted_stream).type == CompiledModelDesc::kOrcType) {
+ consume_submodel(decrypted_stream);
+ }
+ if (require_weights_bank) {
+ if (decrypted_stream.peek() == std::char_traits<char>::eof()) {
+ OPENVINO_THROW("Missing ORC weights bank container");
+ }
+ consume_weights_bank(decrypted_stream);
+ }
} else {
- CompiledContext ctx(true, nullptr, enc_callbacks.decrypt);
- compiled_model = ov::npuw::CompiledModel::deserialize(stream, plugin, properties, ctx);
+ while (!root.done() && peek_child_header(stream).type == CompiledModelDesc::kOrcType) {
+ consume_submodel(stream);
+ }
+ if (require_weights_bank) {
+ if (root.done()) {
+ OPENVINO_THROW("Missing ORC weights bank container");
+ }
+ consume_weights_bank(stream);
+ } else if (!root.done()) {
+ OPENVINO_THROW("Unexpected ORC child after CompiledModelDesc containers");
+ }
+ root.expect_end();
}
- NPUW_ASSERT(compiled_model && "Couldn't import NPUW compiled model!");
- read_and_finalize_bank(stream, compiled_model);
+ if (require_weights_bank && !have_weights) {
+ OPENVINO_THROW("Missing ORC weights bank container");
+ }
- LOG_INFO("Done.");
- return compiled_model;
+ compiled->implement_properties();
+ return compiled;
}
void ov::npuw::CompiledModel::serialize(std::ostream& stream, const ov::npuw::s11n::CompiledContext& enc_ctx) const {
- LOG_INFO("Serializing CompiledModel...");
- LOG_BLOCK();
-
- using namespace ov::npuw::s11n;
-
- auto write_model = [&](std::ostream& model_stream) {
- auto stream = Stream::writer(model_stream);
- // Serialize name
- stream & m_name;
-
- // Serialize inputs and outputs
- stream& inputs() & outputs();
-
- // Serialize meta
- stream & m_inputs_to_submodels_inputs & m_outputs_to_submodels_outputs & m_param_subscribers &
- m_submodels_input_to_prev_output;
-
- // Write device list
- stream & m_dev_list;
-
- // Write config
- stream & m_cfg;
- // FIXME: utilize overload instead
- 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()) {
- bool should_write = false;
- stream & should_write;
- continue;
- }
- 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);
- stream & is_weightless;
-
- // Write bf16 consts cache
- stream & enc_ctx.bf16_consts;
-
- // Create weightless context
- WeightsContext ctx(is_weightless, m_const_to_offset);
-
- // Serialize compiled submodels
- auto submodel_count = m_compiled_submodels.size();
- stream & submodel_count;
- for (std::size_t i = 0; i < m_compiled_submodels.size(); ++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 = [&]() {
- return find_device_index(m_dev_list, submodel_device(real_idx));
- };
- auto device_index = real_idx == i ? dev_idx() : 0;
- stream & device_index;
- // Write ICompiledModel if it's there
- if (subm.compiled_model) {
- 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);
- auto exported_model = ss.str();
- stream & exported_model;
- } else {
- bool has_compiled_model = false;
- stream & has_compiled_model;
- }
- // Write the rest of the submodel desc
- subm.serialize(stream, ctx);
- }
- };
-
- std::stringstream non_encrypted_stream;
if (enc_ctx.encrypted) {
NPUW_ASSERT(enc_ctx.encrypt && "Encryption function isn't provided!");
- non_encrypted_stream.copyfmt(stream);
- write_model(non_encrypted_stream);
- std::string encrypted_str = enc_ctx.encrypt(non_encrypted_stream.str());
- write(stream, encrypted_str);
- } else {
- write_model(stream);
}
-
- LOG_INFO("Done.");
+ serialize_orc_container(stream,
+ false,
+ enc_ctx.encrypted ? enc_ctx.encrypt : std::function<std::string(const std::string&)>{});
}
std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
@@ -1130,196 +1277,15 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties,
const ov::npuw::s11n::CompiledContext& enc_ctx) {
- LOG_INFO("Deserializing CompiledModel...");
- LOG_BLOCK();
-
- 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;
- 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;
-
- 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::CompiledModel>(ov_model, plugin, true);
-
- // Deserialize meta
- compiled->m_name = model_name;
- 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
- stream & compiled->m_dev_list;
-
- // Deserialize config
- stream & compiled->m_cfg;
- compiled->m_cfg.parseEnvVars();
- // FIXME: utilize overload instead
- std::size_t props_size;
- stream & props_size;
- for (std::size_t i = 0; i < props_size; ++i) {
- bool should_read = true;
- 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;
- stream & key;
- ov::Any 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;
- stream & is_weightless;
-
- // Read bf16 consts cache
- stream & compiled->m_bf16_consts;
-
- // Initialize weights stream if weightless flow
- std::string weights_path;
- std::shared_ptr<ov::Model> model_ptr;
- // Cache model's constants
- WeightsContext::ConstsCache consts_cache;
- ov::FileHandleProvider handle_provider = nullptr;
- if (is_weightless) {
- // Check if weights_handle_provider function is provided
- if (const auto handle_it = properties.find(ov::intel_npu::npuw::weights_handle_provider.name());
- handle_it != properties.end()) {
- if (handle_it->second.is<ov::FileHandleProvider>()) {
- handle_provider = handle_it->second.as<ov::FileHandleProvider>();
- }
- } else if (properties.find(ov::weights_path.name()) != properties.end()) {
- weights_path = properties.at(ov::weights_path.name()).as<std::string>();
- NPUW_ASSERT(!weights_path.empty() &&
- "Empty weights_path. Please provide WEIGHTS_PATH or MODEL_PTR in the configuration.");
- } else if (properties.find(ov::hint::model.name()) != properties.end()) {
- model_ptr = std::const_pointer_cast<ov::Model>(
- properties.at(ov::hint::model.name()).as<std::shared_ptr<const ov::Model>>())
- ->clone();
- NPUW_ASSERT(
- model_ptr &&
- "Empty model passed in MODEL_PTR. Please provide WEIGHTS_PATH or MODEL_PTR in the configuration.");
- // NOTE: very important to do preprocessing here since MODEL_PTR contains the original model
- // without any plugin preprocessing. Due to some passes (e.g. bf16_to_f16) we might get
- // modified weights and thus mismatch during weights read.
- // FIXME: consider adding a config it will influence weight modification in the future
- pre_load_transform(model_ptr, {});
- // Fill the cache
- for (const auto& node : model_ptr->get_ordered_ops()) {
- if (ov::op::util::is_constant(node)) {
- const auto& c = std::static_pointer_cast<ov::op::v0::Constant>(node);
- auto rt_info = c->get_rt_info();
- auto weightless_cache_attr = rt_info.find(ov::WeightlessCacheAttribute::get_type_info_static());
- if (weightless_cache_attr == rt_info.end()) {
- continue;
- }
- std::size_t offset =
- weightless_cache_attr->second.as<ov::WeightlessCacheAttribute>().bin_offset;
- std::size_t size = c->get_byte_size();
- consts_cache[{offset, size}] = node;
- }
- }
- } else {
- NPUW_ASSERT(false && "Blob is weightless but no WEIGHTS_PATH nor MODEL_PTR property is provided!");
- }
- }
-
- ov::npuw::s11n::WeightsPtr weights = nullptr;
- if (is_weightless) {
- std::shared_ptr<ov::MappedMemory> mapped_memory;
- // Use handle_provider if available, otherwise use default mmap with weights_path
- if (handle_provider) {
- ov::FileHandle handle = handle_provider();
- mapped_memory = ov::load_mmap_object(handle);
- } else if (!weights_path.empty()) {
- mapped_memory = ov::load_mmap_object(ov::util::make_path(weights_path));
- }
- if (mapped_memory) {
- weights = std::make_shared<ov::npuw::s11n::Weights>(mapped_memory->data(),
- mapped_memory->size(),
- mapped_memory);
- }
- }
-
- // FIXME: prolong lifetime of ov::Model for import with MODEL_PTR.
- // Unclear why it's needed, but without saving consts_cache until bank evaluation,
- // the memory is freed somewhere.
- compiled->m_import_weights_ctx =
- WeightsContext(weights, weights_path, consts_cache, compiled->m_bf16_consts, handle_provider);
-
- // Deserialize compiled submodels
- std::size_t subm_size = 0;
- 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;
- stream & device_idx;
-
- bool has_compiled_model = false;
- stream & has_compiled_model;
-
- // Build import config for NPU device
- ov::AnyMap import_config;
- const auto& device = compiled->m_dev_list[device_idx];
- if (ov::npuw::util::starts_with(device, "NPU")) {
- // Pass NPU_RUN_INFERENCES_SEQUENTIALLY if NPUW_UNFOLD_IREQS is enabled
- if (compiled->m_cfg.get<::intel_npu::NPUW_UNFOLD_IREQS>()) {
- import_config["NPU_RUN_INFERENCES_SEQUENTIALLY"] = "YES";
- }
- }
-
- if (has_compiled_model) {
- // Import model from the plugin
- // FIXME: workaround for import/export model since import model seems to reset the file pointer
- std::string buf;
- stream & buf;
- std::stringstream buffer(buf);
- compiled->m_compiled_submodels[i].compiled_model =
- plugin->get_core()->import_model(buffer, device, import_config);
- }
-
- // Create unified deserialization context for submodels with dynamic mechanisms
- // (Pyramid Attention, Host Flash Attention, etc.)
- ov::npuw::s11n::SubmodelDeserializeCtx submodel_ctx(plugin,
- device,
- compiled->m_compiled_submodels[i].compiled_model,
- import_config);
- compiled->m_compiled_submodels[i].serialize(stream, compiled->m_import_weights_ctx, &submodel_ctx);
- }
-
- compiled->implement_properties();
- compiled->report_io();
- LOG_INFO("Done.");
- return compiled;
- };
-
- std::shared_ptr<ov::npuw::CompiledModel> compiled = nullptr;
if (enc_ctx.encrypted) {
- std::string encrypted_string;
- read(stream, encrypted_string);
- std::istringstream decrypted_stream(std::move(enc_ctx.decrypt(encrypted_string)));
- compiled = read_model(decrypted_stream);
- } else {
- compiled = read_model(stream);
- }
-
- NPUW_ASSERT(compiled && "Couldn't create NPUW compiled model!");
-
- return compiled;
+ NPUW_ASSERT(enc_ctx.decrypt && "Decryption function isn't provided!");
+ }
+ return deserialize_orc_container(
+ stream,
+ plugin,
+ properties,
+ false,
+ enc_ctx.encrypted ? enc_ctx.decrypt : std::function<std::string(const std::string&)>{});
}
void ov::npuw::CompiledModel::reconstruct_closure() {
@@ -2344,6 +2310,7 @@ void ov::npuw::CompiledModel::implement_properties() {
BIND(npuw::partitioning::dcoff_with_scale, NPUW_DCOFF_SCALE),
BIND(npuw::partitioning::attn_hfa_fused, NPUW_ATTN_HFA_FUSED),
BIND(npuw::parallel_compilation, NPUW_PARALLEL_COMPILE),
+ BIND(npuw::ensure_compatibility, NPUW_ENSURE_COMPATIBILITY),
BIND(npuw::funcall_async, NPUW_FUNCALL_ASYNC),
BIND(npuw::unfold_ireqs, NPUW_UNFOLD_IREQS),
BIND(npuw::weights_bank, NPUW_WEIGHTS_BANK),
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 bc97a8f9046..174d35ce4d1 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -18,6 +18,7 @@
#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/runtime/so_ptr.hpp"
#include "openvino/util/mmap_object.hpp"
+#include "orc/schema_npuw.hpp"
#include "partitioning/partitioning.hpp"
#include "perf.hpp"
#include "pyramid_attention.hpp"
@@ -85,6 +86,12 @@ class CompiledModel : public ov::npuw::ICompiledModel_v0 {
std::map<std::string, std::tuple<ov::PropertyMutability, std::function<ov::Any(const ::intel_npu::Config&)>>>;
public:
+ static constexpr ov::npuw::orc::TypeId kOrcType =
+ static_cast<ov::npuw::orc::TypeId>(ov::npuw::orc::schema_npuw::PartitionedModel::ID);
+ // Version 0 is the frozen baseline on the wire. Any further layout changes
+ // must be introduced through a new versioned payload rather than by mutating v0.
+ static constexpr ov::npuw::orc::Version kOrcVersion = 0u;
+
CompiledModel(const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties);
@@ -150,6 +157,20 @@ private:
const std::shared_ptr<const ov::IPlugin>& plugin,
const ov::AnyMap& properties,
const ov::npuw::s11n::CompiledContext& ctx);
+ static std::shared_ptr<CompiledModel> deserialize_orc(std::istream& stream,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ const ov::AnyMap& properties);
+ void serialize_orc(std::ostream& stream) const;
+ static std::shared_ptr<CompiledModel> deserialize_orc_container(
+ std::istream& stream,
+ const std::shared_ptr<const ov::IPlugin>& plugin,
+ const ov::AnyMap& properties,
+ bool require_weights_bank,
+ const std::function<std::string(const std::string&)>& decrypt);
+ void serialize_orc_container(std::ostream& stream,
+ bool include_weights_bank,
+ const std::function<std::string(const std::string&)>& encrypt) const;
+ void ensure_phase0_compatibility() const;
// This is used for removing too long output tensor names to fix some compilation issues
// NB: These two methods has nothing to do with this particular class and should be
@@ -223,6 +244,12 @@ private:
void init_profiling();
struct CompiledModelDesc {
+ static constexpr ov::npuw::orc::TypeId kOrcType =
+ static_cast<ov::npuw::orc::TypeId>(ov::npuw::orc::schema_npuw::Subgraph::ID);
+ // Version 0 is the frozen baseline on the wire. Any further layout
+ // changes must be introduced through a new versioned payload.
+ static constexpr ov::npuw::orc::Version kOrcVersion = 0u;
+
std::set<std::string> devices_to_avoid;
std::shared_ptr<ov::Model> model;
ov::SoPtr<ov::ICompiledModel> compiled_model;
@@ -269,6 +296,7 @@ private:
void serialize(ov::npuw::s11n::Stream& stream,
const ov::npuw::s11n::WeightsContext& ctx,
+ std::optional<std::size_t> orc_device_index = std::nullopt,
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 502ce66e589..3d3c137e327 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp
@@ -16,6 +16,7 @@
#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/util/file_util.hpp"
#include "openvino/util/mmap_object.hpp"
+#include "orc.hpp"
#include "util.hpp"
using ov::npuw::weights::LazyTensor;
@@ -357,7 +358,17 @@ void Gather::detach() {
} // namespace op
-enum class TransformType : int { CONST = 0, CONCAT, UNPACK, PERMUTE, CONVERT, GATHER };
+// Stable, permanently assigned op-type IDs.
+// Once assigned, IDs are NEVER changed and NEVER reused, even if an op is retired.
+// Retired IDs must be kept as comments to prevent accidental recycling.
+enum class TransformType : std::uint16_t {
+ CONST = 1,
+ CONCAT = 2,
+ UNPACK = 3,
+ PERMUTE = 4,
+ CONVERT = 5,
+ GATHER = 6,
+};
struct LazyTensorImpl {
LazyTensorImpl() = default;
@@ -372,7 +383,7 @@ struct LazyTensorImpl {
void detach();
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
- void serialize(ov::npuw::s11n::Stream& stream);
+ void serialize(ov::npuw::orc::Stream& stream);
LazyTensor::Transform m_transform;
std::size_t m_hash = 0;
@@ -426,7 +437,7 @@ namespace npuw {
namespace weights {
namespace op {
-void Const::serialize(ov::npuw::s11n::Stream& stream) {
+void Const::serialize(ov::npuw::orc::Stream& stream) {
std::string type_str;
if (stream.output()) {
type_str = m_cached_type.to_string();
@@ -448,11 +459,11 @@ void Const::serialize(ov::npuw::s11n::Stream& stream) {
}
}
-void Concat::serialize(ov::npuw::s11n::Stream& stream) {
+void Concat::serialize(ov::npuw::orc::Stream& stream) {
stream & axis & tensors;
}
-void Unpack::serialize(ov::npuw::s11n::Stream& stream) {
+void Unpack::serialize(ov::npuw::orc::Stream& stream) {
std::string type_str;
if (stream.output()) {
type_str = type.to_string();
@@ -463,11 +474,11 @@ void Unpack::serialize(ov::npuw::s11n::Stream& stream) {
}
}
-void Permute::serialize(ov::npuw::s11n::Stream& stream) {
+void Permute::serialize(ov::npuw::orc::Stream& stream) {
stream & axes & tensor;
}
-void Convert::serialize(ov::npuw::s11n::Stream& stream) {
+void Convert::serialize(ov::npuw::orc::Stream& stream) {
std::string type_str;
if (stream.output()) {
type_str = type.to_string();
@@ -478,7 +489,7 @@ void Convert::serialize(ov::npuw::s11n::Stream& stream) {
}
}
-void Gather::serialize(ov::npuw::s11n::Stream& stream) {
+void Gather::serialize(ov::npuw::orc::Stream& stream) {
std::string type_str;
if (stream.output()) {
type_str = dst_type.to_string();
@@ -491,54 +502,48 @@ void Gather::serialize(ov::npuw::s11n::Stream& stream) {
} // namespace op
-void LazyTensorImpl::serialize(ov::npuw::s11n::Stream& stream) {
+void LazyTensorImpl::serialize(ov::npuw::orc::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);
+ const auto type_id = static_cast<ov::npuw::orc::TypeId>(get_transform_type(op));
+ auto section = ov::npuw::orc::make_payload_section(type_id, op.kVersion, op);
+ ov::npuw::orc::serialize(stream, section);
},
m_transform);
return;
}
- stream & op_type;
- switch (TransformType(op_type)) {
+ ov::npuw::orc::Section section;
+ ov::npuw::orc::serialize(stream, section);
+ switch (static_cast<TransformType>(section.type)) {
case TransformType::CONCAT:
- m_transform.emplace<op::Concat>();
- std::get<op::Concat>(m_transform).serialize(stream);
+ m_transform.emplace<op::Concat>(ov::npuw::orc::load_versioned_payload<op::Concat>(section));
break;
case TransformType::CONST:
- m_transform.emplace<op::Const>();
- std::get<op::Const>(m_transform).serialize(stream);
+ m_transform.emplace<op::Const>(ov::npuw::orc::load_versioned_payload<op::Const>(section));
break;
case TransformType::CONVERT:
- m_transform.emplace<op::Convert>();
- std::get<op::Convert>(m_transform).serialize(stream);
+ m_transform.emplace<op::Convert>(ov::npuw::orc::load_versioned_payload<op::Convert>(section));
break;
case TransformType::PERMUTE:
- m_transform.emplace<op::Permute>();
- std::get<op::Permute>(m_transform).serialize(stream);
+ m_transform.emplace<op::Permute>(ov::npuw::orc::load_versioned_payload<op::Permute>(section));
break;
case TransformType::UNPACK:
- m_transform.emplace<op::Unpack>();
- std::get<op::Unpack>(m_transform).serialize(stream);
+ m_transform.emplace<op::Unpack>(ov::npuw::orc::load_versioned_payload<op::Unpack>(section));
break;
case TransformType::GATHER:
- m_transform.emplace<op::Gather>();
- std::get<op::Gather>(m_transform).serialize(stream);
+ m_transform.emplace<op::Gather>(ov::npuw::orc::load_versioned_payload<op::Gather>(section));
break;
default:
- NPUW_ASSERT(false && "Unsupported type");
+ OPENVINO_THROW("ORC LazyTensor: unknown op_type ", section.type, " — please upgrade NPUW");
break;
}
}
-void LazyTensor::serialize(ov::npuw::s11n::Stream& stream) {
+void LazyTensor::serialize(ov::npuw::orc::Stream& stream) {
bool is_initialized = static_cast<bool>(m_impl);
stream & is_initialized;
if (!is_initialized) {
@@ -558,11 +563,11 @@ void LazyTensor::serialize(ov::npuw::s11n::Stream& stream) {
} // namespace weights
-namespace s11n {
-void serialize(ov::npuw::s11n::Stream& stream, ov::npuw::weights::LazyTensor& var) {
+namespace orc {
+void serialize(ov::npuw::orc::Stream& stream, ov::npuw::weights::LazyTensor& var) {
var.serialize(stream);
}
-} // namespace s11n
+} // namespace orc
} // namespace npuw
} // namespace ov
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 e7b71cfc2cd..42c5aec7251 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.hpp
@@ -77,18 +77,22 @@ public:
operator bool() const;
private:
- friend void ov::npuw::s11n::serialize(ov::npuw::s11n::Stream& stream, LazyTensor& var);
- void serialize(ov::npuw::s11n::Stream& stream);
+ friend void ov::npuw::orc::serialize(ov::npuw::orc::Stream& stream, LazyTensor& var);
+ void serialize(ov::npuw::orc::Stream& stream);
std::shared_ptr<LazyTensorImpl> m_impl = nullptr;
};
namespace op {
+// These v0 payloads are now part of the frozen on-wire baseline. Any new field
+// or semantic change must be introduced through a versioned successor payload
+// instead of changing the existing v0 layout.
class Const {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
- Const() = default;
+ static constexpr std::uint16_t kVersion = 0u;
+ Const() = default;
explicit Const(const std::shared_ptr<ov::op::v0::Constant>& n);
std::size_t hash() const;
bool operator==(const Const& other) const;
@@ -96,9 +100,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& 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;
@@ -119,6 +123,8 @@ class Concat {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
+ static constexpr std::uint16_t kVersion = 0u;
+
Concat() = default;
Concat(const std::vector<LazyTensor>& _tensors, std::size_t _axis) : tensors(_tensors), axis(_axis) {}
@@ -128,9 +134,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& stream);
private:
- void serialize(ov::npuw::s11n::Stream& stream);
std::vector<LazyTensor> tensors;
std::size_t axis = 0;
};
@@ -139,6 +145,8 @@ class Unpack {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
+ static constexpr std::uint16_t kVersion = 0u;
+
Unpack() = default;
Unpack(const LazyTensor& _w, const LazyTensor& _z, const LazyTensor& _s, ov::element::Type _type, ov::Shape _shape)
: w(_w),
@@ -153,9 +161,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& stream);
private:
- void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor w, z, s;
ov::element::Type type;
ov::Shape shape;
@@ -165,6 +173,8 @@ class Permute {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
+ static constexpr std::uint16_t kVersion = 0u;
+
Permute() = default;
Permute(const LazyTensor& _tensor, const std::vector<std::size_t>& _axes) : tensor(_tensor), axes(_axes) {}
@@ -174,9 +184,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& stream);
private:
- void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor tensor;
std::vector<std::size_t> axes;
};
@@ -185,6 +195,8 @@ class Convert {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
+ static constexpr std::uint16_t kVersion = 0u;
+
Convert() = default;
Convert(const LazyTensor& _tensor, ov::element::Type _type) : tensor(_tensor), type(_type) {}
@@ -194,9 +206,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& stream);
private:
- void serialize(ov::npuw::s11n::Stream& stream);
LazyTensor tensor;
ov::element::Type type;
};
@@ -205,6 +217,8 @@ class Gather {
friend struct ov::npuw::weights::LazyTensorImpl;
public:
+ static constexpr std::uint16_t kVersion = 0u;
+
Gather() = default;
Gather(const LazyTensor& _w, const ov::Tensor& _t, const ov::element::Type& _dst_type, const ov::Shape& _dst_shape)
: w(_w),
@@ -218,9 +232,9 @@ public:
LazyTensor::Meta eval_meta() const;
void read_weight(const ov::npuw::s11n::WeightsContext& ctx);
void detach();
+ void serialize(ov::npuw::orc::Stream& 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 77d9d3e8cf1..e8d4cbf9100 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
@@ -1235,7 +1235,7 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::n
stream & bank_name;
if (!is_weightless) {
- ov::npuw::s11n::serialize(stream, *kv_bank);
+ stream&* kv_bank;
}
LOG_INFO("Done.");
@@ -1317,7 +1317,7 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_m
}
} else {
auto bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");
- ov::npuw::s11n::serialize(stream, *bank);
+ stream&* bank;
compiled->m_kvcache_compiled->set_weights_bank(bank);
for (const auto& compiled_variant : compiled->m_generate_compiled_variants) {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp
index 6aceef1a3c3..d2933950818 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp
@@ -10,6 +10,7 @@
#include <memory>
#include <vector>
+#include "../serialization.hpp"
#include "../v1/subgraph_pipeline.hpp"
namespace ov {
@@ -23,10 +24,6 @@ namespace compiled {
struct MoEExperts;
struct MoEDownstream;
} // namespace compiled
-namespace s11n {
-class Stream;
-struct SubmodelDeserializeCtx;
-} // namespace s11n
namespace moe {
enum class BehaviorRole {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/orc.cpp b/src/plugins/intel_npu/src/plugin/npuw/orc.cpp
index 35cc7ce59fd..3b7aa71db1d 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/orc.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/orc.cpp
@@ -13,7 +13,23 @@
namespace {
constexpr std::array<std::uint8_t, 8> ORC_FILE_MAGIC = {'N', 'P', 'U', 'W', 'O', 'R', 'C', '\0'};
-constexpr std::uint16_t ORC_FILE_VERSION = 1u;
+constexpr std::uint16_t ORC_FILE_VERSION = 0u;
+
+std::streampos checked_tellp(std::ostream& stream, const char* context) {
+ const auto pos = stream.tellp();
+ if (pos == std::streampos(-1)) {
+ OPENVINO_THROW("ORC export requires a seekable output stream for ", context);
+ }
+ return pos;
+}
+
+std::streampos checked_tellg(std::istream& stream, const char* context) {
+ const auto pos = stream.tellg();
+ if (pos == std::streampos(-1)) {
+ OPENVINO_THROW("ORC import requires a seekable input stream for ", context);
+ }
+ return pos;
+}
std::streamsize checked_stream_size(const std::size_t size) {
if (size > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
@@ -133,6 +149,18 @@ ov::npuw::orc::Stream ov::npuw::orc::Stream::reader(std::istream& stream) {
return s;
}
+void ov::npuw::orc::serialize(Stream& stream, Section& section) {
+ if (stream.output()) {
+ write_section(stream, section);
+ } else {
+ section = read_section(stream);
+ }
+}
+
+void ov::npuw::orc::serialize(Stream& stream, SectionHeader& header) {
+ stream & header.type & header.version & header.flags & header.size;
+}
+
ov::npuw::orc::Stream ov::npuw::orc::Stream::memory_reader(const void* data, const std::size_t size) {
Stream s;
s.m_memory = reinterpret_cast<const std::byte*>(data);
@@ -146,6 +174,18 @@ ov::npuw::orc::Stream ov::npuw::orc::Stream::writer(std::ostream& stream) {
return s;
}
+bool ov::npuw::orc::try_read_bytes(std::istream& stream, void* data, const std::size_t size) {
+ const auto saved = stream.tellg();
+ stream.read(reinterpret_cast<char*>(data), checked_stream_size(size));
+ if (stream.good()) {
+ return true;
+ }
+
+ stream.clear();
+ stream.seekg(saved);
+ return false;
+}
+
bool ov::npuw::orc::Stream::input() const {
return m_input != nullptr || m_memory != nullptr;
}
@@ -228,12 +268,12 @@ ov::npuw::orc::Section ov::npuw::orc::Section::container(const TypeId type,
Section section;
section.type = type;
section.version = version;
- section.flags = flags; // LEAF not set — this is a structural container section
+ section.flags = flags; // LEAF not set; this is a structural container section
section.children = std::move(children);
return section;
}
-void ov::npuw::orc::write_file(std::ostream& stream, const Section& root, const SchemaUUID& uuid) {
+void ov::npuw::orc::write_file_header(std::ostream& stream, const SchemaUUID& uuid) {
auto writer = Stream::writer(stream);
auto magic = ORC_FILE_MAGIC;
@@ -242,10 +282,9 @@ void ov::npuw::orc::write_file(std::ostream& stream, const Section& root, const
writer & version;
auto uuid_copy = uuid;
writer & uuid_copy;
- write_section(writer, root);
}
-ov::npuw::orc::Section ov::npuw::orc::read_file(std::istream& stream) {
+ov::npuw::orc::OrcHeader ov::npuw::orc::read_file_header(std::istream& stream) {
const auto header = is_orc(stream);
if (!header) {
OPENVINO_THROW("Not an ORC file (invalid magic)");
@@ -254,15 +293,126 @@ ov::npuw::orc::Section ov::npuw::orc::read_file(std::istream& stream) {
OPENVINO_THROW("Unsupported ORC file version ", header->version);
}
- // is_orc() restores the stream position; skip past the file header before reading sections.
constexpr auto skip =
static_cast<std::streamoff>(ORC_FILE_MAGIC.size() + sizeof(ORC_FILE_VERSION) + sizeof(SchemaUUID));
stream.seekg(skip, std::ios::cur);
+ if (!stream.good()) {
+ OPENVINO_THROW("Failed to seek past ORC file header");
+ }
+ return *header;
+}
+void ov::npuw::orc::write_file(std::ostream& stream, const Section& root, const SchemaUUID& uuid) {
+ write_file_header(stream, uuid);
+ auto writer = Stream::writer(stream);
+ write_section(writer, root);
+}
+
+ov::npuw::orc::Section ov::npuw::orc::read_file(std::istream& stream) {
+ read_file_header(stream);
auto reader = Stream::reader(stream);
return read_section(reader);
}
+std::streamsize ov::npuw::orc::checked_stream_size(const std::size_t size) {
+ return ::checked_stream_size(size);
+}
+
+std::size_t ov::npuw::orc::checked_size(const std::uint64_t size) {
+ return ::checked_size(size);
+}
+
+std::streamoff ov::npuw::orc::checked_streamoff(const std::uint64_t size) {
+ if (size > static_cast<std::uint64_t>(std::numeric_limits<std::streamoff>::max())) {
+ OPENVINO_THROW("ORC section size exceeds std::streamoff range");
+ }
+ return static_cast<std::streamoff>(size);
+}
+
+ov::npuw::orc::ScopedWriteSection::ScopedWriteSection(std::ostream& stream,
+ const TypeId type,
+ const Version version,
+ const SectionFlags flags)
+ : m_stream(stream) {
+ SectionHeader header;
+ header.type = type;
+ header.version = version;
+ header.flags = flags;
+ header.size = 0u;
+
+ auto writer = Stream::writer(stream);
+ writer & header.type & header.version & header.flags;
+ m_size_pos = checked_tellp(stream, "section size patching");
+ writer & header.size;
+ m_body_pos = checked_tellp(stream, "section body tracking");
+}
+
+void ov::npuw::orc::ScopedWriteSection::close() {
+ if (m_closed) {
+ return;
+ }
+
+ const auto end_pos = checked_tellp(m_stream, "section size patching");
+ const auto body_size = end_pos - m_body_pos;
+ if (body_size < 0) {
+ OPENVINO_THROW("ORC section body size underflow");
+ }
+
+ const auto restore_pos = end_pos;
+ m_stream.seekp(m_size_pos);
+ if (!m_stream.good()) {
+ OPENVINO_THROW("Failed to seek to ORC section size field");
+ }
+
+ auto writer = Stream::writer(m_stream);
+ auto size = static_cast<std::uint64_t>(body_size);
+ writer & size;
+ m_stream.seekp(restore_pos);
+ if (!m_stream.good()) {
+ OPENVINO_THROW("Failed to restore ORC output position after patching section size");
+ }
+ m_closed = true;
+}
+
+ov::npuw::orc::ScopedReadSection::ScopedReadSection(std::istream& stream) : m_stream(stream) {
+ auto reader = Stream::reader(stream);
+ reader & m_header;
+ m_end = checked_tellg(stream, "section bounds") + checked_streamoff(m_header.size);
+}
+
+const ov::npuw::orc::SectionHeader& ov::npuw::orc::ScopedReadSection::header() const {
+ return m_header;
+}
+
+bool ov::npuw::orc::ScopedReadSection::done() const {
+ return checked_tellg(m_stream, "section iteration") >= m_end;
+}
+
+std::size_t ov::npuw::orc::ScopedReadSection::remaining() const {
+ const auto pos = checked_tellg(m_stream, "section remaining");
+ if (pos > m_end) {
+ OPENVINO_THROW("ORC stream advanced past the end of the current section");
+ }
+ return checked_size(static_cast<std::uint64_t>(m_end - pos));
+}
+
+void ov::npuw::orc::ScopedReadSection::expect_end() const {
+ if (!done() || checked_tellg(m_stream, "section completion") != m_end) {
+ OPENVINO_THROW("Malformed ORC section contents");
+ }
+}
+
+std::string ov::npuw::orc::ScopedReadSection::read_remaining_blob() {
+ std::string blob(remaining(), '\0');
+ if (!blob.empty()) {
+ m_stream.read(blob.data(), checked_stream_size(blob.size()));
+ if (!m_stream.good()) {
+ OPENVINO_THROW("Unexpected end of ORC input stream");
+ }
+ }
+ return blob;
+}
+
bool ov::npuw::orc::Schema::knows(const TypeId type) const {
return m_entries.count(type) != 0u;
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/orc.hpp b/src/plugins/intel_npu/src/plugin/npuw/orc.hpp
index 058a23ae1f2..c0f8cf34e15 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/orc.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/orc.hpp
@@ -10,14 +10,17 @@
#include <cstdint>
#include <cstring>
#include <functional>
+#include <ios>
#include <iosfwd>
#include <limits>
+#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
+#include <unordered_set>
#include <utility>
#include <vector>
@@ -29,12 +32,13 @@ namespace orc {
using TypeId = std::uint16_t;
using Version = std::uint16_t;
-using SectionFlags = std::uint32_t;
+using SectionFlags = std::uint64_t;
using SchemaUUID = std::array<std::uint8_t, 16>;
enum class SectionFlag : SectionFlags {
- OPTIONAL = 1u << 0,
- LEAF = 1u << 1, // payload contains raw bytes only, no child sections
+ OPTIONAL = 1ull << 0,
+ LEAF = 1ull << 1, // payload contains raw bytes only, no child sections
+ ENCRYPTED = 1ull << 2,
};
constexpr SectionFlags operator|(SectionFlag lhs, SectionFlag rhs) {
@@ -46,7 +50,7 @@ constexpr SectionFlags operator|(SectionFlags lhs, SectionFlag rhs) {
}
constexpr bool has_flag(SectionFlags flags, SectionFlag flag) {
- return (flags & static_cast<SectionFlags>(flag)) != 0u;
+ return (flags & static_cast<SectionFlags>(flag)) != 0ull;
}
class Stream;
@@ -99,6 +103,8 @@ private:
std::size_t m_memory_offset = 0u;
};
+bool try_read_bytes(std::istream& stream, void* data, std::size_t size);
+
template <typename T, std::enable_if_t<std::is_integral<T>::value || std::is_floating_point<T>::value, bool> = true>
void serialize(Stream& stream, T& value) {
stream.bytes(&value, sizeof(value));
@@ -168,6 +174,70 @@ void serialize(Stream& stream, std::optional<T>& value) {
value = std::move(unpacked);
}
+template <typename K, typename V>
+void serialize(Stream& stream, std::map<K, V>& value) {
+ if (stream.output()) {
+ auto size = value.size();
+ stream & size;
+ for (auto& el : value) {
+ auto pair = el;
+ stream & pair;
+ }
+ return;
+ }
+
+ value.clear();
+ std::size_t size = 0u;
+ stream & size;
+ for (std::size_t idx = 0u; idx < size; ++idx) {
+ std::pair<K, V> elem{};
+ stream & elem;
+ value[elem.first] = std::move(elem.second);
+ }
+}
+
+template <typename T>
+void serialize(Stream& stream, std::unordered_set<T>& value) {
+ if (stream.output()) {
+ auto size = value.size();
+ stream & size;
+ for (auto el : value) {
+ stream & el;
+ }
+ return;
+ }
+
+ value.clear();
+ std::size_t size = 0u;
+ stream & size;
+ for (std::size_t idx = 0u; idx < size; ++idx) {
+ T elem{};
+ stream & elem;
+ value.insert(std::move(elem));
+ }
+}
+
+template <typename T, typename H>
+void serialize(Stream& stream, std::unordered_set<T, H>& value) {
+ if (stream.output()) {
+ auto size = value.size();
+ stream & size;
+ for (auto el : value) {
+ stream & el;
+ }
+ return;
+ }
+
+ value.clear();
+ std::size_t size = 0u;
+ stream & size;
+ for (std::size_t idx = 0u; idx < size; ++idx) {
+ T elem{};
+ stream & elem;
+ value.insert(std::move(elem));
+ }
+}
+
template <typename T>
std::vector<std::byte> encode(const T& value) {
std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
@@ -197,14 +267,16 @@ T decode(const std::vector<std::byte>& bytes) {
struct SectionHeader {
TypeId type = 0u;
Version version = 0u;
- SectionFlags flags = 0u;
+ SectionFlags flags = 0ull;
std::uint64_t size = 0u;
};
+void serialize(Stream& stream, SectionHeader& header);
+
struct Section {
TypeId type = 0u;
Version version = 0u;
- SectionFlags flags = 0u;
+ SectionFlags flags = 0ull;
std::vector<std::byte> payload;
std::vector<Section> children;
@@ -220,24 +292,80 @@ struct Section {
return !is_leaf();
}
- static Section raw(TypeId type, Version version, std::vector<std::byte> payload, SectionFlags flags = 0u);
- static Section container(TypeId type, Version version, std::vector<Section> children, SectionFlags flags = 0u);
+ static Section raw(TypeId type, Version version, std::vector<std::byte> payload, SectionFlags flags = 0ull);
+ static Section container(TypeId type, Version version, std::vector<Section> children, SectionFlags flags = 0ull);
};
template <typename T>
-Section make_payload_section(TypeId type, Version version, const T& value, SectionFlags flags = 0u) {
+Section make_payload_section(TypeId type, Version version, const T& value, SectionFlags flags = 0ull) {
return Section::raw(type, version, encode(value), flags);
}
+// Serialize an ORC section (header + body) inline into a stream.
+// On output: writes the section wire format.
+// On input: reads and reconstructs a Section.
+void serialize(Stream& stream, Section& section);
+
// File-level metadata returned by is_orc().
struct OrcHeader {
std::uint16_t version = 0u;
SchemaUUID schema_uuid{};
};
+void write_file_header(std::ostream& stream, const SchemaUUID& uuid);
+OrcHeader read_file_header(std::istream& stream);
void write_file(std::ostream& stream, const Section& root, const SchemaUUID& uuid);
Section read_file(std::istream& stream);
+std::streamsize checked_stream_size(std::size_t size);
+std::size_t checked_size(std::uint64_t size);
+std::streamoff checked_streamoff(std::uint64_t size);
+
+class ScopedWriteSection {
+public:
+ ScopedWriteSection(std::ostream& stream, TypeId type, Version version, SectionFlags flags = 0ull);
+ ScopedWriteSection(const ScopedWriteSection&) = delete;
+ ScopedWriteSection& operator=(const ScopedWriteSection&) = delete;
+
+ void close();
+
+private:
+ std::ostream& m_stream;
+ std::streampos m_size_pos{};
+ std::streampos m_body_pos{};
+ bool m_closed = false;
+};
+
+template <typename Writer>
+void with_section(std::ostream& stream, TypeId type, Version version, SectionFlags flags, Writer&& writer) {
+ ScopedWriteSection section(stream, type, version, flags);
+ writer();
+ section.close();
+}
+
+template <typename Writer>
+void with_leaf_section(std::ostream& stream, TypeId type, Version version, Writer&& writer, SectionFlags flags = 0ull) {
+ ScopedWriteSection section(stream, type, version, flags | SectionFlag::LEAF);
+ writer();
+ section.close();
+}
+
+class ScopedReadSection {
+public:
+ explicit ScopedReadSection(std::istream& stream);
+
+ const SectionHeader& header() const;
+ bool done() const;
+ std::size_t remaining() const;
+ void expect_end() const;
+ std::string read_remaining_blob();
+
+private:
+ std::istream& m_stream;
+ SectionHeader m_header{};
+ std::streampos m_end{};
+};
+
// Peeks at the stream to check whether it contains an ORC blob.
// Returns the file header (format_version + schema_uuid) on success,
// nullopt if the magic does not match.
@@ -338,13 +466,61 @@ Target load_versioned_payload_impl(const Section& section) {
} // namespace detail
-template <typename Target, typename... Versions>
+// Multi-arg form: explicit version list — use as an escape hatch when the
+// Prev chain is insufficient (e.g., legacy types without a frozen V0 struct,
+// or migration logic too complex to express as typed constructors).
+// Requires at least one version type (First) so this overload is unambiguous
+// with the single-arg form when Target is the only template argument.
+template <typename Target, typename First, typename... Rest>
+Target load_versioned_payload(const Section& section) {
+ if (section.is_container()) {
+ OPENVINO_THROW("Cannot decode a container section as a raw ORC payload");
+ }
+ return detail::load_versioned_payload_impl<Target, First, Rest...>(section);
+}
+
+namespace detail {
+
+// Walk the Prev chain of Current (oldest → newest) to find a matching version,
+// then migrate up to Target via migrate_chain. Requires Target to define Prev
+// pointing at its immediately preceding frozen type.
+template <typename Target, typename Current>
+Target load_versioned_payload_chain_impl(const Section& section) {
+ static_assert(has_version<Current>::value, "All versioned ORC types must define kVersion");
+ if (section.version == Current::kVersion) {
+ return migrate_chain<Target>(decode<Current>(section.payload));
+ }
+ if constexpr (has_prev<Current>::value) {
+ return load_versioned_payload_chain_impl<Target, typename Current::Prev>(section);
+ }
+ OPENVINO_THROW("Unsupported ORC section version ", section.version, " for type ID ", section.type);
+}
+
+} // namespace detail
+
+// Single-arg form: version list is derived automatically from the Target's Prev chain.
+//
+// For V1+ types, Target must define:
+// using Prev = <most-recent frozen snapshot>; // updated when a new version ships
+// static constexpr Version kVersion = ...; // via ORC_DECLARE_VERSION
+// The chain is walked at compile time: Target::Prev → Prev::Prev → … → V0.
+// Call site stays permanently neutral: load_versioned_payload<MyType>(section).
+//
+// For V0 types (no Prev, kVersion=0): decodes directly — no chain needed.
+template <typename Target>
Target load_versioned_payload(const Section& section) {
- static_assert(sizeof...(Versions) != 0u, "At least one versioned payload type must be provided");
+ static_assert(detail::has_version<Target>::value, "Target must define kVersion");
if (section.is_container()) {
OPENVINO_THROW("Cannot decode a container section as a raw ORC payload");
}
- return detail::load_versioned_payload_impl<Target, Versions...>(section);
+ if constexpr (has_prev<Target>::value) {
+ return detail::load_versioned_payload_chain_impl<Target, typename Target::Prev>(section);
+ } else {
+ if (section.version != Target::kVersion) {
+ OPENVINO_THROW("Unsupported ORC section version ", section.version, " for type ID ", section.type);
+ }
+ return decode<Target>(section.payload);
+ }
}
} // namespace orc
@@ -353,12 +529,19 @@ Target load_versioned_payload(const Section& section) {
// Injects the standard versioning boilerplate into a frozen versioned type.
// PrevType must already define kVersion; ThisType must be the enclosing struct name.
+// The base (V0) type defines kVersion = 0 manually — ORC_DECLARE_VERSION is only
+// used for V1 and later.
//
// Example:
-// struct MyTypeV2 : MyTypeV1 {
-// ORC_DECLARE_VERSION(MyTypeV2, MyTypeV1)
-// int new_field = 0;
-// void serialize(Stream& stream) { Prev::serialize(stream); stream & new_field; }
+// struct V0 {
+// static constexpr Version kVersion = 0;
+// int x = 0;
+// void serialize(Stream& stream) { stream & x; }
+// };
+// struct V1 : V0 {
+// ORC_DECLARE_VERSION(V1, V0) // kVersion = 1
+// int y = 0;
+// void serialize(Stream& stream) { Prev::serialize(stream); stream & y; }
// };
#define ORC_DECLARE_VERSION(ThisType, PrevType) \
using Prev = PrevType; \
diff --git a/src/plugins/intel_npu/src/plugin/npuw/orc/schema_npuw.hpp b/src/plugins/intel_npu/src/plugin/npuw/orc/schema_npuw.hpp
new file mode 100644
index 00000000000..756b2785ed6
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/orc/schema_npuw.hpp
@@ -0,0 +1,28 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "../orc.hpp"
+
+namespace ov::npuw::orc::schema_npuw {
+
+inline constexpr SchemaUUID NPUW_ORC_PARTITIONED_SCHEMA =
+ {0x4E, 0x50, 0x55, 0x57, 0x43, 0x4D, 0x4F, 0x44, 0x50, 0x48, 0x41, 0x53, 0x45, 0x30, 0x30, 0x31};
+
+// Keep the top-level on-wire type IDs centralized so future schemas can reuse
+// the same registry without accidental collisions.
+enum class PartitionedModel : TypeId {
+ ID = 100,
+};
+
+enum class Subgraph : TypeId {
+ ID = 200,
+};
+
+enum class WeightsBank : TypeId {
+ ID = 300,
+};
+
+} // namespace ov::npuw::orc::schema_npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
index 39cc31bfdfa..895ae8b7a81 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
@@ -21,24 +21,13 @@
#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
+// NOTE: This constructor 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)
: is_weightless(_is_weightless),
const_to_offset(_const_to_offset) {}
-// NOTE: This construtor can and should only be used when importing blobs
+// NOTE: This constructor is used when importing blobs.
ov::npuw::s11n::WeightsContext::WeightsContext(const ov::npuw::s11n::WeightsPtr& _weights,
const std::string& _weights_path,
const s11n::WeightsContext::ConstsCache& _consts_cache,
@@ -71,64 +60,39 @@ ov::npuw::s11n::BF16Cache ov::npuw::s11n::get_bf16_consts(const std::shared_ptr<
return bf16_cache;
}
-void ov::npuw::s11n::serialize(Stream& stream, std::streampos& var) {
- stream.bytes(&var, sizeof var);
-}
-
-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()));
- }
- } else {
- 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));
- }
- }
-}
-
-void ov::npuw::s11n::serialize(Stream& stream, bool& var) {
+void ov::npuw::orc::serialize(Stream& stream, std::streampos& var) {
stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::serialize(Stream& stream, float& var) {
- stream.bytes(&var, sizeof var);
-}
-
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Spatial& var) {
+void ov::npuw::orc::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::serialize(Stream& stream, ov::npuw::compiled::Spatial::Param& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::Spatial::Param& var) {
stream & var.idx & var.dim;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::Attention& var) {
+void ov::npuw::orc::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::serialize(Stream& stream, ov::npuw::compiled::Attention::Param& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::Attention::Param& var) {
stream & var.idx & var.dim;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::PyramidAttention& var) {
+void ov::npuw::orc::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::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo& var) {
stream & var.params & var.mask_idx & var.query_size & var.context_length;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo::Param& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo::Param& var) {
stream & var.idx & var.dim;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::HostFlashAttention& var) {
+void ov::npuw::orc::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 &
@@ -139,20 +103,20 @@ void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::HostFlashAtte
var._can_use_tensor_view;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::compiled::MoEExperts& var) {
+void ov::npuw::orc::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::serialize(Stream& stream, ov::npuw::compiled::MoEDownstream& var) {
+void ov::npuw::orc::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::serialize(Stream& stream, ov::Tensor& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::Tensor& var) {
transfer_tensor(stream, var);
}
-void ov::npuw::s11n::serialize(Stream& stream, ::intel_npu::Config& var) {
+void ov::npuw::orc::serialize(Stream& stream, ::intel_npu::Config& var) {
std::string str;
if (stream.output()) {
str = var.toString();
@@ -163,7 +127,7 @@ void ov::npuw::s11n::serialize(Stream& stream, ::intel_npu::Config& var) {
}
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::Output<const ov::Node>& var) {
+void ov::npuw::orc::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();
@@ -174,7 +138,7 @@ void ov::npuw::s11n::serialize(Stream& stream, ov::Output<const ov::Node>& var)
}
}
-void ov::npuw::s11n::transfer_tensor(Stream& stream, ov::Tensor& var, const TensorAllocator& allocator) {
+void ov::npuw::orc::transfer_tensor(Stream& stream, ov::Tensor& var, const s11n::TensorAllocator& allocator) {
if (stream.output()) {
bool is_initialized = static_cast<bool>(var);
stream & is_initialized;
@@ -227,45 +191,46 @@ void ov::npuw::s11n::transfer_tensor(Stream& stream, ov::Tensor& var, const Tens
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");
+void ov::npuw::orc::serialize(Stream& stream, std::shared_ptr<ov::op::v0::Parameter>& var) {
+ if (stream.output()) {
+ OPENVINO_THROW(
+ "Serializing shared_ptr<ov::op::v0::Parameter> is not supported, serialize an output port instead");
}
+
+ 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);
}
-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::orc::serialize(Stream& stream, std::shared_ptr<ov::Node>& var) {
+ if (stream.output()) {
+ OPENVINO_THROW("Serializing shared_ptr<ov::Node> is not supported, serialize an output port instead");
+ }
+
+ 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());
}
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::Any& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::Any& var) {
std::string str;
if (stream.output()) {
str = ov::npuw::s11n::anyToString(var);
@@ -276,19 +241,19 @@ void ov::npuw::s11n::serialize(Stream& stream, ov::Any& var) {
}
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::CacheMode& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::CacheMode& var) {
stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::element::Type& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::element::Type& var) {
stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::hint::PerformanceMode& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::hint::PerformanceMode& var) {
stream.bytes(&var, sizeof var);
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::AnyMap& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::AnyMap& var) {
std::string str;
if (stream.output()) {
str = ov::npuw::s11n::anyMapToString(var);
@@ -301,9 +266,9 @@ void ov::npuw::s11n::serialize(Stream& stream, ov::AnyMap& var) {
// Weightless
// FIXME: all serialization needs a good rewriting
-void ov::npuw::s11n::serialize_weightless(Stream& stream,
- std::vector<ov::Tensor>& var,
- const ov::npuw::s11n::WeightsContext& ctx) {
+void ov::npuw::orc::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);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index 731c6c3361d..ee78db033ff 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -23,6 +23,7 @@
#include "host_flash_attention.hpp"
#include "openvino/core/shape.hpp"
#include "openvino/runtime/file_handle.hpp"
+#include "orc.hpp"
#include "pyramid_attention.hpp"
#include "spatial.hpp"
@@ -43,7 +44,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.23";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.24";
// Forward declaration
namespace intel_npu {
@@ -97,6 +98,9 @@ class LazyTensor;
class Bank;
} // namespace weights
+// --------------------------------------------------------------------------
+// s11n: context types, helper aliases, and utilities
+// --------------------------------------------------------------------------
namespace s11n {
class PairHash {
@@ -137,10 +141,11 @@ struct WeightsContext {
WeightsContext() = default;
- // NOTE: This construtor should only be used when exporting blobs
+ // NOTE: This constructor should only be used when exporting blobs.
WeightsContext(bool _is_weightless, const std::unordered_map<const void*, std::size_t>& _const_to_offset);
- // NOTE: This construtor can and should only be used when importing weightless blobs
+ // NOTE: This constructor is used on blob import to carry the resolved weight source
+ // (embedded weights, mmap'ed weights file, or model-backed constants cache).
WeightsContext(const ov::npuw::s11n::WeightsPtr& _weights,
const std::string& _weights_path,
const ConstsCache& _consts_cache,
@@ -176,74 +181,66 @@ struct SubmodelDeserializeCtx {
compiled_model(_compiled_model),
import_config(_import_config) {}
+ SubmodelDeserializeCtx(const std::shared_ptr<const ov::IPlugin>& _plugin,
+ const ov::SoPtr<ov::ICompiledModel>& _compiled_model,
+ std::function<std::string(std::size_t)> _device_by_index,
+ std::function<std::map<std::string, Any>(const std::string&)> _import_config_for_device)
+ : plugin(_plugin),
+ compiled_model(_compiled_model),
+ device_by_index(std::move(_device_by_index)),
+ import_config_for_device(std::move(_import_config_for_device)) {}
+
std::shared_ptr<const ov::IPlugin> plugin;
std::string device;
const ov::SoPtr<ov::ICompiledModel>& compiled_model;
std::map<std::string, Any> import_config;
+ std::function<std::string(std::size_t)> device_by_index;
+ std::function<std::map<std::string, Any>(const std::string&)> import_config_for_device;
};
BF16Cache get_bf16_consts(const std::shared_ptr<ov::Model>& model);
-class Stream {
-public:
- static Stream reader(std::istream& stream) {
- return Stream(&stream, nullptr);
- }
+// The NPUW stream type IS the ORC stream.
+using Stream = ::ov::npuw::orc::Stream;
- static Stream writer(std::ostream& stream) {
- return Stream(nullptr, &stream);
- }
-
- bool input() const {
- return m_input != nullptr;
- }
+// Bring all orc serialize overloads into s11n namespace so that
+// qualified ov::npuw::s11n::serialize(...) call sites continue to work.
+using ::ov::npuw::orc::serialize;
- 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;
- }
+using TensorAllocator = std::function<ov::Tensor(const ov::element::Type&, const ov::Shape&)>;
- void operator()() {}
+template <typename T>
+void write(std::ostream& stream, const T& var) {
+ auto stream_io = Stream::writer(stream);
+ auto& mutable_var = const_cast<std::remove_const_t<T>&>(var);
+ stream_io & mutable_var;
+}
- template <typename T, typename... Ts>
- void operator()(T&& value, Ts&&... values) {
- (*this) & std::forward<T>(value);
- (*this)(std::forward<Ts>(values)...);
- }
+template <typename T>
+void read(std::istream& stream, T& var) {
+ auto stream_io = Stream::reader(stream);
+ stream_io & var;
+}
- 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);
- }
- }
+inline void write_any(std::ostream& stream, const ov::Any& var) {
+ write(stream, var);
+}
-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);
- }
+inline void read_any(std::istream& stream, ov::Any& var) {
+ read(stream, var);
+}
- Stream(std::istream* input, std::ostream* output) : m_input(input), m_output(output) {}
+} // namespace s11n
- std::istream* m_input = nullptr;
- std::ostream* m_output = nullptr;
-};
+// --------------------------------------------------------------------------
+// NPUW-specific orc serializers (in orc namespace for ADL from orc::Stream)
+// --------------------------------------------------------------------------
+namespace orc {
+// Raw stream position — used by the compiled model blob header.
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);
+
+// NPUW compiled structures
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);
@@ -254,191 +251,46 @@ void serialize(Stream& stream, ov::npuw::compiled::PyramidAttentionInfo::Param&
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);
+
+// OpenVINO runtime types
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::Any& var);
+void serialize(Stream& stream, ov::AnyMap& 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 serialize_weightless(Stream& stream, std::vector<ov::Tensor>& var, const WeightsContext& ctx);
-
-// Forward declaration
-template <typename T1, typename T2>
-void serialize(Stream& stream, std::pair<T1, T2>& var);
-template <typename T>
-void serialize(Stream& stream, std::vector<T>& var);
-template <typename T, size_t N>
-void serialize(Stream& stream, std::array<T, N>& var);
+// NPU plugin configuration
+void serialize(Stream& stream, ::intel_npu::Config& var);
-template <typename T>
-void write(std::ostream& stream, const T& var) {
- auto stream_io = Stream::writer(stream);
- auto& mutable_var = const_cast<std::remove_const_t<T>&>(var);
- serialize(stream_io, mutable_var);
-}
+// NPUW weight types
+void serialize(Stream& stream, ov::npuw::weights::LazyTensor& var);
+void serialize(Stream& stream, ov::npuw::weights::Bank& var);
-template <typename T>
-void read(std::istream& stream, T& var) {
- auto stream_io = Stream::reader(stream);
- serialize(stream_io, var);
-}
+// Weightless tensor utilities
+void serialize_weightless(Stream& stream, std::vector<ov::Tensor>& var, const s11n::WeightsContext& ctx);
+void transfer_tensor(Stream& stream, ov::Tensor& var, const s11n::TensorAllocator& allocator = {});
-inline void write_any(std::ostream& stream, const ov::Any& var) {
- write(stream, var);
-}
+} // namespace orc
-inline void read_any(std::istream& stream, ov::Any& var) {
- read(stream, var);
-}
+// Reopen s11n for weightless helpers that need the orc declarations above.
+namespace s11n {
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);
+ orc::serialize_weightless(stream_io, mutable_var, ctx);
}
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);
-}
-
-// Serialization
-template <typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>
-void serialize(Stream& stream, T& var) {
- stream.bytes(&var, sizeof var);
+ orc::serialize_weightless(stream_io, var, ctx);
}
-template <typename T1, typename T2>
-void serialize(Stream& stream, std::pair<T1, T2>& var) {
- stream & var.first & var.second;
-}
-
-template <typename T>
-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, size_t N>
-void serialize(Stream& stream, std::array<T, N>& var) {
- for (auto& el : var) {
- stream & el;
- }
-}
-
-template <typename T>
-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 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 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 serialize(Stream& stream, std::optional<T>& var) {
- bool has_value = var.has_value();
- stream & has_value;
- if (has_value) {
- 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 9823a467ae9..f93760220ad 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp
@@ -196,7 +196,7 @@ bool Bank::is_remote(int64_t uid) const {
return false;
}
-void Bank::serialize(ov::npuw::s11n::Stream& stream) {
+void Bank::serialize(ov::npuw::orc::Stream& stream) {
LOG_INFO("Serializing weights bank...");
LOG_BLOCK();
@@ -226,7 +226,7 @@ void Bank::serialize(ov::npuw::s11n::Stream& stream) {
LOG_INFO("DONE.");
}
-void Bank::read_and_add_tensor(ov::npuw::s11n::Stream& stream, int64_t uid, const std::string& device) {
+void Bank::read_and_add_tensor(ov::npuw::orc::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);
@@ -261,7 +261,7 @@ std::string Bank::get_name() const {
return m_bank_name;
}
-void ov::npuw::s11n::serialize(Stream& stream, ov::npuw::weights::Bank& var) {
+void ov::npuw::orc::serialize(Stream& stream, ov::npuw::weights::Bank& var) {
if (stream.output()) {
var.serialize(stream);
} else {
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 2375b644565..3f8f69876ab 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/weights_bank.hpp
@@ -15,6 +15,8 @@
#include "openvino/runtime/iremote_context.hpp"
#include "openvino/runtime/make_tensor.hpp"
#include "openvino/runtime/tensor.hpp"
+#include "orc.hpp"
+#include "orc/schema_npuw.hpp"
namespace ov {
namespace npuw {
@@ -25,6 +27,12 @@ namespace weights {
class Bank {
public:
+ static constexpr ov::npuw::orc::TypeId kOrcType =
+ static_cast<ov::npuw::orc::TypeId>(ov::npuw::orc::schema_npuw::WeightsBank::ID);
+ // Version 0 is the frozen baseline on the wire. Any further layout changes
+ // must be introduced through a new versioned payload rather than by mutating v0.
+ static constexpr ov::npuw::orc::Version kOrcVersion = 0u;
+
Bank(const std::shared_ptr<const ov::ICore>& core, const std::string& alloc_device, const std::string& bank_name);
// Register LazyTensor in a bank if it's not there. Returns LazyTensor's unique id
@@ -43,7 +51,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);
+ friend void ov::npuw::orc::serialize(ov::npuw::orc::Stream& stream, ov::npuw::weights::Bank& var);
struct StoredTensor {
LazyTensor lt;
@@ -61,8 +69,8 @@ private:
const std::vector<LazyTensor>& to_process,
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);
+ void serialize(ov::npuw::orc::Stream& stream);
+ void read_and_add_tensor(ov::npuw::orc::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/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index c11b00d1ad8..4c245cad106 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -21,6 +21,7 @@
#include "metrics.hpp"
#include "npuw/compiled_model.hpp"
#include "npuw/llm_compiled_model.hpp"
+#include "npuw/orc/schema_npuw.hpp"
#include "npuw/serialization.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
#include "openvino/op/constant.hpp"
@@ -148,26 +149,35 @@ void check_weightless_cache_attribute_occurrence(const std::shared_ptr<const ov:
std::shared_ptr<ov::ICompiledModel> import_model_npuw(std::istream& stream,
ov::AnyMap& properties,
std::shared_ptr<const ov::IPlugin> pluginSO) {
+ if (const auto header = ov::npuw::orc::is_orc(stream);
+ header.has_value() &&
+ header->schema_uuid == ov::npuw::orc::schema_npuw::NPUW_ORC_PARTITIONED_SCHEMA) {
+ return ov::npuw::CompiledModel::import_model(stream, pluginSO, properties);
+ }
+
// If was exported via NPUW
auto stream_start_pos = stream.tellg();
ov::npuw::s11n::IndicatorType serialization_indicator;
- ov::npuw::s11n::read(stream, serialization_indicator);
- if (serialization_indicator == NPUW_SERIALIZATION_INDICATOR) {
+ if (ov::npuw::orc::try_read_bytes(stream, serialization_indicator.data(), serialization_indicator.size()) &&
+ serialization_indicator == NPUW_SERIALIZATION_INDICATOR) {
ov::npuw::s11n::IndicatorType compiled_model_indicator;
- ov::npuw::s11n::read(stream, compiled_model_indicator);
- stream.seekg(-stream.tellg() + stream_start_pos, std::ios::cur);
-
- if (compiled_model_indicator == NPUW_LLM_COMPILED_MODEL_INDICATOR) {
- // Properties are required for ov::weights_path
- return ov::npuw::LLMCompiledModel::import_model(stream, pluginSO, properties);
- } else if (compiled_model_indicator == NPUW_COMPILED_MODEL_INDICATOR) {
- // Properties are required for ov::weights_path
- return ov::npuw::CompiledModel::import_model(stream, pluginSO, properties);
- } else {
- OPENVINO_THROW("Couldn't deserialize NPUW blob - fatal error!");
+ if (ov::npuw::orc::try_read_bytes(stream, compiled_model_indicator.data(), compiled_model_indicator.size())) {
+ stream.clear();
+ stream.seekg(stream_start_pos);
+
+ if (compiled_model_indicator == NPUW_LLM_COMPILED_MODEL_INDICATOR) {
+ // Properties are required for ov::weights_path
+ return ov::npuw::LLMCompiledModel::import_model(stream, pluginSO, properties);
+ } else if (compiled_model_indicator == NPUW_COMPILED_MODEL_INDICATOR) {
+ OPENVINO_THROW("Legacy flat NPUW CompiledModel blobs are no longer supported. Re-export the model with "
+ "the current ORC serializer.");
+ } else {
+ OPENVINO_THROW("Couldn't deserialize NPUW blob - fatal error!");
+ }
}
}
- stream.seekg(-stream.tellg() + stream_start_pos, std::ios::cur);
+ stream.clear();
+ stream.seekg(stream_start_pos);
// Drop NPUW properties if there are any
for (auto it = properties.begin(); it != properties.end(); ++it) {
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/serialization.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/serialization.cpp
index 1c80b96f5c3..0aac43f513d 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/serialization.cpp
@@ -4,11 +4,106 @@
#include <gtest/gtest.h>
+#include <map>
+
#include "npuw/test_engine/models/model_builder.hpp"
#include "openvino/core/parallel.hpp"
+#include "openvino/pass/stateful_to_stateless.hpp"
+using ov::test::npuw::LLMConfig;
using ov::test::npuw::ModelBuilder;
+namespace {
+
+LLMConfig make_llm_config() {
+ LLMConfig cfg;
+ cfg.num_layers = 2;
+ cfg.hidden_size = 64;
+ cfg.num_heads = 4;
+ cfg.head_dim = 16;
+ cfg.num_kv_heads = 4;
+ cfg.vocab_size = 256;
+ return cfg;
+}
+
+std::shared_ptr<ov::Model> build_chunked_prefill_model() {
+ auto cfg = make_llm_config();
+ cfg.num_kv_heads = 2;
+ cfg.force_gqa_broadcast = true;
+
+ ModelBuilder mb;
+ auto model = mb.build_llm(cfg);
+ ov::pass::StatefulToStateless().run_on_model(model);
+ model = model->clone();
+
+ constexpr std::size_t kSeq = 8;
+ constexpr std::size_t kPast = 8;
+
+ std::map<std::string, ov::PartialShape> new_shapes;
+ for (const auto& input : model->inputs()) {
+ const auto& name = input.get_any_name();
+ auto pshape = input.get_partial_shape();
+ const auto rank = pshape.rank();
+
+ if (name.find("input_ids") != std::string::npos || name.find("token_type_ids") != std::string::npos) {
+ new_shapes[name] = ov::PartialShape{1, kSeq};
+ } else if (name.find("inputs_embeds") != std::string::npos && rank.is_static() && rank.get_length() == 3) {
+ new_shapes[name] = ov::PartialShape{1, kSeq, pshape[2]};
+ } else if (name.find("attention_mask") != std::string::npos) {
+ new_shapes[name] = ov::PartialShape{1, kSeq + kPast};
+ } else if (name.find("position_ids") != std::string::npos) {
+ new_shapes[name] =
+ rank.get_length() == 3 ? ov::PartialShape{3, 1, kSeq} : ov::PartialShape{1, kSeq};
+ } else if (name.find("beam_idx") != std::string::npos) {
+ new_shapes[name] = ov::PartialShape{1};
+ } else if (rank.is_static() && rank.get_length() > 2) {
+ pshape[0] = 1;
+ pshape[2] = kPast;
+ new_shapes[name] = pshape;
+ } else {
+ new_shapes[name] = pshape;
+ }
+ }
+
+ model->reshape(new_shapes);
+ model->validate_nodes_and_infer_types();
+ return model;
+}
+
+ov::AnyMap make_phase0_decode_npu_opts() {
+ return {
+ {"NPU_USE_NPUW", "YES"},
+ {"NPUW_DEVICES", "NPU"},
+ {"NPUW_WEIGHTS_BANK", "shared"},
+ {"NPUW_FUNCALL_FOR_ALL", "YES"},
+ {"NPUW_CWAI", "YES"},
+ {"NPUW_ONLINE_PIPELINE", "NONE"},
+ {"NPU_COMPILER_DYNAMIC_QUANTIZATION", "YES"},
+ };
+}
+
+ov::AnyMap make_phase0_base_config() {
+ auto config = make_phase0_decode_npu_opts();
+ config["NPUW_ENSURE_COMPATIBILITY"] = "YES";
+ return config;
+}
+
+ov::AnyMap make_phase0_cpu_subgraph_config() {
+ auto config = make_phase0_base_config();
+ config["NPUW_DEVICES"] = "NPU,CPU";
+ config["NPUW_SUBMODEL_DEVICE"] = "0:CPU";
+ return config;
+}
+
+void skip_if_no_npu(ov::Core& core) {
+ const auto devices = core.get_available_devices();
+ if (std::find(devices.begin(), devices.end(), "NPU") == devices.end()) {
+ GTEST_SKIP() << "No available devices.";
+ }
+}
+
+} // namespace
+
// FIXME: parametrize all the tests below
TEST(SerializationTestNPUW, Stress_ParallelImport) {
@@ -79,3 +174,28 @@ TEST(SerializationTestNPUW, Stress_ParallelImport) {
}
}
}
+
+TEST(SerializationTestNPUW, CompiledModelPhase0CompatibilityExportSucceedsWithStaticAttention) {
+ ov::Core ov_core;
+ skip_if_no_npu(ov_core);
+
+ auto compiled = ov_core.compile_model(build_chunked_prefill_model(), "NPU", make_phase0_base_config());
+ std::stringstream blob;
+ EXPECT_NO_THROW(compiled.export_model(blob));
+}
+
+TEST(SerializationTestNPUW, CompiledModelPhase0CompatibilityRejectsCpuPinnedSubgraphExport) {
+ ov::Core ov_core;
+ skip_if_no_npu(ov_core);
+
+ auto compiled = ov_core.compile_model(build_chunked_prefill_model(), "NPU", make_phase0_cpu_subgraph_config());
+ std::stringstream blob;
+
+ try {
+ compiled.export_model(blob);
+ FAIL() << "Expected phase-0 compatibility export to reject a CPU-pinned subgraph";
+ } catch (const ov::Exception& ex) {
+ EXPECT_NE(std::string(ex.what()).find("device \"CPU\""), std::string::npos) << ex.what();
+ }
+}
+
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 1a2b3544442..9e3d7c3d37c 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,8 @@
#include "intel_npu/config/npuw.hpp"
#include "model_builder.hpp"
#include "openvino/openvino.hpp"
+#include "openvino/util/codec_xor.hpp"
+#include "orc.hpp"
#include "serialization.hpp"
using ov::test::npuw::ModelBuilder;
@@ -24,6 +26,10 @@ public:
}
protected:
+ static ov::EncryptionCallbacks xor_callbacks() {
+ return {ov::util::codec_xor, ov::util::codec_xor};
+ }
+
static ov::Tensor make_input_tensor(const ov::Output<const ov::Node>& input) {
ov::Tensor tensor(input.get_element_type(), input.get_shape());
@@ -98,6 +104,7 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeed) {
std::stringstream blob;
compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
EXPECT_NO_THROW({
auto imported = m_core.import_model(blob, "NPU", m_props);
@@ -106,6 +113,65 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeed) {
});
}
+TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeedEncrypted) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SPEED";
+ m_props[ov::cache_encryption_callbacks.name()] = xor_callbacks();
+
+ 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_TRUE(ov::npuw::orc::is_orc(blob).has_value());
+
+ EXPECT_NO_THROW({
+ auto imported = m_core.import_model(blob, "NPU", m_props);
+ auto imported_outputs = infer_outputs(imported);
+ expect_outputs_equal(compiled_outputs, imported_outputs);
+ });
+}
+
+TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeedEncryptedRequiresDecryptCallback) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SPEED";
+ m_props[ov::cache_encryption_callbacks.name()] = ov::EncryptionCallbacks{ov::util::codec_xor, nullptr};
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+
+ std::stringstream blob;
+ compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
+
+ auto import_props = m_props;
+ import_props.erase(ov::cache_encryption_callbacks.name());
+ try {
+ auto imported = m_core.import_model(blob, "NPU", import_props);
+ (void)imported;
+ FAIL() << "Expected encrypted ORC import to require a decrypt callback";
+ } catch (const ov::Exception& ex) {
+ EXPECT_NE(std::string(ex.what()).find("Blob is encrypted, but no decryption callback was provided"),
+ std::string::npos)
+ << ex.what();
+ }
+}
+
+TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSpeedEnsureCompatibility) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SPEED";
+ m_props["NPUW_ENSURE_COMPATIBILITY"] = "YES";
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ std::stringstream blob;
+ // This synthetic repeated-block model does not satisfy the phase-0 compatibility contract:
+ // even with NPU-only placement it still exercises non-versioned behavior-owned state today,
+ // so ENSURE_COMPATIBILITY is expected to reject export rather than produce a misleading blob.
+ EXPECT_THROW(compiled.export_model(blob), ov::Exception);
+}
+
TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtr) {
ov::AnyMap wai_props = GetParam();
m_props.insert(wai_props.begin(), wai_props.end());
@@ -116,6 +182,7 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtr) {
std::stringstream blob;
compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
EXPECT_NO_THROW({
auto import_props = m_props;
@@ -126,6 +193,47 @@ TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtr) {
});
}
+TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtrEncryptedDifferentDecryptSize) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
+ m_props[ov::cache_encryption_callbacks.name()] =
+ ov::EncryptionCallbacks{[](const std::string& unencrypted_blob) {
+ std::string copy_blob = unencrypted_blob;
+ copy_blob += "<encrypt-tail>";
+ return ov::util::codec_xor(copy_blob);
+ },
+ [](const std::string& encrypted_blob) {
+ std::string decrypted_blob = ov::util::codec_xor(encrypted_blob);
+ decrypted_blob += "<decrypt-tail>";
+ return decrypted_blob;
+ }};
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+
+ std::stringstream blob;
+ compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
+
+ auto import_props = m_props;
+ import_props[ov::hint::model.name()] = std::static_pointer_cast<const ov::Model>(m_ov_model);
+ EXPECT_NO_THROW({
+ auto imported = m_core.import_model(blob, "NPU", import_props);
+ (void)imported;
+ });
+}
+
+TEST_P(ImportNonLLMBlobTestNPUW, CacheModeOptimizeSizeWithModelPtrEnsureCompatibility) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
+ m_props["NPUW_ENSURE_COMPATIBILITY"] = "YES";
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ std::stringstream blob;
+ EXPECT_THROW(compiled.export_model(blob), ov::Exception);
+}
+
using ImportNonLLMNonWAIBlobTestNPUW = ImportNonLLMBlobTestNPUW;
TEST_P(ImportNonLLMNonWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
ov::AnyMap wai_props = GetParam();
@@ -137,6 +245,7 @@ TEST_P(ImportNonLLMNonWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
std::stringstream blob;
compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
EXPECT_NO_THROW({
auto imported = m_core.import_model(blob, "NPU", m_props);
@@ -145,6 +254,17 @@ TEST_P(ImportNonLLMNonWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
});
}
+TEST_P(ImportNonLLMNonWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtrEnsureCompatibility) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
+ m_props["NPUW_ENSURE_COMPATIBILITY"] = "YES";
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+ std::stringstream blob;
+ EXPECT_THROW(compiled.export_model(blob), ov::Exception);
+}
+
using ImportNonLLMWAIBlobTestNPUW = ImportNonLLMBlobTestNPUW;
TEST_P(ImportNonLLMWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
ov::AnyMap wai_props = GetParam();
@@ -155,27 +275,38 @@ TEST_P(ImportNonLLMWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtr) {
std::stringstream blob;
compiled.export_model(blob);
+ EXPECT_TRUE(ov::npuw::orc::is_orc(blob).has_value());
try {
auto imported = m_core.import_model(blob, "NPU", m_props);
FAIL() << "Expected import to throw when WAI weightless blob is imported without MODEL_PTR/WEIGHTS_PATH";
} catch (const ov::Exception& ex) {
const std::string what = ex.what();
- const bool has_expected_text =
- what.find("Blob is weightless") != std::string::npos &&
- what.find("WEIGHTS_PATH") != std::string::npos &&
- what.find("MODEL_PTR") != std::string::npos;
+ const bool has_expected_text = what.find("Blob is weightless") != std::string::npos &&
+ what.find("WEIGHTS_PATH") != std::string::npos &&
+ what.find("MODEL_PTR") != std::string::npos;
EXPECT_TRUE(has_expected_text) << "Unexpected exception message: " << what;
}
}
-INSTANTIATE_TEST_SUITE_P(Only_NPU_USE_NPUW, ImportNonLLMBlobTestNPUW,
- testing::Values(ov::AnyMap{}));
-INSTANTIATE_TEST_SUITE_P(NPUW_FOLD, ImportNonLLMBlobTestNPUW,
- testing::Values(ov::AnyMap{{"NPUW_FOLD", "YES"}}));
-INSTANTIATE_TEST_SUITE_P(NPUW_CWAI, ImportNonLLMBlobTestNPUW,
- testing::Values(ov::AnyMap{{"NPUW_CWAI", "YES"}}));
-
-INSTANTIATE_TEST_SUITE_P(NPUW_NON_WAI, ImportNonLLMNonWAIBlobTestNPUW,
- testing::Values(ov::AnyMap{}, ov::AnyMap{{"NPUW_FUNCALL_FOR_ALL", "YES"}}));
-INSTANTIATE_TEST_SUITE_P(NPUW_WAI, ImportNonLLMWAIBlobTestNPUW,
- testing::Values(ov::AnyMap{{"NPUW_FOLD", "YES"}}, ov::AnyMap{{"NPUW_CWAI", "YES"}}));
+TEST_P(ImportNonLLMWAIBlobTestNPUW, CacheModeOptimizeSizeNoModelPtrEnsureCompatibility) {
+ ov::AnyMap wai_props = GetParam();
+ m_props.insert(wai_props.begin(), wai_props.end());
+ m_props["CACHE_MODE"] = "OPTIMIZE_SIZE";
+ m_props["NPUW_ENSURE_COMPATIBILITY"] = "YES";
+
+ auto compiled = m_core.compile_model(m_ov_model, "NPU", m_props);
+
+ std::stringstream blob;
+ EXPECT_THROW(compiled.export_model(blob), ov::Exception);
+}
+
+INSTANTIATE_TEST_SUITE_P(Only_NPU_USE_NPUW, ImportNonLLMBlobTestNPUW, testing::Values(ov::AnyMap{}));
+INSTANTIATE_TEST_SUITE_P(NPUW_FOLD, ImportNonLLMBlobTestNPUW, testing::Values(ov::AnyMap{{"NPUW_FOLD", "YES"}}));
+INSTANTIATE_TEST_SUITE_P(NPUW_CWAI, ImportNonLLMBlobTestNPUW, testing::Values(ov::AnyMap{{"NPUW_CWAI", "YES"}}));
+
+INSTANTIATE_TEST_SUITE_P(NPUW_NON_WAI,
+ ImportNonLLMNonWAIBlobTestNPUW,
+ testing::Values(ov::AnyMap{}, ov::AnyMap{{"NPUW_FUNCALL_FOR_ALL", "YES"}}));
+INSTANTIATE_TEST_SUITE_P(NPUW_WAI,
+ ImportNonLLMWAIBlobTestNPUW,
+ testing::Values(ov::AnyMap{{"NPUW_FOLD", "YES"}}, ov::AnyMap{{"NPUW_CWAI", "YES"}}));
diff --git a/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
index fc998213569..f5244939d39 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/npuw_options_smoke_test.cpp
@@ -121,6 +121,7 @@ std::vector<Case> make_cases() {
bool_case<::intel_npu::NPUW_ATTN_NO_COPY>("NPUW_ATTN_NO_COPY", "YES", true),
bool_case<::intel_npu::NPUW_ATTN_HFA_FUSED>("NPUW_ATTN_HFA_FUSED", "YES", true),
bool_case<::intel_npu::NPUW_PARALLEL_COMPILE>("NPUW_PARALLEL_COMPILE", "YES", true),
+ bool_case<::intel_npu::NPUW_ENSURE_COMPATIBILITY>("NPUW_ENSURE_COMPATIBILITY", "YES", true),
bool_case<::intel_npu::NPUW_FUNCALL_ASYNC>("NPUW_FUNCALL_ASYNC", "YES", true),
bool_case<::intel_npu::NPUW_UNFOLD_IREQS>("NPUW_UNFOLD_IREQS", "YES", true),
bool_case<::intel_npu::NPUW_FALLBACK_EXEC>("NPUW_FALLBACK_EXEC", "NO", false),
diff --git a/src/plugins/intel_npu/tests/unit/npuw/orc.cpp b/src/plugins/intel_npu/tests/unit/npuw/orc.cpp
index 295bd650595..c17a3dafa02 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/orc.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/orc.cpp
@@ -15,17 +15,15 @@ namespace {
using namespace ov::npuw::orc;
// Small sequential TypeIds that fit in u16.
-constexpr TypeId TYPE_NCMD = 0x0001u;
-constexpr TypeId TYPE_META = 0x0002u;
-constexpr TypeId TYPE_PART = 0x0003u;
-constexpr TypeId TYPE_WGHT = 0x0004u;
-constexpr TypeId TYPE_TEST = 0x0005u;
+constexpr TypeId TYPE_NCMD = 0x0001u;
+constexpr TypeId TYPE_META = 0x0002u;
+constexpr TypeId TYPE_PART = 0x0003u;
+constexpr TypeId TYPE_WGHT = 0x0004u;
+constexpr TypeId TYPE_TEST = 0x0005u;
constexpr TypeId TYPE_UNKNOWN = 0xFFFFu;
-const SchemaUUID TEST_UUID = {
- 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
- 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10
-};
+const SchemaUUID TEST_UUID =
+ {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10};
struct BlobSummary {
std::uint32_t subgraph_count = 0u;
@@ -74,6 +72,17 @@ void expect_blob_summary(const BlobSummary& expected, const BlobSummary& actual)
EXPECT_EQ(expected.devices, actual.devices);
}
+struct CounterMeta {
+ static constexpr Version kVersion = 0u;
+ std::uint32_t value = 0u;
+
+ // Tiny fixed payload used to prove that scoped sections can stream inline metadata
+ // before nested ORC children without going through the higher-level Section tree API.
+ void serialize(Stream& stream) {
+ stream & value;
+ }
+};
+
} // namespace
TEST(OrcTest, FileRoundTripsNestedSections) {
@@ -81,13 +90,12 @@ TEST(OrcTest, FileRoundTripsNestedSections) {
const BlobSummary part{7u, {"prefill", "decode"}};
const BlobSummary wght{1u, {"lazy"}};
- const auto root = Section::container(TYPE_NCMD,
- 1u,
- {make_payload_section(TYPE_META, 1u, meta),
- Section::container(TYPE_PART,
- 1u,
- {make_payload_section(TYPE_TEST, 1u, part)}),
- make_payload_section(TYPE_WGHT, 1u, wght)});
+ const auto root =
+ Section::container(TYPE_NCMD,
+ 1u,
+ {make_payload_section(TYPE_META, 1u, meta),
+ Section::container(TYPE_PART, 1u, {make_payload_section(TYPE_TEST, 1u, part)}),
+ make_payload_section(TYPE_WGHT, 1u, wght)});
std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
write_file(buffer, root, TEST_UUID);
@@ -109,7 +117,8 @@ TEST(OrcTest, FileRoundTripsNestedSections) {
}
TEST(OrcTest, RejectsTruncatedFile) {
- const auto root = Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{3u, {"NPU"}})});
+ const auto root =
+ Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{3u, {"NPU"}})});
std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
write_file(buffer, root, TEST_UUID);
@@ -122,8 +131,43 @@ TEST(OrcTest, RejectsTruncatedFile) {
EXPECT_THROW(read_file(truncated), ov::Exception);
}
+TEST(OrcTest, ScopedSectionsRoundTripMetadataBeforeChildren) {
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ write_file_header(buffer, TEST_UUID);
+ with_section(buffer, TYPE_NCMD, CounterMeta::kVersion, 0u, [&] {
+ auto root_stream = Stream::writer(buffer);
+ CounterMeta root_meta{2u};
+ root_stream & root_meta;
+
+ with_section(buffer, TYPE_TEST, CounterMeta::kVersion, 0u, [&] {
+ auto child_stream = Stream::writer(buffer);
+ CounterMeta child_meta{7u};
+ child_stream & child_meta;
+ });
+ });
+
+ EXPECT_EQ(read_file_header(buffer).schema_uuid, TEST_UUID);
+
+ ScopedReadSection root(buffer);
+ EXPECT_EQ(root.header().type, TYPE_NCMD);
+ auto root_stream = Stream::reader(buffer);
+ CounterMeta root_meta;
+ root_stream & root_meta;
+ EXPECT_EQ(root_meta.value, 2u);
+
+ ScopedReadSection child(buffer);
+ EXPECT_EQ(child.header().type, TYPE_TEST);
+ auto child_stream = Stream::reader(buffer);
+ CounterMeta child_meta;
+ child_stream & child_meta;
+ EXPECT_EQ(child_meta.value, 7u);
+ child.expect_end();
+ root.expect_end();
+}
+
TEST(OrcTest, IsOrcReturnsTrueForValidBlob) {
- const auto root = Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{1u, {"NPU"}})});
+ const auto root =
+ Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{1u, {"NPU"}})});
std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
write_file(buffer, root, TEST_UUID);
@@ -131,7 +175,7 @@ TEST(OrcTest, IsOrcReturnsTrueForValidBlob) {
// is_orc must return a header and leave the stream at its original position
const auto header = is_orc(buffer);
ASSERT_TRUE(header.has_value());
- EXPECT_EQ(header->version, 1u);
+ EXPECT_EQ(header->version, 0u);
EXPECT_EQ(header->schema_uuid, TEST_UUID);
// read_file must still work after the probe
EXPECT_NO_THROW(read_file(buffer));
@@ -142,6 +186,21 @@ TEST(OrcTest, IsOrcReturnsFalseForGarbage) {
EXPECT_FALSE(is_orc(buffer).has_value());
}
+TEST(OrcTest, TryReadBytesAdvancesOnSuccessAndRollsBackOnFailure) {
+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);
+ buffer.write("abcdef", 6);
+
+ std::array<char, 3> prefix{};
+ EXPECT_TRUE(try_read_bytes(buffer, prefix.data(), prefix.size()));
+ EXPECT_EQ(std::string(prefix.data(), prefix.size()), "abc");
+ EXPECT_EQ(buffer.tellg(), std::streampos{3});
+
+ std::array<char, 8> oversized{};
+ const auto pos_before_failure = buffer.tellg();
+ EXPECT_FALSE(try_read_bytes(buffer, oversized.data(), oversized.size()));
+ EXPECT_EQ(buffer.tellg(), pos_before_failure);
+}
+
TEST(OrcTest, SchemaSkipsUnknownOptionalChildren) {
const auto root = Section::container(TYPE_NCMD,
1u,
@@ -215,7 +274,8 @@ TEST(OrcTest, LoadVersionedPayloadMigratesAcrossVersions) {
return load_versioned_payload<MetaV3, MetaV1, MetaV2, MetaV3>(section);
});
- const auto meta_v1 = schema.load<MetaV3>(make_payload_section(TYPE_META, MetaV1::kVersion, MetaV1{3u, {"NPU", "CPU"}}));
+ const auto meta_v1 =
+ schema.load<MetaV3>(make_payload_section(TYPE_META, MetaV1::kVersion, MetaV1{3u, {"NPU", "CPU"}}));
EXPECT_EQ(meta_v1.subgraph_count, 3u);
EXPECT_EQ(meta_v1.devices, (std::vector<std::string>{"NPU", "CPU"}));
EXPECT_FALSE(meta_v1.weightless);