OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[HETERO] Add HSM support in Hetero Plugin (#39341)
Pawel Raaszd955a2b5c3c0
diff --git a/src/common/util/include/openvino/util/memory.hpp b/src/common/util/include/openvino/util/memory.hppindex f8b77e27815..1b33be974f0 100644--- a/src/common/util/include/openvino/util/memory.hpp+++ b/src/common/util/include/openvino/util/memory.hpp@@ -8,6 +8,7 @@#include <cstdint>#include <cstdlib>#include <future>+#include <iterator>#include <limits>#include <memory>#include <optional>@@ -172,11 +173,33 @@ private:size_t m_size = 0;};-/** @brief Non-owning byte view of @p value's object representation; @p value must outlive the view. */+/** @brief True for types with std::data() and std::size() (containers, arrays). */+template <typename T, typename = void>+struct IsContiguousRange : std::false_type {};++template <typename T>+struct IsContiguousRange<+ T,+ std::void_t<decltype(std::data(std::declval<const T&>())), decltype(std::size(std::declval<const T&>()))>>+ : std::true_type {};++/**+ * @brief Non-owning byte view of @p value; @p value must outlive the view.+ *+ * A contiguous container (std::string, std::vector, std::array, C array) is viewed by its elements,+ * any other trivially copyable type by its object representation.+ */template <typename T>MemoryView as_memory_view(const T& value) noexcept {- static_assert(std::is_trivially_copyable_v<T>, "as_memory_view requires a trivially copyable type");- return {reinterpret_cast<const std::byte*>(std::addressof(value)), sizeof(T)};+ if constexpr (IsContiguousRange<T>::value) {+ using element_type = std::remove_cv_t<std::remove_pointer_t<decltype(std::data(value))>>;+ static_assert(std::is_trivially_copyable_v<element_type>,+ "as_memory_view requires trivially copyable elements");+ return {reinterpret_cast<const std::byte*>(std::data(value)), std::size(value) * sizeof(element_type)};+ } else {+ static_assert(std::is_trivially_copyable_v<T>, "as_memory_view requires a trivially copyable type");+ return {reinterpret_cast<const std::byte*>(std::addressof(value)), sizeof(T)};+ }}template <typename T, std::enable_if_t<!std::is_lvalue_reference_v<T>>* = nullptr>diff --git a/src/plugins/hetero/CMakeLists.txt b/src/plugins/hetero/CMakeLists.txtindex 7d886d57659..848c20be202 100644--- a/src/plugins/hetero/CMakeLists.txt+++ b/src/plugins/hetero/CMakeLists.txt@@ -14,6 +14,8 @@ set(SOURCES${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/config.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/graph_debug_dump.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/hsm_reader_handler.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/hsm_writer_handler.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/op/device_subgraph.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/plugin.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/remote_context.cpp@@ -28,6 +30,9 @@ set(HEADERS${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/config.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/graph_debug_dump.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/hsm_common.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/hsm_reader_handler.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/hsm_writer_handler.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/itt.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/op/device_subgraph.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/perf_log.hppdiff --git a/src/plugins/hetero/src/blob_serialization.cpp b/src/plugins/hetero/src/blob_serialization.cppindex c75b2993b11..5306af9e937 100644--- a/src/plugins/hetero/src/blob_serialization.cpp+++ b/src/plugins/hetero/src/blob_serialization.cpp@@ -496,20 +496,21 @@ void write_ir_payload(std::ostream& model_stream, const std::shared_ptr<ov::ModeOPENVINO_THROW("OpenVINO Model is empty");}- std::stringstream xmlFile, binFile;- ov::pass::Serialize serializer(xmlFile, binFile);+ std::stringstream xml_file, bin_file;+ ov::pass::Serialize serializer(xml_file, bin_file);serializer.run_on_model(model);- auto constants = binFile.str();- auto model_str = xmlFile.str();-- auto dataSize = static_cast<std::uint64_t>(model_str.size());- write_size(model_stream, dataSize, "IR XML size");- write_bytes(model_stream, model_str.data(), dataSize, "IR XML content");-- dataSize = static_cast<std::uint64_t>(constants.size());- write_size(model_stream, dataSize, "IR weights size");- write_bytes(model_stream, constants.data(), dataSize, "IR weights content");+ // The serialized parts are streamed out of their buffers instead of being copied into strings first.+ const auto write_part = [&model_stream](std::stringstream& part, const char* size_name, const char* content_name) {+ const auto data_size = static_cast<std::uint64_t>(part.tellp());+ write_size(model_stream, data_size, size_name);+ if (data_size > 0) {+ model_stream << part.rdbuf();+ }+ OPENVINO_ASSERT(model_stream, "Failed to write HETERO compiled blob ", content_name);+ };+ write_part(xml_file, "IR XML size", "IR XML content");+ write_part(bin_file, "IR weights size", "IR weights content");}} // namespace ov::heterodiff --git a/src/plugins/hetero/src/compiled_model.cpp b/src/plugins/hetero/src/compiled_model.cppindex c46bea974d3..f0689681873 100644--- a/src/plugins/hetero/src/compiled_model.cpp+++ b/src/plugins/hetero/src/compiled_model.cpp@@ -9,26 +9,86 @@#include <cstdint>#include <limits>#include <memory>+#include <optional>#include <sstream>#include <string>#include "async_infer_request.hpp"#include "blob_serialization.hpp"#include "graph_debug_dump.hpp"+#include "hsm_writer_handler.hpp"#include "itt.hpp"#include "op/device_subgraph.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/pass/constant_folding.hpp"#include "openvino/pass/manager.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/properties.hpp"+#include "openvino/runtime/shared_buffer.hpp"#include "openvino/util/common_util.hpp"+#include "openvino/util/container_util.hpp"#include "openvino/util/xml_parse_utils.hpp"#include "perf_log.hpp"#include "properties.hpp"namespace {+// Core hands a mapped blob to the devices that report caching_with_mmap, which is also how a tensor import is+// advertised.+bool device_imports_tensor(const std::shared_ptr<ov::ICore>& core, const std::string& device) {+ return ov::util::contains(core->get_property(device, ov::internal::supported_properties),+ ov::internal::caching_with_mmap);+}++// Like a legacy blob read, an import leaves the stream right after the blob.+// The header was validated by the reader.+void seek_to_container_end(std::istream& stream, std::streampos start) {+ ov::runtime::hsm::Header header{};+ stream.clear();+ stream.seekg(start);+ stream.read(reinterpret_cast<char*>(&header), sizeof(header));+ stream.seekg(start + static_cast<std::streamoff>(header.container_size));+}++bool starts_with_hsm_magic(const std::string& text) {+ const auto& magic = ov::runtime::hsm::BlobMagic::single.value;+ return text.size() >= magic.size() &&+ std::equal(magic.begin(), magic.end(), text.begin(), [](uint8_t expected, char actual) {+ return expected == static_cast<uint8_t>(actual);+ });+}++ov::SoPtr<ov::ICompiledModel> import_submodel_blob(const std::shared_ptr<ov::ICore>& core,+ const std::string& device,+ const ov::AnyMap& load_config,+ const ov::hetero::HsmLocatedSection& located,+ const ov::hetero::HsmBlobSource& source) {+ if (source.stream != nullptr) {+ auto& stream = *source.stream;+ stream.clear();+ stream.seekg(source.start + static_cast<std::streamoff>(located.entry.offset));+ OPENVINO_ASSERT(stream, "Failed to seek to a HETERO compiled submodel section");+ ov::hetero::BoundedStreamBuffer buffer{stream, located.entry.size};+ std::istream payload{&buffer};+ auto compiled_model = core->import_model(payload, device, load_config);+ // The sub-device may leave the shared stream in a failed state; other sections are read next.+ stream.clear();+ return compiled_model;+ }++ const auto view = located.section.view();+ OPENVINO_ASSERT(!view.empty(), "HETERO compiled submodel section is empty");+ if (source.tensor.get_element_type() == ov::element::u8 && source.tensor.get_shape().size() == 1 &&+ device_imports_tensor(core, device)) {+ // A view of the mapped container lets the sub-device keep its weights zero-copy.+ return core->import_model(ov::hetero::read_hsm_tensor(located, source), device, load_config);+ }+ ov::SharedStreamBuffer buffer{view.data(), view.size()};+ std::istream payload{&buffer};+ return core->import_model(payload, device, load_config);+}+class CountingOutputBuffer : public std::streambuf {public:std::uint64_t size() const {@@ -124,6 +184,84 @@ void write_framed_payload_via_seekable_stream(std::ostream& modelStream,ov::hetero::write_framed_payload(modelStream, payloadType, payloadStream, payloadSize);}+ov::hetero::Configuration hetero_read_config(const pugi::xml_node& hetero_node, const ov::hetero::Configuration& base) {+ using namespace ov::util::pugixml;++ ov::AnyMap properties;+ auto hetero_configs_node = hetero_node.child("hetero_config");+ FOREACH_CHILD (hetero_config_node, hetero_configs_node, "config") {+ properties.emplace(get_str_attr(hetero_config_node, "key"), get_str_attr(hetero_config_node, "value"));+ }+ return ov::hetero::Configuration(properties, base);+}++ov::hetero::SubgraphsMappingInfo hetero_read_mapping(const pugi::xml_node& hetero_node) {+ using namespace ov::util::pugixml;++ ov::hetero::SubgraphsMappingInfo mapping_info;+ auto inputs_map_node = hetero_node.child("inputs_to_submodels_inputs");+ FOREACH_CHILD (xml_node, inputs_map_node, "pair") {+ mapping_info._inputs_to_submodels_inputs.emplace_back(get_uint64_attr(xml_node, "submodel_idx"),+ get_uint64_attr(xml_node, "node_idx"));+ }+ auto outputs_map_node = hetero_node.child("outputs_to_submodels_outputs");+ FOREACH_CHILD (xml_node, outputs_map_node, "pair") {+ mapping_info._outputs_to_submodels_outputs.emplace_back(get_uint64_attr(xml_node, "submodel_idx"),+ get_uint64_attr(xml_node, "node_idx"));+ }+ auto submodels_input_to_prev_output_node = hetero_node.child("submodels_input_to_prev_output");+ FOREACH_CHILD (xml_node, submodels_input_to_prev_output_node, "record") {+ std::pair<uint64_t, uint64_t> in_pair = {get_uint64_attr(xml_node, "in_submodel_idx"),+ get_uint64_attr(xml_node, "in_node_idx")};+ std::pair<uint64_t, uint64_t> out_pair = {get_uint64_attr(xml_node, "out_submodel_idx"),+ get_uint64_attr(xml_node, "out_node_idx")};+ mapping_info._submodels_input_to_prev_output.emplace(in_pair, out_pair);+ }+ return mapping_info;+}++// Metadata shared by the legacy and the HSM blob: everything but the name and the legacy format version.+template <typename Submodels>+void hetero_write_metadata(pugi::xml_node& hetero_node,+ const ov::hetero::SubgraphsMappingInfo& mapping_info,+ const Submodels& submodels,+ const ov::hetero::Configuration& cfg) {+ auto inputs_map_node = hetero_node.append_child("inputs_to_submodels_inputs");+ for (const auto& it : mapping_info._inputs_to_submodels_inputs) {+ auto xml_node = inputs_map_node.append_child("pair");+ xml_node.append_attribute("submodel_idx").set_value(std::to_string(it.first).c_str());+ xml_node.append_attribute("node_idx").set_value(std::to_string(it.second).c_str());+ }+ auto outputs_map_node = hetero_node.append_child("outputs_to_submodels_outputs");+ for (const auto& it : mapping_info._outputs_to_submodels_outputs) {+ auto xml_node = outputs_map_node.append_child("pair");+ xml_node.append_attribute("submodel_idx").set_value(std::to_string(it.first).c_str());+ xml_node.append_attribute("node_idx").set_value(std::to_string(it.second).c_str());+ }++ auto submodels_input_to_prev_output_node = hetero_node.append_child("submodels_input_to_prev_output");+ for (const auto& it : mapping_info._submodels_input_to_prev_output) {+ auto xml_node = submodels_input_to_prev_output_node.append_child("record");+ xml_node.append_attribute("in_submodel_idx").set_value(std::to_string(it.first.first).c_str());+ xml_node.append_attribute("in_node_idx").set_value(std::to_string(it.first.second).c_str());+ xml_node.append_attribute("out_submodel_idx").set_value(std::to_string(it.second.first).c_str());+ xml_node.append_attribute("out_node_idx").set_value(std::to_string(it.second.second).c_str());+ }++ auto subnetworksNode = hetero_node.append_child("compiled_submodels");+ for (const auto& submodel : submodels) {+ auto sub_network_node = subnetworksNode.append_child("compiled_submodel");+ sub_network_node.append_attribute("device").set_value(submodel.device.c_str());+ }++ auto heteroConfigsNode = hetero_node.append_child("hetero_config");+ for (const auto& config : cfg.get_hetero_properties()) {+ auto hetero_config_node = heteroConfigsNode.append_child("config");+ hetero_config_node.append_attribute("key").set_value(config.first.c_str());+ hetero_config_node.append_attribute("value").set_value(config.second.as<std::string>().c_str());+ }+}+} // namespaceov::hetero::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,@@ -254,14 +392,33 @@ ov::hetero::CompiledModel::CompiledModel(std::istream& model,m_cfg(cfg),m_name(),m_loaded_from_cache(loaded_from_cache) {+ const auto start = model.tellg();+ if (auto reader = ov::runtime::hsm::Reader::open(model)) {+ import_container(*reader, HsmBlobSource{&model, start, {}});+ seek_to_container_end(model, start);+ return;+ }+ // Not an HSM container: rewind and read the legacy layout. A non-seekable stream was not consumed.+ if (start != std::streampos(-1)) {+ model.clear();+ model.seekg(start);+ }+std::string heteroXmlStr;std::getline(model, heteroXmlStr);pugi::xml_document heteroXmlDoc;pugi::xml_parse_result res = heteroXmlDoc.load_string(heteroXmlStr.c_str());- if (res.status != pugi::status_ok)+ if (res.status != pugi::status_ok) {+ // The legacy parser got an HSM container: the reader rejected it or the stream cannot seek.+ if (starts_with_hsm_magic(heteroXmlStr)) {+ OPENVINO_THROW(start == std::streampos(-1)+ ? "[HETERO] Cannot import an HSM compiled blob from a non-seekable stream."+ : "[HETERO] Cannot import compiled blob: invalid HSM container.");+ }OPENVINO_THROW("Failed to read Hetero device xml header");+ }using namespace ov::util::pugixml;@@ -285,22 +442,13 @@ ov::hetero::CompiledModel::CompiledModel(std::istream& model,}const bool is_framed_blob = blob_format_version == HETERO_BLOB_FORMAT_VERSION;- ov::AnyMap properties;- auto heteroConfigsNode = heteroNode.child("hetero_config");// clang-format off- FOREACH_CHILD(heteroConfigNode, heteroConfigsNode, "config") {- properties.emplace(get_str_attr(heteroConfigNode, "key"), get_str_attr(heteroConfigNode, "value"));- }-- m_cfg = ov::hetero::Configuration(properties, m_cfg);+ m_cfg = hetero_read_config(heteroNode, m_cfg);pugi::xml_node subnetworksNode = heteroNode.child("compiled_submodels");FOREACH_CHILD(subnetworkNode, subnetworksNode, "compiled_submodel") {auto device = get_str_attr(subnetworkNode, "device");-- auto meta_devices = get_hetero_plugin()->get_properties_per_device(device, m_cfg.get_device_properties());- assert(meta_devices.size() == 1);- auto& loadConfig = meta_devices[device];+ auto loadConfig = get_load_config(device);ov::SoPtr<ov::ICompiledModel> compiled_model;std::shared_ptr<ov::Model> ov_model;@@ -348,25 +496,80 @@ ov::hetero::CompiledModel::CompiledModel(std::istream& model,});}- auto inputs_map_node = heteroNode.child("inputs_to_submodels_inputs");- FOREACH_CHILD(xml_node, inputs_map_node, "pair") {- m_mapping_info._inputs_to_submodels_inputs.emplace_back(get_uint64_attr(xml_node, "submodel_idx"),- get_uint64_attr(xml_node, "node_idx"));- }- auto outputs_map_node = heteroNode.child("outputs_to_submodels_outputs");- FOREACH_CHILD(xml_node, outputs_map_node, "pair") {- m_mapping_info._outputs_to_submodels_outputs.emplace_back(get_uint64_attr(xml_node, "submodel_idx"),- get_uint64_attr(xml_node, "node_idx"));+ m_mapping_info = hetero_read_mapping(heteroNode);+ // clang-format on+ set_inputs_and_outputs();+}++ov::hetero::CompiledModel::CompiledModel(const ov::Tensor& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const Configuration& cfg,+ const bool loaded_from_cache)+ : ov::ICompiledModel(nullptr, plugin),+ m_cfg(cfg),+ m_name(),+ m_loaded_from_cache(loaded_from_cache) {+ auto reader = ov::runtime::hsm::Reader::open(static_cast<const std::byte*>(model.data()), model.get_byte_size());+ OPENVINO_ASSERT(reader, "[HETERO] Cannot import compiled blob: invalid HSM container.");+ import_container(*reader, HsmBlobSource{nullptr, {}, model});+}++ov::AnyMap ov::hetero::CompiledModel::get_load_config(const std::string& device) const {+ auto meta_devices = get_hetero_plugin()->get_properties_per_device(device, m_cfg.get_device_properties());+ assert(meta_devices.size() == 1);+ return meta_devices[device];+}++void ov::hetero::CompiledModel::import_container(const ov::runtime::hsm::Reader& reader, const HsmBlobSource& source) {+ using namespace ov::util::pugixml;++ // Before any other section is read: an incompatible blob must be rejected without touching its payload.+ check_hsm_runtime_requirements(reader);++ // Records the sections without reading them, so the structure is validated before any payload is touched.+ HsmReaderHandler handler;+ reader.read_sections({&handler});+ handler.check_structure();++ pugi::xml_document hetero_xml_doc;+ OPENVINO_ASSERT(+ hetero_xml_doc.load_string(read_hsm_string(handler.metadata().section).c_str()).status == pugi::status_ok,+ "Failed to read Hetero device xml header");+ const auto hetero_node = hetero_xml_doc.document_element();+ m_name = get_str_attr(hetero_node, "name");+ m_cfg = hetero_read_config(hetero_node, m_cfg);++ std::vector<std::string> devices;+ const auto sub_networks_node = hetero_node.child("compiled_submodels");+ FOREACH_CHILD (sub_network_node, sub_networks_node, "compiled_submodel") {+ devices.push_back(get_str_attr(sub_network_node, "device"));}- auto submodels_input_to_prev_output_node = heteroNode.child("submodels_input_to_prev_output");- FOREACH_CHILD(xml_node, submodels_input_to_prev_output_node, "record") {- std::pair<uint64_t, uint64_t> in_pair = {get_uint64_attr(xml_node, "in_submodel_idx"),- get_uint64_attr(xml_node, "in_node_idx")};- std::pair<uint64_t, uint64_t> out_pair = {get_uint64_attr(xml_node, "out_submodel_idx"),- get_uint64_attr(xml_node, "out_node_idx")};- m_mapping_info._submodels_input_to_prev_output.emplace(in_pair, out_pair);+ OPENVINO_ASSERT(handler.submodel_count() == devices.size(),+ "[HETERO] Cannot import compiled blob: expected sections of ",+ devices.size(),+ " submodels, found ",+ handler.submodel_count());++ const auto& core = get_hetero_plugin()->get_core();+ for (size_t i = 0; i < devices.size(); ++i) {+ const auto& device = devices[i];+ const auto& sections = handler.submodel(i);+ const auto load_config = get_load_config(device);++ ov::SoPtr<ov::ICompiledModel> compiled_model;+ std::shared_ptr<ov::Model> ov_model;+ if (sections.blob) {+ compiled_model = import_submodel_blob(core, device, load_config, *sections.blob, source);+ } else {+ const auto xml = read_hsm_string(sections.ir_xml->section);+ const auto weights = sections.ir_weights ? read_hsm_tensor(*sections.ir_weights, source) : ov::Tensor{};+ ov_model = core->read_model(xml, weights);+ compiled_model = core->compile_model(ov_model, device, load_config);+ }+ m_compiled_submodels.emplace_back(CompiledModelDesc{device, ov_model, compiled_model});}- // clang-format on++ m_mapping_info = hetero_read_mapping(hetero_node);set_inputs_and_outputs();}@@ -519,49 +722,82 @@ void ov::hetero::CompiledModel::set_inputs_and_outputs() {}}-void ov::hetero::CompiledModel::export_model(std::ostream& model_stream) const {- OV_ITT_SCOPED_TASK(itt::domains::Hetero, "CompiledModel::export_model");-+void ov::hetero::CompiledModel::export_container(std::ostream& model_stream) const {pugi::xml_document doc;- auto heteroNode = doc.append_child("hetero");- heteroNode.append_attribute("name").set_value(m_name.c_str());- heteroNode.append_attribute(HETERO_BLOB_FORMAT_VERSION_ATTR).set_value(HETERO_BLOB_FORMAT_VERSION);-- auto inputs_map_node = heteroNode.append_child("inputs_to_submodels_inputs");- for (const auto& it : m_mapping_info._inputs_to_submodels_inputs) {- auto xml_node = inputs_map_node.append_child("pair");- xml_node.append_attribute("submodel_idx").set_value(std::to_string(it.first).c_str());- xml_node.append_attribute("node_idx").set_value(std::to_string(it.second).c_str());- }- auto outputs_map_node = heteroNode.append_child("outputs_to_submodels_outputs");- for (const auto& it : m_mapping_info._outputs_to_submodels_outputs) {- auto xml_node = outputs_map_node.append_child("pair");- xml_node.append_attribute("submodel_idx").set_value(std::to_string(it.first).c_str());- xml_node.append_attribute("node_idx").set_value(std::to_string(it.second).c_str());+ auto hetero_node = doc.append_child("hetero");+ hetero_node.append_attribute("name").set_value(m_name.c_str());+ hetero_write_metadata(hetero_node, m_mapping_info, m_compiled_submodels, m_cfg);+ std::ostringstream metadata;+ doc.save(metadata, nullptr, pugi::format_raw);++ const auto& core = get_plugin()->get_core();+ const auto metadata_text = metadata.str();+ std::vector<bool> use_ir(m_compiled_submodels.size());+ for (size_t i = 0; i < m_compiled_submodels.size(); ++i) {+ OPENVINO_ASSERT(m_compiled_submodels[i].compiled_model);+ use_ir[i] = !core->device_supports_model_caching(m_compiled_submodels[i].device);}- auto submodels_input_to_prev_output_node = heteroNode.append_child("submodels_input_to_prev_output");- for (const auto& it : m_mapping_info._submodels_input_to_prev_output) {- auto xml_node = submodels_input_to_prev_output_node.append_child("record");- xml_node.append_attribute("in_submodel_idx").set_value(std::to_string(it.first.first).c_str());- xml_node.append_attribute("in_node_idx").set_value(std::to_string(it.first.second).c_str());- xml_node.append_attribute("out_submodel_idx").set_value(std::to_string(it.second.first).c_str());- xml_node.append_attribute("out_node_idx").set_value(std::to_string(it.second.second).c_str());- }+ const auto write_container = [&](std::ostream& stream) {+ const auto container_start = stream.tellp();+ while (true) {+ std::vector<HsmSubmodelPayload> submodels(m_compiled_submodels.size());+ std::optional<size_t> exporting;+ for (size_t i = 0; i < submodels.size(); ++i) {+ const auto& comp_model_desc = m_compiled_submodels[i];+ if (use_ir[i]) {+ submodels[i].ir_model = comp_model_desc.model;+ } else {+ submodels[i].export_blob = [&comp_model_desc, &exporting, i](std::ostream& blob_stream) {+ exporting = i;+ comp_model_desc.compiled_model->export_model(blob_stream);+ exporting.reset();+ };+ }+ }- auto subnetworksNode = heteroNode.append_child("compiled_submodels");- for (const auto& comp_model_desc : m_compiled_submodels) {- auto subnetworkNode = subnetworksNode.append_child("compiled_submodel");- subnetworkNode.append_attribute("device").set_value(comp_model_desc.device.c_str());+ HsmWriterHandler handler{stream, metadata_text, std::move(submodels)};+ try {+ auto writer = ov::runtime::hsm::DeferredWriter::open(stream);+ OPENVINO_ASSERT(writer, "[HETERO] Cannot export in HSM format: the output stream must be seekable.");+ writer->add_sections({&handler});+ const auto error = writer->finalize();+ OPENVINO_ASSERT(!error, "[HETERO] HSM export failed: ", error.message());+ return;+ } catch (const ov::NotImplemented& ex) {+ OPENVINO_ASSERT(exporting, "[HETERO] Unexpected NotImplemented during HSM export: ", ex.what());+ // E.g. the Auto batch plugin reports caching but cannot export: write the container again with IR.+ use_ir[*exporting] = true;+ stream.clear();+ stream.seekp(container_start);+ }+ }+ };++ if (is_output_stream_seekable(model_stream)) {+ write_container(model_stream);+ } else {+ std::stringstream staging_stream(std::ios::in | std::ios::out | std::ios::binary);+ write_container(staging_stream);+ model_stream << staging_stream.rdbuf();+ OPENVINO_ASSERT(model_stream, "Failed to write HETERO compiled blob");}+}- auto heteroConfigsNode = heteroNode.append_child("hetero_config");- for (const auto& config : m_cfg.get_hetero_properties()) {- auto heteroConfigNode = heteroConfigsNode.append_child("config");- heteroConfigNode.append_attribute("key").set_value(config.first.c_str());- heteroConfigNode.append_attribute("value").set_value(config.second.as<std::string>().c_str());+void ov::hetero::CompiledModel::export_model(std::ostream& model_stream) const {+ OV_ITT_SCOPED_TASK(itt::domains::Hetero, "CompiledModel::export_model");++ if (m_cfg.export_hsm_format) {+ export_container(model_stream);+ return;}+ pugi::xml_document doc;+ auto heteroNode = doc.append_child("hetero");+ heteroNode.append_attribute("name").set_value(m_name.c_str());+ heteroNode.append_attribute(HETERO_BLOB_FORMAT_VERSION_ATTR).set_value(HETERO_BLOB_FORMAT_VERSION);+ hetero_write_metadata(heteroNode, m_mapping_info, m_compiled_submodels, m_cfg);+doc.save(model_stream, nullptr, pugi::format_raw);doc.reset();model_stream << std::endl;diff --git a/src/plugins/hetero/src/compiled_model.hpp b/src/plugins/hetero/src/compiled_model.hppindex 648d41b91e4..2a4f80161a4 100644--- a/src/plugins/hetero/src/compiled_model.hpp+++ b/src/plugins/hetero/src/compiled_model.hpp@@ -5,8 +5,10 @@#pragma once#include "config.hpp"+#include "hsm_reader_handler.hpp"#include "openvino/runtime/icompiled_model.hpp"#include "openvino/runtime/so_ptr.hpp"+#include "openvino/runtime/tensor.hpp"#include "plugin.hpp"#include "remote_context.hpp"#include "subgraph_collector.hpp"@@ -31,6 +33,12 @@ public:const Configuration& cfg,const bool loaded_from_cache);+ /// Imports an HSM blob; the tensor must hold the whole container.+ CompiledModel(const ov::Tensor& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const Configuration& cfg,+ const bool loaded_from_cache);+void export_model(std::ostream& model) const override;std::shared_ptr<const ov::Model> get_runtime_model() const override;@@ -56,6 +64,11 @@ private:void set_inputs_and_outputs();+ void export_container(std::ostream& model_stream) const;+ void import_container(const ov::runtime::hsm::Reader& reader, const HsmBlobSource& source);++ ov::AnyMap get_load_config(const std::string& device) const;+Configuration m_cfg;std::string m_name;const bool m_loaded_from_cache;diff --git a/src/plugins/hetero/src/config.cpp b/src/plugins/hetero/src/config.cppindex e64625fcc6b..d57df82f5d1 100644--- a/src/plugins/hetero/src/config.cpp+++ b/src/plugins/hetero/src/config.cpp@@ -35,6 +35,16 @@ Configuration::Configuration(const ov::AnyMap& config, const Configuration& defamodelDistributionPolicy = value.as<std::set<ov::hint::ModelDistributionPolicy>>();} else if (ov::cache_encryption_callbacks == key) {encryption_callbacks = value.as<EncryptionCallbacks>();+ } else if (ov::hetero::export_hsm_format == key) {+ try {+ export_hsm_format = value.as<bool>();+ } catch (const ov::Exception&) {+ OPENVINO_THROW("Wrong value ",+ value.as<std::string>(),+ " for property key ",+ ov::hetero::export_hsm_format.name(),+ ". Expected only true/false.");+ }} else {if (throwOnUnsupported)OPENVINO_THROW("Property was not found: ", key);@@ -48,6 +58,8 @@ ov::Any Configuration::get(const std::string& name) const {return {device_priorities};} else if (name == ov::hint::model_distribution_policy) {return {modelDistributionPolicy};+ } else if (name == ov::hetero::export_hsm_format) {+ return {export_hsm_format};} else {OPENVINO_THROW("Property was not found: ", name);}@@ -69,4 +81,4 @@ ov::AnyMap Configuration::get_device_properties() const {bool Configuration::dump_dot_files() const {return std::getenv("OPENVINO_HETERO_VISUALIZE") != NULL;-}\ No newline at end of file+}diff --git a/src/plugins/hetero/src/config.hpp b/src/plugins/hetero/src/config.hppindex 09b161a286c..a3c3363c335 100644--- a/src/plugins/hetero/src/config.hpp+++ b/src/plugins/hetero/src/config.hpp@@ -40,7 +40,9 @@ struct Configuration {EncryptionCallbacks encryption_callbacks;+ bool export_hsm_format = false;+ov::AnyMap device_properties;};} // namespace hetero-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/plugins/hetero/src/hsm_common.hpp b/src/plugins/hetero/src/hsm_common.hppnew file mode 100644index 00000000000..6b8b3705d3e--- /dev/null+++ b/src/plugins/hetero/src/hsm_common.hpp@@ -0,0 +1,92 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Wire contract of the HETERO HSM blob, shared by HsmReaderHandler and HsmWriterHandler. Keep it free of reader and+// writer code - the two handlers must stay independent. `hsm` is this plugin's own namespace; the runtime API is+// spelled runtime::hsm.+//+// The container itself (header, manifest, section tags, device ids, compatibility rules) is defined by+// src/inference/dev_api/openvino/runtime/hsm_format.hpp; the legacy HETERO layout it replaces is described in+// blob_serialization.hpp. This file only defines what HETERO stores in the sections.+//+// Layout of the container, in file order:+//+// [ HSM header ]+// [ runtime_requirements ] common section, checked first so an incompatible blob is rejected before any payload+// [ metadata ] hetero XML: name, I/O mapping, hetero config, one <compiled_submodel> per submodel+// per submodel i, in order, either+// [ submodel_blob ] page-aligned; the blob exported by the sub-device, opaque to HETERO+// or+// [ submodel_ir_weights ] page-aligned; IR fallback for devices without export/import, may be empty+// [ submodel_ir_xml ]+// [ manifest ]+//+// Submodel sections carry the submodel index in ManifestEntry::tag_reserved (see decode_section_index()). Every+// submodel index of the metadata must have exactly one of the two variants above.++#pragma once++#include <array>+#include <cstdint>+#include <cstring>++#include "openvino/runtime/hsm_format.hpp"++namespace ov::hetero::hsm {++inline constexpr runtime::hsm::DeviceId device_id = runtime::hsm::hetero_device_id;++struct SectionId {+ runtime::hsm::DeviceId device{};+ runtime::hsm::SectionTag tag{};+};++constexpr uint32_t section_key(runtime::hsm::DeviceId device, uint32_t tag_id) noexcept {+ return (static_cast<uint32_t>(device) << 24) | tag_id;+}++constexpr uint32_t section_key(const SectionId& id) noexcept {+ return section_key(id.device, id.tag.id());+}++/// Core-owned: the string checked by check_hsm_runtime_requirements() on import.+// TODO CVS-196454: use the common Runtime Requirements codec instead of the plain string.+inline constexpr SectionId runtime_requirements{runtime::hsm::any_device_id, runtime::hsm::runtime_requirements_tag};+/// The hetero metadata XML.+inline constexpr SectionId metadata{device_id, runtime::hsm::model_tag};++/// Device-local ids of the HETERO sections - wire values: never change or reuse one once shipped.+/// They are turned into section tags by runtime::hsm::SectionTag::make_device_tag(), see hsm_format.hpp.+enum class Tags : uint32_t {+ submodel_blob = 0, //!< See #submodel_blob.+ submodel_ir_xml = 1, //!< See #submodel_ir_xml.+ submodel_ir_weights = 2, //!< See #submodel_ir_weights.+};++constexpr SectionId make_section_id(Tags tag) noexcept {+ return {device_id, runtime::hsm::SectionTag::make_device_tag(static_cast<uint32_t>(tag), false)};+}++/// The blob exported by the sub-device of the submodel given by the section index.+inline constexpr SectionId submodel_blob = make_section_id(Tags::submodel_blob);+/// IR xml of a submodel whose device cannot export a blob.+inline constexpr SectionId submodel_ir_xml = make_section_id(Tags::submodel_ir_xml);+/// IR weights of the same submodel.+inline constexpr SectionId submodel_ir_weights = make_section_id(Tags::submodel_ir_weights);++inline std::array<uint8_t, 4> encode_section_index(uint32_t index) noexcept {+ std::array<uint8_t, 4> bytes{};+ std::memcpy(bytes.data(), &index, sizeof(index));+ return bytes;+}++inline uint32_t decode_section_index(const std::array<uint8_t, 4>& bytes) noexcept {+ uint32_t index = 0;+ std::memcpy(&index, bytes.data(), sizeof(index));+ return index;+}++inline constexpr uint32_t requirements_format_version = 1;++} // namespace ov::hetero::hsmdiff --git a/src/plugins/hetero/src/hsm_reader_handler.cpp b/src/plugins/hetero/src/hsm_reader_handler.cppnew file mode 100644index 00000000000..8bd26108a8b--- /dev/null+++ b/src/plugins/hetero/src/hsm_reader_handler.cpp@@ -0,0 +1,117 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "hsm_reader_handler.hpp"++#include <algorithm>+#include <utility>++#include "hsm_common.hpp"+#include "hsm_writer_handler.hpp"+#include "openvino/core/coordinate.hpp"+#include "openvino/core/except.hpp"++namespace ov::hetero {++namespace {++// Stores a decoded section; a second section of the same kind makes the blob invalid.+template <class Slot, class T>+void hsm_store_unique(Slot& slot, T value, const char* section_name) {+ OPENVINO_ASSERT(!slot, "[HETERO] Cannot import compiled blob: duplicated ", section_name, " section.");+ slot = std::move(value);+}++// The only requirement HETERO has: it must understand the layout the blob was written with.+void hsm_check_requirements(const std::string& requirements) {+ OPENVINO_ASSERT(requirements == build_hsm_runtime_requirements(),+ "[HETERO] Cannot import compiled blob: incompatible runtime requirements, blob: ",+ requirements,+ ", current: ",+ build_hsm_runtime_requirements());+}++} // namespace++std::string read_hsm_string(const runtime::hsm::Section& section) {+ std::string value(section.size(), '\0');+ OPENVINO_ASSERT(section.read(value.data()), "[HETERO] Cannot import compiled blob: failed to read a section.");+ return value;+}++ov::Tensor read_hsm_tensor(const HsmLocatedSection& located, const HsmBlobSource& source) {+ const auto size = located.section.size();+ if (size == 0) {+ return {};+ }++ const auto& parent = source.tensor;+ if (parent && parent.get_element_type() == ov::element::u8 && parent.get_shape().size() == 1) {+ const auto view = located.section.view();+ const auto base = static_cast<const std::byte*>(parent.data());+ if (!view.empty() && view.data() >= base && view.data() + view.size() <= base + parent.get_byte_size()) {+ const auto begin = static_cast<size_t>(view.data() - base);+ return ov::Tensor(parent, ov::Coordinate{begin}, ov::Coordinate{begin + view.size()});+ }+ }++ ov::Tensor tensor(ov::element::u8, ov::Shape{size});+ OPENVINO_ASSERT(located.section.read(tensor.data()),+ "[HETERO] Cannot import compiled blob: failed to read a section.");+ return tensor;+}++void check_hsm_runtime_requirements(const runtime::hsm::Reader& reader) {+ const auto& id = hsm::runtime_requirements;+ const auto count = reader.count(id.device, id.tag.id());+ OPENVINO_ASSERT(count == 1,+ "[HETERO] Cannot import compiled blob: expected one runtime requirements section, found ",+ count);+ const auto section = reader.section(id.device, id.tag.id());+ OPENVINO_ASSERT(section->tag().is_pointer(), "[HETERO] Cannot import compiled blob: unexpected inline section.");+ hsm_check_requirements(read_hsm_string(*section));+}++bool HsmReaderHandler::handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) {+ const auto key = hsm::section_key(entry.device, entry.tag.id());+ const auto index = hsm::decode_section_index(entry.tag_reserved);+ const auto located = [&entry, §ion] {+ OPENVINO_ASSERT(entry.tag.is_pointer(), "[HETERO] Cannot import compiled blob: unexpected inline section.");+ return HsmLocatedSection{entry, section};+ };++ if (key == hsm::section_key(hsm::metadata)) {+ hsm_store_unique(m_metadata, located(), "metadata");+ } else if (key == hsm::section_key(hsm::submodel_blob)) {+ hsm_store_unique(m_submodels[index].blob, located(), "submodel blob");+ } else if (key == hsm::section_key(hsm::submodel_ir_xml)) {+ hsm_store_unique(m_submodels[index].ir_xml, located(), "submodel IR xml");+ } else if (key == hsm::section_key(hsm::submodel_ir_weights)) {+ hsm_store_unique(m_submodels[index].ir_weights, located(), "submodel IR weights");+ } else {+ return false;+ }+ return true;+}++void HsmReaderHandler::check_structure() const {+ OPENVINO_ASSERT(m_metadata, "[HETERO] Cannot import compiled blob: missing metadata section.");+ size_t expected_index = 0;+ for (const auto& [index, submodel] : m_submodels) {+ // std::map is ordered: indexes must be exactly 0..n-1.+ OPENVINO_ASSERT(index == expected_index++,+ "[HETERO] Cannot import compiled blob: unexpected submodel index ",+ index);+ const auto has_blob = submodel.blob.has_value();+ const auto has_ir = submodel.ir_xml.has_value();+ // IR weights are the optional half of the IR variant and make no sense next to a blob.+ const auto is_single_variant = has_blob != has_ir && (has_ir || !submodel.ir_weights);+ OPENVINO_ASSERT(is_single_variant,+ "[HETERO] Cannot import compiled blob: a submodel must have either a blob or IR sections, "+ "submodel index: ",+ index);+ }+}++} // namespace ov::heterodiff --git a/src/plugins/hetero/src/hsm_reader_handler.hpp b/src/plugins/hetero/src/hsm_reader_handler.hppnew file mode 100644index 00000000000..520d3bf0bcb--- /dev/null+++ b/src/plugins/hetero/src/hsm_reader_handler.hpp@@ -0,0 +1,72 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <istream>+#include <map>+#include <optional>+#include <string>++#include "openvino/runtime/hsm_reader.hpp"+#include "openvino/runtime/tensor.hpp"++namespace ov::hetero {++/// Where the sections of an opened container live, for sections that are imported by the sub-devices.+struct HsmBlobSource {+ std::istream* stream = nullptr; //!< Set when the container is read from a stream.+ std::streampos start{}; //!< Container start in #stream.+ ov::Tensor tensor; //!< Set when the container is read from a buffer.+};++/// A section together with its manifest entry, which holds the offset needed to address it in a stream.+struct HsmLocatedSection {+ runtime::hsm::ManifestEntry entry;+ runtime::hsm::Section section;+};++class HsmReaderHandler final : public runtime::hsm::ISectionReaderHandler {+public:+ struct Submodel {+ std::optional<HsmLocatedSection> blob;+ std::optional<HsmLocatedSection> ir_xml;+ std::optional<HsmLocatedSection> ir_weights;+ };++ bool handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) override;++ /// Validates the sections found, without reading any of them: the metadata is present and the submodels are+ /// numbered 0..n-1, each with either a blob or IR sections.+ void check_structure() const;++ const HsmLocatedSection& metadata() const {+ return *m_metadata;+ }++ size_t submodel_count() const {+ return m_submodels.size();+ }++ const Submodel& submodel(size_t index) const {+ return m_submodels.at(index);+ }++private:+ std::optional<HsmLocatedSection> m_metadata;+ std::map<size_t, Submodel> m_submodels;+};++/// Throws unless the container has exactly one runtime requirements section that this HETERO can import.+/// Call it before reading any other section.+void check_hsm_runtime_requirements(const runtime::hsm::Reader& reader);++std::string read_hsm_string(const runtime::hsm::Section& section);++/// Reads the section into a tensor; maps the bytes of the source tensor instead of copying when possible.+ov::Tensor read_hsm_tensor(const HsmLocatedSection& located, const HsmBlobSource& source);++} // namespace ov::heterodiff --git a/src/plugins/hetero/src/hsm_writer_handler.cpp b/src/plugins/hetero/src/hsm_writer_handler.cppnew file mode 100644index 00000000000..49819b9820b--- /dev/null+++ b/src/plugins/hetero/src/hsm_writer_handler.cpp@@ -0,0 +1,243 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "hsm_writer_handler.hpp"++#include <algorithm>+#include <cstddef>+#include <cstdint>+#include <limits>+#include <memory>+#include <sstream>+#include <streambuf>+#include <utility>++#include "hsm_common.hpp"+#include "openvino/core/except.hpp"+#include "openvino/core/model.hpp"+#include "openvino/pass/serialize.hpp"+#include "openvino/util/memory.hpp"++namespace ov::hetero {++namespace {+// Page-aligned start and slot size: a section covers whole pages, so a mapped blob can hand it out as is.+constexpr runtime::hsm::SectionAlignment hsm_page_alignment{ov::util::min_page_alignment};++// Seekable view of the section being written: appends go through the writer's sink, so it keeps its own size+// accounting, while a write behind the end (a producer patching a header) overwrites the bytes already in the+// destination. Seeks are limited to [0, bytes appended].+class HsmSectionWindowBuf final : public std::streambuf {+public:+ HsmSectionWindowBuf(std::ostream& destination, const runtime::hsm::SectionSink& sink)+ : m_destination(destination),+ m_sink(sink),+ m_start(destination.tellp()) {}++ size_t written() const {+ return m_high;+ }++protected:+ std::streamsize xsputn(const char* data, std::streamsize count) override {+ if (count <= 0) {+ return 0;+ }+ auto left = static_cast<size_t>(count);+ if (m_pos < m_high) {+ const auto patch = std::min(left, m_high - m_pos);+ m_destination.seekp(m_start + static_cast<std::streamoff>(m_pos));+ m_destination.write(data, static_cast<std::streamsize>(patch));+ m_destination.seekp(m_start + static_cast<std::streamoff>(m_high));+ if (!m_destination) {+ return 0;+ }+ data += patch;+ left -= patch;+ m_pos += patch;+ }+ if (left > 0) {+ m_sink({reinterpret_cast<const std::byte*>(data), left});+ m_pos += left;+ m_high += left;+ if (!m_destination) {+ return 0;+ }+ }+ return count;+ }++ int_type overflow(int_type ch) override {+ if (traits_type::eq_int_type(ch, traits_type::eof())) {+ return traits_type::not_eof(ch);+ }+ const char c = traits_type::to_char_type(ch);+ return xsputn(&c, 1) == 1 ? ch : traits_type::eof();+ }++ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override {+ if ((which & std::ios_base::out) == 0) {+ return pos_type(off_type(-1));+ }+ off_type base = 0;+ if (dir == std::ios_base::cur) {+ base = static_cast<off_type>(m_pos);+ } else if (dir == std::ios_base::end) {+ base = static_cast<off_type>(m_high);+ } else if (dir != std::ios_base::beg) {+ return pos_type(off_type(-1));+ }+ const auto target = base + off;+ if (target < 0 || static_cast<size_t>(target) > m_high) {+ return pos_type(off_type(-1));+ }+ m_pos = static_cast<size_t>(target);+ return pos_type(target);+ }++ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {+ return seekoff(static_cast<off_type>(pos), std::ios_base::beg, which);+ }++private:+ std::ostream& m_destination;+ const runtime::hsm::SectionSink& m_sink;+ std::streampos m_start;+ size_t m_pos = 0;+ size_t m_high = 0;+};++// One serialization pass feeds both IR sections: the weights go to the sink as they are produced, only the small+// XML is kept for the section that follows.+struct HsmIrSerialization {+ std::shared_ptr<ov::Model> model;+ std::string xml;+};++class HsmIrWeightsEncoder final : public runtime::hsm::ISectionEncoder {+public:+ HsmIrWeightsEncoder(std::ostream& destination, std::shared_ptr<HsmIrSerialization> state)+ : m_destination(destination),+ m_state(std::move(state)) {}++ void encode(const runtime::hsm::SectionSink& sink) const override {+ OPENVINO_ASSERT(m_state->model, "OpenVINO Model is empty");+ HsmSectionWindowBuf weights_buf{m_destination, sink};+ std::ostream weights_stream{&weights_buf};+ std::ostringstream xml_stream;+ ov::pass::Serialize{xml_stream, weights_stream}.run_on_model(m_state->model);+ OPENVINO_ASSERT(weights_stream, "[HETERO] Failed to serialize the IR weights into the HSM blob");+ m_state->xml = xml_stream.str();+ }++private:+ std::ostream& m_destination;+ std::shared_ptr<HsmIrSerialization> m_state;+};++class HsmIrXmlEncoder final : public runtime::hsm::ISectionEncoder {+public:+ explicit HsmIrXmlEncoder(std::shared_ptr<HsmIrSerialization> state) : m_state(std::move(state)) {}++ void encode(const runtime::hsm::SectionSink& sink) const override {+ sink(ov::util::as_memory_view(m_state->xml));+ std::string{}.swap(m_state->xml);+ }++private:+ std::shared_ptr<HsmIrSerialization> m_state;+};++class HsmBlobEncoder final : public runtime::hsm::ISectionEncoder {+public:+ HsmBlobEncoder(std::ostream& destination, std::function<void(std::ostream&)> export_blob)+ : m_destination(destination),+ m_export_blob(std::move(export_blob)) {}++ void encode(const runtime::hsm::SectionSink& sink) const override {+ HsmSectionWindowBuf window{m_destination, sink};+ std::ostream stream{&window};+ try {+ m_export_blob(stream);+ } catch (const ov::NotImplemented& ex) {+ // Only a producer that has not written anything can still be replaced by the IR sections.+ OPENVINO_ASSERT(window.written() == 0, "[HETERO] Submodel export failed after partial output: ", ex.what());+ throw;+ }+ OPENVINO_ASSERT(stream && m_destination, "[HETERO] Failed to export a compiled submodel into the HSM blob");+ }++private:+ std::ostream& m_destination;+ std::function<void(std::ostream&)> m_export_blob;+};+} // namespace++std::string build_hsm_runtime_requirements() {+ return "hetero=" + std::to_string(hsm::requirements_format_version);+}++HsmWriterHandler::HsmWriterHandler(std::ostream& destination,+ std::string metadata,+ std::vector<HsmSubmodelPayload> submodels)+ : m_destination(destination),+ m_runtime_requirements(build_hsm_runtime_requirements()),+ m_metadata(std::move(metadata)),+ m_submodels(std::move(submodels)) {+ OPENVINO_ASSERT(m_submodels.size() <= std::numeric_limits<uint32_t>::max(),+ "[HETERO] Too many submodels for the HSM blob");+}++void HsmWriterHandler::handle_section(runtime::hsm::IWriter& writer) const {+ const auto add = [&writer](const hsm::SectionId& id,+ uint32_t index,+ ov::util::MemoryView payload,+ runtime::hsm::SectionAlignment alignment = {}) {+ OPENVINO_ASSERT(writer.add_section(id.device,+ runtime::hsm::SectionTagReserved{id.tag, hsm::encode_section_index(index)},+ payload,+ alignment),+ "[HETERO] Cannot add HSM section ",+ id.tag.id());+ };++ // Requirements come first so that an import can reject an incompatible blob before reading any payload.+ add(hsm::runtime_requirements, 0, ov::util::as_memory_view(m_runtime_requirements));+ add(hsm::metadata, 0, ov::util::as_memory_view(m_metadata));++ for (size_t i = 0; i < m_submodels.size(); ++i) {+ const auto index = static_cast<uint32_t>(i);+ const auto& submodel = m_submodels[i];+ if (submodel.export_blob) {+ // Unsized: the size is whatever the sub-device writes.+ OPENVINO_ASSERT(writer.add_section(hsm::submodel_blob.device,+ runtime::hsm::SectionTagReserved{hsm::submodel_blob.tag,+ hsm::encode_section_index(index)},+ std::make_shared<HsmBlobEncoder>(m_destination, submodel.export_blob),+ hsm_page_alignment),+ "[HETERO] Cannot add HSM section ",+ hsm::submodel_blob.tag.id());+ } else {+ // The weights are encoded first: the same pass produces the XML kept for the next section.+ const auto state = std::make_shared<HsmIrSerialization>(HsmIrSerialization{submodel.ir_model, {}});+ const auto add_encoded = [&](const hsm::SectionId& id,+ std::shared_ptr<runtime::hsm::ISectionEncoder> encoder,+ runtime::hsm::SectionAlignment alignment) {+ OPENVINO_ASSERT(+ writer.add_section(id.device,+ runtime::hsm::SectionTagReserved{id.tag, hsm::encode_section_index(index)},+ std::move(encoder),+ alignment),+ "[HETERO] Cannot add HSM section ",+ id.tag.id());+ };+ add_encoded(hsm::submodel_ir_weights,+ std::make_shared<HsmIrWeightsEncoder>(m_destination, state),+ hsm_page_alignment);+ add_encoded(hsm::submodel_ir_xml, std::make_shared<HsmIrXmlEncoder>(state), {});+ }+ }+}++} // namespace ov::heterodiff --git a/src/plugins/hetero/src/hsm_writer_handler.hpp b/src/plugins/hetero/src/hsm_writer_handler.hppnew file mode 100644index 00000000000..deba7355cbe--- /dev/null+++ b/src/plugins/hetero/src/hsm_writer_handler.hpp@@ -0,0 +1,42 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <functional>+#include <memory>+#include <ostream>+#include <string>+#include <vector>++#include "openvino/core/model.hpp"+#include "openvino/runtime/hsm_writer.hpp"++namespace ov::hetero {++/// Content of one submodel: a blob written by the sub-device, or an IR fallback.+struct HsmSubmodelPayload {+ std::function<void(std::ostream&)> export_blob; //!< Set for a blob; the stream is seekable.+ std::shared_ptr<ov::Model> ir_model; //!< Serialized straight into the sections, when there is no #export_blob.+};++std::string build_hsm_runtime_requirements();++class HsmWriterHandler final : public runtime::hsm::ISectionWriterHandler {+public:+ /// @p destination is the stream the IWriter writes into; it must be seekable.+ HsmWriterHandler(std::ostream& destination, std::string metadata, std::vector<HsmSubmodelPayload> submodels);++ /// The handler must outlive IWriter::finalize(): the sections borrow its buffers and run its exporters.+ void handle_section(runtime::hsm::IWriter& writer) const override;++private:+ std::ostream& m_destination;+ std::string m_runtime_requirements;+ std::string m_metadata;+ std::vector<HsmSubmodelPayload> m_submodels;+};++} // namespace ov::heterodiff --git a/src/plugins/hetero/src/plugin.cpp b/src/plugins/hetero/src/plugin.cppindex 589a2b40255..0ecca95256d 100644--- a/src/plugins/hetero/src/plugin.cpp+++ b/src/plugins/hetero/src/plugin.cpp@@ -20,12 +20,14 @@#include "openvino/core/rt_info.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/runtime/device_id_parser.hpp"+#include "openvino/runtime/hsm_format.hpp"#include "openvino/runtime/intel_gpu/properties.hpp"#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/shared_buffer.hpp"#include "openvino/util/common_util.hpp"#include "openvino/util/container_util.hpp"+#include "openvino/util/log.hpp"#include "perf_log.hpp"#include "properties.hpp"#include "remote_context.hpp"@@ -125,6 +127,13 @@ std::shared_ptr<ov::ICompiledModel> ov::hetero::Plugin::compile_model(const std:}auto config = Configuration{properties, m_cfg};+ // Core decides on its blob header from the plugin-level flag, so a per-compile false must not override a true.+ if (m_cfg.export_hsm_format && !config.export_hsm_format) {+ OPENVINO_DEBUG("[HETERO] Ignoring per-compile ",+ ov::hetero::export_hsm_format.name(),+ "=false: it is on at the plugin level");+ config.export_hsm_format = true;+ }if (perf_logging_enabled) {t_clone_start = clock::now();@@ -200,18 +209,21 @@ std::shared_ptr<ov::ICompiledModel> ov::hetero::Plugin::import_model(std::istreaconst ov::AnyMap& properties) const {OPENVINO_NOT_IMPLEMENTED;}++namespace {+// Removes ov::loaded_from_cache from the properties: it is not a device property.+bool get_loaded_from_cache(ov::AnyMap& properties) {+ const auto node = properties.extract(ov::loaded_from_cache.name());+ return !node.empty() && node.mapped().as<bool>();+}+} // namespace+std::shared_ptr<ov::ICompiledModel> ov::hetero::Plugin::import_model(std::istream& model,const ov::AnyMap& properties) const {OV_ITT_SCOPED_TASK(itt::domains::Hetero, "Plugin::import_model");- // check ov::loaded_from_cache property and erase it due to not needed any more.auto _properties = properties;- const auto& it = _properties.find(ov::loaded_from_cache.name());- bool loaded_from_cache = false;- if (it != _properties.end()) {- loaded_from_cache = it->second.as<bool>();- _properties.erase(it);- }+ const auto loaded_from_cache = get_loaded_from_cache(_properties);auto config = Configuration{_properties, m_cfg};auto compiled_model = std::make_shared<CompiledModel>(model, shared_from_this(), config, loaded_from_cache);@@ -220,6 +232,16 @@ std::shared_ptr<ov::ICompiledModel> ov::hetero::Plugin::import_model(std::istreastd::shared_ptr<ov::ICompiledModel> ov::hetero::Plugin::import_model(const ov::Tensor& model,const ov::AnyMap& properties) const {+ if (model.get_byte_size() >= sizeof(ov::runtime::hsm::Header) &&+ ov::runtime::hsm::Header::view(model.data()).magic == ov::runtime::hsm::BlobMagic::single) {+ auto _properties = properties;+ const auto loaded_from_cache = get_loaded_from_cache(_properties);+ return std::make_shared<CompiledModel>(model,+ shared_from_this(),+ Configuration{_properties, m_cfg},+ loaded_from_cache);+ }+ov::SharedStreamBuffer buffer{model.data(), model.get_byte_size()};std::istream stream{&buffer};return import_model(stream, properties);@@ -590,12 +612,20 @@ ov::Any ov::hetero::Plugin::get_property(const std::string& name, const ov::AnyMsupported_properties.insert(supported_properties.end(), rw_properties.begin(), rw_properties.end());return decltype(ov::supported_properties)::value_type(std::move(supported_properties));} else if (ov::internal::supported_properties == name) {- return decltype(ov::internal::supported_properties)::value_type{- ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO}};+ decltype(ov::internal::supported_properties)::value_type internal_properties{+ ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO},+ ov::PropertyName{ov::internal::emit_hsm_format.name(), ov::PropertyMutability::RO}};+ if (full_config.export_hsm_format) {+ // Core then hands over a mapped cache blob, which the sub-devices can import without a copy.+ internal_properties.emplace_back(ov::internal::caching_with_mmap.name(), ov::PropertyMutability::RO);+ }+ return internal_properties;} else if (ov::device::full_name == name) {return decltype(ov::device::full_name)::value_type{get_device_name()};} else if (ov::internal::caching_properties == name) {return decltype(ov::internal::caching_properties)::value_type{ov::hetero::caching_device_properties.name()};+ } else if (ov::internal::emit_hsm_format == name) {+ return decltype(ov::internal::emit_hsm_format)::value_type{full_config.export_hsm_format};} else if (ov::hetero::caching_device_properties == name) {return caching_device_properties(full_config.device_priorities);} else if (ov::device::capabilities == name) {diff --git a/src/plugins/hetero/src/properties.hpp b/src/plugins/hetero/src/properties.hppindex d21c9cbd0ef..1620cc249da 100644--- a/src/plugins/hetero/src/properties.hpp+++ b/src/plugins/hetero/src/properties.hpp@@ -17,5 +17,12 @@ static constexpr Property<std::string, PropertyMutability::RO> caching_device_pr* @brief Read-only property showing number of compiled submodels*/static constexpr Property<size_t, PropertyMutability::RO> number_of_submodels{"HETERO_NUMBER_OF_SUBMODELS"};++/**+ * @brief Selects the export_model() blob format: true = HSM container, false = legacy framed layout (default).+ * @note Transition switch; removed together with the legacy format. Set it on the plugin (not only per compile call)+ * so that Core caching picks up the matching blob format. A per-compile false does not override a plugin-level true.+ */+static constexpr Property<bool, PropertyMutability::RW> export_hsm_format{"HETERO_EXPORT_HSM_FORMAT"};} // namespace hetero} // namespace ovdiff --git a/src/plugins/hetero/tests/functional/hetero_tests.cpp b/src/plugins/hetero/tests/functional/hetero_tests.cppindex 262af682a98..04c1b1e8c99 100644--- a/src/plugins/hetero/tests/functional/hetero_tests.cpp+++ b/src/plugins/hetero/tests/functional/hetero_tests.cpp@@ -5,6 +5,7 @@#include "hetero_tests.hpp"#include <memory>+#include <sstream>#include <string>#include "common_test_utils/file_utils.hpp"@@ -15,6 +16,8 @@#include "openvino/pass/manager.hpp"#include "openvino/pass/serialize.hpp"#include "openvino/runtime/exec_model_info.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"+#include "openvino/runtime/hsm_reader.hpp"#include "openvino/runtime/intel_gpu/properties.hpp"#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/iplugin.hpp"@@ -971,6 +974,166 @@ private:bool exclusive_async_requests = false;};+ov::hetero::tests::MockHsmImport& ov::hetero::tests::mock_hsm_import() {+ static MockHsmImport record;+ return record;+}++namespace {++constexpr ov::runtime::hsm::DeviceId mock_hsm_device = 250;+constexpr auto mock_hsm_weights_tag = ov::runtime::hsm::SectionTag::make_device_tag(1, false);+constexpr auto mock_hsm_xml_tag = ov::runtime::hsm::SectionTag::make_device_tag(2, false);+const std::string mock_hsm_requirements = "mock_hsm=1";++// Exports the model as its own HSM container: requirements, page-aligned weights, XML.+class MockHsmCompiledModel final : public MockCompiledModel {+public:+ using MockCompiledModel::MockCompiledModel;++ void export_model(std::ostream& stream) const override {+ if (ov::hetero::tests::mock_hsm_import().export_not_implemented) {+ OPENVINO_THROW_NOT_IMPLEMENTED("[MOCKHSM] export_model is not implemented");+ }+ std::ostringstream xml;+ std::ostringstream weights;+ ov::pass::Serialize(xml, weights).run_on_model(std::const_pointer_cast<ov::Model>(get_model()));+ const auto xml_text = xml.str();+ const auto weights_bytes = weights.str();++ auto writer = ov::runtime::hsm::DeferredWriter::open(stream);+ OPENVINO_ASSERT(writer, "[MOCKHSM] the output stream must be seekable");+ const auto as_view = [](const std::string& data) {+ return ov::util::MemoryView{reinterpret_cast<const std::byte*>(data.data()), data.size()};+ };+ OPENVINO_ASSERT(writer->add_section(ov::runtime::hsm::any_device_id,+ {ov::runtime::hsm::runtime_requirements_tag, {}},+ as_view(mock_hsm_requirements)));+ OPENVINO_ASSERT(+ writer->add_section(mock_hsm_device, {mock_hsm_weights_tag, {}}, as_view(weights_bytes), {4096}));+ OPENVINO_ASSERT(writer->add_section(mock_hsm_device, {mock_hsm_xml_tag, {}}, as_view(xml_text)));+ OPENVINO_ASSERT(!writer->finalize(), "[MOCKHSM] export failed");+ }+};++class MockPluginHsm : public MockPluginBase {+public:+ explicit MockPluginHsm(const std::string& name)+ : MockPluginBase(name, {"Parameter", "Result", "Add", "Constant"}) {}++ const ov::Version& get_const_version() override {+ static const ov::Version version = {CI_BUILD_NUMBER, "openvino_mock_hsm_plugin"};+ return version;+ }++ void set_property(const ov::AnyMap& properties) override {+ for (const auto& it : properties) {+ if (it.first == ov::enable_profiling.name())+ m_profiling = it.second.as<bool>();+ else if (it.first == ov::internal::exclusive_async_requests.name() || it.first == ov::device::id.name())+ continue;+ else+ OPENVINO_THROW(get_device_name(), " set config: " + it.first);+ }+ }++ ov::Any get_property(const std::string& name, const ov::AnyMap& arguments) const override {+ const static std::vector<ov::PropertyName> properties{+ RO_property(ov::supported_properties.name()),+ RO_property(ov::available_devices.name()),+ RO_property(ov::loaded_from_cache.name()),+ RO_property(ov::device::capabilities.name()),+ RO_property(ov::device::uuid.name()),+ RW_property(ov::enable_profiling.name()),+ };+ if (name == ov::supported_properties) {+ return decltype(ov::supported_properties)::value_type(properties);+ } else if (name == ov::internal::supported_properties) {+ return decltype(ov::internal::supported_properties)::value_type(+ {ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO},+ ov::PropertyName{ov::internal::caching_with_mmap.name(), ov::PropertyMutability::RO},+ ov::PropertyName{ov::internal::exclusive_async_requests.name(), ov::PropertyMutability::RW}});+ } else if (name == ov::internal::exclusive_async_requests) {+ return decltype(ov::internal::exclusive_async_requests)::value_type{false};+ } else if (name == ov::device::uuid) {+ ov::device::UUID uuid{};+ for (size_t i = 0; i < uuid.MAX_UUID_SIZE; i++)+ uuid.uuid[i] = static_cast<uint8_t>(i * 11);+ return decltype(ov::device::uuid)::value_type{uuid};+ } else if (name == ov::available_devices) {+ return decltype(ov::available_devices)::value_type(std::vector<std::string>{"0"});+ } else if (name == ov::device::capabilities) {+ return decltype(ov::device::capabilities)::value_type({ov::device::capability::EXPORT_IMPORT});+ } else if (ov::internal::caching_properties == name) {+ return decltype(ov::internal::caching_properties)::value_type({ov::PropertyName(ov::device::uuid)});+ } else if (name == ov::loaded_from_cache.name()) {+ return m_loaded_from_cache;+ } else if (name == ov::enable_profiling.name()) {+ return decltype(ov::enable_profiling)::value_type{m_profiling};+ }+ OPENVINO_THROW("Unsupported property: ", name);+ }++ std::shared_ptr<ov::ICompiledModel> compile_model(const std::shared_ptr<const ov::Model>& model,+ const ov::AnyMap& properties) const override {+ OPENVINO_ASSERT(model);+ if (!support_model(model, query_model(model, properties)))+ OPENVINO_THROW("Unsupported model");+ return std::make_shared<MockHsmCompiledModel>(model, shared_from_this(), properties);+ }++ std::shared_ptr<ov::ICompiledModel> import_model(const ov::Tensor& model,+ const ov::AnyMap& properties) const override {+ ++ov::hetero::tests::mock_hsm_import().tensor_imports;+ auto reader =+ ov::runtime::hsm::Reader::open(static_cast<const std::byte*>(model.data()), model.get_byte_size());+ OPENVINO_ASSERT(reader, "[MOCKHSM] invalid container");+ return import_sections(*reader, properties, ov::hetero::tests::MockHsmImport::Source::tensor);+ }++ std::shared_ptr<ov::ICompiledModel> import_model(std::istream& model, const ov::AnyMap& properties) const override {+ ++ov::hetero::tests::mock_hsm_import().stream_imports;+ auto reader = ov::runtime::hsm::Reader::open(model);+ OPENVINO_ASSERT(reader, "[MOCKHSM] invalid container");+ return import_sections(*reader, properties, ov::hetero::tests::MockHsmImport::Source::stream);+ }++private:+ std::shared_ptr<ov::ICompiledModel> import_sections(const ov::runtime::hsm::Reader& reader,+ const ov::AnyMap& properties,+ ov::hetero::tests::MockHsmImport::Source source) const {+ const auto read_text = [](const ov::runtime::hsm::Section& section) {+ std::string text(section.size(), '\0');+ OPENVINO_ASSERT(section.read(text.data()), "[MOCKHSM] cannot read a section");+ return text;+ };+ const auto requirements =+ reader.section(ov::runtime::hsm::any_device_id, ov::runtime::hsm::runtime_requirements_tag.id());+ OPENVINO_ASSERT(requirements && read_text(*requirements) == mock_hsm_requirements,+ "[MOCKHSM] incompatible container");++ const auto xml = reader.section(mock_hsm_device, mock_hsm_xml_tag.id());+ const auto weights = reader.section(mock_hsm_device, mock_hsm_weights_tag.id());+ OPENVINO_ASSERT(xml && weights, "[MOCKHSM] missing sections");++ ov::Tensor weights_tensor(ov::element::u8, ov::Shape{weights->size()});+ OPENVINO_ASSERT(weights->read(weights_tensor.data()), "[MOCKHSM] cannot read the weights");++ auto& record = ov::hetero::tests::mock_hsm_import();+ record.source = source;+ for (const auto& entry : reader.entries()) {+ if (entry.device == mock_hsm_device && entry.tag.id() == mock_hsm_weights_tag.id()) {+ record.weights_offset = entry.offset;+ }+ }++ ov::Core core;+ return compile_model(core.read_model(read_text(*xml), weights_tensor), properties);+ }+};++} // namespace+void ov::hetero::tests::HeteroTests::reg_plugin(std::shared_ptr<ov::IPlugin>& plugin) {const auto library_path = ov::test::utils::get_mock_engine_path();if (!m_so) {@@ -996,6 +1159,8 @@ void ov::hetero::tests::HeteroTests::SetUp() {reg_plugin_type<MockPluginReshape>("MOCK0");reg_plugin_type<MockPluginSubtract>("MOCK1");reg_plugin_type<MockPluginGPU>("MOCKGPU");+ // The mock engine gives out the injected plugins in the order the devices are loaded: by name.+ reg_plugin_type<MockPluginHsm>("MOCKHSM");reg_plugin_type<MockPluginNoExportImport>("MOCKIR");}}diff --git a/src/plugins/hetero/tests/functional/hetero_tests.hpp b/src/plugins/hetero/tests/functional/hetero_tests.hppindex 7b111c33d61..efd670012f7 100644--- a/src/plugins/hetero/tests/functional/hetero_tests.hpp+++ b/src/plugins/hetero/tests/functional/hetero_tests.hpp@@ -6,6 +6,8 @@#include <gtest/gtest.h>#include <memory>+#include <streambuf>+#include <string>#include "common_test_utils/test_assertions.hpp"#include "openvino/runtime/core.hpp"@@ -15,6 +17,64 @@ namespace ov {namespace hetero {namespace tests {+// State of the mock device MOCKHSM, which exports a nested HSM container: how it was imported last.+struct MockHsmImport {+ enum class Source { none, stream, tensor };+ Source source = Source::none;+ uint64_t weights_offset = 0; //!< Offset of the weights section in the nested container.+ size_t tensor_imports = 0; //!< import_model(Tensor) calls, including failed ones.+ size_t stream_imports = 0; //!< import_model(istream) calls, including failed ones.+ bool export_not_implemented = false; //!< export_model throws ov::NotImplemented, like the Auto batch plugin.+};+MockHsmImport& mock_hsm_import();++// Output buffer that collects the written bytes and fails every seek.+class NonSeekableOutputBuffer : public std::streambuf {+public:+ const std::string& str() const {+ return _data;+ }++protected:+ std::streamsize xsputn(const char* data, std::streamsize count) override {+ if (count <= 0) {+ return 0;+ }+ _data.append(data, static_cast<std::string::size_type>(count));+ return count;+ }++ int_type overflow(int_type ch) override {+ if (traits_type::eq_int_type(ch, traits_type::eof())) {+ return traits_type::not_eof(ch);+ }+ _data.push_back(traits_type::to_char_type(ch));+ return ch;+ }++ pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) override {+ return pos_type(off_type(-1));+ }++ pos_type seekpos(pos_type, std::ios_base::openmode) override {+ return pos_type(off_type(-1));+ }++private:+ std::string _data;+};++// Input buffer that serves the given bytes and fails every seek, so tellg() reports -1.+class NonSeekableInputBuffer : public std::streambuf {+public:+ explicit NonSeekableInputBuffer(std::string data) : _data(std::move(data)) {+ setg(_data.data(), _data.data(), _data.data() + _data.size());+ }++private:+ std::string _data;+};+class HeteroTests : public ::testing::Test {public:ov::Core core;diff --git a/src/plugins/hetero/tests/functional/hsm_blob_tests.cpp b/src/plugins/hetero/tests/functional/hsm_blob_tests.cppnew file mode 100644index 00000000000..8f23d1d2449--- /dev/null+++ b/src/plugins/hetero/tests/functional/hsm_blob_tests.cpp@@ -0,0 +1,705 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <functional>+#include <iterator>+#include <numeric>+#include <sstream>+#include <string>+#include <vector>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/file_utils.hpp"+#include "common_test_utils/test_constants.hpp"+#include "hetero_tests.hpp"+#include "hsm_common.hpp"+#include "openvino/opsets/opset11.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"+#include "openvino/runtime/hsm_reader.hpp"+#include "openvino/runtime/internal_properties.hpp"+#include "properties.hpp"++namespace ov::hetero::tests {++namespace {++struct HsmEntry {+ runtime::hsm::DeviceId device;+ runtime::hsm::SectionTagReserved tag;+ std::vector<std::byte> payload;+};++// A blob together with the id of the section that carries the payload of its submodels.+struct ExportedBlob {+ std::string name;+ std::string blob;+ hsm::SectionId payload;+ size_t submodels;+ ov::Tensor expected; //!< Output of the original model for the fixed input.+};++// Mock devices cannot cache, so their submodels are stored as IR; CPU stores its own blob.+constexpr auto ir_variant = "ir";+constexpr auto cpu_variant = "cpu_blob";++const std::byte* as_bytes(const std::string& blob) {+ return reinterpret_cast<const std::byte*>(blob.data());+}++bool is_hsm_blob(const std::string& blob) {+ return blob.size() >= sizeof(runtime::hsm::Header) &&+ runtime::hsm::Header::view(blob.data()).magic == runtime::hsm::BlobMagic::single;+}++bool has_section_id(const runtime::hsm::ManifestEntry& entry, const hsm::SectionId& id) {+ return hsm::section_key(entry.device, entry.tag.id()) == hsm::section_key(id);+}++bool has_section_id(const HsmEntry& entry, const hsm::SectionId& id) {+ return hsm::section_key(entry.device, entry.tag.tag.id()) == hsm::section_key(id);+}++// Rebuilds an HSM blob from its sections after `modify` edited them.+std::string hsm_repack(const std::string& blob, const std::function<void(std::vector<HsmEntry>&)>& modify) {+ const auto reader = runtime::hsm::Reader::open(as_bytes(blob), blob.size());+ OPENVINO_ASSERT(reader, "Not an HSM blob");++ std::vector<HsmEntry> entries;+ for (const auto& entry : reader->entries()) {+ const auto section =+ entry.tag.is_inline()+ ? runtime::hsm::Section{entry}+ : runtime::hsm::Section{entry, {as_bytes(blob) + entry.offset, static_cast<size_t>(entry.size)}};+ entries.push_back({entry.device, {entry.tag, entry.tag_reserved}, section.to_bytes().value()});+ }+ modify(entries);++ std::stringstream out;+ auto writer = runtime::hsm::DeferredWriter::open(out);+ OPENVINO_ASSERT(writer, "Cannot open HSM writer");+ for (const auto& entry : entries) {+ OPENVINO_ASSERT(+ writer->add_section(entry.device, entry.tag, {entry.payload.data(), entry.payload.size()}, {4096}),+ "Cannot add HSM section");+ }+ OPENVINO_ASSERT(!writer->finalize(), "HSM repack failed");+ return out.str();+}++// Rebuilds an HSM blob with the payload of every section with the given id replaced by `edit(payload)`.+std::string hsm_edit_payload(const std::string& blob,+ const hsm::SectionId& id,+ const std::function<std::string(const std::string&)>& edit) {+ return hsm_repack(blob, [&](std::vector<HsmEntry>& entries) {+ for (auto& entry : entries) {+ if (has_section_id(entry, id)) {+ const auto text = reinterpret_cast<const char*>(entry.payload.data());+ const auto edited = edit(std::string(text, entry.payload.size()));+ entry.payload.assign(reinterpret_cast<const std::byte*>(edited.data()),+ reinterpret_cast<const std::byte*>(edited.data()) + edited.size());+ }+ }+ });+}++// output = input + weights, weights[i] = i: a wrong or missing weights section changes the result.+std::shared_ptr<ov::Model> create_model_with_weights(size_t size) {+ auto input = std::make_shared<ov::opset11::Parameter>(ov::element::f32, ov::Shape{1, size});+ std::vector<float> values(size);+ std::iota(values.begin(), values.end(), 0.0f);+ auto weights = ov::opset11::Constant::create(ov::element::f32, ov::Shape{1, size}, values);+ auto sum = std::make_shared<ov::opset11::Add>(input, weights);+ return std::make_shared<ov::Model>(ov::OutputVector{sum}, ov::ParameterVector{input});+}++} // namespace++// IR frontend is needed for import+#ifdef IR_FRONTEND_ENABLED+class HeteroHsmBlobTests : public HeteroTests {+protected:+ ov::CompiledModel compile(const std::shared_ptr<ov::Model>& model,+ const std::string& priorities,+ bool hsm_format = true) {+ return core.compile_model(model,+ ov::test::utils::DEVICE_HETERO,+ ov::device::priorities(priorities),+ ov::hetero::export_hsm_format(hsm_format));+ }++ static std::string export_blob(ov::CompiledModel compiled_model) {+ std::stringstream stream;+ compiled_model.export_model(stream);+ return stream.str();+ }++ ov::CompiledModel import_from_stream(const std::string& blob) {+ std::stringstream stream(blob);+ return core.import_model(stream, ov::test::utils::DEVICE_HETERO, {});+ }++ ov::CompiledModel import_from_tensor(const std::string& blob) {+ ov::Tensor tensor(ov::element::u8, ov::Shape{blob.size()});+ if (!blob.empty()) {+ std::memcpy(tensor.data(), blob.data(), blob.size());+ }+ return core.import_model(tensor, ov::test::utils::DEVICE_HETERO, {});+ }++ // Runs the model on a fixed input and returns a copy of its output.+ ov::Tensor infer_fixed_input(ov::CompiledModel compiled_model) {+ auto request = compiled_model.create_infer_request();+ request.set_input_tensor(+ create_and_fill_tensor(compiled_model.input().get_element_type(), compiled_model.input().get_shape()));+ request.infer();+ const auto result = request.get_output_tensor();+ ov::Tensor output(result.get_element_type(), result.get_shape());+ result.copy_to(output);+ return output;+ }++ void expect_same_output(const ov::Tensor& expected, ov::CompiledModel compiled_model) {+ ASSERT_EQ(1, compiled_model.inputs().size());+ ASSERT_EQ(1, compiled_model.outputs().size());+ ov::Tensor actual;+ ASSERT_NO_THROW(actual = infer_fixed_input(compiled_model));+ ASSERT_EQ(expected.get_element_type(), actual.get_element_type());+ ASSERT_EQ(expected.get_shape(), actual.get_shape());+ EXPECT_EQ(0, std::memcmp(expected.data(), actual.data(), expected.get_byte_size()));+ }++ // Checks output[i] == 1 + weight_scale * i for the input filled with ones.+ void expect_adds_weights(ov::CompiledModel compiled_model, size_t size, float weight_scale) {+ auto request = compiled_model.create_infer_request();+ ov::Tensor input(ov::element::f32, ov::Shape{1, size});+ std::fill_n(input.data<float>(), size, 1.0f);+ request.set_input_tensor(input);+ ASSERT_NO_THROW(request.infer());+ const auto output = request.get_output_tensor();+ ASSERT_EQ(size, output.get_size());+ for (size_t i = 0; i < size; ++i) {+ ASSERT_EQ(1.0f + weight_scale * static_cast<float>(i), output.data<float>()[i]) << "element " << i;+ }+ }++ void expect_import_rejected(const std::string& blob) {+ EXPECT_THROW(import_from_stream(blob), ov::Exception);+ EXPECT_THROW(import_from_tensor(blob), ov::Exception);+ }++ ExportedBlob export_variant(const std::string& name) {+ if (name == cpu_variant) {+ auto compiled_model = compile(create_model_with_reshape(), ov::test::utils::DEVICE_CPU);+ return {name, export_blob(compiled_model), hsm::submodel_blob, 1, infer_fixed_input(compiled_model)};+ }+ auto compiled_model = compile(create_model_with_subtract(), "MOCK0,MOCK1");+ return {name, export_blob(compiled_model), hsm::submodel_ir_xml, 2, infer_fixed_input(compiled_model)};+ }+};++class HeteroHsmBlobVariantTests : public HeteroHsmBlobTests, public ::testing::WithParamInterface<std::string> {+protected:+ void SetUp() override {+ HeteroHsmBlobTests::SetUp();+ const auto devices = core.get_available_devices();+ if (GetParam() == cpu_variant &&+ std::find(devices.begin(), devices.end(), ov::test::utils::DEVICE_CPU) == devices.end()) {+ GTEST_SKIP() << "CPU plugin is not available";+ }+ variant = export_variant(GetParam());+ }++ ExportedBlob variant;+};++INSTANTIATE_TEST_SUITE_P(Hsm,+ HeteroHsmBlobVariantTests,+ ::testing::Values(ir_variant, cpu_variant),+ [](const ::testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++TEST_P(HeteroHsmBlobVariantTests, export_is_hsm_with_hetero_sections_per_submodel) {+ ASSERT_TRUE(is_hsm_blob(variant.blob));++ const auto reader = runtime::hsm::Reader::open(as_bytes(variant.blob), variant.blob.size());+ ASSERT_TRUE(reader.has_value());+ EXPECT_EQ(1u, reader->count(hsm::runtime_requirements.device, hsm::runtime_requirements.tag.id()));+ EXPECT_EQ(1u, reader->count(hsm::metadata.device, hsm::metadata.tag.id()));+ EXPECT_EQ(variant.submodels, reader->count(variant.payload.device, variant.payload.tag.id()));++ std::vector<uint32_t> indexes;+ for (const auto& entry : reader->entries()) {+ if (has_section_id(entry, variant.payload)) {+ indexes.push_back(hsm::decode_section_index(entry.tag_reserved));+ }+ if (has_section_id(entry, hsm::submodel_blob) || has_section_id(entry, hsm::submodel_ir_weights)) {+ EXPECT_EQ(0u, entry.offset % ov::util::min_page_alignment);+ }+ }+ std::vector<uint32_t> expected(variant.submodels);+ std::iota(expected.begin(), expected.end(), 0);+ EXPECT_EQ(expected, indexes);+}++TEST_P(HeteroHsmBlobVariantTests, import_from_stream_and_tensor_runs) {+ expect_same_output(variant.expected, import_from_stream(variant.blob));+ expect_same_output(variant.expected, import_from_tensor(variant.blob));+}++TEST_F(HeteroHsmBlobTests, export_to_non_seekable_stream) {+ auto compiled_model = compile(create_model_with_subtract(), "MOCK0,MOCK1");+ const auto expected = infer_fixed_input(compiled_model);+ NonSeekableOutputBuffer buffer;+ std::ostream stream(&buffer);++ compiled_model.export_model(stream);++ ASSERT_TRUE(stream);+ EXPECT_TRUE(is_hsm_blob(buffer.str()));+ expect_same_output(expected, import_from_stream(buffer.str()));+}++TEST_F(HeteroHsmBlobTests, hsm_blob_from_non_seekable_stream_is_rejected_with_a_clear_error) {+ const auto variant = export_variant(ir_variant);+ NonSeekableInputBuffer buffer{variant.blob};+ std::istream stream(&buffer);++ OV_EXPECT_THROW(core.import_model(stream, ov::test::utils::DEVICE_HETERO, {}),+ ov::Exception,+ testing::HasSubstr("seekable"));+}++TEST_F(HeteroHsmBlobTests, corrupted_hsm_container_is_reported_as_invalid) {+ const auto variant = export_variant(ir_variant);+ auto corrupted = variant.blob;+ corrupted.resize(sizeof(runtime::hsm::Header));++ OV_EXPECT_THROW(import_from_stream(corrupted), ov::Exception, testing::HasSubstr("HSM"));+}++TEST_F(HeteroHsmBlobTests, submodel_that_cannot_export_falls_back_to_ir_sections) {+ constexpr size_t size = 2048;+ EXPECT_NO_THROW(core.get_available_devices());+ auto compiled_model = compile(create_model_with_weights(size), "MOCKHSM");++ mock_hsm_import() = {};+ mock_hsm_import().export_not_implemented = true;+ const auto blob = export_blob(compiled_model);+ mock_hsm_import() = {};++ const auto reader = runtime::hsm::Reader::open(as_bytes(blob), blob.size());+ ASSERT_TRUE(reader.has_value());+ EXPECT_EQ(0u, reader->count(hsm::submodel_blob.device, hsm::submodel_blob.tag.id()));+ EXPECT_EQ(1u, reader->count(hsm::submodel_ir_xml.device, hsm::submodel_ir_xml.tag.id()));+ EXPECT_EQ(1u, reader->count(hsm::submodel_ir_weights.device, hsm::submodel_ir_weights.tag.id()));+ expect_adds_weights(import_from_stream(blob), size, 1.0f);+ expect_adds_weights(import_from_tensor(blob), size, 1.0f);+}++TEST_F(HeteroHsmBlobTests, legacy_blob_imports_in_hsm_mode) {+ auto reference = compile(create_model_with_subtract(), "MOCK0,MOCK1", false);+ const auto expected = infer_fixed_input(reference);+ const auto legacy = export_blob(reference);+ EXPECT_FALSE(is_hsm_blob(legacy));++ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(true));+ expect_same_output(expected, import_from_stream(legacy));+ expect_same_output(expected, import_from_tensor(legacy));+}++TEST_F(HeteroHsmBlobTests, plugin_property_selects_format_and_is_reported) {+ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(false));+ EXPECT_FALSE(core.get_property(ov::test::utils::DEVICE_HETERO, ov::internal::emit_hsm_format));+ auto model = create_model_with_subtract();+ const auto default_blob =+ export_blob(core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0,MOCK1")));+ EXPECT_FALSE(is_hsm_blob(default_blob));++ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(true));+ EXPECT_TRUE(core.get_property(ov::test::utils::DEVICE_HETERO, ov::internal::emit_hsm_format));+ const auto hsm_blob =+ export_blob(core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0,MOCK1")));+ EXPECT_TRUE(is_hsm_blob(hsm_blob));+}++TEST_F(HeteroHsmBlobTests, re_export_of_imported_model_round_trips) {+ // Only the IR variant: the CPU plugin cannot re-export a model it has imported.+ const auto variant = export_variant(ir_variant);+ std::stringstream stream(variant.blob);+ const auto first = core.import_model(stream, ov::test::utils::DEVICE_HETERO, {ov::hetero::export_hsm_format(true)});++ const auto re_exported = export_blob(first);++ EXPECT_TRUE(is_hsm_blob(re_exported));+ expect_same_output(variant.expected, import_from_tensor(re_exported));+}++TEST_F(HeteroHsmBlobTests, ir_submodel_stores_xml_and_weights_sections) {+ constexpr size_t size = 2048;+ const auto blob = export_blob(compile(create_model_with_weights(size), "MOCKIR"));++ const auto reader = runtime::hsm::Reader::open(as_bytes(blob), blob.size());+ ASSERT_TRUE(reader.has_value());+ EXPECT_EQ(0u, reader->count(hsm::submodel_blob.device, hsm::submodel_blob.tag.id()));+ EXPECT_EQ(1u, reader->count(hsm::submodel_ir_xml.device, hsm::submodel_ir_xml.tag.id()));+ EXPECT_EQ(1u, reader->count(hsm::submodel_ir_weights.device, hsm::submodel_ir_weights.tag.id()));+ const auto weights = reader->section(hsm::submodel_ir_weights.device, hsm::submodel_ir_weights.tag.id());+ ASSERT_TRUE(weights.has_value());+ EXPECT_EQ(size * sizeof(float), weights->size());++ expect_adds_weights(import_from_stream(blob), size, 1.0f);+ expect_adds_weights(import_from_tensor(blob), size, 1.0f);+}++TEST_F(HeteroHsmBlobTests, ir_weights_are_taken_from_the_weights_section) {+ constexpr size_t size = 2048;+ const auto blob = export_blob(compile(create_model_with_weights(size), "MOCKIR"));+ const auto zeroed = hsm_edit_payload(blob, hsm::submodel_ir_weights, [](const std::string& weights) {+ return std::string(weights.size(), '\0');+ });++ expect_adds_weights(import_from_stream(zeroed), size, 0.0f);+ expect_adds_weights(import_from_tensor(zeroed), size, 0.0f);+}++TEST_F(HeteroHsmBlobTests, import_rejects_ir_weights_shorter_than_the_model_needs) {+ constexpr size_t size = 2048;+ const auto blob = export_blob(compile(create_model_with_weights(size), "MOCKIR"));+ for (const size_t length : {size_t{0}, size_t{8}, size * sizeof(float) - sizeof(float)}) {+ SCOPED_TRACE(length);+ expect_import_rejected(hsm_edit_payload(blob, hsm::submodel_ir_weights, [&](const std::string& weights) {+ return weights.substr(0, length);+ }));+ }+}++TEST_F(HeteroHsmBlobTests, per_compile_false_does_not_override_plugin_level_hsm_flag) {+ // Core omits its own blob header when the plugin-level flag is on, so the blob has to stay HSM.+ EXPECT_NO_THROW(core.get_available_devices());+ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(true));+ const auto model = create_model_with_weights(64);++ EXPECT_TRUE(is_hsm_blob(export_blob(compile(model, "MOCKIR", false))));++ const auto cache_dir = ov::test::utils::generateTestFilePrefix() + "_hetero_hsm_cache";+ const auto compile_cached = [&] {+ return core.compile_model(model,+ ov::test::utils::DEVICE_HETERO,+ ov::device::priorities("MOCKIR"),+ ov::cache_dir(cache_dir),+ ov::hetero::export_hsm_format(false));+ };+ EXPECT_FALSE(compile_cached().get_property(ov::loaded_from_cache));+ EXPECT_TRUE(compile_cached().get_property(ov::loaded_from_cache));+ ov::test::utils::removeDir(cache_dir);+}++TEST_F(HeteroHsmBlobTests, legacy_cache_entry_loads_when_plugin_level_hsm_flag_is_on) {+ EXPECT_NO_THROW(core.get_available_devices());+ constexpr size_t size = 64;+ const auto model = create_model_with_weights(size);+ const auto cache_dir = ov::test::utils::generateTestFilePrefix() + "_hetero_legacy_cache";+ const auto compile_cached = [&] {+ return core.compile_model(model,+ ov::test::utils::DEVICE_HETERO,+ ov::device::priorities("MOCKIR"),+ ov::cache_dir(cache_dir));+ };++ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(false));+ EXPECT_FALSE(compile_cached().get_property(ov::loaded_from_cache));+ for (const auto& entry : std::filesystem::directory_iterator(cache_dir)) {+ std::ifstream file(entry.path(), std::ios::binary);+ std::string head(sizeof(runtime::hsm::Header), '\0');+ file.read(head.data(), static_cast<std::streamsize>(head.size()));+ EXPECT_FALSE(is_hsm_blob(head)) << entry.path();+ }++ // Core now hands cache entries to HETERO as mapped tensors.+ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(true));+ auto cached = compile_cached();+ EXPECT_TRUE(cached.get_property(ov::loaded_from_cache));+ expect_adds_weights(cached, size, 1.0f);+ ov::test::utils::removeDir(cache_dir);+}++// MOCKHSM exports its own HSM container, so it ends up nested in the HETERO one.+TEST_F(HeteroHsmBlobTests, nested_hsm_blob_of_a_sub_device_keeps_page_alignment) {+ constexpr size_t size = 2048;+ // Loads all mock plugins, which the mock engine hands out in the order of loading.+ EXPECT_NO_THROW(core.get_available_devices());+ const auto blob = export_blob(compile(create_model_with_weights(size), "MOCKHSM"));++ const auto reader = runtime::hsm::Reader::open(as_bytes(blob), blob.size());+ ASSERT_TRUE(reader.has_value());+ EXPECT_EQ(1u, reader->count(hsm::submodel_blob.device, hsm::submodel_blob.tag.id()));+ EXPECT_EQ(0u, reader->count(hsm::submodel_ir_xml.device, hsm::submodel_ir_xml.tag.id()));+ const auto outer = std::find_if(reader->entries().begin(), reader->entries().end(), [](const auto& entry) {+ return has_section_id(entry, hsm::submodel_blob);+ });+ ASSERT_NE(reader->entries().end(), outer);++ mock_hsm_import() = {};+ expect_adds_weights(import_from_tensor(blob), size, 1.0f);+ EXPECT_EQ(MockHsmImport::Source::tensor, mock_hsm_import().source);+ // The weights are page-aligned in the nested container and, as it starts on a page, in the whole blob.+ EXPECT_NE(0u, mock_hsm_import().weights_offset);+ EXPECT_EQ(0u, mock_hsm_import().weights_offset % ov::util::min_page_alignment);+ EXPECT_EQ(0u, (outer->offset + mock_hsm_import().weights_offset) % ov::util::min_page_alignment);++ mock_hsm_import() = {};+ expect_adds_weights(import_from_stream(blob), size, 1.0f);+ EXPECT_EQ(MockHsmImport::Source::stream, mock_hsm_import().source);+}++TEST_F(HeteroHsmBlobTests, nested_hsm_blob_of_a_sub_device_exported_to_non_seekable_stream) {+ constexpr size_t size = 2048;+ EXPECT_NO_THROW(core.get_available_devices());+ auto compiled_model = compile(create_model_with_weights(size), "MOCKHSM");+ NonSeekableOutputBuffer buffer;+ std::ostream stream(&buffer);++ compiled_model.export_model(stream);++ ASSERT_TRUE(stream);+ expect_adds_weights(import_from_tensor(buffer.str()), size, 1.0f);+ expect_adds_weights(import_from_stream(buffer.str()), size, 1.0f);+}++TEST_F(HeteroHsmBlobTests, sub_device_tensor_import_error_is_not_retried_through_a_stream) {+ EXPECT_NO_THROW(core.get_available_devices());+ const auto blob = export_blob(compile(create_model_with_weights(64), "MOCKHSM"));+ const auto broken = hsm_edit_payload(blob, hsm::submodel_blob, [](const std::string&) {+ return std::string(64, '\xFF');+ });++ mock_hsm_import() = {};+ EXPECT_THROW(import_from_tensor(broken), ov::Exception);+ EXPECT_EQ(1u, mock_hsm_import().tensor_imports);+ EXPECT_EQ(0u, mock_hsm_import().stream_imports);+}++TEST_P(HeteroHsmBlobVariantTests, import_from_stream_stops_at_the_end_of_the_container) {+ const auto variant = export_variant(GetParam());+ std::stringstream stream(variant.blob + "tail");++ ASSERT_NO_THROW(core.import_model(stream, ov::test::utils::DEVICE_HETERO, {}));++ EXPECT_EQ(static_cast<std::streampos>(variant.blob.size()), stream.tellg());+}++TEST_P(HeteroHsmBlobVariantTests, unknown_sections_are_skipped) {+ const auto blob = hsm_repack(variant.blob, [](std::vector<HsmEntry>& entries) {+ entries.push_back({runtime::hsm::any_device_id,+ {runtime::hsm::SectionTag::make(runtime::hsm::core_tag_id_range_end - 1, false), {}},+ std::vector<std::byte>(19, std::byte{1})});+ entries.push_back({250, {runtime::hsm::SectionTag::make_device_tag(0x123, false), {}}, {std::byte{1}}});+ entries.push_back({hsm::device_id,+ {runtime::hsm::SectionTag::make_device_tag(0x456, false), {}},+ std::vector<std::byte>(7, std::byte{2})});+ });++ expect_same_output(variant.expected, import_from_stream(blob));+ expect_same_output(variant.expected, import_from_tensor(blob));+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_blob_without_mandatory_sections) {+ for (const auto& id : {hsm::runtime_requirements, hsm::metadata, variant.payload}) {+ SCOPED_TRACE(id.tag.id());+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ entries.erase(std::remove_if(entries.begin(),+ entries.end(),+ [&](const HsmEntry& entry) {+ return has_section_id(entry, id);+ }),+ entries.end());+ }));+ }+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_missing_submodel_section) {+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ const auto found = std::find_if(entries.begin(), entries.end(), [&](const HsmEntry& entry) {+ return has_section_id(entry, variant.payload) && hsm::decode_section_index(entry.tag.bytes) == 0;+ });+ ASSERT_NE(found, entries.end());+ entries.erase(found);+ }));+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_duplicated_sections) {+ for (const auto& id : {hsm::runtime_requirements, hsm::metadata, variant.payload}) {+ SCOPED_TRACE(id.tag.id());+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ const auto found = std::find_if(entries.begin(), entries.end(), [&](const HsmEntry& entry) {+ return has_section_id(entry, id);+ });+ ASSERT_NE(found, entries.end());+ entries.push_back(*found);+ }));+ }+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_submodel_with_both_blob_and_ir_sections) {+ const bool has_blob = hsm::section_key(variant.payload) == hsm::section_key(hsm::submodel_blob);+ const auto& other = has_blob ? hsm::submodel_ir_xml : hsm::submodel_blob;+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ entries.push_back(+ {hsm::device_id, {other.tag, hsm::encode_section_index(0)}, std::vector<std::byte>(4, std::byte{'x'})});+ }));+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_submodel_index_out_of_range) {+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ for (auto& entry : entries) {+ if (has_section_id(entry, variant.payload)) {+ entry.tag.bytes = hsm::encode_section_index(7);+ }+ }+ }));+}++TEST_F(HeteroHsmBlobTests, import_rejects_incompatible_runtime_requirements) {+ const auto blob = export_variant(ir_variant).blob;+ for (const std::string requirements : {"hetero=2", "hetero=", "hetero=1 ", "garbage", ""}) {+ SCOPED_TRACE(requirements);+ expect_import_rejected(hsm_edit_payload(blob, hsm::runtime_requirements, [&](const std::string&) {+ return requirements;+ }));+ }+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_truncated_blob) {+ auto blob = variant.blob;+ blob.pop_back();++ expect_import_rejected(blob);+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_blob_truncated_at_any_point) {+ const auto size = variant.blob.size();+ for (const size_t cut : {size_t{0},+ size_t{1},+ size_t{31},+ size_t{32},+ size_t{33},+ size_t{4095},+ size_t{4096},+ size / 2,+ size - 33,+ size - 32,+ size - 31,+ size - 1}) {+ SCOPED_TRACE(cut);+ expect_import_rejected(variant.blob.substr(0, cut));+ }+}++TEST_F(HeteroHsmBlobTests, import_rejects_tiny_or_garbage_input) {+ const auto blob = export_variant(ir_variant).blob;+ const auto magic_only = blob.substr(0, sizeof(runtime::hsm::Header));+ for (const auto& input :+ {std::string{}, std::string("x"), std::string(4096, '\0'), std::string(4096, '\xFF'), magic_only}) {+ SCOPED_TRACE(input.size());+ expect_import_rejected(input);+ }+}++TEST_F(HeteroHsmBlobTests, import_never_crashes_on_corrupted_header_or_manifest) {+ const auto blob = export_variant(ir_variant).blob;+ const auto header = runtime::hsm::Header::view(blob.data());+ std::vector<size_t> positions(sizeof(runtime::hsm::Header));+ std::iota(positions.begin(), positions.end(), size_t{0});+ for (auto pos = static_cast<size_t>(header.manifest_offset);+ pos < static_cast<size_t>(header.manifest_offset + header.manifest_size);+ ++pos) {+ positions.push_back(pos);+ }++ for (const auto pos : positions) {+ for (const auto value : {'\x00', '\xFF'}) {+ auto corrupted = blob;+ corrupted[pos] = value;+ SCOPED_TRACE("byte " + std::to_string(pos) + " = " + std::to_string(static_cast<int>(value)));+ // A corrupted copy may still be valid; the only requirement is an ov exception instead of a crash.+ try {+ import_from_stream(corrupted);+ } catch (const ov::Exception&) {+ }+ try {+ import_from_tensor(corrupted);+ } catch (const ov::Exception&) {+ }+ }+ }+}++TEST_F(HeteroHsmBlobTests, import_rejects_malformed_metadata) {+ const auto blob = export_variant(ir_variant).blob;+ const auto edit_metadata = [&](const std::function<std::string(const std::string&)>& edit) {+ return hsm_edit_payload(blob, hsm::metadata, edit);+ };++ expect_import_rejected(edit_metadata([](const std::string&) {+ return std::string{};+ }));+ expect_import_rejected(edit_metadata([](const std::string&) {+ return std::string{"not xml"};+ }));+ expect_import_rejected(edit_metadata([](const std::string&) {+ return std::string{"<hetero/>"};+ }));+ // Fewer submodels in the metadata than sections in the blob.+ expect_import_rejected(edit_metadata([](std::string text) {+ const auto begin = text.rfind("<compiled_submodel ");+ const auto end = text.find("/>", begin);+ EXPECT_NE(std::string::npos, begin);+ EXPECT_NE(std::string::npos, end);+ return text.erase(begin, end + 2 - begin);+ }));+ // Mapping that points to a submodel that does not exist.+ expect_import_rejected(edit_metadata([](std::string text) {+ const std::string from = "submodel_idx=\"0\"";+ const auto pos = text.find(from);+ EXPECT_NE(std::string::npos, pos);+ return text.replace(pos, from.size(), "submodel_idx=\"99\"");+ }));+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_corrupted_submodel_payload) {+ for (const auto& payload : {std::string{}, std::string{"x"}, std::string(64, '\xFF')}) {+ SCOPED_TRACE(payload.size());+ expect_import_rejected(hsm_edit_payload(variant.blob, variant.payload, [&](const std::string&) {+ return payload;+ }));+ }+}++TEST_P(HeteroHsmBlobVariantTests, import_rejects_inline_sections) {+ for (const auto& id : {hsm::runtime_requirements, hsm::metadata, variant.payload}) {+ SCOPED_TRACE(id.tag.id());+ expect_import_rejected(hsm_repack(variant.blob, [&](std::vector<HsmEntry>& entries) {+ for (auto& entry : entries) {+ if (has_section_id(entry, id)) {+ entry.tag.tag = runtime::hsm::SectionTag::make(entry.tag.tag.id(), true);+ entry.payload.resize(8);+ }+ }+ }));+ }+}++TEST_P(HeteroHsmBlobVariantTests, import_from_multi_dimensional_tensor_runs) {+ ov::Tensor tensor(ov::element::u8, ov::Shape{1, variant.blob.size()});+ std::memcpy(tensor.data(), variant.blob.data(), variant.blob.size());+ expect_same_output(variant.expected, core.import_model(tensor, ov::test::utils::DEVICE_HETERO, {}));+}+#endif++} // namespace ov::hetero::testsdiff --git a/src/plugins/hetero/tests/functional/import_model_tests.cpp b/src/plugins/hetero/tests/functional/import_model_tests.cppindex 66ab53ec275..2eaea49f35b 100644--- a/src/plugins/hetero/tests/functional/import_model_tests.cpp+++ b/src/plugins/hetero/tests/functional/import_model_tests.cpp@@ -12,6 +12,7 @@#include "blob_serialization.hpp"#include "common_test_utils/test_constants.hpp"#include "hetero_tests.hpp"+#include "properties.hpp"namespace ov {namespace hetero {@@ -65,41 +66,6 @@ private:bool m_has_old_value = false;};-class NonSeekableOutputBuffer : public std::streambuf {-public:- const std::string& str() const {- return _data;- }--protected:- std::streamsize xsputn(const char* data, std::streamsize count) override {- if (count <= 0) {- return 0;- }- _data.append(data, static_cast<std::string::size_type>(count));- return count;- }-- int_type overflow(int_type ch) override {- if (traits_type::eq_int_type(ch, traits_type::eof())) {- return traits_type::not_eof(ch);- }- _data.push_back(traits_type::to_char_type(ch));- return ch;- }-- pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) override {- return pos_type(off_type(-1));- }-- pos_type seekpos(pos_type, std::ios_base::openmode) override {- return pos_type(off_type(-1));- }--private:- std::string _data;-};-class SeekCountingOutputBuffer : public std::streambuf {public:const std::string& str() const {@@ -288,6 +254,15 @@ void expect_compiled_model_runs(HeteroTests& fixture, ov::CompiledModel compiled// IR frontend is needed for import#ifdef IR_FRONTEND_ENABLED+// Tests of the legacy blob layout: it is pinned until the legacy format is removed.+class HeteroLegacyBlobTests : public HeteroTests {+protected:+ void SetUp() override {+ HeteroTests::SetUp();+ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(false));+ }+};+TEST_F(HeteroTests, import_single_plugins) {std::stringstream model_stream;auto model = create_model_with_reshape();@@ -309,7 +284,7 @@ TEST_F(HeteroTests, import_single_plugins) {EXPECT_EQ(input_tensor.get_element_type(), model->input().get_element_type());}-TEST_F(HeteroTests, export_single_plugin_uses_framed_payload) {+TEST_F(HeteroLegacyBlobTests, export_single_plugin_uses_framed_payload) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -330,7 +305,7 @@ TEST_F(HeteroTests, export_single_plugin_uses_framed_payload) {EXPECT_EQ(1, imported_model.outputs().size());}-TEST_F(HeteroTests, export_single_plugin_without_export_import_uses_framed_ir_payload) {+TEST_F(HeteroLegacyBlobTests, export_single_plugin_without_export_import_uses_framed_ir_payload) {auto model = create_model_with_reshape();EXPECT_NO_THROW(core.get_available_devices());auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));@@ -365,7 +340,7 @@ TEST_F(HeteroTests, export_single_plugin_to_non_seekable_stream) {EXPECT_EQ(1, imported_model.outputs().size());}-TEST_F(HeteroTests, export_ir_payload_to_non_seekable_stream) {+TEST_F(HeteroLegacyBlobTests, export_ir_payload_to_non_seekable_stream) {auto model = create_model_with_reshape();EXPECT_NO_THROW(core.get_available_devices());auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));@@ -388,7 +363,7 @@ TEST_F(HeteroTests, export_ir_payload_to_non_seekable_stream) {expect_compiled_model_runs(*this, imported_model);}-TEST_F(HeteroTests, export_ir_payload_does_not_depend_on_temp_directory_environment) {+TEST_F(HeteroLegacyBlobTests, export_ir_payload_does_not_depend_on_temp_directory_environment) {auto model = create_model_with_reshape();EXPECT_NO_THROW(core.get_available_devices());auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCKIR"));@@ -477,7 +452,7 @@ TEST_F(HeteroTests, bounded_string_output_buffer_rejects_payload_larger_than_limEXPECT_EQ("abc", payload_buffer.str());}-TEST_F(HeteroTests, import_large_compiled_payload_uses_bounded_stream_and_throws) {+TEST_F(HeteroLegacyBlobTests, import_large_compiled_payload_uses_bounded_stream_and_throws) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -491,7 +466,7 @@ TEST_F(HeteroTests, import_large_compiled_payload_uses_bounded_stream_and_throwsEXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);}-TEST_F(HeteroTests, import_single_plugin_legacy_unframed_blob_without_format_version) {+TEST_F(HeteroLegacyBlobTests, import_single_plugin_legacy_unframed_blob_without_format_version) {auto model = create_model_with_reshape();const auto hetero_compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -517,7 +492,7 @@ TEST_F(HeteroTests, import_single_plugin_legacy_unframed_blob_without_format_verEXPECT_EQ(1, imported_model.outputs().size());}-TEST_F(HeteroTests, import_single_plugin_legacy_unframed_ir_blob_without_format_version) {+TEST_F(HeteroLegacyBlobTests, import_single_plugin_legacy_unframed_ir_blob_without_format_version) {auto model = create_model_with_reshape();EXPECT_NO_THROW(core.get_available_devices());const auto hetero_compiled_model =@@ -530,7 +505,7 @@ TEST_F(HeteroTests, import_single_plugin_legacy_unframed_ir_blob_without_format_expect_compiled_model_runs(*this, imported_model);}-TEST_F(HeteroTests, import_truncated_framed_payload_throws) {+TEST_F(HeteroLegacyBlobTests, import_truncated_framed_payload_throws) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -542,7 +517,7 @@ TEST_F(HeteroTests, import_truncated_framed_payload_throws) {EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);}-TEST_F(HeteroTests, import_truncated_framed_cpu_payload_throws) {+TEST_F(HeteroLegacyBlobTests, import_truncated_framed_cpu_payload_throws) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities(ov::test::utils::DEVICE_CPU));@@ -554,7 +529,7 @@ TEST_F(HeteroTests, import_truncated_framed_cpu_payload_throws) {EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);}-TEST_F(HeteroTests, import_framed_ir_payload_with_oversized_xml_size_throws) {+TEST_F(HeteroLegacyBlobTests, import_framed_ir_payload_with_oversized_xml_size_throws) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -567,7 +542,7 @@ TEST_F(HeteroTests, import_framed_ir_payload_with_oversized_xml_size_throws) {EXPECT_THROW(core.import_model(model_stream, ov::test::utils::DEVICE_HETERO, {}), ov::Exception);}-TEST_F(HeteroTests, import_framed_ir_payload_with_oversized_weights_size_throws) {+TEST_F(HeteroLegacyBlobTests, import_framed_ir_payload_with_oversized_weights_size_throws) {auto model = create_model_with_reshape();const auto compiled_model =core.compile_model(model, ov::test::utils::DEVICE_HETERO, ov::device::priorities("MOCK0"));@@ -605,4 +580,4 @@ TEST_F(HeteroTests, import_several_plugins) {#endif} // namespace tests} // namespace hetero-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/plugins/hetero/tests/functional/properties_tests.cpp b/src/plugins/hetero/tests/functional/properties_tests.cppindex c420870bc11..b5e4ecdd0b5 100644--- a/src/plugins/hetero/tests/functional/properties_tests.cpp+++ b/src/plugins/hetero/tests/functional/properties_tests.cpp@@ -26,14 +26,23 @@ TEST_F(HeteroTests, get_property_supported_properties) {}TEST_F(HeteroTests, get_property_internal_supported_properties) {- const std::vector<ov::PropertyName> supported_properties = {ov::internal::caching_properties};- auto actual_supported_properties =- core.get_property(ov::test::utils::DEVICE_HETERO, ov::internal::supported_properties);- EXPECT_EQ(supported_properties.size(), actual_supported_properties.size());- for (auto& supported_property : supported_properties) {- ASSERT_TRUE(std::find(actual_supported_properties.begin(),- actual_supported_properties.end(),- supported_property) != actual_supported_properties.end());+ for (const bool hsm_format : {false, true}) {+ SCOPED_TRACE(hsm_format);+ core.set_property(ov::test::utils::DEVICE_HETERO, ov::hetero::export_hsm_format(hsm_format));++ std::vector<ov::PropertyName> supported_properties = {ov::internal::caching_properties,+ ov::internal::emit_hsm_format};+ if (hsm_format) {+ supported_properties.emplace_back(ov::internal::caching_with_mmap);+ }+ auto actual_supported_properties =+ core.get_property(ov::test::utils::DEVICE_HETERO, ov::internal::supported_properties);+ EXPECT_EQ(supported_properties.size(), actual_supported_properties.size());+ for (auto& supported_property : supported_properties) {+ ASSERT_TRUE(std::find(actual_supported_properties.begin(),+ actual_supported_properties.end(),+ supported_property) != actual_supported_properties.end());+ }}}@@ -67,4 +76,4 @@ TEST_F(HeteroTests, set_property_ModelDistributionPolicy) {}} // namespace tests} // namespace hetero-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/plugins/hetero/tests/functional/shared_tests_instances/behavior/ov_compiled_model/import_export.cpp b/src/plugins/hetero/tests/functional/shared_tests_instances/behavior/ov_compiled_model/import_export.cppindex d97acb5abfb..9923caf6dd0 100644--- a/src/plugins/hetero/tests/functional/shared_tests_instances/behavior/ov_compiled_model/import_export.cpp+++ b/src/plugins/hetero/tests/functional/shared_tests_instances/behavior/ov_compiled_model/import_export.cpp@@ -4,6 +4,7 @@#include "behavior/compiled_model/import_export.hpp"#include "common_test_utils/test_constants.hpp"+#include "properties.hpp"using namespace ov::test::behavior;namespace {@@ -20,7 +21,9 @@ const std::vector<ov::element::Type_t> netPrecisions = {ov::element::f32,};-const std::vector<ov::AnyMap> heteroConfigs = {{ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE)}};+const std::vector<ov::AnyMap> heteroConfigs = {+ {ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE)},+ {ov::device::priorities(ov::test::utils::DEVICE_TEMPLATE), ov::hetero::export_hsm_format(true)}};INSTANTIATE_TEST_SUITE_P(smoke_Hetero_BehaviorTests,OVCompiledGraphImportExportTest,diff --git a/src/plugins/hetero/tests/functional/sources.cmake b/src/plugins/hetero/tests/functional/sources.cmakeindex a6a94445074..449c76bc175 100644--- a/src/plugins/hetero/tests/functional/sources.cmake+++ b/src/plugins/hetero/tests/functional/sources.cmake@@ -8,6 +8,7 @@ set(OV_HETERO_FUNC_TESTS_SRC${CMAKE_CURRENT_LIST_DIR}/hetero_synthetic.cpp${CMAKE_CURRENT_LIST_DIR}/hetero_tests.cpp${CMAKE_CURRENT_LIST_DIR}/hetero_tests.hpp+ ${CMAKE_CURRENT_LIST_DIR}/hsm_blob_tests.cpp${CMAKE_CURRENT_LIST_DIR}/import_model_tests.cpp${CMAKE_CURRENT_LIST_DIR}/properties_tests.cpp${CMAKE_CURRENT_LIST_DIR}/query_model_tests.cppdiff --git a/src/tests/test_utils/common_test_utils/tests/memory_test.cpp b/src/tests/test_utils/common_test_utils/tests/memory_test.cppindex d7d2935ab88..53ab2ef8e7b 100644--- a/src/tests/test_utils/common_test_utils/tests/memory_test.cpp+++ b/src/tests/test_utils/common_test_utils/tests/memory_test.cpp@@ -10,8 +10,10 @@#include <cstdint>#include <cstring>#include <limits>+#include <string>#include <type_traits>#include <utility>+#include <vector>namespace ov::test {@@ -254,6 +256,25 @@ TEST_F(MemoryViewTest, as_memory_view_of_array_covers_all_elements) {EXPECT_EQ(reinterpret_cast<const std::byte*>(arr.data()), view.data());}+TEST_F(MemoryViewTest, as_memory_view_of_string_spans_characters) {+ const std::string text = "hetero";+ const auto view = util::as_memory_view(text);+ EXPECT_EQ(reinterpret_cast<const std::byte*>(text.data()), view.data());+ EXPECT_EQ(text.size(), view.size());+}++TEST_F(MemoryViewTest, as_memory_view_of_vector_covers_all_elements) {+ const std::vector<uint32_t> vec{1, 2, 3};+ const auto view = util::as_memory_view(vec);+ EXPECT_EQ(reinterpret_cast<const std::byte*>(vec.data()), view.data());+ EXPECT_EQ(vec.size() * sizeof(uint32_t), view.size());+}++TEST_F(MemoryViewTest, as_memory_view_of_empty_container_is_empty) {+ const std::string empty_text;+ EXPECT_TRUE(util::as_memory_view(empty_text).empty());+}+template <typename T, typename = void>struct CanMakeMemoryView : std::false_type {};