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
[TEMPLATE] Add HSM model export import in Template plugin (#39056)
Pawel Raasz1a09513a24ab
diff --git a/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/compiled-model.rst b/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/compiled-model.rstindex e343983633f..dba502e73d4 100644--- a/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/compiled-model.rst+++ b/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/compiled-model.rst@@ -78,6 +78,29 @@ to import a backend specific graph later in the ``Plugin::import_model`` method::language: cpp:fragment: [compiled_model:export_model]+By default, the Template plugin exports an HSM blob: a container of sections. The export stream must be+seekable. The blob has these sections:++* model id and runtime requirements+* compiled options: the values of the properties listed by ``ov::internal::caching_properties`` and+ ``ov::weights_path``, if it is set+* model structure (XML) and weights+* blob info, which tells if the weights are stored in the blob++The plugin adds the sections with a handler that implements ``ov::runtime::hsm::ISectionWriterHandler``.+Small sections are kept in memory. The model structure and the weights are written to the stream+while the model is serialized, so the plugin does not make a second copy of them.++.. doxygensnippet:: src/plugins/template/src/hsm_writer_handler.cpp+ :language: cpp+ :fragment: [hsm_writer_handler:handle_section]++When the model is compiled with ``ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE)``, the weights section+is not written. On import, the weights are restored from ``ov::weights_path``.++To write the legacy layout instead, set ``ov::template_plugin::export_hsm_format`` to ``false``.+This is a transition switch and is removed together with the legacy format.+create_sync_infer_request()+++++++++++++++++++++++++++@@ -151,4 +174,3 @@ The methods returns the runtime model with backend specific information.:fragment: [compiled_model:get_runtime_model]The next step in plugin library implementation is the :doc:`Synchronous Inference Request <synch-inference-request>` class.-diff --git a/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/plugin.rst b/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/plugin.rstindex ece7ad45571..c8e2985eb81 100644--- a/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/plugin.rst+++ b/docs/articles_en/documentation/openvino-extensibility/openvino-plugin-library/plugin.rst@@ -172,6 +172,10 @@ Returns a current value for a specified property key:The function is implemented with the ``Configuration::Get`` method, which wraps an actual configurationkey value to the ov::Any and returns it.+The ``ov::internal::caching_properties`` property lists the properties that affect the compiled model,+so a model compiled with different values of them is not the same model. The Template plugin returns the+device architecture, the performance mode, the execution mode and the inference precision.+.. note::The function must throw an exception if it receives an unsupported configuration key.@@ -200,6 +204,25 @@ For example, the export information may include::language: cpp:fragment: [plugin:import_model_with_remote]+For an HSM blob, the Template plugin reads the sections with ``ov::runtime::hsm::Reader``.+The import works in these steps:++* The model structure and the blob info sections are mandatory.+* The blob is rejected if its runtime requirements are not supported by the plugin.+* The compiled options are restored into the plugin configuration. Properties passed to+ ``import_model`` have a higher priority.+* The weights are taken from the blob. If the blob has no weights section (for example, it was exported+ with ``ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE)``), they are read from ``ov::weights_path``,+ or from the path stored in the compiled options.+* Sections that the plugin does not know are skipped, so blobs written by a newer format minor version+ still import.++If the stream is not an HSM blob, the plugin reads it as the legacy format.++.. doxygensnippet:: src/plugins/template/src/plugin.cpp+ :language: cpp+ :fragment: [plugin:read_hsm_blob]+create_context()++++++++++++++++@@ -231,4 +254,3 @@ OpenVINO plugin library must export only one function creating a plugin instanceNext step in a plugin library implementation is the :doc:`CompiledModel <compiled-model>` class.-diff --git a/src/inference/src/dev/hsm_reader.cpp b/src/inference/src/dev/hsm_reader.cppindex a14336f7f05..e7e4d09f463 100644--- a/src/inference/src/dev/hsm_reader.cpp+++ b/src/inference/src/dev/hsm_reader.cpp@@ -80,9 +80,8 @@ bool read_manifest(std::istream& stream,}bool has_container_size_bytes(std::istream& stream, std::streampos start, const Header& header) {- stream.seekg(start);- stream.ignore(static_cast<std::streamsize>(header.container_size));- return stream.gcount() == static_cast<std::streamsize>(header.container_size);+ stream.seekg(start + static_cast<std::streamoff>(header.container_size - 1));+ return stream.peek() != std::istream::traits_type::eof();}// 32-bit size_t can't represent every SizeType value - reject oversized sections before they're constructed.diff --git a/src/inference/tests/unit/hsm_deferred_writer.cpp b/src/inference/tests/unit/hsm_deferred_writer.cppindex 0ad01d4725c..e0c65898415 100644--- a/src/inference/tests/unit/hsm_deferred_writer.cpp+++ b/src/inference/tests/unit/hsm_deferred_writer.cpp@@ -945,7 +945,7 @@ TEST(HsmDeferredWriterTest, section_encoder_avoids_materializing_a_view_for_a_trpublic:explicit ValueEncoder(int value) : m_value(value) {}void encode(const hsm::SectionSink& sink) const override {- sink({reinterpret_cast<const std::byte*>(&m_value), sizeof(m_value)});+ sink(ov::util::as_memory_view(m_value));}private:@@ -1044,7 +1044,7 @@ TEST(HsmDeferredWriterTest, handler_forwards_to_a_named_member_function_instead_private:void write_options(const hsm::SectionSink& sink) const {- sink({reinterpret_cast<const std::byte*>(&m_options), sizeof(m_options)});+ sink(ov::util::as_memory_view(m_options));}CompiledOptions m_options;diff --git a/src/inference/tests/unit/hsm_format.cpp b/src/inference/tests/unit/hsm_format.cppindex 8032f8ed516..5b015d90c4f 100644--- a/src/inference/tests/unit/hsm_format.cpp+++ b/src/inference/tests/unit/hsm_format.cpp@@ -591,7 +591,7 @@ TEST(IHsmSectionExtensionTest, recognizes_own_device_and_tag) {const std::byte payload[4] = {};RecordingExtension extension;- EXPECT_TRUE(extension.read_section(entry, ov::util::MemoryView{payload, 4}));+ EXPECT_TRUE(extension.read_section(entry, ov::util::as_memory_view(payload)));EXPECT_EQ(extension.last_section_size, 4u);}diff --git a/src/inference/tests/unit/hsm_reader.cpp b/src/inference/tests/unit/hsm_reader.cppindex acdbb838f4e..836f044e8a4 100644--- a/src/inference/tests/unit/hsm_reader.cpp+++ b/src/inference/tests/unit/hsm_reader.cpp@@ -230,7 +230,7 @@ TEST(ISectionReaderHandlerTest, recognizes_own_device_and_tag) {entry.size = 4;const std::byte payload[4] = {};- const hsm::Section section(entry, ov::util::MemoryView{payload, 4});+ const hsm::Section section(entry, ov::util::as_memory_view(payload));RecordingHandler handler(fake_device_id, /*tag_id=*/42);EXPECT_TRUE(handler.handle_section(entry, section));EXPECT_EQ(handler.last_payload.size(), 4u);diff --git a/src/plugins/template/include/template/properties.hpp b/src/plugins/template/include/template/properties.hppindex 06d1b022b5c..094bc5c152f 100644--- a/src/plugins/template/include/template/properties.hpp+++ b/src/plugins/template/include/template/properties.hpp@@ -27,5 +27,11 @@ static constexpr Property<bool, PropertyMutability::RW> disable_transformations{// ! [properties:public_header]+/**+ * @brief Selects the export_model() blob format: true = HSM container (default), false = legacy layout.+ * @note Transition/test-only switch; removed together with the legacy format.+ */+static constexpr Property<bool, PropertyMutability::RW> export_hsm_format{"TEMPLATE_EXPORT_HSM_FORMAT"};+} // namespace template_plugin} // namespace ovdiff --git a/src/plugins/template/src/CMakeLists.txt b/src/plugins/template/src/CMakeLists.txtindex ed7f74dfaba..6a2a567a550 100644--- a/src/plugins/template/src/CMakeLists.txt+++ b/src/plugins/template/src/CMakeLists.txt@@ -9,6 +9,8 @@ set(SOURCES${CMAKE_CURRENT_SOURCE_DIR}/async_infer_request.cpp${CMAKE_CURRENT_SOURCE_DIR}/compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/config.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_reader_handler.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_writer_handler.cpp${CMAKE_CURRENT_SOURCE_DIR}/plugin.cpp${CMAKE_CURRENT_SOURCE_DIR}/remote_context.cpp${CMAKE_CURRENT_SOURCE_DIR}/sync_infer_request.cpp@@ -18,6 +20,9 @@ set(HEADERS${CMAKE_CURRENT_SOURCE_DIR}/attach_cache_manager_to_paged_attention.hpp${CMAKE_CURRENT_SOURCE_DIR}/compiled_model.hpp${CMAKE_CURRENT_SOURCE_DIR}/config.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_common.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_reader_handler.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_writer_handler.hpp${CMAKE_CURRENT_SOURCE_DIR}/itt.hpp${CMAKE_CURRENT_SOURCE_DIR}/plugin.hpp${CMAKE_CURRENT_SOURCE_DIR}/remote_context.hppdiff --git a/src/plugins/template/src/compiled_model.cpp b/src/plugins/template/src/compiled_model.cppindex af798b21868..d3979b021de 100644--- a/src/plugins/template/src/compiled_model.cpp+++ b/src/plugins/template/src/compiled_model.cpp@@ -7,10 +7,13 @@#include <memory>#include "async_infer_request.hpp"+#include "hsm_writer_handler.hpp"#include "itt.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/pass/serialize.hpp"#include "openvino/runtime/exec_model_info.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"+#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/properties.hpp"#include "perf_counter.hpp"#include "plugin.hpp"@@ -154,6 +157,8 @@ ov::Any ov::template_plugin::CompiledModel::get_property(const std::string& name} else if (ov::runtime_requirements == name) {// A real plugin would encode compilation capabilities.return std::string(get_template_plugin()->get_runtime_requirements());+ } else if (ov::internal::caching_properties == name || ov::device::architecture == name) {+ return get_plugin()->get_property(name, {});} else if (ov::supported_properties == name) {auto ro_properties = default_ro_properties();auto rw_properties = default_rw_properties();@@ -173,21 +178,35 @@ ov::Any ov::template_plugin::CompiledModel::get_property(const std::string& namevoid ov::template_plugin::CompiledModel::export_model(std::ostream& model_stream) const {OV_ITT_SCOPED_TASK(itt::domains::TemplatePlugin, "CompiledModel::export_model");- std::stringstream xmlFile, binFile;- ov::pass::Serialize serializer(xmlFile, binFile);- serializer.run_on_model(m_model);-- auto m_constants = binFile.str();- auto m_model = xmlFile.str();-- auto dataSize = static_cast<std::uint64_t>(m_model.size());- model_stream.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));- model_stream.write(m_model.c_str(), dataSize);-- if (m_cfg.cache_mode == CacheMode::OPTIMIZE_SPEED) {- dataSize = static_cast<std::uint64_t>(m_constants.size());+ if (m_cfg.export_hsm_format) {+ ov::AnyMap cache_options;+ const auto caching_properties = get_property(ov::internal::caching_properties.name());+ for (const auto& name : caching_properties.as<decltype(ov::internal::caching_properties)::value_type>()) {+ cache_options.emplace(name, get_property(name));+ }+ HsmWriterHandler handler{m_model, m_cfg, cache_options, get_template_plugin()->get_runtime_requirements()};+ auto writer = ov::runtime::hsm::DeferredWriter::open(model_stream);+ OPENVINO_ASSERT(writer, "TEMPLATE: cannot open HSM writer, the export stream must be seekable");+ writer->add_sections({&handler});+ const auto error = writer->finalize();+ OPENVINO_ASSERT(!error, "TEMPLATE: HSM export failed: ", error.message());+ } else {+ std::stringstream xmlFile, binFile;+ ov::pass::Serialize serializer(xmlFile, binFile);+ serializer.run_on_model(m_model);++ auto m_constants = binFile.str();+ auto m_model = xmlFile.str();++ auto dataSize = static_cast<std::uint64_t>(m_model.size());model_stream.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));- model_stream.write(reinterpret_cast<char*>(&m_constants[0]), dataSize);+ model_stream.write(m_model.c_str(), dataSize);++ if (m_cfg.cache_mode == CacheMode::OPTIMIZE_SPEED) {+ dataSize = static_cast<std::uint64_t>(m_constants.size());+ model_stream.write(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));+ model_stream.write(reinterpret_cast<char*>(&m_constants[0]), dataSize);+ }}}// ! [compiled_model:export_model]diff --git a/src/plugins/template/src/config.cpp b/src/plugins/template/src/config.cppindex 15a6933cd9f..a0f5d84c10d 100644--- a/src/plugins/template/src/config.cpp+++ b/src/plugins/template/src/config.cpp@@ -126,6 +126,8 @@ Configuration::Configuration(const ov::AnyMap& config, const Configuration& defa}} else if (ov::cache_mode == key) {cache_mode = value.as<CacheMode>();+ } else if (ov::template_plugin::export_hsm_format == key) {+ export_hsm_format = value.as<bool>();} else if (throwOnUnsupported) {OPENVINO_THROW("Property was not found: ", key);}@@ -175,6 +177,8 @@ ov::Any Configuration::Get(const std::string& name) const {return cache_mode;} else if (name == ov::internal::cache_header_alignment) {return 4096; // page size in bytes+ } else if (name == ov::template_plugin::export_hsm_format || name == ov::internal::emit_hsm_format) {+ return export_hsm_format;} else {OPENVINO_THROW("Property was not found: ", name);}diff --git a/src/plugins/template/src/config.hpp b/src/plugins/template/src/config.hppindex 258a96128ed..4305c50fcf6 100644--- a/src/plugins/template/src/config.hpp+++ b/src/plugins/template/src/config.hpp@@ -57,6 +57,8 @@ struct Configuration {std::filesystem::path weights_path{};AnyMap compiled_model_runtime_properties{};CacheMode cache_mode{CacheMode::OPTIMIZE_SPEED};+ // Transition switch: false selects the legacy blob layout; removed together with it.+ bool export_hsm_format = true;};// ! [configuration:header]diff --git a/src/plugins/template/src/hsm_common.hpp b/src/plugins/template/src/hsm_common.hppnew file mode 100644index 00000000000..3521355cf23--- /dev/null+++ b/src/plugins/template/src/hsm_common.hpp@@ -0,0 +1,54 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Wire contract of the TEMPLATE HSM blob (device id, section ids, BlobInfo), 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.++#pragma once++#include <cstdint>++#include "openvino/runtime/hsm_format.hpp"++namespace ov::template_plugin {+namespace hsm {++// Placeholder until the HSM device catalog gives TEMPLATE its own id (private range starts at 0x80).+inline constexpr runtime::hsm::DeviceId device_id = runtime::hsm::private_device_id_range_start;+struct SectionId {+ runtime::hsm::DeviceId device;+ runtime::hsm::SectionTag tag;+};++constexpr uint32_t section_key(runtime::hsm::DeviceId device, runtime::hsm::SectionTag tag) noexcept {+ return (static_cast<uint32_t>(device) << 24) | (static_cast<uint32_t>(tag.value[0]) << 16) |+ (static_cast<uint32_t>(tag.value[1]) << 8) | static_cast<uint32_t>(tag.value[2]);+}++constexpr uint32_t section_key(const SectionId& id) noexcept {+ return section_key(id.device, id.tag);+}++inline constexpr SectionId model_id{runtime::hsm::any_device_id, runtime::hsm::model_id_tag};+inline constexpr SectionId runtime_requirements{runtime::hsm::any_device_id, runtime::hsm::runtime_requirements_tag};+inline constexpr SectionId model_struct{device_id, runtime::hsm::model_tag};+inline constexpr SectionId weights{device_id, runtime::hsm::weights_tag};+inline constexpr SectionId compiled_options{device_id, runtime::hsm::compiled_options_tag};+// TEMPLATE-specific: layout version and feature flags, no common equivalent.+inline constexpr SectionId blob_info{device_id, runtime::hsm::SectionTag::make_device_tag(3, /*is_inline=*/true)};++/// Inline section: layout version of this plugin's own sections plus feature flags.+struct BlobInfo {+ static constexpr uint32_t current_layout_version = 1;+ static constexpr uint32_t weights_embedded = 1u << 0;+ static constexpr uint32_t weightless = 1u << 1; //!< Model needs no weights at all - not just "stored externally".++ uint32_t layout_version = current_layout_version;+ uint32_t flags = 0;+};+static_assert(sizeof(BlobInfo) == 8, "BlobInfo must fit the inline slot without padding");++} // namespace hsm+} // namespace ov::template_plugindiff --git a/src/plugins/template/src/hsm_reader_handler.cpp b/src/plugins/template/src/hsm_reader_handler.cppnew file mode 100644index 00000000000..56604ff0af6--- /dev/null+++ b/src/plugins/template/src/hsm_reader_handler.cpp@@ -0,0 +1,112 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "hsm_reader_handler.hpp"++#include <algorithm>+#include <string_view>++#include "openvino/core/except.hpp"+#include "openvino/runtime/hsm_model_id_codec.hpp"+#include "openvino/runtime/shared_buffer.hpp"++namespace ov::template_plugin {++namespace {+std::optional<std::string> decode_string(const runtime::hsm::Section& section) {+ std::string value(section.size(), '\0');+ return section.read(value.data()) ? std::optional(std::move(value)) : std::nullopt;+}++std::optional<hsm::BlobInfo> decode_blob_info(const runtime::hsm::Section& section) {+ hsm::BlobInfo info{};+ return section.size() >= sizeof(info) && section.read(0, sizeof(info), &info) ? std::optional(info) : std::nullopt;+}++// Zero-copy only when the section's bytes are addressable AND something keeps them alive past this call+// (m_source_blob) - a stream-backed import has neither, so it always copies into an owned buffer.+std::shared_ptr<ov::AlignedBuffer> decode_buffer(const HsmReaderHandler& handler,+ const runtime::hsm::Section& section) {+ const auto section_view = section.view();+ if (handler.m_source_blob && !section_view.empty()) {+ return std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(+ const_cast<std::byte*>(section_view.data()),+ section_view.size(),+ handler.m_source_blob);+ } else {+ auto buffer = std::make_shared<ov::AlignedBuffer>(section.size());+ return section.read(buffer->get_ptr()) ? buffer : nullptr;+ }+}++// Inverse of encode_compiled_options() in hsm_writer_handler.cpp - one `key=value` per line, split on the first '='.+ov::AnyMap decode_compiled_options(std::string_view encoded) {+ ov::AnyMap options;+ while (!encoded.empty()) {+ const auto line_end = std::min(encoded.find('\n'), encoded.size());+ const auto line = encoded.substr(0, line_end);+ if (const auto separator = line.find('='); separator != std::string_view::npos) {+ options.emplace(std::string(line.substr(0, separator)), std::string(line.substr(separator + 1)));+ }+ encoded.remove_prefix(std::min(line_end + 1, encoded.size()));+ }+ return options;+}++void set_model_id(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ handler.m_model_id = runtime::hsm::decode_model_id(section);+}++void set_runtime_requirements(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ handler.m_runtime_requirements = decode_string(section);+}++void set_model(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ handler.m_model = decode_buffer(handler, section);+}++void set_weights(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ // An empty section means "no weights embedded" (weightless) - a null buffer represents that, matching+ // check_mandatory_sections()/read_hsm_blob()'s "falsy means absent" convention.+ handler.m_weights = section.size() == 0 ? nullptr : decode_buffer(handler, section);+}++void set_compiled_options(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ handler.m_compiled_options = decode_compiled_options(decode_string(section).value_or(""));+}++void set_blob_info(HsmReaderHandler& handler, const runtime::hsm::Section& section) {+ handler.m_blob_info = decode_blob_info(section);+}+} // namespace++const std::map<uint32_t, HsmReaderHandler::Decoder> HsmReaderHandler::s_decoders = {+ // model id and weights are each registered under BOTH device scopes - a blob may carry either as a+ // common (any_device_id) tag or scoped to this device, decoded identically either way.+ {hsm::section_key(runtime::hsm::any_device_id, hsm::weights.tag), set_weights},+ {hsm::section_key(hsm::model_id), set_model_id},+ {hsm::section_key(hsm::device_id, hsm::model_id.tag), set_model_id},+ {hsm::section_key(hsm::runtime_requirements), set_runtime_requirements},+ {hsm::section_key(hsm::model_struct), set_model},+ {hsm::section_key(hsm::weights), set_weights},+ {hsm::section_key(hsm::compiled_options), set_compiled_options},+ {hsm::section_key(hsm::blob_info), set_blob_info},+};++bool HsmReaderHandler::handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) {+ if (const auto decoder = s_decoders.find(hsm::section_key(entry.device, entry.tag)); decoder != s_decoders.end()) {+ decoder->second(*this, section);+ return true;+ } else {+ return false; // unrecognized (device, tag) pair - skip, per the unknown-tag rule.+ }+}++void HsmReaderHandler::check_mandatory_sections() const {+ OPENVINO_ASSERT(m_blob_info && m_blob_info->layout_version <= hsm::BlobInfo::current_layout_version,+ "TEMPLATE: missing or unsupported blob info section");+ OPENVINO_ASSERT(m_model, "TEMPLATE: missing mandatory model struct section");+}++} // namespace ov::template_plugindiff --git a/src/plugins/template/src/hsm_reader_handler.hpp b/src/plugins/template/src/hsm_reader_handler.hppnew file mode 100644index 00000000000..1df89c08c0d--- /dev/null+++ b/src/plugins/template/src/hsm_reader_handler.hpp@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Reader-side HSM logic for this plugin: HsmReaderHandler is the ISectionReaderHandler that claims every+// section of this blob (Core-owned and TEMPLATE-owned alike) during+// ov::runtime::hsm::Reader::read_sections() dispatch - decoding is entirely internal to it, nothing is+// exposed as a free function.++#pragma once++#include <map>+#include <optional>+#include <string>++#include "hsm_common.hpp"+#include "openvino/core/any.hpp"+#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/hsm_reader.hpp"+#include "openvino/runtime/tensor.hpp"++namespace ov::template_plugin {++class HsmReaderHandler final : public runtime::hsm::ISectionReaderHandler {+public:+ bool handle_section(const runtime::hsm::ManifestEntry& entry, const runtime::hsm::Section& section) override;++ void check_mandatory_sections() const;++ std::shared_ptr<ov::AlignedBuffer> m_source_blob; // Set before read_sections() when importing ov::Tensor+ std::optional<uint64_t> m_model_id;+ std::optional<std::string> m_runtime_requirements;+ std::shared_ptr<ov::AlignedBuffer> m_model;+ std::shared_ptr<ov::AlignedBuffer> m_weights;+ std::optional<hsm::BlobInfo> m_blob_info;+ ov::AnyMap m_compiled_options;++private:+ using Decoder = void (*)(HsmReaderHandler&, const runtime::hsm::Section&);+ static const std::map<uint32_t, Decoder> s_decoders;+};++} // namespace ov::template_plugindiff --git a/src/plugins/template/src/hsm_writer_handler.cpp b/src/plugins/template/src/hsm_writer_handler.cppnew file mode 100644index 00000000000..a7f1fcd68fb--- /dev/null+++ b/src/plugins/template/src/hsm_writer_handler.cpp@@ -0,0 +1,271 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "hsm_writer_handler.hpp"++#include <functional>+#include <optional>+#include <ostream>+#include <streambuf>+#include <string>+#include <string_view>+#include <type_traits>++#include "openvino/core/except.hpp"+#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/compilation_context.hpp"+#include "openvino/runtime/properties.hpp"+#include "openvino/util/hash_util.hpp"++namespace ov::template_plugin {++namespace {+// Page-aligned start keeps the large sections mmap/DMA friendly; no slot padding, nothing follows that needs it.+constexpr runtime::hsm::SectionAlignment page_alignment{util::min_page_alignment, 0};++// Forwards written chunks to a sink (may be empty) and tracks the position for tellp(); never stores data.+class ForwardingStreamBuf final : public std::streambuf {+public:+ using Callback = runtime::hsm::SectionSink;++ explicit ForwardingStreamBuf(Callback callback = {}) : m_callback(std::move(callback)), m_pos(0) {}++ size_t size() const noexcept {+ return static_cast<size_t>(m_pos);+ }++protected:+ std::streamsize xsputn(const char* s, std::streamsize n) override {+ put(s, static_cast<size_t>(n));+ return n;+ }++ int_type overflow(int_type ch) override {+ if (!traits_type::eq_int_type(ch, traits_type::eof())) {+ const auto c = traits_type::to_char_type(ch);+ put(&c, 1);+ }+ return traits_type::not_eof(ch);+ }++ pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode) override {+ return off == 0 && dir == std::ios_base::cur ? pos_type(m_pos) : pos_type(off_type(-1));+ }++private:+ void put(const char* data, size_t size) {+ if (m_callback) {+ m_callback({reinterpret_cast<const std::byte*>(data), size});+ }+ m_pos += static_cast<off_type>(size);+ }++ Callback m_callback;+ off_type m_pos;+};++struct ModelStats {+ size_t weights_size = 0;+ uint64_t hash = 0; // of the serialized structure and the weights size, not the weight values+};++// Serializes into counting/hashing buffers only, so nothing of the model is kept in memory.+ModelStats measure_model(const std::shared_ptr<ov::Model>& model) {+ uint64_t hash = 0;+ ForwardingStreamBuf xml_buf{[&hash](ov::util::MemoryView chunk) {+ const std::string_view text{reinterpret_cast<const char*>(chunk.data()), chunk.size()};+ hash = util::u64_hash_combine(hash, std::hash<std::string_view>{}(text));+ }};+ ForwardingStreamBuf bin_buf;+ std::ostream xml(&xml_buf), bin(&bin_buf);+ ov::pass::Serialize(xml, bin).run_on_model(model);+ return {bin_buf.size(), util::u64_hash_combine(hash, bin_buf.size())};+}++// Serializes the model in one pass: write_weights() streams the weights as produced and keeps the small XML for+// write_structure(), so calling them in that order avoids a second pass.+class ModelSerializer {+public:+ explicit ModelSerializer(std::shared_ptr<ov::Model> model) : m_model(std::move(model)) {}++ void write_weights(const runtime::hsm::SectionSink& sink) {+ auto& xml = m_xml.emplace();+ ForwardingStreamBuf xml_buf{[&xml](ov::util::MemoryView chunk) {+ xml.append(reinterpret_cast<const char*>(chunk.data()), chunk.size());+ }};+ ForwardingStreamBuf bin_buf{sink};+ std::ostream xml_out(&xml_buf), bin_out(&bin_buf);+ ov::pass::Serialize(xml_out, bin_out).run_on_model(m_model);+ }++ // Runs its own pass when write_weights() was not called before.+ void write_structure(const runtime::hsm::SectionSink& sink) {+ if (m_xml) {+ sink({reinterpret_cast<const std::byte*>(m_xml->data()), m_xml->size()});+ m_xml.reset();+ } else {+ ForwardingStreamBuf xml_buf{sink}, discard_buf;+ std::ostream xml_out(&xml_buf), bin_out(&discard_buf);+ ov::pass::Serialize(xml_out, bin_out).run_on_model(m_model);+ }+ }++private:+ std::shared_ptr<ov::Model> m_model;+ std::optional<std::string> m_xml;+};++class SerializeEncoder final : public runtime::hsm::ISectionEncoder {+public:+ using Write = void (ModelSerializer::*)(const runtime::hsm::SectionSink&);++ SerializeEncoder(std::shared_ptr<ModelSerializer> serializer, Write write)+ : m_serializer(std::move(serializer)),+ m_write(write) {}++ void encode(const runtime::hsm::SectionSink& sink) const override {+ ((*m_serializer).*m_write)(sink);+ }++private:+ std::shared_ptr<ModelSerializer> m_serializer;+ Write m_write;+};++// Cache-relevant options plus the weights path, which a weightless blob needs on import; restored through+// Configuration.+ov::AnyMap get_compiled_options(const Configuration& cfg, ov::AnyMap cache_options) {+ if (!cfg.weights_path.empty()) {+ cache_options.emplace(ov::weights_path.name(), cfg.weights_path.string());+ }+ return cache_options;+}++// One `key=value` per line; inverse of decode_compiled_options() in hsm_reader_handler.cpp.+std::string encode_compiled_options(const ov::AnyMap& options) {+ std::string encoded;+ for (const auto& [key, value] : options) {+ encoded.append(key).append(1, '=').append(value.as<std::string>()).append(1, '\n');+ }+ return encoded;+}+} // namespace++/// Owns a small section's bytes (metadata only); large payloads must be streamed to avoid a second in-memory copy.+class HsmWriterHandler::BytesEncoder final : public runtime::hsm::ISectionEncoder {+ static constexpr auto max_size = util::min_page_alignment; // one page+public:+ explicit BytesEncoder(std::string bytes) : m_bytes(std::move(bytes)) {+ OPENVINO_ASSERT(m_bytes.size() <= max_size, "TEMPLATE: HSM section too large to buffer: ", m_bytes.size());+ }++ template <class T>+ static std::shared_ptr<BytesEncoder> from_value(const T& value) {+ static_assert(std::is_trivially_copyable_v<T>);+ return std::make_shared<BytesEncoder>(std::string(reinterpret_cast<const char*>(&value), sizeof(T)));+ }++ size_t size() const noexcept {+ return m_bytes.size();+ }++ ov::util::MemoryView view() const noexcept {+ return {reinterpret_cast<const std::byte*>(m_bytes.data()), m_bytes.size()};+ }++ void encode(const runtime::hsm::SectionSink& sink) const override {+ sink(view());+ }++private:+ std::string m_bytes;+};++HsmWriterHandler::HsmWriterHandler(const std::shared_ptr<ov::Model>& model,+ const Configuration& cfg,+ const ov::AnyMap& cache_options,+ std::string_view runtime_requirements) {+ const auto stats = measure_model(model);+ const auto is_weights_embedded = stats.weights_size > 0 && cfg.cache_mode == ov::CacheMode::OPTIMIZE_SPEED;+ hsm::BlobInfo info;+ info.flags = (is_weights_embedded ? hsm::BlobInfo::weights_embedded : 0u) |+ (stats.weights_size == 0 ? hsm::BlobInfo::weightless : 0u);+ const auto model_hash = std::stoull(ov::ModelCache::compute_hash(std::to_string(stats.hash), {}, cache_options));++ m_encoders.emplace(hsm::section_key(hsm::model_id),+ Slot{hsm::model_id, BytesEncoder::from_value(static_cast<uint64_t>(model_hash))});+ m_encoders.emplace(+ hsm::section_key(hsm::runtime_requirements),+ Slot{hsm::runtime_requirements, std::make_shared<BytesEncoder>(std::string(runtime_requirements))});+ m_encoders.emplace(+ hsm::section_key(hsm::compiled_options),+ Slot{hsm::compiled_options,+ std::make_shared<BytesEncoder>(encode_compiled_options(get_compiled_options(cfg, cache_options)))});++ const auto serializer = std::make_shared<ModelSerializer>(model);+ m_encoders.emplace(hsm::section_key(hsm::model_struct),+ Slot{hsm::model_struct,+ std::make_shared<SerializeEncoder>(serializer, &ModelSerializer::write_structure),+ std::nullopt,+ page_alignment});++ if (is_weights_embedded) {+ m_encoders.emplace(hsm::section_key(hsm::weights),+ Slot{hsm::weights,+ std::make_shared<SerializeEncoder>(serializer, &ModelSerializer::write_weights),+ stats.weights_size,+ page_alignment});+ }+ m_encoders.emplace(hsm::section_key(hsm::blob_info), Slot{hsm::blob_info, BytesEncoder::from_value(info)});+}++HsmWriterHandler::Slot::Slot(const hsm::SectionId& id,+ const std::shared_ptr<BytesEncoder>& bytes,+ runtime::hsm::SectionAlignment align)+ : m_id(id),+ m_align(align),+ m_encoder(bytes),+ m_size(bytes->size()),+ m_view(bytes->view()) {}++HsmWriterHandler::Slot::Slot(const hsm::SectionId& id,+ runtime::hsm::SectionEncoderPtr encoder,+ std::optional<size_t> size,+ runtime::hsm::SectionAlignment align)+ : m_id(id),+ m_align(align),+ m_encoder(std::move(encoder)),+ m_size(size),+ m_view{} {}++bool HsmWriterHandler::Slot::add_to(runtime::hsm::IWriter& writer) const {+ if (m_id.tag.is_inline()) {+ return writer.add_section(m_id.device, m_id.tag, m_view);+ } else if (m_size) {+ return writer.add_section(m_id.device, m_id.tag, *m_size, m_encoder, m_align);+ } else {+ return writer.add_section(m_id.device, m_id.tag, m_encoder, m_align);+ }+}++// ! [hsm_writer_handler:handle_section]+void HsmWriterHandler::handle_section(runtime::hsm::IWriter& writer) const {+ const auto add_slot = [&writer](uint32_t key, const Slot& slot) {+ OPENVINO_ASSERT(slot.add_to(writer), "TEMPLATE: cannot add HSM section ", key);+ };++ // Weights first: the serialization pass streams them before the structure section is written.+ const auto weights_key = hsm::section_key(hsm::weights);+ if (const auto weights = m_encoders.find(weights_key); weights != m_encoders.end()) {+ add_slot(weights->first, weights->second);+ }+ for (const auto& [key, slot] : m_encoders) {+ if (key != weights_key) {+ add_slot(key, slot);+ }+ }+}+// ! [hsm_writer_handler:handle_section]++} // namespace ov::template_plugindiff --git a/src/plugins/template/src/hsm_writer_handler.hpp b/src/plugins/template/src/hsm_writer_handler.hppnew file mode 100644index 00000000000..a051ff60697--- /dev/null+++ b/src/plugins/template/src/hsm_writer_handler.hpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Writer-side HSM logic for this plugin: HsmWriterHandler is the ISectionWriterHandler that contributes every+// section of the blob (Core-owned and TEMPLATE-owned alike) during ov::runtime::hsm::IWriter::add_sections().++#pragma once++#include <cstdint>+#include <map>+#include <memory>+#include <optional>+#include <string_view>++#include "config.hpp"+#include "hsm_common.hpp"+#include "openvino/core/model.hpp"+#include "openvino/runtime/hsm_writer.hpp"++namespace ov::template_plugin {++class HsmWriterHandler final : public runtime::hsm::ISectionWriterHandler {+public:+ /// Keeps @p model and streams its serialized form into the blob at IWriter::finalize(), so the structure and the+ /// weights are never copied into temporary buffers.+ /// @p cache_options are the compile options that form the Core cache ID; they are persisted and hashed with the+ /// model.+ HsmWriterHandler(const std::shared_ptr<ov::Model>& model,+ const Configuration& cfg,+ const ov::AnyMap& cache_options,+ std::string_view runtime_requirements);++ /// The handler must outlive IWriter::finalize(): inline sections are borrowed from its encoders.+ void handle_section(runtime::hsm::IWriter& writer) const override;++private:+ class BytesEncoder;++ struct Slot {+ Slot(const hsm::SectionId& id,+ const std::shared_ptr<BytesEncoder>& bytes,+ runtime::hsm::SectionAlignment align = {});+ Slot(const hsm::SectionId& id,+ runtime::hsm::SectionEncoderPtr encoder,+ std::optional<size_t> size,+ runtime::hsm::SectionAlignment align);++ bool add_to(runtime::hsm::IWriter& writer) const;++ hsm::SectionId m_id;+ runtime::hsm::SectionAlignment m_align;+ runtime::hsm::SectionEncoderPtr m_encoder;+ std::optional<size_t> m_size; // unset: the size is known only after encoding+ ov::util::MemoryView m_view; // set for the sections small enough to be borrowed as inline+ };++ std::map<uint32_t, Slot> m_encoders;+};++} // namespace ov::template_plugindiff --git a/src/plugins/template/src/plugin.cpp b/src/plugins/template/src/plugin.cppindex 23a4da95201..03c1ddb9f8b 100644--- a/src/plugins/template/src/plugin.cpp+++ b/src/plugins/template/src/plugin.cpp@@ -4,13 +4,16 @@#include "plugin.hpp"-#include <fstream>#include <memory>#include "attach_cache_manager_to_paged_attention.hpp"+#include "hsm_common.hpp"+#include "hsm_reader_handler.hpp"#include "itt.hpp"#include "openvino/op/ops.hpp"#include "openvino/pass/manager.hpp"+#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/hsm_reader.hpp"#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/shared_buffer.hpp"@@ -33,6 +36,16 @@ static constexpr const char* wait_executor_name = "TemplateWaitExecutor";static constexpr const char* stream_executor_name = "TemplateStreamsExecutor";static constexpr const char* template_exclusive_executor = "TemplateExecutor";+using ov::template_plugin::Plugin, ov::template_plugin::Configuration, ov::template_plugin::HsmReaderHandler;++// Properties that affect the compiled model; they form the cache ID and are persisted in the HSM blob.+std::vector<ov::PropertyName> caching_properties() {+ return {ov::device::architecture,+ ov::hint::performance_mode,+ ov::hint::execution_mode,+ ov::hint::inference_precision};+}+uint64_t get_blob_data_size(std::istream& model) {uint64_t size = 0;model.read(reinterpret_cast<char*>(&size), sizeof(size));@@ -59,19 +72,26 @@ ov::Tensor get_model_weights(std::istream& model) {}ov::Tensor get_model_weights(const ov::AnyMap& properties) {- ov::Tensor weights;if (auto weights_path = properties.find(ov::weights_path.name()); weights_path != properties.end()) {- const auto w_path = std::filesystem::path(weights_path->second.as<std::string>());- if (auto size = ov::util::file_size(w_path); size > 0) {- auto f_weights = std::ifstream(w_path, std::ios::binary | std::ios::in);- weights = read_weights(f_weights, size);- }+ const auto w_path = ov::util::make_path(weights_path->second.as<std::string>());+ return ov::read_tensor_data(w_path);+ } else {+ return {};}- return weights;+}++// Removes import-only hints from properties; returns the ov::loaded_from_cache value.+bool consume_cache_import_hints(ov::AnyMap& properties) {+ bool loaded_from_cache = false;+ if (auto node = properties.extract(ov::loaded_from_cache.name())) {+ loaded_from_cache = node.mapped().as<bool>();+ }+ properties.erase(ov::hint::compiled_blob.name());+ return loaded_from_cache;}std::shared_ptr<ov::Model> get_ov_model_from_blob(const ov::template_plugin::Plugin& plugin,- ov::Tensor& weights,+ const ov::Tensor& weights,size_t offset,const ov::AnyMap& properties) {if (auto blob_it = properties.find(ov::hint::compiled_blob.name()); blob_it != properties.end()) {@@ -88,6 +108,57 @@ std::shared_ptr<ov::Model> get_ov_model_from_blob(const ov::template_plugin::Plu}return nullptr;};++// ! [plugin:read_hsm_blob]+std::shared_ptr<ov::AlignedBuffer> to_aligned_buffer(ov::Tensor tensor) {+ if (!tensor) {+ return nullptr;+ }+ // const data(): tensor may be read-only (e.g. mmap'd weights) - never written through, only wrapped.+ const auto* data = reinterpret_cast<const std::byte*>(static_cast<const ov::Tensor&>(tensor).data());+ return std::make_shared<ov::SharedBuffer<ov::Tensor>>(const_cast<std::byte*>(data), tensor.get_byte_size(), tensor);+}++std::pair<std::shared_ptr<ov::Model>, Configuration> read_hsm_blob(+ const std::shared_ptr<ov::ICore>& core,+ std::string_view runtime_requirements,+ const Configuration& default_cfg,+ const ov::runtime::hsm::Reader& reader,+ const ov::AnyMap& properties,+ ov::Tensor properties_weights_hint,+ std::shared_ptr<ov::AlignedBuffer> source_blob = {}) {+ HsmReaderHandler handler;+ handler.m_source_blob = source_blob;+ reader.read_sections({&handler});+ handler.check_mandatory_sections();++ // Opaque and optional, like NPU's own ov::runtime_requirements: absent means "nothing to check", not+ // an import failure - only a present-but-mismatched descriptor rejects the blob.+ if (const auto& requirements = handler.m_runtime_requirements) {+ OPENVINO_ASSERT(requirements->find(runtime_requirements) == 0,+ "TEMPLATE: unsupported blob runtime requirements: ",+ *requirements);+ }++ auto config = Configuration{properties, Configuration{handler.m_compiled_options, default_cfg, false}};++ const bool weightless = handler.m_blob_info->flags & ov::template_plugin::hsm::BlobInfo::weightless;+ auto weights = handler.m_weights;+ if (!weights) {+ weights = to_aligned_buffer(properties_weights_hint);+ }+ // Last resort: the path the model was originally compiled with, restored from the blob's own compiled+ // options - properties_weights_hint only covers what the caller already knew from @p properties.+ if (!weights && !config.weights_path.empty() && ov::util::file_size(config.weights_path) > 0) {+ weights = to_aligned_buffer(ov::read_tensor_data(config.weights_path));+ }+ OPENVINO_ASSERT(weightless || weights,+ "TEMPLATE: missing mandatory weights section (model is not weightless and no external "+ "weights were provided)");++ return {core->read_model(handler.m_model, weights), std::move(config)};+}+// ! [plugin:read_hsm_blob]} // namespace// ! [plugin:ctor]@@ -240,74 +311,85 @@ std::shared_ptr<ov::ICompiledModel> ov::template_plugin::Plugin::import_model(const ov::AnyMap& properties) const {OV_ITT_SCOPED_TASK(itt::domains::TemplatePlugin, "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);- }- _properties.erase(ov::hint::compiled_blob.name());+ auto import_properties = properties;+ const auto loaded_from_cache = consume_cache_import_hints(import_properties);- auto fullConfig = Configuration{_properties, m_cfg};- fullConfig.streams_executor_config = ov::threading::IStreamsExecutor::Config{stream_executor_name,- fullConfig.streams,- fullConfig.threads_per_stream};auto weights = get_model_weights(properties);- if (!weights) {- if (auto model_hint = properties.find(ov::hint::model.name()); model_hint != properties.end()) {- if (auto m = model_hint->second.as<std::shared_ptr<ov::Model>>()) {- if (m->has_rt_info("__weights_path")) {- AnyMap rt_info;- rt_info[ov::weights_path.name()] = m->get_rt_info<ov::Any>("__weights_path");- weights = get_model_weights(rt_info);- }- }- }- }auto ov_model = get_ov_model_from_blob(*this, weights, model.tellg(), properties);- if (!ov_model) {++ Configuration config;+ const auto hsm_start = model.tellg();+ if (ov_model) {+ // Already fully imported from the hint above - no need to parse `model` at all.+ config = Configuration{import_properties, m_cfg};+ } else if (auto hsm_reader = ov::runtime::hsm::Reader::open(model)) {+ std::tie(ov_model, config) =+ read_hsm_blob(get_core(), get_runtime_requirements(), m_cfg, *hsm_reader, import_properties, weights);+ } else {+ // hsm reader failed on open (not valid hsm blob) - fall back to legacy path and restore stream possition+ // when legacy import removed this should be import error+ model.clear();+ model.seekg(hsm_start);++ config = Configuration{import_properties, m_cfg};// read XML content- std::string xmlString = get_model_str(model);+ const auto model_xml = get_model_str(model);// read blob contentif (!weights) {weights = get_model_weights(model);}- ov_model = get_core()->read_model(xmlString, weights);+ ov_model = get_core()->read_model(model_xml, weights);}- auto streamsExecutorConfig =- ov::threading::IStreamsExecutor::Config::make_default_multi_threaded(fullConfig.streams_executor_config);- fullConfig.streams = streamsExecutorConfig.get_streams();- fullConfig.threads = streamsExecutorConfig.get_threads();- fullConfig.threads_per_stream = streamsExecutorConfig.get_threads_per_stream();- auto compiled_model =- std::make_shared<CompiledModel>(ov_model,- shared_from_this(),- context,- get_executor_manager()->get_idle_cpu_streams_executor(streamsExecutorConfig),- fullConfig,- loaded_from_cache);- return compiled_model;++ const auto task_executor = get_executor_manager()->get_idle_cpu_streams_executor(+ ov::threading::IStreamsExecutor::Config::make_default_multi_threaded(config.streams_executor_config));+ return std::make_shared<CompiledModel>(ov_model,+ shared_from_this(),+ context,+ task_executor,+ config,+ loaded_from_cache);}// ! [plugin:import_model_with_remote]std::shared_ptr<ov::ICompiledModel> ov::template_plugin::Plugin::import_model(const ov::Tensor& model,const ov::AnyMap& properties) const {- ov::SharedStreamBuffer buffer{model.data(), model.get_byte_size()};- std::istream stream{&buffer};- return import_model(stream, properties);+ return import_model(model, {}, properties);}std::shared_ptr<ov::ICompiledModel> ov::template_plugin::Plugin::import_model(const ov::Tensor& model,const ov::SoPtr<ov::IRemoteContext>& context,const ov::AnyMap& properties) const {- ov::SharedStreamBuffer buffer{model.data(), model.get_byte_size()};- std::istream stream{&buffer};- return import_model(stream, properties);+ if (auto reader =+ ov::runtime::hsm::Reader::open(static_cast<const std::byte*>(model.data()), model.get_byte_size())) {+ auto import_properties = properties;+ const auto loaded_from_cache = consume_cache_import_hints(import_properties);+ const auto [imported_model, imported_config] = read_hsm_blob(get_core(),+ get_runtime_requirements(),+ m_cfg,+ *reader,+ import_properties,+ get_model_weights(properties),+ to_aligned_buffer(model));++ const auto executor = get_executor_manager()->get_idle_cpu_streams_executor(+ ov::threading::IStreamsExecutor::Config::make_default_multi_threaded(+ imported_config.streams_executor_config));+ return std::make_shared<CompiledModel>(imported_model,+ shared_from_this(),+ context,+ executor,+ imported_config,+ loaded_from_cache);+ } else {+ // legacy format+ ov::SharedStreamBuffer buffer{model.data(), model.get_byte_size()};+ std::istream stream{&buffer};+ return import_model(stream, properties);+ }}// ! [plugin:query_model]@@ -417,14 +499,21 @@ ov::Any ov::template_plugin::Plugin::get_property(const std::string& name, constsupported_properties.insert(supported_properties.end(), rw_properties.begin(), rw_properties.end());return supported_properties;} else if (ov::internal::supported_properties == name) {- return decltype(ov::internal::supported_properties)::value_type{+ auto internal_properties = decltype(ov::internal::supported_properties)::value_type{ov::PropertyName{ov::internal::caching_properties.name(), ov::PropertyMutability::RO},ov::PropertyName{ov::internal::exclusive_async_requests.name(), ov::PropertyMutability::RW},ov::PropertyName{ov::inference_num_threads.name(), ov::PropertyMutability::RW},ov::PropertyName{ov::internal::threads_per_stream.name(), ov::PropertyMutability::RW},ov::PropertyName{ov::internal::compiled_model_runtime_properties.name(), ov::PropertyMutability::RO},ov::PropertyName{ov::internal::cache_header_alignment.name(), ov::PropertyMutability::RO},+ ov::PropertyName{ov::internal::emit_hsm_format.name(), ov::PropertyMutability::RO},+ ov::PropertyName{ov::template_plugin::export_hsm_format.name(), ov::PropertyMutability::RW},};+ // Only the HSM reader imports from a mapped blob without copying; the legacy path would copy it.+ if (m_cfg.export_hsm_format) {+ internal_properties.emplace_back(ov::internal::caching_with_mmap.name(), ov::PropertyMutability::RO);+ }+ return internal_properties;} else if (ov::available_devices == name) {// TODO: fill list of available devicesreturn decltype(ov::available_devices)::value_type{{""}};@@ -436,7 +525,7 @@ ov::Any ov::template_plugin::Plugin::get_property(const std::string& name, const} else if (ov::device::type == name) {return decltype(ov::device::type)::value_type{ov::device::Type::INTEGRATED};} else if (ov::internal::caching_properties == name) {- return decltype(ov::internal::caching_properties)::value_type{ov::device::architecture};+ return decltype(ov::internal::caching_properties)::value_type{caching_properties()};} else if (ov::device::capabilities == name) {// TODO: fill actual list of supported capabilities: e.g. Template device supports only FP32 and EXPORT_IMPORTreturn decltype(ov::device::capabilities)::value_type{ov::device::capability::FP32,diff --git a/src/plugins/template/tests/functional/CMakeLists.txt b/src/plugins/template/tests/functional/CMakeLists.txtindex 590d65bb7c6..8a7301e2e16 100644--- a/src/plugins/template/tests/functional/CMakeLists.txt+++ b/src/plugins/template/tests/functional/CMakeLists.txt@@ -11,6 +11,7 @@ endif()set(OV_TEMPLATE_TESTS_SRCS${CMAKE_CURRENT_SOURCE_DIR}/core_config.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/hsm_blob_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/set_device_name.cpp${CMAKE_CURRENT_SOURCE_DIR}/skip_tests_config.cpp${CMAKE_CURRENT_SOURCE_DIR}/specific_properties_test.cppdiff --git a/src/plugins/template/tests/functional/hsm_blob_test.cpp b/src/plugins/template/tests/functional/hsm_blob_test.cppnew file mode 100644index 00000000000..5b3aeadab09--- /dev/null+++ b/src/plugins/template/tests/functional/hsm_blob_test.cpp@@ -0,0 +1,516 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <algorithm>+#include <bitset>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <functional>+#include <optional>+#include <sstream>++#include "behavior/compiled_model/import_export.hpp"+#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/file_utils.hpp"+#include "common_test_utils/ov_plugin_cache.hpp"+#include "common_test_utils/ov_tensor_utils.hpp"+#include "common_test_utils/test_assertions.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/core.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"+#include "openvino/runtime/hsm_reader.hpp"+#include "openvino/runtime/internal_properties.hpp"+#include "openvino/util/file_util.hpp"+#include "template/properties.hpp"++namespace ov::test {+namespace hsm = ov::runtime::hsm;++class TemplateHsmBlobTest : public ::testing::Test {+protected:+ static inline auto* const device = utils::DEVICE_TEMPLATE;+ static constexpr hsm::DeviceId template_device_id = 128;+ static constexpr auto blob_info_tag = hsm::SectionTag::make_device_tag(3, /*is_inline=*/true);+ static constexpr size_t blob_info_weights_embedded = 0;+ static constexpr size_t blob_info_weightless = 1;++ struct BlobInfoWire {+ uint32_t layout_version = 1;+ uint32_t flags = 0;+ };++ struct SerializedModel {+ std::string xml;+ std::shared_ptr<ov::AlignedBuffer> weights;+ };++ struct BlobSpec {+ std::string model_xml;+ bool include_model_struct = true;+ std::shared_ptr<ov::AlignedBuffer> weights;+ bool weightless = false;+ hsm::DeviceId weights_device = template_device_id;+ bool include_model_id = true;+ hsm::DeviceId model_id_device = hsm::any_device_id;+ bool reverse_order = false;+ };++ static std::shared_ptr<ov::Model> make_model() {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4});+ input->set_friendly_name("input");+ auto add = std::make_shared<ov::op::v1::Add>(+ input,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {1.f, 2.f, 3.f, 4.f}));+ auto mul = std::make_shared<ov::op::v1::Multiply>(+ add,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {0.5f, -1.f, 2.f, 3.f}));+ auto result = std::make_shared<ov::op::v0::Result>(mul);+ result->set_friendly_name("output");+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input}, "hsm_template_model");+ }++ static std::string export_blob(ov::CompiledModel compiled) {+ std::stringstream stream;+ compiled.export_model(stream);+ return stream.str();+ }++ static ov::util::MemoryView view_of(const std::string& data) {+ return {reinterpret_cast<const std::byte*>(data.data()), data.size()};+ }+ static ov::util::MemoryView view_of(const ov::AlignedBuffer& data) {+ return {reinterpret_cast<const std::byte*>(data.get_ptr()), data.size()};+ }++ static SerializedModel serialize_model(const std::shared_ptr<ov::Model>& model) {+ std::stringstream xml_stream, weights_stream;+ ov::pass::Serialize(xml_stream, weights_stream).run_on_model(model);+ const auto weights_str = weights_stream.str();+ auto weights = std::make_shared<ov::AlignedBuffer>(weights_str.size());+ std::memcpy(weights->get_ptr(), weights_str.data(), weights_str.size());+ return {xml_stream.str(), weights};+ }++ static std::string build_blob(const BlobSpec& spec) {+ std::stringstream stream;+ auto writer = hsm::DeferredWriter::open(stream);+ OPENVINO_ASSERT(writer, "Cannot open HSM writer");++ const uint64_t model_id_value = 0xC0FFEE;+ std::bitset<32> blob_info_flags;+ blob_info_flags[blob_info_weights_embedded] = spec.weights != nullptr;+ blob_info_flags[blob_info_weightless] = spec.weightless;+ const BlobInfoWire blob_info{1, static_cast<uint32_t>(blob_info_flags.to_ulong())};++ std::vector<std::function<void()>> sections;+ if (spec.include_model_struct) {+ sections.push_back([&] {+ OPENVINO_ASSERT(writer->add_section(template_device_id, hsm::model_tag, view_of(spec.model_xml)));+ });+ }+ if (spec.weights) {+ sections.push_back([&] {+ OPENVINO_ASSERT(writer->add_section(spec.weights_device, hsm::weights_tag, view_of(*spec.weights)));+ });+ }+ if (spec.include_model_id) {+ sections.push_back([&] {+ OPENVINO_ASSERT(writer->add_section(spec.model_id_device,+ hsm::model_id_tag,+ ov::util::as_memory_view(model_id_value)));+ });+ }+ sections.push_back([&] {+ OPENVINO_ASSERT(+ writer->add_section(template_device_id, blob_info_tag, ov::util::as_memory_view(blob_info)));+ });++ if (spec.reverse_order) {+ std::reverse(sections.begin(), sections.end());+ }+ for (const auto& add_section : sections) {+ add_section();+ }+ OPENVINO_ASSERT(!writer->finalize(), "HSM build failed");+ return stream.str();+ }++ static ov::Tensor infer(ov::CompiledModel& compiled) {+ const auto input =+ ov::test::utils::create_tensor<float>(ov::element::f32, ov::Shape{1, 4}, {1.f, -2.f, 3.f, -4.f});+ auto request = compiled.create_infer_request();+ request.set_input_tensor(input);+ request.infer();+ const auto output = request.get_output_tensor();+ ov::Tensor result(output.get_element_type(), output.get_shape());+ output.copy_to(result);+ return result;+ }++ static std::string read_file(const std::filesystem::path& path) {+ std::ifstream file(path, std::ios::binary);+ return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};+ }++ // Lazily generate one blob per suite; generateTestFilePrefix() requires an active test.+ static void generated_blob() {+ if (generated_blob_path.empty()) {+ const auto serialized = serialize_model(make_model());+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.weights = serialized.weights;+ const auto blob = build_blob(spec);++ generated_blob_path = std::filesystem::path(ov::test::utils::getExecutableDirectory()) /+ (ov::test::utils::generateTestFilePrefix() + "_hsm_generated.blob");+ std::ofstream(generated_blob_path, std::ios::binary).write(blob.data(), blob.size());+ }+ }++ static void TearDownTestSuite() {+ std::filesystem::remove(generated_blob_path);+ }++ // Exports in HSM format; @p config selects e.g. the weightless mode.+ std::string export_hsm(ov::AnyMap config = {}) {+ config.emplace(ov::template_plugin::export_hsm_format(true));+ auto compiled = core.compile_model(model, device, config);+ return export_blob(compiled);+ }++ static auto find_entry(std::vector<behavior::HsmEntry>& entries, hsm::DeviceId device, hsm::SectionTag tag) {+ return std::find_if(entries.begin(), entries.end(), [&](const auto& entry) {+ return entry.device == device && entry.tag.tag.id() == tag.id();+ });+ }++ // Saves the weights embedded in @p blob to a file that can be used as ov::weights_path.+ std::string save_weights(const std::string& blob) {+ std::stringstream stream(blob);+ const auto reader = hsm::Reader::open(stream);+ OPENVINO_ASSERT(reader, "Not an HSM blob");+ const auto weights = reader->section(template_device_id, hsm::weights);+ OPENVINO_ASSERT(weights, "No weights section");+ const auto bytes = weights->to_bytes();+ OPENVINO_ASSERT(bytes, "Cannot read the weights section");++ weights_file = ov::test::utils::generateTestFilePrefix() + "_hsm_weights.bin";+ std::ofstream(weights_file, std::ios::binary)+ .write(reinterpret_cast<const char*>(bytes->data()), static_cast<std::streamsize>(bytes->size()));+ return weights_file.string();+ }++ void check_cache_format(bool hsm_format) {+ const std::filesystem::path cache_path = "template_hsm_cache_" + utils::generateTestFilePrefix();+ // Plugin-level: Core reads the format from the plugin, not from the compile config, to decide on the header.+ core.set_property(device, ov::template_plugin::export_hsm_format(hsm_format));++ core.compile_model(model, device, ov::cache_path(cache_path));+ auto cached = core.compile_model(model, device, ov::cache_path(cache_path));++ EXPECT_TRUE(cached.get_property(ov::loaded_from_cache));+ utils::compare(reference, infer(cached));+ const auto blobs = utils::listFilesWithExt(ov::util::path_to_string(cache_path), "blob");+ ASSERT_EQ(blobs.size(), 1u);+ EXPECT_EQ(behavior::is_hsm(read_file(blobs.front())), hsm_format);++ utils::removeFilesWithExt(ov::util::path_to_string(cache_path), "blob");+ utils::removeDir(ov::util::path_to_string(cache_path));+ }++ void SetUp() override {+ core = utils::create_core(device);+ model = make_model();+ auto reference_compiled = core.compile_model(model, device);+ reference = infer(reference_compiled);+ }++ void TearDown() override {+ if (ov::util::file_exists(weights_file)) {+ std::filesystem::remove(weights_file);+ }+ }++ static inline std::filesystem::path generated_blob_path;++ ov::Core core;+ std::shared_ptr<ov::Model> model;+ ov::Tensor reference;+ std::filesystem::path weights_file;+};++TEST_F(TemplateHsmBlobTest, weights_path_hint_restores_model_when_weights_section_is_omitted) {+ const auto serialized = serialize_model(model);+ const auto weights_path = ov::test::utils::generateTestFilePrefix() + "_hsm_weights.bin";+ {+ std::ofstream file(weights_path, std::ios::binary);+ file.write((serialized.weights->get_ptr<char>()), static_cast<std::streamsize>(serialized.weights->size()));+ }++ BlobSpec spec;+ spec.model_xml = serialized.xml;+ const auto blob = build_blob(spec);++ std::stringstream stream(blob);+ auto imported = core.import_model(stream, device, {ov::weights_path(weights_path)});+ utils::compare(reference, infer(imported));++ std::filesystem::remove(weights_path);+}++TEST_F(TemplateHsmBlobTest, missing_mandatory_weights_section_is_rejected) {+ BlobSpec spec;+ spec.model_xml = serialize_model(model).xml;+ const auto blob = build_blob(spec);+ std::stringstream stream(blob);++ OV_EXPECT_THROW_HAS_SUBSTRING(core.import_model(stream, device), ov::Exception, "missing mandatory weights");+}++TEST_F(TemplateHsmBlobTest, missing_mandatory_model_struct_section_is_rejected) {+ const auto serialized = serialize_model(model);+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.include_model_struct = false;+ spec.weights = serialized.weights;+ const auto blob = build_blob(spec);+ std::stringstream stream(blob);++ OV_EXPECT_THROW_HAS_SUBSTRING(core.import_model(stream, device), ov::Exception, "missing mandatory model struct");+}++TEST_F(TemplateHsmBlobTest, model_struct_stored_inline_is_not_recognized) {+ const auto blob = behavior::hsm_repack(export_hsm(), [](std::vector<behavior::HsmEntry>& entries) {+ const auto entry = find_entry(entries, template_device_id, hsm::model_tag);+ ASSERT_NE(entry, entries.end());+ entry->tag = hsm::SectionTag::make(hsm::model_tag.id(), /*is_inline=*/true);+ entry->payload.resize(8);+ });+ std::stringstream stream(blob);++ OV_EXPECT_THROW_HAS_SUBSTRING(core.import_model(stream, device), ov::Exception, "missing mandatory model struct");+}++TEST_F(TemplateHsmBlobTest, blob_info_stored_as_pointer_is_not_recognized) {+ const auto blob = behavior::hsm_repack(export_hsm(), [](std::vector<behavior::HsmEntry>& entries) {+ const auto entry = find_entry(entries, template_device_id, blob_info_tag);+ ASSERT_NE(entry, entries.end());+ entry->tag = hsm::SectionTag::make(blob_info_tag.id(), /*is_inline=*/false);+ });+ std::stringstream stream(blob);++ OV_EXPECT_THROW_HAS_SUBSTRING(core.import_model(stream, device), ov::Exception, "missing or unsupported blob info");+}++TEST_F(TemplateHsmBlobTest, unknown_sections_are_skipped) {+ const auto blob = behavior::hsm_repack(export_hsm(), [](std::vector<behavior::HsmEntry>& entries) {+ entries.push_back({template_device_id, hsm::SectionTag::make_device_tag(100, false), {std::byte{1}}});+ entries.push_back({hsm::any_device_id, hsm::SectionTag::make(hsm::core_tag_id_range_end - 1, true), {}});+ });+ std::stringstream stream(blob);++ OV_ASSERT_NO_THROW(core.import_model(stream, device));+}++TEST_F(TemplateHsmBlobTest, model_id_section_is_optional) {+ const auto serialized = serialize_model(model);+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.weights = serialized.weights;+ spec.include_model_id = false;+ const auto blob = build_blob(spec);+ std::stringstream stream(blob);++ EXPECT_NO_THROW(core.import_model(stream, device));+}++TEST_F(TemplateHsmBlobTest, weights_and_model_id_sections_decode_under_any_device_id) {+ const auto serialized = serialize_model(model);+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.weights = serialized.weights;+ spec.weights_device = hsm::any_device_id;+ spec.model_id_device = hsm::any_device_id;+ const auto blob = build_blob(spec);++ std::stringstream stream(blob);+ auto imported = core.import_model(stream, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, weights_and_model_id_sections_decode_under_template_device_id) {+ const auto serialized = serialize_model(model);+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.weights = serialized.weights;+ spec.weights_device = template_device_id;+ spec.model_id_device = template_device_id;+ const auto blob = build_blob(spec);++ std::stringstream stream(blob);+ auto imported = core.import_model(stream, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, section_order_does_not_affect_import) {+ const auto serialized = serialize_model(model);+ BlobSpec spec;+ spec.model_xml = serialized.xml;+ spec.weights = serialized.weights;+ spec.reverse_order = true;+ const auto blob = build_blob(spec);++ std::stringstream stream(blob);+ auto imported = core.import_model(stream, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, generated_blob_is_imported_from_file) {+ generated_blob();+ const auto blob = read_file(generated_blob_path);+ const auto& header = hsm::Header::view(blob.data());+ EXPECT_EQ(header.version_major, hsm::FormatVersion::major);+ EXPECT_EQ(header.version_minor, hsm::FormatVersion::minor);++ std::stringstream stream(blob);+ auto imported = core.import_model(stream, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, generated_blob_is_imported_from_file_via_tensor) {+ generated_blob();+ const auto blob_tensor = ov::read_tensor_data(generated_blob_path);++ auto imported = core.import_model(blob_tensor, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, import_restores_compiled_options) {+ std::stringstream stream(export_hsm({ov::hint::performance_mode(ov::hint::PerformanceMode::THROUGHPUT)}));++ auto imported = core.import_model(stream, device);++ EXPECT_EQ(imported.get_property(ov::hint::performance_mode), ov::hint::PerformanceMode::THROUGHPUT);+ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, compiled_options_hold_the_cache_relevant_properties) {+ // A non-default value, so a persisted option can be told apart from the plugin default.+ std::stringstream stream(export_hsm({ov::hint::performance_mode(ov::hint::PerformanceMode::THROUGHPUT)}));+ const auto reader = hsm::Reader::open(stream);+ ASSERT_TRUE(reader);+ const auto section = reader->section(template_device_id, hsm::compiled_options);+ ASSERT_TRUE(section);+ const auto bytes = section->to_bytes();+ ASSERT_TRUE(bytes);+ // The section is `key=value` text, one option per line.+ const std::string options(reinterpret_cast<const char*>(bytes->data()), bytes->size());++ // Every property the plugin reports as cache-relevant is stored.+ for (const auto& name : core.get_property(device, ov::internal::caching_properties)) {+ EXPECT_NE(options.find(name + "="), std::string::npos) << name;+ }+ // The stored value is the one used for compilation, not the default.+ EXPECT_NE(options.find(std::string(ov::hint::performance_mode.name()) + "=THROUGHPUT"), std::string::npos)+ << options;+}++TEST_F(TemplateHsmBlobTest, model_id_is_stable_for_a_compiled_model) {+ auto compiled = core.compile_model(model, device, {ov::template_plugin::export_hsm_format(true)});+ const auto model_id = [&] {+ std::stringstream stream(export_blob(compiled));+ const auto reader = hsm::Reader::open(stream);+ OPENVINO_ASSERT(reader, "Not an HSM blob");+ const auto bytes = reader->section(hsm::any_device_id, hsm::model_id)->to_bytes();+ OPENVINO_ASSERT(bytes, "Cannot read the model id section");+ return std::string(reinterpret_cast<const char*>(bytes->data()), bytes->size());+ };++ EXPECT_EQ(model_id(), model_id());+}++TEST_F(TemplateHsmBlobTest, exported_blob_has_all_sections) {+ std::stringstream stream(export_hsm());+ const auto reader = hsm::Reader::open(stream);+ ASSERT_TRUE(reader);++ EXPECT_EQ(reader->entries().size(), 6u);+ EXPECT_EQ(reader->count(hsm::any_device_id, hsm::model_id), 1u);+ EXPECT_EQ(reader->count(hsm::any_device_id, hsm::runtime_requirements), 1u);+ EXPECT_EQ(reader->count(template_device_id, hsm::model), 1u);+ EXPECT_EQ(reader->count(template_device_id, hsm::weights), 1u);+ EXPECT_EQ(reader->count(template_device_id, hsm::compiled_options), 1u);+ EXPECT_EQ(reader->count(template_device_id, blob_info_tag.id()), 1u);+}++TEST_F(TemplateHsmBlobTest, weights_section_starts_on_a_page_boundary) {+ std::stringstream stream(export_hsm());+ const auto reader = hsm::Reader::open(stream);+ ASSERT_TRUE(reader);++ const auto& entries = reader->entries();+ const auto weights = std::find_if(entries.begin(), entries.end(), [](const hsm::ManifestEntry& entry) {+ return entry.device == template_device_id && entry.tag.id() == hsm::weights;+ });++ ASSERT_NE(weights, entries.end());+ EXPECT_EQ(weights->offset % 4096, 0u);+}++TEST_F(TemplateHsmBlobTest, cache_mode_optimize_size_omits_weights_section) {+ std::stringstream stream(export_hsm({ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE)}));+ const auto reader = hsm::Reader::open(stream);+ ASSERT_TRUE(reader);++ EXPECT_EQ(reader->count(template_device_id, hsm::model), 1u);+ EXPECT_EQ(reader->count(template_device_id, hsm::weights), 0u);+}++TEST_F(TemplateHsmBlobTest, weightless_blob_is_imported_with_weights_path_hint) {+ const auto weights_path = save_weights(export_hsm());+ std::stringstream stream(export_hsm({ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE)}));++ auto imported = core.import_model(stream, device, {ov::weights_path(weights_path)});++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, weightless_blob_restores_weights_path_from_compiled_options) {+ const auto weights_path = save_weights(export_hsm());+ std::stringstream stream(+ export_hsm({ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE), ov::weights_path(weights_path)}));++ auto imported = core.import_model(stream, device);++ utils::compare(reference, infer(imported));+}++TEST_F(TemplateHsmBlobTest, weightless_blob_without_weights_is_rejected) {+ std::stringstream stream(export_hsm({ov::cache_mode(ov::CacheMode::OPTIMIZE_SIZE)}));++ OV_EXPECT_THROW_HAS_SUBSTRING(core.import_model(stream, device), ov::Exception, "missing mandatory weights");+}++TEST_F(TemplateHsmBlobTest, cache_uses_hsm_format_selected_at_plugin_level) {+ check_cache_format(true);+}++TEST_F(TemplateHsmBlobTest, cache_uses_legacy_format_selected_at_plugin_level) {+ check_cache_format(false);+}+} // namespace ov::testdiff --git a/src/plugins/template/tests/functional/shared_tests_instances/behavior/ov_executable_network/ov_exec_net_import_export.cpp b/src/plugins/template/tests/functional/shared_tests_instances/behavior/ov_executable_network/ov_exec_net_import_export.cppindex c8842f8ecf5..29bd2209bcf 100644--- a/src/plugins/template/tests/functional/shared_tests_instances/behavior/ov_executable_network/ov_exec_net_import_export.cpp+++ b/src/plugins/template/tests/functional/shared_tests_instances/behavior/ov_executable_network/ov_exec_net_import_export.cpp@@ -3,6 +3,7 @@//#include "behavior/compiled_model/import_export.hpp"#include "common_test_utils/test_constants.hpp"+#include "template/properties.hpp"using namespace ov::test::behavior;namespace {@@ -19,7 +20,8 @@ const std::vector<ov::element::Type_t> netPrecisions = {ov::element::f32,};const std::vector<ov::AnyMap> configs = {- {},+ {ov::template_plugin::export_hsm_format(true)},+ {ov::template_plugin::export_hsm_format(false)},};INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,@@ -29,4 +31,16 @@ INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,::testing::ValuesIn(configs)),OVCompiledGraphImportExportTest::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,+ OVClassCompiledModelImportExportTestP,+ ::testing::Values(ov::test::utils::DEVICE_TEMPLATE),+ ::testing::PrintToStringParamName());++INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests,+ OVCompiledModelHsmBlobTest,+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_TEMPLATE),+ ::testing::Values(ov::AnyMap{+ ov::template_plugin::export_hsm_format(true)})),+ OVCompiledModelHsmBlobTest::getTestCaseName);+} // namespacediff --git a/src/plugins/template/tests/functional/skip_tests_config.cpp b/src/plugins/template/tests/functional/skip_tests_config.cppindex 6998128b5c6..a94bc7f68d2 100644--- a/src/plugins/template/tests/functional/skip_tests_config.cpp+++ b/src/plugins/template/tests/functional/skip_tests_config.cpp@@ -95,8 +95,6 @@ const std::vector<std::regex>& disabled_test_patterns() {// Precision not high enough to get exact result for the complex test cases// (both tiny values and very high values necessary)std::regex(R"(.*ReferenceInverse.*bf16.*[4,4].*)"),- // model import is not supported- std::regex(R"(.*OVCompiledModelBaseTest.import_from_.*)"),#ifdef _WIN32// CVS-63989std::regex(R"(.*ReferenceSigmoidLayerTest.*u64.*)"),diff --git a/src/tests/functional/base_func_tests/include/behavior/compiled_model/import_export.hpp b/src/tests/functional/base_func_tests/include/behavior/compiled_model/import_export.hppindex 5b6e11b0403..5534bc3deef 100644--- a/src/tests/functional/base_func_tests/include/behavior/compiled_model/import_export.hpp+++ b/src/tests/functional/base_func_tests/include/behavior/compiled_model/import_export.hpp@@ -1,26 +1,28 @@// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifcorer: Apache-2.0+// SPDX-License-Identifier: Apache-2.0//+#include <filesystem>#include <fstream>+#include <functional>-#include "shared_test_classes/base/ov_behavior_test_utils.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/split.hpp"#include "openvino/runtime/exec_model_info.hpp"+#include "openvino/runtime/hsm_format.hpp"#include "pugixml.hpp"+#include "shared_test_classes/base/ov_behavior_test_utils.hpp"#include "shared_test_classes/base/ov_subgraph.hpp"-#include "openvino/op/concat.hpp"-#include "openvino/op/split.hpp"-namespace ov {namespace test {namespace behavior {-typedef std::tuple<- ov::element::Type_t, // Element type- std::string, // Device name- ov::AnyMap // Config-> OVCompiledGraphImportExportTestParams;+typedef std::tuple<ov::element::Type_t, // Element type+ std::string, // Device name+ ov::AnyMap // Config+ >+ OVCompiledGraphImportExportTestParams;class OVCompiledGraphImportExportTest : public testing::WithParamInterface<OVCompiledGraphImportExportTestParams>,public OVCompiledNetworkTestBase {@@ -60,8 +62,7 @@ protected:std::shared_ptr<ov::Model> model;};-class OVExecGraphSerializationTest : public testing::WithParamInterface<std::string>,- public OVCompiledNetworkTestBase {+class OVExecGraphSerializationTest : public testing::WithParamInterface<std::string>, public OVCompiledNetworkTestBase {public:static std::string getTestCaseName(testing::TestParamInfo<std::string> obj);void SetUp() override;@@ -72,12 +73,11 @@ private:// vector which is later used for comparisonstruct exec_graph_walker : pugi::xml_tree_walker {std::vector<pugi::xml_node> nodes;- bool for_each(pugi::xml_node &node) override;+ bool for_each(pugi::xml_node& node) override;};// compare_docs() helper- std::pair<bool, std::string> compare_nodes(const pugi::xml_node &node1,- const pugi::xml_node &node2);+ std::pair<bool, std::string> compare_nodes(const pugi::xml_node& node1, const pugi::xml_node& node2);protected:// checks if two exec graph xml's are equivalent:@@ -85,12 +85,54 @@ protected:// - the same count of attributes of each node// - the same name of each attribute (value is not checked, since it can differ// beetween different devices)- std::pair<bool, std::string> compare_docs(const pugi::xml_document &doc1,- const pugi::xml_document &doc2);+ std::pair<bool, std::string> compare_docs(const pugi::xml_document& doc1, const pugi::xml_document& doc2);std::string m_out_xml_path, m_out_bin_path;};+struct HsmEntry {+ ov::runtime::hsm::DeviceId device;+ ov::runtime::hsm::SectionTagReserved tag;+ std::vector<std::byte> payload;+};++/// Rebuilds an HSM blob from its sections after @p modify edited them; throws if @p blob is not HSM.+std::string hsm_repack(const std::string& blob, const std::function<void(std::vector<HsmEntry>&)>& modify);++/// Returns a copy of @p blob with its header's format minor version set to @p minor.+std::string hsm_with_minor_version(std::string blob, uint8_t minor);++bool is_hsm(const std::string& blob);++using HsmBlobTestParams = std::tuple<std::string, // device name+ ov::AnyMap // device configuration+ >;++/// Same checks as OVCompiledGraphImportExportTest, for plugins whose export_model() emits HSM instead of the+/// legacy blob format (skipped otherwise) - kept alongside it since one is meant to eventually replace the other.+class OVCompiledModelHsmBlobTest : public testing::WithParamInterface<HsmBlobTestParams>,+ public OVCompiledNetworkTestBase {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<HsmBlobTestParams>& obj);++ void SetUp() override;+ void TearDown() override;++protected:+ ov::CompiledModel compile(bool with_cache);+ std::string export_blob(ov::CompiledModel compiled) const;+ std::string read_cache_blob() const;+ void write_cache_blob(const std::string& blob) const;+ void expect_same_inference(ov::CompiledModel& actual);++ ov::Core core;+ ov::AnyMap configuration;+ std::shared_ptr<ov::Model> model;+ std::filesystem::path cache_path;+ ov::Tensor input;+ ov::Tensor reference;+};+} // namespace behavior} // namespace test} // namespace ovdiff --git a/src/tests/functional/base_func_tests/src/behavior/compiled_model/import_export.cpp b/src/tests/functional/base_func_tests/src/behavior/compiled_model/import_export.cppindex 7383d525a1f..b87f15196ff 100644--- a/src/tests/functional/base_func_tests/src/behavior/compiled_model/import_export.cpp+++ b/src/tests/functional/base_func_tests/src/behavior/compiled_model/import_export.cpp@@ -2,21 +2,30 @@// SPDX-License-Identifier: Apache-2.0//-#include <gmock/gmock-matchers.h>#include "behavior/compiled_model/import_export.hpp"-#include "common_test_utils/ov_test_utils.hpp"+#include <gmock/gmock-matchers.h>++#include <cstring>+#include "common_test_utils/common_utils.hpp"#include "common_test_utils/file_utils.hpp"-+#include "common_test_utils/ov_tensor_utils.hpp"+#include "common_test_utils/ov_test_utils.hpp"+#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"#include "common_test_utils/subgraph_builders/multiple_input_outpput_double_concat.hpp"#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/hsm_deferred_writer.hpp"+#include "openvino/runtime/hsm_reader.hpp"+#include "openvino/runtime/internal_properties.hpp"namespace ov {namespace test {namespace behavior {+namespace hsm = ov::runtime::hsm;-std::string OVCompiledGraphImportExportTest::getTestCaseName(testing::TestParamInfo<OVCompiledGraphImportExportTestParams> obj) {+std::string OVCompiledGraphImportExportTest::getTestCaseName(+ testing::TestParamInfo<OVCompiledGraphImportExportTestParams> obj) {const auto& [elementType, _targetDevice, configuration] = obj.param;auto targetDevice = _targetDevice;std::replace(targetDevice.begin(), targetDevice.end(), ':', '.');@@ -35,14 +44,14 @@ std::string OVCompiledGraphImportExportTest::getTestCaseName(testing::TestParamIreturn result.str();}-void OVCompiledGraphImportExportTest::SetUp() {+void OVCompiledGraphImportExportTest::SetUp() {// Skip test according to plugin specific disabled_test_patterns() (if any)SKIP_IF_CURRENT_TEST_IS_DISABLED();std::tie(elementType, target_device, configuration) = this->GetParam();APIBaseTest::SetUp();}-void OVCompiledGraphImportExportTest::TearDown() {+void OVCompiledGraphImportExportTest::TearDown() {if (!configuration.empty()) {utils::PluginCache::get().reset();}@@ -68,15 +77,13 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunction) {importedExecNet.input(0).get_tensor().get_partial_shape());EXPECT_EQ(function->input(0).get_tensor().get_element_type(),importedExecNet.input(0).get_tensor().get_element_type());- EXPECT_EQ(function->input(0).get_element_type(),- importedExecNet.input(0).get_tensor().get_element_type());+ EXPECT_EQ(function->input(0).get_element_type(), importedExecNet.input(0).get_tensor().get_element_type());EXPECT_EQ(function->input(1).get_tensor().get_names(), importedExecNet.input(1).get_tensor().get_names());EXPECT_EQ(function->input(1).get_tensor().get_partial_shape(),importedExecNet.input(1).get_tensor().get_partial_shape());EXPECT_EQ(function->input(1).get_tensor().get_element_type(),importedExecNet.input(1).get_tensor().get_element_type());- EXPECT_EQ(function->input(1).get_element_type(),- importedExecNet.input(1).get_tensor().get_element_type());+ EXPECT_EQ(function->input(1).get_element_type(), importedExecNet.input(1).get_tensor().get_element_type());EXPECT_EQ(importedExecNet.input(0).get_node(), importedExecNet.input("data1").get_node());EXPECT_NE(importedExecNet.input(1).get_node(), importedExecNet.input("data1").get_node());EXPECT_EQ(importedExecNet.input(1).get_node(), importedExecNet.input("data2").get_node());@@ -89,15 +96,13 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunction) {importedExecNet.output(0).get_tensor().get_partial_shape());EXPECT_EQ(function->output(0).get_tensor().get_element_type(),importedExecNet.output(0).get_tensor().get_element_type());- EXPECT_EQ(function->output(0).get_element_type(),- importedExecNet.output(0).get_tensor().get_element_type());+ EXPECT_EQ(function->output(0).get_element_type(), importedExecNet.output(0).get_tensor().get_element_type());EXPECT_EQ(function->output(1).get_tensor().get_names(), importedExecNet.output(1).get_tensor().get_names());EXPECT_EQ(function->output(1).get_tensor().get_partial_shape(),importedExecNet.output(1).get_tensor().get_partial_shape());EXPECT_EQ(function->output(1).get_tensor().get_element_type(),importedExecNet.output(1).get_tensor().get_element_type());- EXPECT_EQ(function->output(1).get_element_type(),- importedExecNet.output(1).get_tensor().get_element_type());+ EXPECT_EQ(function->output(1).get_element_type(), importedExecNet.output(1).get_tensor().get_element_type());EXPECT_EQ(importedExecNet.output(0).get_node(), importedExecNet.output("concat1").get_node());EXPECT_NE(importedExecNet.output(1).get_node(), importedExecNet.output("concat1").get_node());EXPECT_EQ(importedExecNet.output(1).get_node(), importedExecNet.output("concat2").get_node());@@ -116,8 +121,7 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunctionParameterResultOnlparam->output(0).get_tensor().set_names({"data"});auto result = std::make_shared<ov::op::v0::Result>(param);result->set_friendly_name("result");- function = std::make_shared<ov::Model>(ov::ResultVector{result},- ov::ParameterVector{param});+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});function->set_friendly_name("ParamResult");}@@ -135,8 +139,7 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunctionParameterResultOnlEXPECT_EQ(function->outputs().size(), 1);EXPECT_EQ(function->outputs().size(), importedCompiledModel.outputs().size());EXPECT_NO_THROW(importedCompiledModel.output());- EXPECT_EQ(function->output(0).get_tensor().get_names(),- importedCompiledModel.output(0).get_tensor().get_names());+ EXPECT_EQ(function->output(0).get_tensor().get_names(), importedCompiledModel.output(0).get_tensor().get_names());EXPECT_NO_THROW(importedCompiledModel.output("data").get_node());EXPECT_THROW(importedCompiledModel.output("param"), ov::Exception);@@ -152,8 +155,7 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunctionConstantResultOnlyconstant->output(0).get_tensor().set_names({"data"});auto result = std::make_shared<ov::op::v0::Result>(constant);result->set_friendly_name("result");- function = std::make_shared<ov::Model>(ov::ResultVector{result},- ov::ParameterVector{});+ function = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{});function->set_friendly_name("ConstResult");}@@ -171,8 +173,7 @@ TEST_P(OVCompiledGraphImportExportTest, importExportedFunctionConstantResultOnlyEXPECT_EQ(function->outputs().size(), 1);EXPECT_EQ(function->outputs().size(), importedCompiledModel.outputs().size());EXPECT_NO_THROW(importedCompiledModel.output());- EXPECT_EQ(function->output(0).get_tensor().get_names(),- importedCompiledModel.output(0).get_tensor().get_names());+ EXPECT_EQ(function->output(0).get_tensor().get_names(), importedCompiledModel.output(0).get_tensor().get_names());EXPECT_NO_THROW(importedCompiledModel.output("data").get_node());EXPECT_THROW(importedCompiledModel.output("constant"), ov::Exception);@@ -300,18 +301,21 @@ TEST_P(OVClassCompiledModelImportExportTestP, smoke_ImportNetworkThrowWithDeviceSKIP_IF_CURRENT_TEST_IS_DISABLED();ov::Core ie = ov::test::utils::create_core();std::stringstream wrongStm;- // Import model with wrong format throws exception+ // Plugins with their own blob header (CPU/Hetero) reject it there; others fall back to the generic+ // Core::read_model rejection.OV_EXPECT_THROW((ie.import_model(wrongStm, target_device)),ov::Exception,testing::AnyOf(testing::HasSubstr("device xml header"),- testing::HasSubstr("requirements header")));+ testing::HasSubstr("requirements header"),+ testing::HasSubstr("Unable to read the model")));}//// GetRuntimeModel//-std::string OVCompiledModelGraphUniqueNodeNamesTest::getTestCaseName(testing::TestParamInfo<OVCompiledModelGraphUniqueNodeNamesTestParams> obj) {+std::string OVCompiledModelGraphUniqueNodeNamesTest::getTestCaseName(+ testing::TestParamInfo<OVCompiledModelGraphUniqueNodeNamesTestParams> obj) {const auto& [netPrecision, inputShapes, _targetDevice] = obj.param;auto targetDevice = _targetDevice;std::replace(targetDevice.begin(), targetDevice.end(), ':', '_');@@ -662,7 +666,6 @@ const char expected_serialized_model_cpu[] = R"V0G0N(</net>)V0G0N";-std::string OVExecGraphSerializationTest::getTestCaseName(testing::TestParamInfo<std::string> obj) {std::ostringstream result;std::string target_device = obj.param;@@ -690,7 +693,7 @@ void OVExecGraphSerializationTest::TearDown() {ov::test::utils::removeIRFiles(m_out_xml_path, m_out_bin_path);}-bool OVExecGraphSerializationTest::exec_graph_walker::for_each(pugi::xml_node &node) {+bool OVExecGraphSerializationTest::exec_graph_walker::for_each(pugi::xml_node& node) {std::string node_name{node.name()};if (node_name == "layer" || node_name == "data") {nodes.push_back(node);@@ -698,8 +701,8 @@ bool OVExecGraphSerializationTest::exec_graph_walker::for_each(pugi::xml_node &nreturn true; // continue traversal}-std::pair<bool, std::string> OVExecGraphSerializationTest::compare_nodes(const pugi::xml_node &node1,- const pugi::xml_node &node2) {+std::pair<bool, std::string> OVExecGraphSerializationTest::compare_nodes(const pugi::xml_node& node1,+ const pugi::xml_node& node2) {// node names must be the sameconst std::string node1_name{node1.name()};const std::string node2_name{node2.name()};@@ -713,9 +716,9 @@ std::pair<bool, std::string> OVExecGraphSerializationTest::compare_nodes(const pconst auto attr1_size = std::distance(attr1.begin(), attr1.end());const auto attr2_size = std::distance(attr2.begin(), attr2.end());if (attr1_size != attr2_size) {- return {false, "Attribute count is different in <" + node1_name + "> :" +- std::to_string(attr1_size) + " != " +- std::to_string(attr2_size)};+ return {false,+ "Attribute count is different in <" + node1_name + "> :" + std::to_string(attr1_size) ++ " != " + std::to_string(attr2_size)};}// every node attribute name must be the same@@ -731,27 +734,26 @@ std::pair<bool, std::string> OVExecGraphSerializationTest::compare_nodes(const pif (a1_value == "Output" && a2_value == "Result") {continue;}- return {false, "Attributes are different in <" + node1_name + "> : " +- a1_name + "=" + a1_value + " != " + a2_name +- "=" + a2_value};+ return {false,+ "Attributes are different in <" + node1_name + "> : " + a1_name + "=" + a1_value ++ " != " + a2_name + "=" + a2_value};}}return {true, ""};}-std::pair<bool, std::string> OVExecGraphSerializationTest::compare_docs(const pugi::xml_document &doc1,- const pugi::xml_document &doc2) {+std::pair<bool, std::string> OVExecGraphSerializationTest::compare_docs(const pugi::xml_document& doc1,+ const pugi::xml_document& doc2) {// traverse document and prepare vector of <layer> & <data> nodes to compareexec_graph_walker walker1, walker2;doc1.child("net").child("layers").traverse(walker1);doc2.child("net").child("layers").traverse(walker2);// nodes count must be the same- const auto &nodes1 = walker1.nodes;- const auto &nodes2 = walker2.nodes;+ const auto& nodes1 = walker1.nodes;+ const auto& nodes2 = walker2.nodes;if (nodes1.size() != nodes2.size()) {- return {false, "Node count differ: " + std::to_string(nodes1.size()) +- " != " + std::to_string(nodes2.size())};+ return {false, "Node count differ: " + std::to_string(nodes1.size()) + " != " + std::to_string(nodes2.size())};}// every node must be equivalent@@ -786,7 +788,207 @@ TEST_P(OVExecGraphSerializationTest, ExecutionGraph) {ASSERT_TRUE(status) << message;}+std::string hsm_repack(const std::string& blob, const std::function<void(std::vector<HsmEntry>&)>& modify) {+ const auto data = reinterpret_cast<const std::byte*>(blob.data());+ const auto reader = hsm::Reader::open(data, blob.size());+ OPENVINO_ASSERT(reader, "Not an HSM blob");++ std::vector<HsmEntry> entries;+ for (const auto& entry : reader->entries()) {+ // Built directly from the entry, so duplicated (device, tag) pairs are kept too.+ const auto section = entry.tag.is_inline()+ ? hsm::Section{entry}+ : hsm::Section{entry, {data + 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 = 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();+}++std::string hsm_with_minor_version(std::string blob, uint8_t minor) {+ OPENVINO_ASSERT(blob.size() >= sizeof(hsm::Header), "Blob too small for an HSM header");+ blob[offsetof(hsm::Header, version_minor)] = static_cast<char>(minor);+ return blob;+}++bool is_hsm(const std::string& blob) {+ return blob.size() >= sizeof(hsm::Header) && hsm::Header::view(blob.data()).magic == hsm::BlobMagic::single;+}++namespace {+ov::Tensor hsm_infer(ov::CompiledModel& compiled, const ov::Tensor& input) {+ auto request = compiled.create_infer_request();+ request.set_input_tensor(input);+ request.infer();+ const auto output = request.get_output_tensor();+ ov::Tensor result(output.get_element_type(), output.get_shape());+ output.copy_to(result);+ return result;+}++void add_unknown_sections(std::vector<HsmEntry>& entries) {+ const auto bytes = [](std::string_view text, size_t size) {+ std::vector<std::byte> payload(size);+ std::memcpy(payload.data(), text.data(), std::min(size, text.size()));+ return payload;+ };+ // A Core tag id not assigned yet, another device's pointer section and another device's inline section.+ entries.push_back({hsm::any_device_id,+ hsm::SectionTag::make(hsm::core_tag_id_range_end - 1, false),+ bytes("future core section", 19)});+ entries.push_back({250, hsm::SectionTag::make_device_tag(0x123, false), bytes("other device", 12)});+ entries.push_back({251, hsm::SectionTag::make_device_tag(0, true), bytes("inline", 24)});+}+} // namespace++std::string OVCompiledModelHsmBlobTest::getTestCaseName(const testing::TestParamInfo<HsmBlobTestParams>& obj) {+ auto [device, configuration] = obj.param;+ std::replace(device.begin(), device.end(), ':', '.');+ std::ostringstream result;+ result << "targetDevice=" << device;+ for (const auto& [key, value] : configuration) {+ result << "_" << key << "=" << value.as<std::string>();+ }+ return result.str();+}++void OVCompiledModelHsmBlobTest::SetUp() {+ std::tie(target_device, configuration) = GetParam();+ SKIP_IF_CURRENT_TEST_IS_DISABLED();+ APIBaseTest::SetUp();++ core = ov::test::utils::create_core();+ // Plugin-level too: Core picks the cache blob format from the plugin, not from the compile config.+ core.set_property(target_device, configuration);+ ASSERT_TRUE(core.get_property(target_device, ov::internal::emit_hsm_format));++ model = ov::test::utils::make_conv_pool_relu({1, 3, 16, 16}, ov::element::f32);+ cache_path = "hsm_blob_cache_" + ov::test::utils::generateTestFilePrefix();+ input = ov::test::utils::create_and_fill_tensor(ov::element::f32, model->input().get_shape());+ auto compiled = compile(false);+ reference = hsm_infer(compiled, input);+}++void OVCompiledModelHsmBlobTest::TearDown() {+ if (!cache_path.empty()) {+ ov::test::utils::removeFilesWithExt(ov::util::path_to_string(cache_path), "blob");+ ov::test::utils::removeDir(ov::util::path_to_string(cache_path));+ }+ APIBaseTest::TearDown();+}++ov::CompiledModel OVCompiledModelHsmBlobTest::compile(bool with_cache) {+ auto config = configuration;+ if (with_cache) {+ config.emplace(ov::cache_path(cache_path));+ }+ return core.compile_model(model, target_device, config);+}++std::string OVCompiledModelHsmBlobTest::export_blob(ov::CompiledModel compiled) const {+ std::stringstream stream;+ compiled.export_model(stream);+ return stream.str();+}++std::string OVCompiledModelHsmBlobTest::read_cache_blob() const {+ const auto blobs = ov::test::utils::listFilesWithExt(ov::util::path_to_string(cache_path), "blob");+ OPENVINO_ASSERT(blobs.size() == 1, "Expected exactly one cache blob, got ", blobs.size());+ std::ifstream file(blobs.front(), std::ios::binary);+ return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};+}++void OVCompiledModelHsmBlobTest::write_cache_blob(const std::string& blob) const {+ const auto blobs = ov::test::utils::listFilesWithExt(ov::util::path_to_string(cache_path), "blob");+ ASSERT_EQ(blobs.size(), 1u) << "Expected exactly one cache blob";+ // Cache files may be created read-only, so replace the file instead of overwriting it.+ std::filesystem::remove(blobs.front());+ std::ofstream file(blobs.front(), std::ios::binary);+ file.write(blob.data(), blob.size());+ ASSERT_TRUE(file.good()) << "Cannot write cache blob " << blobs.front();+}++void OVCompiledModelHsmBlobTest::expect_same_inference(ov::CompiledModel& actual) {+ ov::test::utils::compare(reference, hsm_infer(actual, input));+}++TEST_P(OVCompiledModelHsmBlobTest, cache_blob_is_identical_to_exported_blob) {+ auto compiled = compile(true);+ const auto exported = export_blob(compiled);++ EXPECT_TRUE(is_hsm(exported));+ EXPECT_EQ(read_cache_blob(), exported);+}++TEST_P(OVCompiledModelHsmBlobTest, cache_blob_is_imported_via_import_model) {+ compile(true);+ const auto blob = read_cache_blob();++ std::stringstream stream(blob);+ auto from_stream = core.import_model(stream, target_device, configuration);+ expect_same_inference(from_stream);++ ov::Tensor tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data(), blob.data(), blob.size());+ auto from_tensor = core.import_model(tensor, target_device, configuration);+ expect_same_inference(from_tensor);+}++TEST_P(OVCompiledModelHsmBlobTest, exported_blob_is_loaded_from_cache) {+ // The extra section makes the exported blob distinguishable from what the cache itself would write.+ const auto exported = hsm_repack(export_blob(compile(false)), add_unknown_sections);+ compile(true);+ write_cache_blob(exported);++ auto cached = compile(true);++ EXPECT_TRUE(cached.get_property(ov::loaded_from_cache));+ EXPECT_EQ(read_cache_blob(), exported);+ expect_same_inference(cached);+}++TEST_P(OVCompiledModelHsmBlobTest, unknown_sections_are_skipped_on_import) {+ std::stringstream stream(hsm_repack(export_blob(compile(false)), add_unknown_sections));++ auto imported = core.import_model(stream, target_device, configuration);++ expect_same_inference(imported);+}++TEST_P(OVCompiledModelHsmBlobTest, newer_minor_version_is_imported) {+ const auto newer = hsm_with_minor_version(hsm_repack(export_blob(compile(false)), add_unknown_sections),+ hsm::FormatVersion::minor + 1);+ std::stringstream stream(newer);++ auto imported = core.import_model(stream, target_device, configuration);++ expect_same_inference(imported);+}++TEST_P(OVCompiledModelHsmBlobTest, exported_blob_is_a_valid_container_of_the_current_version) {+ const auto exported = export_blob(compile(false));+ const auto data = reinterpret_cast<const std::byte*>(exported.data());++ EXPECT_TRUE(hsm::ContainerView(data, exported.size()).validate());+ EXPECT_TRUE(hsm::Reader::open(data, exported.size()));+ const auto& header = hsm::Header::view(exported.data());+ EXPECT_EQ(header.version_major, hsm::FormatVersion::major);+ EXPECT_EQ(header.version_minor, hsm::FormatVersion::minor);+ EXPECT_EQ(header.container_size, exported.size());+}+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OVClassCompiledModelImportExportTestP);+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OVCompiledModelHsmBlobTest);GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OVCompiledModelGraphUniqueNodeNamesTest);GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OVExecGraphSerializationTest);