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
NPUW: Introduce basic ORC constructs (#35662)
Dmitry Matveev71c50599d59a
diff --git a/src/plugins/intel_npu/src/plugin/npuw/orc.cpp b/src/plugins/intel_npu/src/plugin/npuw/orc.cppnew file mode 100644index 00000000000..35cc7ce59fd--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/orc.cpp@@ -0,0 +1,346 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "orc.hpp"++#include <algorithm>+#include <cstring>+#include <istream>+#include <ostream>+#include <sstream>++namespace {++constexpr std::array<std::uint8_t, 8> ORC_FILE_MAGIC = {'N', 'P', 'U', 'W', 'O', 'R', 'C', '\0'};+constexpr std::uint16_t ORC_FILE_VERSION = 1u;++std::streamsize checked_stream_size(const std::size_t size) {+ if (size > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {+ OPENVINO_THROW("ORC size exceeds std::streamsize range");+ }+ return static_cast<std::streamsize>(size);+}++std::size_t checked_size(const std::uint64_t size) {+ if (size > static_cast<std::uint64_t>(std::numeric_limits<std::size_t>::max())) {+ OPENVINO_THROW("ORC section size exceeds std::size_t range");+ }+ return static_cast<std::size_t>(size);+}++std::uint64_t checked_add(const std::uint64_t lhs, const std::uint64_t rhs) {+ if (rhs > std::numeric_limits<std::uint64_t>::max() - lhs) {+ OPENVINO_THROW("ORC section size overflow");+ }+ return lhs + rhs;+}++constexpr std::uint64_t header_size() {+ // Section header layout: type_id (u16) + version (u16) + flags (u32) + payload_size (u64)+ return sizeof(ov::npuw::orc::TypeId) + sizeof(ov::npuw::orc::Version) + sizeof(ov::npuw::orc::SectionFlags) ++ sizeof(std::uint64_t);+}++void validate_section_shape(const ov::npuw::orc::Section& section) {+ if (section.is_container()) {+ if (!section.payload.empty()) {+ OPENVINO_THROW("ORC container sections cannot store a raw payload");+ }+ return;+ }++ if (!section.children.empty()) {+ OPENVINO_THROW("ORC raw sections cannot store nested child sections");+ }+}++std::uint64_t encoded_size(const ov::npuw::orc::Section& section);++std::uint64_t body_size(const ov::npuw::orc::Section& section) {+ validate_section_shape(section);+ if (!section.is_container()) {+ return section.payload.size();+ }++ std::uint64_t size = 0u;+ for (const auto& child : section.children) {+ size = checked_add(size, encoded_size(child));+ }+ return size;+}++std::uint64_t encoded_size(const ov::npuw::orc::Section& section) {+ return checked_add(header_size(), body_size(section));+}++void write_section(ov::npuw::orc::Stream& stream, const ov::npuw::orc::Section& section) {+ validate_section_shape(section);++ ov::npuw::orc::SectionHeader header;+ header.type = section.type;+ header.version = section.version;+ header.flags = section.flags;+ header.size = body_size(section);+ stream & header.type & header.version & header.flags & header.size;++ if (!section.is_container()) {+ if (!section.payload.empty()) {+ stream.bytes(const_cast<std::byte*>(section.payload.data()), section.payload.size());+ }+ return;+ }++ for (const auto& child : section.children) {+ write_section(stream, child);+ }+}++ov::npuw::orc::Section read_section(ov::npuw::orc::Stream& stream) {+ ov::npuw::orc::SectionHeader header;+ stream & header.type & header.version & header.flags & header.size;++ ov::npuw::orc::Section section;+ section.type = header.type;+ section.version = header.version;+ section.flags = header.flags;++ const auto size = checked_size(header.size);+ if (!section.is_container()) {+ section.payload.resize(size);+ if (size != 0u) {+ stream.bytes(section.payload.data(), size);+ }+ return section;+ }++ std::vector<std::byte> bytes(size);+ if (size != 0u) {+ stream.bytes(bytes.data(), size);+ }+ auto nested = ov::npuw::orc::Stream::memory_reader(bytes.data(), bytes.size());+ while (nested.remaining() != 0u) {+ section.children.push_back(read_section(nested));+ }+ return section;+}++} // namespace++ov::npuw::orc::Stream ov::npuw::orc::Stream::reader(std::istream& stream) {+ Stream s;+ s.m_input = &stream;+ return s;+}++ov::npuw::orc::Stream ov::npuw::orc::Stream::memory_reader(const void* data, const std::size_t size) {+ Stream s;+ s.m_memory = reinterpret_cast<const std::byte*>(data);+ s.m_memory_size = size;+ return s;+}++ov::npuw::orc::Stream ov::npuw::orc::Stream::writer(std::ostream& stream) {+ Stream s;+ s.m_output = &stream;+ return s;+}++bool ov::npuw::orc::Stream::input() const {+ return m_input != nullptr || m_memory != nullptr;+}++bool ov::npuw::orc::Stream::output() const {+ return m_output != nullptr;+}++bool ov::npuw::orc::Stream::memory() const {+ return m_memory != nullptr;+}++std::size_t ov::npuw::orc::Stream::remaining() const {+ if (!memory()) {+ OPENVINO_THROW("ORC remaining() is only available for memory-backed input streams");+ }+ return m_memory_size - m_memory_offset;+}++void ov::npuw::orc::Stream::bytes(void* data, const std::size_t size) {+ if (output()) {+ m_output->write(reinterpret_cast<const char*>(data), checked_stream_size(size));+ if (!m_output->good()) {+ OPENVINO_THROW("Failed to write ORC stream bytes");+ }+ return;+ }++ if (memory()) {+ if (size > remaining()) {+ OPENVINO_THROW("Unexpected end of ORC memory stream");+ }+ if (size != 0u) {+ std::memcpy(data, m_memory + m_memory_offset, size);+ m_memory_offset += size;+ }+ return;+ }++ m_input->read(reinterpret_cast<char*>(data), checked_stream_size(size));+ if (!m_input->good()) {+ OPENVINO_THROW("Unexpected end of ORC input stream");+ }+}++void ov::npuw::orc::serialize(Stream& stream, std::string& value) {+ if (stream.output()) {+ auto size = value.size();+ stream & size;+ if (!value.empty()) {+ stream.bytes(value.data(), value.size());+ }+ return;+ }++ std::size_t size = 0u;+ stream & size;+ value.resize(size);+ if (size != 0u) {+ stream.bytes(value.data(), value.size());+ }+}++ov::npuw::orc::Section ov::npuw::orc::Section::raw(const TypeId type,+ const Version version,+ std::vector<std::byte> payload,+ const SectionFlags flags) {+ Section section;+ section.type = type;+ section.version = version;+ section.flags = flags | SectionFlag::LEAF;+ section.payload = std::move(payload);+ return section;+}++ov::npuw::orc::Section ov::npuw::orc::Section::container(const TypeId type,+ const Version version,+ std::vector<Section> children,+ const SectionFlags flags) {+ Section section;+ section.type = type;+ section.version = version;+ section.flags = flags; // LEAF not set — this is a structural container section+ section.children = std::move(children);+ return section;+}++void ov::npuw::orc::write_file(std::ostream& stream, const Section& root, const SchemaUUID& uuid) {+ auto writer = Stream::writer(stream);++ auto magic = ORC_FILE_MAGIC;+ writer & magic;+ auto version = ORC_FILE_VERSION;+ writer & version;+ auto uuid_copy = uuid;+ writer & uuid_copy;+ write_section(writer, root);+}++ov::npuw::orc::Section ov::npuw::orc::read_file(std::istream& stream) {+ const auto header = is_orc(stream);+ if (!header) {+ OPENVINO_THROW("Not an ORC file (invalid magic)");+ }+ if (header->version != ORC_FILE_VERSION) {+ OPENVINO_THROW("Unsupported ORC file version ", header->version);+ }++ // is_orc() restores the stream position; skip past the file header before reading sections.+ constexpr auto skip =+ static_cast<std::streamoff>(ORC_FILE_MAGIC.size() + sizeof(ORC_FILE_VERSION) + sizeof(SchemaUUID));+ stream.seekg(skip, std::ios::cur);++ auto reader = Stream::reader(stream);+ return read_section(reader);+}++bool ov::npuw::orc::Schema::knows(const TypeId type) const {+ return m_entries.count(type) != 0u;+}++std::any ov::npuw::orc::Schema::load_any(const Section& section) const {+ const auto it = m_entries.find(section.type);+ if (it == m_entries.end()) {+ OPENVINO_THROW("No ORC loader registered for section type ID ", section.type);+ }+ return it->second.loader(section, *this);+}++std::vector<ov::npuw::orc::Schema::LoadedChild> ov::npuw::orc::Schema::load_children(const Section& container) const {+ if (!container.is_container()) {+ OPENVINO_THROW("ORC child loading requires a container section");+ }++ std::vector<LoadedChild> out;+ out.reserve(container.children.size());+ for (const auto& child : container.children) {+ if (!knows(child.type)) {+ if (child.is_optional()) {+ continue;+ }+ OPENVINO_THROW("Required ORC child section type ID ", child.type, " is not registered in the schema");+ }+ out.push_back({child.type, load_any(child)});+ }+ return out;+}++const ov::npuw::orc::Section* ov::npuw::orc::Schema::find_child(const Section& container, const TypeId type) const {+ if (!container.is_container()) {+ OPENVINO_THROW("ORC child lookup requires a container section");+ }++ const auto it = std::find_if(container.children.begin(), container.children.end(), [type](const Section& child) {+ return child.type == type;+ });+ return it == container.children.end() ? nullptr : &(*it);+}++const ov::npuw::orc::Section& ov::npuw::orc::Schema::require_child(const Section& container, const TypeId type) const {+ const auto* child = find_child(container, type);+ if (child == nullptr) {+ OPENVINO_THROW("Required ORC child section type ID ", type, " is missing");+ }+ return *child;+}++std::optional<ov::npuw::orc::OrcHeader> ov::npuw::orc::is_orc(std::istream& stream) {+ const auto saved = stream.tellg();+ const auto restore = [&] {+ stream.clear();+ stream.seekg(saved);+ };++ std::array<std::uint8_t, 8> magic{};+ stream.read(reinterpret_cast<char*>(magic.data()), magic.size());+ if (!stream.good() || magic != ORC_FILE_MAGIC) {+ restore();+ return std::nullopt;+ }++ std::uint16_t version = 0u;+ stream.read(reinterpret_cast<char*>(&version), sizeof(version));+ if (!stream.good()) {+ restore();+ return std::nullopt;+ }++ SchemaUUID uuid{};+ stream.read(reinterpret_cast<char*>(uuid.data()), uuid.size());+ if (!stream.good()) {+ restore();+ return std::nullopt;+ }++ restore();+ return OrcHeader{version, uuid};+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/orc.hpp b/src/plugins/intel_npu/src/plugin/npuw/orc.hppnew file mode 100644index 00000000000..058a23ae1f2--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/orc.hpp@@ -0,0 +1,367 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <any>+#include <array>+#include <cstddef>+#include <cstdint>+#include <cstring>+#include <functional>+#include <iosfwd>+#include <limits>+#include <optional>+#include <sstream>+#include <string>+#include <type_traits>+#include <typeindex>+#include <unordered_map>+#include <utility>+#include <vector>++#include "openvino/core/except.hpp"++namespace ov {+namespace npuw {+namespace orc {++using TypeId = std::uint16_t;+using Version = std::uint16_t;+using SectionFlags = std::uint32_t;+using SchemaUUID = std::array<std::uint8_t, 16>;++enum class SectionFlag : SectionFlags {+ OPTIONAL = 1u << 0,+ LEAF = 1u << 1, // payload contains raw bytes only, no child sections+};++constexpr SectionFlags operator|(SectionFlag lhs, SectionFlag rhs) {+ return static_cast<SectionFlags>(lhs) | static_cast<SectionFlags>(rhs);+}++constexpr SectionFlags operator|(SectionFlags lhs, SectionFlag rhs) {+ return lhs | static_cast<SectionFlags>(rhs);+}++constexpr bool has_flag(SectionFlags flags, SectionFlag flag) {+ return (flags & static_cast<SectionFlags>(flag)) != 0u;+}++class Stream;++namespace detail {++template <typename T, typename = void>+struct has_member_serialize : std::false_type {};++template <typename T>+struct has_member_serialize<T, std::void_t<decltype(std::declval<T&>().serialize(std::declval<Stream&>()))>>+ : std::true_type {};++} // namespace detail++class Stream {+public:+ static Stream reader(std::istream& stream);+ static Stream memory_reader(const void* data, std::size_t size);+ static Stream writer(std::ostream& stream);++ bool input() const;+ bool output() const;+ bool memory() const;+ std::size_t remaining() const;++ // Dispatches to value.serialize(*this) when the type provides a member serialize,+ // otherwise falls back to the free-function serialize(stream, value) found via ADL.+ template <typename T>+ Stream& operator&(T&& value) {+ using plain_type = std::remove_const_t<std::remove_reference_t<T>>;+ auto& v = const_cast<plain_type&>(value);+ if constexpr (detail::has_member_serialize<plain_type>::value) {+ v.serialize(*this);+ } else {+ serialize(*this, v);+ }+ return *this;+ }++ void bytes(void* data, std::size_t size);++private:+ Stream() = default;++ std::istream* m_input = nullptr;+ std::ostream* m_output = nullptr;+ const std::byte* m_memory = nullptr;+ std::size_t m_memory_size = 0u;+ std::size_t m_memory_offset = 0u;+};++template <typename T, std::enable_if_t<std::is_integral<T>::value || std::is_floating_point<T>::value, bool> = true>+void serialize(Stream& stream, T& value) {+ stream.bytes(&value, sizeof(value));+}++inline void serialize(Stream& stream, std::byte& value) {+ stream.bytes(&value, sizeof(value));+}++void serialize(Stream& stream, std::string& value);++template <typename T1, typename T2>+void serialize(Stream& stream, std::pair<T1, T2>& value) {+ stream & value.first & value.second;+}++template <typename T>+void serialize(Stream& stream, std::vector<T>& value) {+ if (stream.output()) {+ auto size = value.size();+ stream & size;+ for (std::size_t idx = 0; idx < value.size(); ++idx) {+ if constexpr (std::is_same_v<T, bool>) {+ bool element = value[idx];+ stream & element;+ } else {+ stream& value[idx];+ }+ }+ return;+ }++ value.clear();+ std::size_t size = 0u;+ stream & size;+ value.reserve(size);+ for (std::size_t idx = 0; idx < size; ++idx) {+ T element{};+ stream & element;+ value.push_back(std::move(element));+ }+}++template <typename T, std::size_t N>+void serialize(Stream& stream, std::array<T, N>& value) {+ for (auto& element : value) {+ stream & element;+ }+}++template <typename T>+void serialize(Stream& stream, std::optional<T>& value) {+ bool has_value = value.has_value();+ stream & has_value;+ if (!has_value) {+ value.reset();+ return;+ }++ if (stream.output()) {+ stream & value.value();+ return;+ }++ T unpacked{};+ stream & unpacked;+ value = std::move(unpacked);+}++template <typename T>+std::vector<std::byte> encode(const T& value) {+ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);+ auto stream = Stream::writer(buffer);+ auto& mutable_value = const_cast<std::remove_const_t<T>&>(value);+ stream & mutable_value;++ const auto raw = buffer.str();+ std::vector<std::byte> out(raw.size());+ if (!raw.empty()) {+ std::memcpy(out.data(), raw.data(), raw.size());+ }+ return out;+}++template <typename T>+T decode(const std::vector<std::byte>& bytes) {+ auto stream = Stream::memory_reader(bytes.data(), bytes.size());+ T out{};+ stream & out;+ if (stream.remaining() != 0u) {+ OPENVINO_THROW("ORC payload has trailing bytes");+ }+ return out;+}++struct SectionHeader {+ TypeId type = 0u;+ Version version = 0u;+ SectionFlags flags = 0u;+ std::uint64_t size = 0u;+};++struct Section {+ TypeId type = 0u;+ Version version = 0u;+ SectionFlags flags = 0u;+ std::vector<std::byte> payload;+ std::vector<Section> children;++ bool is_optional() const {+ return has_flag(flags, SectionFlag::OPTIONAL);+ }++ bool is_leaf() const {+ return has_flag(flags, SectionFlag::LEAF);+ }++ bool is_container() const {+ return !is_leaf();+ }++ static Section raw(TypeId type, Version version, std::vector<std::byte> payload, SectionFlags flags = 0u);+ static Section container(TypeId type, Version version, std::vector<Section> children, SectionFlags flags = 0u);+};++template <typename T>+Section make_payload_section(TypeId type, Version version, const T& value, SectionFlags flags = 0u) {+ return Section::raw(type, version, encode(value), flags);+}++// File-level metadata returned by is_orc().+struct OrcHeader {+ std::uint16_t version = 0u;+ SchemaUUID schema_uuid{};+};++void write_file(std::ostream& stream, const Section& root, const SchemaUUID& uuid);+Section read_file(std::istream& stream);++// Peeks at the stream to check whether it contains an ORC blob.+// Returns the file header (format_version + schema_uuid) on success,+// nullopt if the magic does not match.+// Does not consume any bytes — the stream position is restored on return.+std::optional<OrcHeader> is_orc(std::istream& stream);++class Schema {+public:+ using Loader = std::function<std::any(const Section&, const Schema&)>;++ struct LoadedChild {+ TypeId type = 0u;+ std::any value;+ };++ template <typename T, typename LoaderT>+ void register_loader(TypeId type, LoaderT&& loader) {+ if (m_entries.count(type) != 0u) {+ OPENVINO_THROW("ORC schema already has a loader for type ID ", type);+ }++ Entry entry;+ entry.type = std::type_index(typeid(T));+ entry.loader = [fn = std::forward<LoaderT>(loader)](const Section& section, const Schema& schema) -> std::any {+ return std::any(fn(section, schema));+ };+ m_entries.emplace(type, std::move(entry));+ }++ bool knows(TypeId type) const;+ std::any load_any(const Section& section) const;++ template <typename T>+ T load(const Section& section) const {+ auto value = load_any(section);+ auto* typed = std::any_cast<T>(&value);+ if (typed == nullptr) {+ OPENVINO_THROW("ORC loader returned unexpected type for section type ID ", section.type);+ }+ return std::move(*typed);+ }++ std::vector<LoadedChild> load_children(const Section& container) const;+ const Section* find_child(const Section& container, TypeId type) const;+ const Section& require_child(const Section& container, TypeId type) const;++private:+ struct Entry {+ std::type_index type = std::type_index(typeid(void));+ Loader loader;+ };++ std::unordered_map<TypeId, Entry> m_entries;+};++template <typename T, typename = void>+struct has_prev : std::false_type {};++template <typename T>+struct has_prev<T, std::void_t<typename T::Prev>> : std::true_type {};++template <typename Target, typename Source>+Target migrate_chain(Source source) {+ if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<Target>>,+ std::remove_cv_t<std::remove_reference_t<Source>>>) {+ return Target(std::move(source));+ } else {+ static_assert(has_prev<Target>::value, "Target must define Prev to use migrate_chain");+ return Target(migrate_chain<typename Target::Prev>(std::move(source)));+ }+}++namespace detail {++template <typename T, typename = void>+struct has_version : std::false_type {};++template <typename T>+struct has_version<T, std::void_t<decltype(T::kVersion)>> : std::true_type {};++template <typename Target, typename Current>+Target load_versioned_payload_impl(const Section& section) {+ static_assert(has_version<Current>::value, "Versioned ORC payload types must define kVersion");+ if (section.version == Current::kVersion) {+ return migrate_chain<Target>(decode<Current>(section.payload));+ }+ OPENVINO_THROW("Unsupported ORC section version ", section.version, " for type ID ", section.type);+}++template <typename Target, typename Current, typename Next, typename... Rest>+Target load_versioned_payload_impl(const Section& section) {+ static_assert(has_version<Current>::value, "Versioned ORC payload types must define kVersion");+ if (section.version == Current::kVersion) {+ return migrate_chain<Target>(decode<Current>(section.payload));+ }+ return load_versioned_payload_impl<Target, Next, Rest...>(section);+}++} // namespace detail++template <typename Target, typename... Versions>+Target load_versioned_payload(const Section& section) {+ static_assert(sizeof...(Versions) != 0u, "At least one versioned payload type must be provided");+ if (section.is_container()) {+ OPENVINO_THROW("Cannot decode a container section as a raw ORC payload");+ }+ return detail::load_versioned_payload_impl<Target, Versions...>(section);+}++} // namespace orc+} // namespace npuw+} // namespace ov++// Injects the standard versioning boilerplate into a frozen versioned type.+// PrevType must already define kVersion; ThisType must be the enclosing struct name.+//+// Example:+// struct MyTypeV2 : MyTypeV1 {+// ORC_DECLARE_VERSION(MyTypeV2, MyTypeV1)+// int new_field = 0;+// void serialize(Stream& stream) { Prev::serialize(stream); stream & new_field; }+// };+#define ORC_DECLARE_VERSION(ThisType, PrevType) \+ using Prev = PrevType; \+ static constexpr ::ov::npuw::orc::Version kVersion = 1u + Prev::kVersion; \+ ThisType() = default; \+ explicit ThisType(PrevType _prev_init) : PrevType(std::move(_prev_init)) {}diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 9ec82cbd11d..da124833203 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -60,6 +60,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/logging.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/orc.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp@@ -126,6 +127,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_graph_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_options_smoke_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/orc.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_nodes_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/subgraph_pipeline.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/subgraph_behavior_infer_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/orc.cpp b/src/plugins/intel_npu/tests/unit/npuw/orc.cppnew file mode 100644index 00000000000..295bd650595--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/orc.cpp@@ -0,0 +1,254 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "orc.hpp"++#include <gtest/gtest.h>++#include <sstream>+#include <string>+#include <vector>++namespace {++using namespace ov::npuw::orc;++// Small sequential TypeIds that fit in u16.+constexpr TypeId TYPE_NCMD = 0x0001u;+constexpr TypeId TYPE_META = 0x0002u;+constexpr TypeId TYPE_PART = 0x0003u;+constexpr TypeId TYPE_WGHT = 0x0004u;+constexpr TypeId TYPE_TEST = 0x0005u;+constexpr TypeId TYPE_UNKNOWN = 0xFFFFu;++const SchemaUUID TEST_UUID = {+ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,+ 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10+};++struct BlobSummary {+ std::uint32_t subgraph_count = 0u;+ std::vector<std::string> devices;+};++void serialize(Stream& stream, BlobSummary& value) {+ stream & value.subgraph_count & value.devices;+}++struct MetaV1 {+ static constexpr Version kVersion = 1u;++ std::uint32_t subgraph_count = 0u;+ std::vector<std::string> devices;++ void serialize(Stream& stream) {+ stream & subgraph_count & devices;+ }+};++struct MetaV2 : MetaV1 {+ ORC_DECLARE_VERSION(MetaV2, MetaV1)++ bool weightless = false;++ void serialize(Stream& stream) {+ Prev::serialize(stream);+ stream & weightless;+ }+};++struct MetaV3 : MetaV2 {+ ORC_DECLARE_VERSION(MetaV3, MetaV2)++ std::string layout;++ void serialize(Stream& stream) {+ Prev::serialize(stream);+ stream & layout;+ }+};++void expect_blob_summary(const BlobSummary& expected, const BlobSummary& actual) {+ EXPECT_EQ(expected.subgraph_count, actual.subgraph_count);+ EXPECT_EQ(expected.devices, actual.devices);+}++} // namespace++TEST(OrcTest, FileRoundTripsNestedSections) {+ const BlobSummary meta{2u, {"NPU"}};+ const BlobSummary part{7u, {"prefill", "decode"}};+ const BlobSummary wght{1u, {"lazy"}};++ const auto root = Section::container(TYPE_NCMD,+ 1u,+ {make_payload_section(TYPE_META, 1u, meta),+ Section::container(TYPE_PART,+ 1u,+ {make_payload_section(TYPE_TEST, 1u, part)}),+ make_payload_section(TYPE_WGHT, 1u, wght)});++ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);+ write_file(buffer, root, TEST_UUID);++ const auto decoded = read_file(buffer);+ ASSERT_TRUE(decoded.is_container());+ ASSERT_EQ(decoded.type, TYPE_NCMD);+ ASSERT_EQ(decoded.children.size(), 3u);++ EXPECT_EQ(decoded.children[0].type, TYPE_META);+ expect_blob_summary(meta, decode<BlobSummary>(decoded.children[0].payload));++ EXPECT_TRUE(decoded.children[1].is_container());+ ASSERT_EQ(decoded.children[1].children.size(), 1u);+ expect_blob_summary(part, decode<BlobSummary>(decoded.children[1].children[0].payload));++ EXPECT_EQ(decoded.children[2].type, TYPE_WGHT);+ expect_blob_summary(wght, decode<BlobSummary>(decoded.children[2].payload));+}++TEST(OrcTest, RejectsTruncatedFile) {+ const auto root = Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{3u, {"NPU"}})});++ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);+ write_file(buffer, root, TEST_UUID);++ auto bytes = buffer.str();+ ASSERT_FALSE(bytes.empty());+ bytes.pop_back();++ std::stringstream truncated(bytes, std::ios::in | std::ios::out | std::ios::binary);+ EXPECT_THROW(read_file(truncated), ov::Exception);+}++TEST(OrcTest, IsOrcReturnsTrueForValidBlob) {+ const auto root = Section::container(TYPE_NCMD, 1u, {make_payload_section(TYPE_META, 1u, BlobSummary{1u, {"NPU"}})});++ std::stringstream buffer(std::ios::in | std::ios::out | std::ios::binary);+ write_file(buffer, root, TEST_UUID);++ // is_orc must return a header and leave the stream at its original position+ const auto header = is_orc(buffer);+ ASSERT_TRUE(header.has_value());+ EXPECT_EQ(header->version, 1u);+ EXPECT_EQ(header->schema_uuid, TEST_UUID);+ // read_file must still work after the probe+ EXPECT_NO_THROW(read_file(buffer));+}++TEST(OrcTest, IsOrcReturnsFalseForGarbage) {+ std::stringstream buffer("not an orc blob", std::ios::in | std::ios::out | std::ios::binary);+ EXPECT_FALSE(is_orc(buffer).has_value());+}++TEST(OrcTest, SchemaSkipsUnknownOptionalChildren) {+ const auto root = Section::container(TYPE_NCMD,+ 1u,+ {make_payload_section(TYPE_META, 1u, BlobSummary{2u, {"NPU"}}),+ Section::raw(TYPE_UNKNOWN,+ 1u,+ std::vector<std::byte>{std::byte{0xAB}, std::byte{0xCD}},+ static_cast<SectionFlags>(SectionFlag::OPTIONAL)),+ make_payload_section(TYPE_WGHT, 1u, BlobSummary{1u, {"lazy"}})});++ Schema schema;+ schema.register_loader<BlobSummary>(TYPE_META, [](const Section& section, const Schema&) {+ return decode<BlobSummary>(section.payload);+ });+ schema.register_loader<BlobSummary>(TYPE_WGHT, [](const Section& section, const Schema&) {+ return decode<BlobSummary>(section.payload);+ });++ const auto children = schema.load_children(root);+ ASSERT_EQ(children.size(), 2u);+ EXPECT_EQ(children[0].type, TYPE_META);+ EXPECT_EQ(children[1].type, TYPE_WGHT);++ expect_blob_summary(BlobSummary{2u, {"NPU"}}, std::any_cast<BlobSummary>(children[0].value));+ expect_blob_summary(BlobSummary{1u, {"lazy"}}, std::any_cast<BlobSummary>(children[1].value));+}++TEST(OrcTest, SchemaRejectsUnknownRequiredChildren) {+ const auto root = Section::container(TYPE_NCMD,+ 1u,+ {make_payload_section(TYPE_META, 1u, BlobSummary{2u, {"NPU"}}),+ Section::raw(TYPE_UNKNOWN, 1u, std::vector<std::byte>{std::byte{0xAA}})});++ Schema schema;+ schema.register_loader<BlobSummary>(TYPE_META, [](const Section& section, const Schema&) {+ return decode<BlobSummary>(section.payload);+ });++ EXPECT_THROW(schema.load_children(root), ov::Exception);+}++TEST(OrcTest, SchemaRejectsDuplicateRegistration) {+ Schema schema;+ schema.register_loader<BlobSummary>(TYPE_META, [](const Section& section, const Schema&) {+ return decode<BlobSummary>(section.payload);+ });++ EXPECT_THROW(+ {+ schema.register_loader<BlobSummary>(TYPE_META, [](const Section& section, const Schema&) {+ return decode<BlobSummary>(section.payload);+ });+ },+ ov::Exception);+}++TEST(OrcTest, SchemaRejectsTypedMismatch) {+ const auto section = make_payload_section(TYPE_META, 1u, BlobSummary{2u, {"NPU"}});++ Schema schema;+ schema.register_loader<BlobSummary>(TYPE_META, [](const Section& payload, const Schema&) {+ return decode<BlobSummary>(payload.payload);+ });++ EXPECT_THROW(schema.load<std::string>(section), ov::Exception);+}++TEST(OrcTest, LoadVersionedPayloadMigratesAcrossVersions) {+ Schema schema;+ schema.register_loader<MetaV3>(TYPE_META, [](const Section& section, const Schema&) {+ return load_versioned_payload<MetaV3, MetaV1, MetaV2, MetaV3>(section);+ });++ const auto meta_v1 = schema.load<MetaV3>(make_payload_section(TYPE_META, MetaV1::kVersion, MetaV1{3u, {"NPU", "CPU"}}));+ EXPECT_EQ(meta_v1.subgraph_count, 3u);+ EXPECT_EQ(meta_v1.devices, (std::vector<std::string>{"NPU", "CPU"}));+ EXPECT_FALSE(meta_v1.weightless);+ EXPECT_TRUE(meta_v1.layout.empty());++ MetaV2 v2;+ v2.subgraph_count = 4u;+ v2.devices = {"NPU"};+ v2.weightless = true;+ const auto meta_v2 = schema.load<MetaV3>(make_payload_section(TYPE_META, MetaV2::kVersion, v2));+ EXPECT_EQ(meta_v2.subgraph_count, 4u);+ EXPECT_EQ(meta_v2.devices, (std::vector<std::string>{"NPU"}));+ EXPECT_TRUE(meta_v2.weightless);+ EXPECT_TRUE(meta_v2.layout.empty());++ MetaV3 v3;+ v3.subgraph_count = 5u;+ v3.devices = {"NPU", "GPU"};+ v3.weightless = true;+ v3.layout = "split";+ const auto meta_v3 = schema.load<MetaV3>(make_payload_section(TYPE_META, MetaV3::kVersion, v3));+ EXPECT_EQ(meta_v3.subgraph_count, 5u);+ EXPECT_EQ(meta_v3.devices, (std::vector<std::string>{"NPU", "GPU"}));+ EXPECT_TRUE(meta_v3.weightless);+ EXPECT_EQ(meta_v3.layout, "split");+}++TEST(OrcTest, LoadVersionedPayloadRejectsUnsupportedVersion) {+ Schema schema;+ schema.register_loader<MetaV3>(TYPE_META, [](const Section& section, const Schema&) {+ return load_versioned_payload<MetaV3, MetaV1, MetaV2, MetaV3>(section);+ });++ const auto unsupported = make_payload_section(TYPE_META, 99u, MetaV1{1u, {"NPU"}});+ EXPECT_THROW(schema.load<MetaV3>(unsupported), ov::Exception);+}