Skip to content

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

CVS 197629 Move VM runtime to NPU plugin (#39001)

Insoo Wood6b2a405d8f1
diff --git a/src/plugins/intel_npu/cmake/download_compiler_libs.cmake b/src/plugins/intel_npu/cmake/download_compiler_libs.cmake
index e98327f0cdf..250f3766538 100644
--- a/src/plugins/intel_npu/cmake/download_compiler_libs.cmake
+++ b/src/plugins/intel_npu/cmake/download_compiler_libs.cmake
@@ -31,8 +31,8 @@
# value is written to runtime/npu_compiler_version.txt of the installation package.
# lib folder with the following libraries that will be copied to the output directory
# and included in the installation package:
-# WINDOWS: openvino_intel_npu_compiler.dll, openvino_intel_npu_compiler_loader.dll, openvino_intel_npu_vm_runtime.dll
-# LINUX: libopenvino_intel_npu_compiler.so, libopenvino_intel_npu_compiler_loader.so, libopenvino_intel_npu_vm_runtime.so
+# WINDOWS: openvino_intel_npu_compiler.dll, openvino_intel_npu_compiler_loader.dll
+# LINUX: libopenvino_intel_npu_compiler.so, libopenvino_intel_npu_compiler_loader.so
function(print_build_manifest extracted_file)
if(NOT EXISTS "${extracted_file}")
@@ -89,8 +89,6 @@ if(ENABLE_INTEL_NPU_COMPILER)
set(PLUGIN_COMPILER_PDB_NAME "openvino_intel_npu_compiler.pdb")
set(PLUGIN_COMPILER_LOADER_LIB_NAME "openvino_intel_npu_compiler_loader.dll")
set(PLUGIN_COMPILER_LOADER_PDB_NAME "openvino_intel_npu_compiler_loader.pdb")
- set(PLUGIN_COMPILER_VM_RT_LIB_NAME "openvino_intel_npu_vm_runtime.dll")
- set(PLUGIN_COMPILER_VM_RT_PDB_NAME "openvino_intel_npu_vm_runtime.pdb")
elseif(UNIX AND NOT APPLE AND NOT ANDROID)
# Get the OS name and OS version
execute_process(COMMAND lsb_release -is OUTPUT_VARIABLE OS_NAME OUTPUT_STRIP_TRAILING_WHITESPACE)
@@ -106,7 +104,6 @@ if(ENABLE_INTEL_NPU_COMPILER)
set(PLUGIN_COMPILER_ARCHIVE_TYPE "ARCHIVE_LIN")
set(PLUGIN_COMPILER_LIB_NAME "libopenvino_intel_npu_compiler.so")
set(PLUGIN_COMPILER_LOADER_LIB_NAME "libopenvino_intel_npu_compiler_loader.so")
- set(PLUGIN_COMPILER_VM_RT_LIB_NAME "libopenvino_intel_npu_vm_runtime.so")
else()
message(STATUS "${OS_NAME} ${OS_VERSION} Linux distribution is not supported, skip downloading prebuilt Plugin Compiler libraries. Can not use plugin compiler libraries!")
return()
@@ -149,13 +146,10 @@ if(ENABLE_INTEL_NPU_COMPILER)
set(PLUGIN_COMPILER_LIB "${PLUGIN_COMPILER_LIB_PATH}/${PLUGIN_COMPILER_LIB_NAME}")
set(PLUGIN_COMPILER_LOADER_LIB "${PLUGIN_COMPILER_LIB_PATH}/${PLUGIN_COMPILER_LOADER_LIB_NAME}")
- set(PLUGIN_COMPILER_VM_RT_LIB "${PLUGIN_COMPILER_LIB_PATH}/${PLUGIN_COMPILER_VM_RT_LIB_NAME}")
file(COPY "${PLUGIN_COMPILER_LIB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
file(COPY "${PLUGIN_COMPILER_LOADER_LIB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
- file(COPY "${PLUGIN_COMPILER_VM_RT_LIB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
message(STATUS "Copying prebuilt Plugin compiler library ${PLUGIN_COMPILER_LIB} to ${PLUGIN_COMPILER_LIB_DESTINATION}")
message(STATUS "Copying prebuilt Plugin compiler loader library ${PLUGIN_COMPILER_LOADER_LIB} to ${PLUGIN_COMPILER_LIB_DESTINATION}")
- message(STATUS "Copying prebuilt Plugin compiler VM runtime library ${PLUGIN_COMPILER_VM_RT_LIB} to ${PLUGIN_COMPILER_LIB_DESTINATION}")
install(FILES ${PLUGIN_COMPILER_LIB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
install(FILES ${PLUGIN_COMPILER_LOADER_LIB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
@@ -163,7 +157,6 @@ if(ENABLE_INTEL_NPU_COMPILER)
install(FILES ${PLUGIN_COMPILER_LIB} DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL)
install(FILES ${PLUGIN_COMPILER_LOADER_LIB} DESTINATION tests COMPONENT tests EXCLUDE_FROM_ALL)
endif()
- install(FILES ${PLUGIN_COMPILER_VM_RT_LIB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
if(EXISTS "${NPU_COMPILER_VERSION_FILE}")
install(FILES ${NPU_COMPILER_VERSION_FILE} DESTINATION runtime COMPONENT ${NPU_PLUGIN_COMPONENT})
@@ -175,12 +168,10 @@ if(ENABLE_INTEL_NPU_COMPILER)
set(PLUGIN_COMPILER_VM_RT_PDB "${PLUGIN_COMPILER_PDB_PATH}/${PLUGIN_COMPILER_VM_RT_PDB_NAME}")
file(COPY "${PLUGIN_COMPILER_PDB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
file(COPY "${PLUGIN_COMPILER_LOADER_PDB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
- file(COPY "${PLUGIN_COMPILER_VM_RT_PDB}" DESTINATION "${PLUGIN_COMPILER_LIB_DESTINATION}")
message(STATUS "Copying prebuilt Plugin compiler PDB files from ${PLUGIN_COMPILER_PDB_PATH} to ${PLUGIN_COMPILER_LIB_DESTINATION}")
install(FILES ${PLUGIN_COMPILER_PDB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT pdb EXCLUDE_FROM_ALL)
install(FILES ${PLUGIN_COMPILER_LOADER_PDB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT pdb EXCLUDE_FROM_ALL)
- install(FILES ${PLUGIN_COMPILER_VM_RT_PDB} DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT pdb EXCLUDE_FROM_ALL)
endif()
else()
message(FATAL_ERROR "Failed to download prebuilt NPU Plugin Compiler libraries. Can not use plugin compiler libraries!")
diff --git a/src/plugins/intel_npu/src/plugin/CMakeLists.txt b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
index f3f3c9de55b..02882baa02b 100644
--- a/src/plugins/intel_npu/src/plugin/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/plugin/CMakeLists.txt
@@ -62,3 +62,7 @@ cross_compiled_file(${TARGET_NAME}
)
ov_add_api_validator_post_build_step(TARGET ${NPU_PLUGIN_TARGET})
+
+if(BUILD_SHARED_LIBS)
+ add_dependencies(${TARGET_NAME} openvino_intel_npu_vm_runtime)
+endif()
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
index 7196804764a..47a6a88aac7 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/mem_ref_type.hpp
@@ -10,7 +10,7 @@
#include <string>
#include <vector>
-#include "intel_npu/utils/vm/npu_vm_runtime.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/shape.hpp"
#include "openvino/runtime/itensor.hpp"
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
index b523da21609..d944df49506 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_api.hpp
@@ -10,7 +10,7 @@
#include <type_traits>
#include <utility>
-#include "npu_vm_runtime.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
#include "openvino/core/except.hpp"
namespace intel_npu {
@@ -52,7 +52,7 @@ public:
static void initialize(std::string_view libName);
// Inspects the blob header to select the appropriate runtime library and calls initialize().
- // Selects "openvino_intel_npu_vm_runtime" for NPUByte blobs, "openvino_intel_npu_mlir_runtime" otherwise.
+ // Selects "openvino_intel_npu_vm_runtime" for NPUByte blobs.
static void initializeFromBlob(const void* data, size_t size);
static const std::shared_ptr<NPUVMRuntimeApi>& getInstance();
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp
index 8c577927c85..447262a237c 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime_utils.hpp
@@ -7,7 +7,7 @@
#include <array>
#include <cstddef>
-#include "intel_npu/utils/vm/npu_vm_runtime.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
#include "openvino/core/except.hpp"
namespace intel_npu {
diff --git a/src/plugins/intel_npu/src/utils/src/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
index 434523deda8..8d7817622ed 100644
--- a/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/utils/src/CMakeLists.txt
@@ -7,5 +7,6 @@ add_subdirectory(logger)
if(ENABLE_NPU_PLUGIN_ENGINE)
add_subdirectory(vcl)
add_subdirectory(zero)
+ add_subdirectory(vm_runtime)
add_subdirectory(vm)
endif()
diff --git a/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt
index 27d34652b8c..233efbed480 100644
--- a/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt
+++ b/src/plugins/intel_npu/src/utils/src/vm/CMakeLists.txt
@@ -24,6 +24,7 @@ target_include_directories(${TARGET_NAME}
$<TARGET_PROPERTY:openvino::util,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:openvino::core::dev,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:openvino::runtime::dev,INTERFACE_INCLUDE_DIRECTORIES>
+ $<TARGET_PROPERTY:openvino::intel_npu_vm_runtime,INTERFACE_INCLUDE_DIRECTORIES>
)
target_link_libraries(${TARGET_NAME} PUBLIC
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/vm_runtime/CMakeLists.txt
new file mode 100644
index 00000000000..ee1f1052959
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/CMakeLists.txt
@@ -0,0 +1,6 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+
+add_subdirectory(npu_bytecode_utils)
+add_subdirectory(vm_runtime)
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/CMakeLists.txt
new file mode 100644
index 00000000000..199aa344203
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/CMakeLists.txt
@@ -0,0 +1,55 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+
+set(TARGET_NAME openvino_intel_npu_bytecode_utils)
+
+list(APPEND SOURCES
+ src/bytecode_reader.cpp
+ src/except.cpp
+ src/format.cpp
+ src/instructions.cpp
+ src/logger.cpp
+ src/magic_number.cpp
+ src/network_description.cpp
+ src/print_utils.cpp
+ src/section_header_table.cpp
+ src/type_section.cpp
+ src/version.cpp
+)
+source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})
+
+add_library(${TARGET_NAME} STATIC ${SOURCES})
+add_library(openvino::intel_npu_bytecode_utils ALIAS ${TARGET_NAME})
+set_target_properties(${TARGET_NAME} PROPERTIES EXPORT_NAME intel_npu_bytecode_utils)
+ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})
+
+if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT ENABLE_DEVELOPER_BUILD)
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=4)
+else()
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=6)
+endif()
+
+target_link_libraries(${TARGET_NAME}
+ PUBLIC
+ openvino::runtime
+)
+
+target_include_directories(${TARGET_NAME}
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+)
+
+# Prevents warning about unused parameters in NPU plugin logger header:
+# include/openvino/core/attribute_adapter.hpp:38:44: error: unused parameter 'x' [-Werror=unused-parameter]
+if(NOT MSVC)
+ target_compile_options(${TARGET_NAME}
+ PRIVATE
+ -Wno-error=unused-parameter
+ )
+endif()
+
+ov_developer_package_export_targets(TARGET ${TARGET_NAME}
+ INSTALL_INCLUDE_DIRECTORIES
+ ${CMAKE_CURRENT_SOURCE_DIR}/include)
+ov_install_static_lib(${TARGET_NAME} ${OV_CPACK_COMP_CORE})
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/bytecode_reader.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/bytecode_reader.hpp
new file mode 100644
index 00000000000..0d58a4afa10
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/bytecode_reader.hpp
@@ -0,0 +1,90 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "npu_bytecode_utils/version.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace intel_npu::vm {
+
+// Deserializes a bytecode binary into its constituent parts: file header and section payloads
+class BytecodeReader {
+ Span<uint8_t> _bytecode;
+
+ MagicNumber _magicNumber{}; // File format identifier parsed from the bytecode header
+ Version _version{}; // Bytecode format version (major.minor.patch)
+ SectionHeaderTable _sectionHeaderTable; // Table of contents describing all sections in the file
+ std::vector<Span<uint8_t>> _sections; // Raw payload bytes for each section, indexed in header order
+
+ // Oldest bytecode version the VM still supports (backward compat floor)
+ static Version getMinSupportedVersion();
+ // Current VM version: the newest bytecode format the VM implements
+ static Version getMaxSupportedVersion();
+
+ // Parses the file header fields (magic number, version, section header table) from the beginning of the bytecode
+ // buffer. Returns false on malformed input.
+ bool parseFileHeader();
+
+ // Extracts raw section payloads using offsets and sizes from the previously
+ // parsed section header table. Must be called after parseFileHeader().
+ // Returns false if any section exceeds the bytecode buffer bounds.
+ bool parseSections();
+
+ void printFunctionSection(const SectionHeader& sectionHeader, Span<uint8_t> sectionContent, size_t sectionIdx,
+ size_t indentLevel);
+ void printDataSection(const SectionHeader& sectionHeader, Span<uint8_t> sectionContent, size_t sectionIdx,
+ SectionType sectionType, bool printFull, size_t indentLevel);
+
+public:
+ // Constructs a reader for the given bytecode buffer. The buffer must remain valid for the lifetime of the reader
+ BytecodeReader(Span<uint8_t> bytecode): _bytecode(bytecode), _sectionHeaderTable() {
+ }
+
+ // Returns a reference to the parsed section header table. Valid only after a successful parseFile() call.
+ SectionHeaderTable& getSectionHeaderTable();
+
+ // Returns the extracted section payloads as a list of byte vectors,
+ // ordered to match the section headers. Valid only after a successful parseFile() call.
+ const std::vector<Span<uint8_t>>& getSections() const;
+
+ Span<uint8_t> getDataSectionEntry(SectionType sectionType, size_t entryIndex) const;
+
+ /// Retrieves a string from the string section given its index, Valid only after a successful parseFile() call.
+ /// @param stringIndex The index of the desired string in the string section
+ /// @return The string value if found, or std::nullopt otherwise
+ std::optional<std::string> getString(size_t stringIndex) const;
+
+ std::optional<FunctionType> getFunctionType(size_t typeIndex) const;
+
+ // Checks whether the parsed bytecode version is compatible with this VM
+ static bool isVersionSupported(Span<uint8_t> bytecode, Version minVersion = getMinSupportedVersion(),
+ Version maxVersion = getMaxSupportedVersion());
+
+ // Checks whether the parsed bytecode version is compatible with this VM
+ bool isVersionSupported() const;
+
+ // Parses the entire bytecode file: header followed by section payloads.
+ // Returns false and logs an error if any stage of parsing fails.
+ bool parseFile();
+
+ // Prints the parsed file header to stdout
+ void printFileHeader(size_t indentLevel = 0);
+
+ /// Prints the entire parsed file to stdout
+ /// @param printFull If true, also prints the content of binary sections such constants or kernels
+ /// @param indentLevel The indentation level for pretty-printing nested structures
+ void printFile(bool printFull = true, size_t indentLevel = 0);
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/except.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/except.hpp
new file mode 100644
index 00000000000..30aee12d4cf
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/except.hpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/format.hpp"
+#include "npu_bytecode_utils/macro.hpp"
+
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <type_traits>
+#include <vector>
+
+namespace intel_npu::vm {
+
+namespace detail {
+
+[[noreturn]] void throwRuntimeError(const char* file, int line, const std::string& message);
+
+template <typename T>
+std::string toString(const T& value) {
+ using ValueType = std::decay_t<T>;
+ if constexpr (std::is_same_v<ValueType, std::string>) {
+ return value;
+ } else if constexpr (std::is_same_v<ValueType, std::string_view>) {
+ return std::string(value);
+ } else if constexpr (std::is_same_v<ValueType, const char*> || std::is_same_v<ValueType, char*>) {
+ const char* strValue = value;
+ return strValue == nullptr ? std::string{} : std::string(strValue);
+ } else {
+ std::ostringstream stream;
+ stream << value;
+ return stream.str();
+ }
+}
+
+template <typename... Args>
+std::string formatMessage(std::string_view format, const Args&... args) {
+ const std::vector<std::string> serializedArgs{toString(args)...};
+ return formatString(format, serializedArgs);
+}
+
+} // namespace detail
+
+} // namespace intel_npu::vm
+
+// NOLINTBEGIN(cppcoreguidelines-macro-usage)
+
+#define NPU_VM_THROW(...) \
+ ::intel_npu::vm::detail::throwRuntimeError(__FILE__, __LINE__, ::intel_npu::vm::detail::formatMessage(__VA_ARGS__))
+
+#define NPU_VM_THROW_WHEN(condition, ...) \
+ if (NPU_VM_UNLIKELY(condition)) { \
+ NPU_VM_THROW(__VA_ARGS__); \
+ }
+
+#define NPU_VM_THROW_UNLESS(condition, ...) \
+ if (NPU_VM_UNLIKELY(!(condition))) { \
+ NPU_VM_THROW(__VA_ARGS__); \
+ }
+
+// NOLINTEND(cppcoreguidelines-macro-usage)
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/format.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/format.hpp
new file mode 100644
index 00000000000..be3a94b6df3
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/format.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace intel_npu::vm {
+
+// Format the string by replacing "{}" placeholders in the input with the provided arguments. If there are
+// more arguments than placeholders, the extra arguments are appended to the end of the message. If there are more
+// placeholders than arguments, the extra placeholders are left as-is in the message
+std::string formatString(std::string_view format, const std::vector<std::string>& args);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/instructions.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/instructions.hpp
new file mode 100644
index 00000000000..a53c4e27180
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/instructions.hpp
@@ -0,0 +1,174 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <iterator>
+#include <optional>
+#include <type_traits>
+
+namespace intel_npu::vm {
+
+// Instruction opcodes recognized by the bytecode interpreter
+enum class OpCode : uint16_t {
+ // v1.0.0
+ ABS_I64 = 0x01,
+ ADD_I64 = 0x02,
+ DIV_I64 = 0x03,
+ MAX_I64 = 0x04,
+ MIN_I64 = 0x05,
+ MUL_I64 = 0x06,
+ REM_I64 = 0x07,
+ SUB_I64 = 0x08,
+ ADD_U64 = 0x09,
+ DIV_U64 = 0x0A,
+ MAX_U64 = 0x0B,
+ MIN_U64 = 0x0C,
+ MUL_U64 = 0x0D,
+ REM_U64 = 0x0E,
+ SUB_U64 = 0x0F,
+ ABS_F64 = 0x10,
+ ADD_F64 = 0x11,
+ CEIL_F64 = 0x12,
+ DIV_F64 = 0x13,
+ FLOOR_F64 = 0x14,
+ MAX_F64 = 0x15,
+ MIN_F64 = 0x16,
+ MUL_F64 = 0x17,
+ NEG_F64 = 0x18,
+ REM_F64 = 0x19,
+ ROUND_F64 = 0x1A,
+ SUB_F64 = 0x1B,
+ AND_64 = 0x1C,
+ NOT_64 = 0x1D,
+ OR_64 = 0x1E,
+ XOR_64 = 0x1F,
+ SLL_64 = 0x20,
+ SRL_64 = 0x21,
+ SRA_64 = 0x22,
+ CMP_I64 = 0x23,
+ CMP_F64 = 0x24,
+ CONVERT_I8_TO_F32 = 0x25,
+ CONVERT_I8_TO_F64 = 0x26,
+ CONVERT_I16_TO_I8 = 0x27,
+ CONVERT_I16_TO_F32 = 0x28,
+ CONVERT_I16_TO_F64 = 0x29,
+ CONVERT_I32_TO_I8 = 0x2A,
+ CONVERT_I32_TO_I16 = 0x2B,
+ CONVERT_I32_TO_F32 = 0x2C,
+ CONVERT_I32_TO_F64 = 0x2D,
+ CONVERT_I64_TO_I8 = 0x2E,
+ CONVERT_I64_TO_I16 = 0x2F,
+ CONVERT_I64_TO_I32 = 0x30,
+ CONVERT_I64_TO_F32 = 0x31,
+ CONVERT_I64_TO_F64 = 0x32,
+ CONVERT_F32_TO_I8 = 0x33,
+ CONVERT_F32_TO_I16 = 0x34,
+ CONVERT_F32_TO_I32 = 0x35,
+ CONVERT_F32_TO_I64 = 0x36,
+ CONVERT_F32_TO_F64 = 0x37,
+ CONVERT_F64_TO_I8 = 0x38,
+ CONVERT_F64_TO_I16 = 0x39,
+ CONVERT_F64_TO_I32 = 0x3A,
+ CONVERT_F64_TO_I64 = 0x3B,
+ CONVERT_F64_TO_F32 = 0x3C,
+ SELECT = 0x3D,
+ CALL = 0x3E,
+ RET = 0x3F,
+ RETV = 0x40,
+ JMP = 0x41,
+ JE = 0x42,
+ JNE = 0x43,
+ ASSERT = 0x44,
+ KERNEL_CREATE = 0x45,
+ CMD_LIST_CREATE = 0x46,
+ CMD_LIST_ADD_KERNEL = 0x47,
+ CMD_LIST_CLOSE = 0x48,
+ CMD_LIST_EXEC = 0x49,
+ BUFFER_CREATE = 0x4A,
+ BUFFER_GET_DIM = 0x4B,
+ BUFFER_SUBVIEW = 0x4C,
+ BUFFER_VIEW = 0x4D,
+ BUFFER_STORE = 0x4E,
+ SET = 0x4F,
+ SET_IMM = 0x50,
+
+ // v1.1.0
+ BUFFER_LOAD = 0x51,
+
+ // v1.2.0
+ BUFFER_FROM_CONST = 0x52,
+ BUFFER_COPY = 0x53,
+};
+
+enum class RoundingMode : int16_t {
+ RNE = 0x0,
+ RNA = 0x1,
+ RDN = 0x2,
+ RUP = 0x3,
+ RTZ = 0x4,
+};
+
+enum class CmpPredicate : uint8_t {
+ EQ = 0x00,
+ NE = 0x01,
+ GT = 0x02,
+ GTE = 0x03,
+ LT = 0x04,
+ LTE = 0x05,
+};
+
+inline constexpr size_t OPCODE_SIZE = sizeof(OpCode);
+inline constexpr size_t OPERAND_SIZE = sizeof(int16_t);
+
+inline constexpr uint16_t CMP_SIGN_BIT = 0x100;
+
+inline constexpr uint16_t makeCmpFlag(CmpPredicate pred, bool isSigned) {
+ return (isSigned ? CMP_SIGN_BIT : 0u) | static_cast<uint16_t>(pred);
+}
+
+// Get the byte size of an instruction that has a static number of operands
+std::optional<size_t> getStaticInstructionSize(OpCode opcode);
+
+// Get the byte size of an instruction. This supports both instructions that have a static or variadic number of
+// operands. For variadic opcodes, 'availableBytes' is validated internally against the decode header before any operand
+// is read. Callers still have to verify that 'availableBytes' is at least equal to the returned size before advancing
+// past the instruction.
+std::optional<size_t> getInstructionSize(OpCode opcode, const uint8_t* instructionBegin, size_t availableBytes);
+
+// Get the opcode of the instruction whose binary representation starts at 'instructionBegin'
+inline OpCode getOpcode(const uint8_t* instructionBegin) {
+ std::underlying_type_t<OpCode> value = 0;
+ std::memcpy(&value, instructionBegin, sizeof(value));
+ return static_cast<OpCode>(value);
+}
+
+// The value of the i-th operand for the instruction whose binary representation starts at 'begin'.
+// This util is intended to be used only for instructions that have operands represented as 16-bit signed integers
+inline int16_t getOperand(const uint8_t* instructionBegin, size_t operandIndex) {
+ int16_t value = 0;
+ const auto byteOffset = static_cast<std::ptrdiff_t>(OPCODE_SIZE + operandIndex * OPERAND_SIZE);
+ std::memcpy(&value, std::next(instructionBegin, byteOffset), sizeof(value));
+ return value;
+}
+
+inline int64_t get64BitImm(const uint8_t* instructionBegin, size_t operandIndex) {
+ int64_t value = 0;
+ const auto byteOffset = static_cast<std::ptrdiff_t>(OPCODE_SIZE + operandIndex * OPERAND_SIZE);
+ std::memcpy(&value, std::next(instructionBegin, byteOffset), sizeof(value));
+ return value;
+}
+
+template <typename T>
+inline T getAsOperand(const uint8_t* instructionBegin, size_t byteOffset) {
+ static_assert(std::is_trivially_copyable_v<T>, "getAsOperand requires a trivially copyable type");
+ T value = {};
+ std::memcpy(&value, std::next(instructionBegin, static_cast<std::ptrdiff_t>(byteOffset)), sizeof(value));
+ return value;
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/logger.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/logger.hpp
new file mode 100644
index 00000000000..2082d0f54fb
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/logger.hpp
@@ -0,0 +1,171 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <type_traits>
+#include <vector>
+// Logging utility for NPU bytecode reader and related components. Provides macros for logging at different levels
+// (Trace, Debug, Info, Warn, Error, Fatal) with support for formatted messages and color output. The log messages
+// include a timestamp, log level, and source information (file name / path and line number):
+// [YYYY-MM-DD HH:MM:SS.mmm] [LOG_LEVEL] file:line message
+//
+// All logs are printed to standard error.
+//
+// Logs can be disabled during build by setting the BUILD_LOG_LEVEL build option to a value from 0 (no logs) to 6 (all
+// logs). For example, setting BUILD_LOG_LEVEL to 4 will include Info, Warn, Error, and Fatal messages, but exclude
+// Debug and Trace messages.
+//
+// For developer builds (i.e. when NPU_PLUGIN_DEVELOPER_BUILD is defined), the logging behavior can be further customized
+// through environment variables:
+// - NPU_VM_LOG_LEVEL or OV_NPU_LOG_LEVEL: Set the log level threshold (e.g. LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARN,
+// LOG_ERROR, LOG_FATAL). If both are set, NPU_VM_LOG_LEVEL takes precedence.
+// - NPU_VM_LOG_FILTER or IE_NPU_LOG_FILTER: A regex pattern to filter log messages based on their source (file name /
+// path and line). Only messages whose source matches the regex will be printed. If both are set, NPU_VM_LOG_FILTER
+// takes precedence.
+// - NPU_VM_LOG_COLORS: Enable or disable colored output. If set to "0", colors are disabled. By default, colors are
+// enabled.
+// - NPU_VM_LOG_FULL_PATH: Control whether log messages include the full file path or just the file name. If set to "0",
+// only the file name is included. By default, only the file name is shown.
+//
+// For non-developer builds, the log level is set to Info by default, colors are enabled, only the file name is printed
+// and all messages are included regardless of their source.
+
+namespace intel_npu::vm {
+
+enum class LogLevel : uint8_t {
+ None = 0,
+ Fatal = 1,
+ Error = 2,
+ Warn = 3,
+ Info = 4,
+ Debug = 5,
+ Trace = 6,
+};
+
+namespace detail {
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+// Reset all logging caches. Intended for unit test isolation; not thread-safe and must not be called concurrently with
+// logging
+void resetLoggingCache();
+#endif
+
+LogLevel getEffectiveLogLevel();
+
+bool isLogIncludedInFilter(const char* file, int line);
+inline bool isLogLevelActive(LogLevel level) {
+ return level <= getEffectiveLogLevel();
+}
+
+void dispatchLogMessage(LogLevel level, const char* file, int line, std::string_view format,
+ const std::vector<std::string>& args);
+
+inline void dispatchLog(LogLevel level, const char* file, int line, std::string_view format) {
+ try {
+ if (!isLogIncludedInFilter(file, line)) {
+ return;
+ }
+ const std::vector<std::string> args;
+ dispatchLogMessage(level, file, line, format, args);
+ } catch (const std::exception& e) {
+ try {
+ std::cerr << "Exception during log printing: " << e.what() << std::endl;
+ } catch (...) {
+ // Swallow exceptions from fallback logging to keep logging noexcept.
+ }
+ } catch (...) {
+ // Swallow any non-std exception to keep logging noexcept.
+ }
+}
+
+template <typename... Args>
+void dispatchLog(LogLevel level, const char* file, int line, std::string_view format, const Args&... args) {
+ try {
+ const auto toLogString = [](const auto& value) -> std::string {
+ using ValueType = std::decay_t<decltype(value)>;
+ if constexpr (std::is_same_v<ValueType, std::string>) {
+ return value;
+ } else if constexpr (std::is_same_v<ValueType, std::string_view>) {
+ return std::string(value);
+ } else if constexpr (std::is_same_v<ValueType, const char*> || std::is_same_v<ValueType, char*>) {
+ const char* strValue = value; // NOLINT(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
+ return strValue == nullptr ? std::string{} : std::string(strValue);
+ } else {
+ std::ostringstream stream;
+ stream << value;
+ return stream.str();
+ }
+ };
+ if (!isLogIncludedInFilter(file, line)) {
+ return;
+ }
+ const std::vector<std::string> serializedArgs{toLogString(args)...};
+ dispatchLogMessage(level, file, line, format, serializedArgs);
+ } catch (const std::exception& e) {
+ try {
+ std::cerr << "Exception during log printing: " << e.what() << std::endl;
+ } catch (...) {
+ // Swallow exceptions from fallback logging to keep logging noexcept.
+ }
+ } catch (...) {
+ // Swallow any non-std exception to keep logging noexcept.
+ }
+}
+
+} // namespace detail
+
+} // namespace intel_npu::vm
+
+// NOLINTBEGIN(cppcoreguidelines-macro-usage)
+
+#define NPU_VM_LOG_DETAIL_IMPL(level, ...) \
+ do { /* NOLINT(cppcoreguidelines-avoid-do-while) */ \
+ if (::intel_npu::vm::detail::isLogLevelActive(::intel_npu::vm::LogLevel::level)) { \
+ ::intel_npu::vm::detail::dispatchLog(::intel_npu::vm::LogLevel::level, __FILE__, __LINE__, __VA_ARGS__); \
+ } \
+ } while (0)
+
+#if BUILD_LOG_LEVEL == 6
+#define NPU_VM_LOG_TRACE(...) NPU_VM_LOG_DETAIL_IMPL(Trace, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_TRACE(...) ((void)0)
+#endif
+
+#if BUILD_LOG_LEVEL >= 5
+#define NPU_VM_LOG_DEBUG(...) NPU_VM_LOG_DETAIL_IMPL(Debug, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_DEBUG(...) ((void)0)
+#endif
+
+#if BUILD_LOG_LEVEL >= 4
+#define NPU_VM_LOG_INFO(...) NPU_VM_LOG_DETAIL_IMPL(Info, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_INFO(...) ((void)0)
+#endif
+
+#if BUILD_LOG_LEVEL >= 3
+#define NPU_VM_LOG_WARN(...) NPU_VM_LOG_DETAIL_IMPL(Warn, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_WARN(...) ((void)0)
+#endif
+
+#if BUILD_LOG_LEVEL >= 2
+#define NPU_VM_LOG_ERROR(...) NPU_VM_LOG_DETAIL_IMPL(Error, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_ERROR(...) ((void)0)
+#endif
+
+#if BUILD_LOG_LEVEL >= 1
+#define NPU_VM_LOG_FATAL(...) NPU_VM_LOG_DETAIL_IMPL(Fatal, __VA_ARGS__)
+#else
+#define NPU_VM_LOG_FATAL(...) ((void)0)
+#endif
+
+// NOLINTEND(cppcoreguidelines-macro-usage)
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/macro.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/macro.hpp
new file mode 100644
index 00000000000..51ec220c391
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/macro.hpp
@@ -0,0 +1,19 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#ifndef __has_builtin
+#define __has_builtin(x) 0
+#endif
+
+// NOLINTBEGIN(cppcoreguidelines-macro-usage)
+
+#if __has_builtin(__builtin_expect) || defined(__GNUC__)
+#define NPU_VM_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false)
+#else
+#define NPU_VM_UNLIKELY(EXPR) (EXPR)
+#endif
+
+// NOLINTEND(cppcoreguidelines-macro-usage)
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/magic_number.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/magic_number.hpp
new file mode 100644
index 00000000000..5d8a2394d02
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/magic_number.hpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+namespace intel_npu::vm {
+
+constexpr uint8_t MAGIC_NUMBER_SIZE = 8;
+constexpr std::array<uint8_t, MAGIC_NUMBER_SIZE> MAGIC_NUMBER = {0x4E, 0x50, 0x55, 0x42,
+ 0x79, 0x74, 0x65, 0x00}; // 'NPUByte\0'
+
+class MagicNumber {
+ std::array<uint8_t, MAGIC_NUMBER_SIZE> _value;
+
+public:
+ MagicNumber() = default;
+ MagicNumber(const std::array<uint8_t, MAGIC_NUMBER_SIZE>& value): _value(value) {
+ }
+
+ const std::array<uint8_t, MAGIC_NUMBER_SIZE>& value() const;
+
+ // Returns the total number of bytes used to represent the magic number
+ static size_t getBinarySize();
+
+ // Appends the magic number bytes to the provided buffer
+ void appendTo(std::vector<uint8_t>& buffer) const;
+
+ // Parses the magic number from the given buffer and populates the value field.
+ // Returns false and logs an error on malformed input. The buffer is advanced past the consumed bytes on success.
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+
+ // Prints the magic number in hexadecimal format to stdout
+ void print(size_t indentLevel = 0) const;
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/managed_vector.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/managed_vector.hpp
new file mode 100644
index 00000000000..4ccd802f4fc
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/managed_vector.hpp
@@ -0,0 +1,119 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <optional>
+#include <type_traits>
+#include <vector>
+
+namespace intel_npu::vm {
+
+/// A vector-like container that can either own its data (by making a copy of it) or reference external data without
+/// taking ownership. The template parameter T represents the type of the elements in the vector.
+template <typename T>
+class ManagedVector {
+ static_assert(std::is_trivially_copyable_v<T>, "ManagedVector requires a trivially copyable element type");
+
+ std::optional<std::vector<T>> _ownedData; // Optional owned copy of the data, if this instance owns its data
+ Span<T> _data; // The data span, either referencing the owned data or external data
+
+public:
+ ManagedVector() = default;
+
+ /// Constructs a ManagedVector that either owns a copy of the provided data or references it directly, depending on
+ /// the value of copyData. If copyData is true, the constructor makes an owned copy of the data; otherwise, it just
+ /// references the provided data without taking ownership. The caller must ensure that the provided data remains
+ /// valid for the lifetime of the ManagedVector if copyData is false.
+ ManagedVector(Span<T> data, bool copyData = false) {
+ if (copyData) {
+ // Make an owned copy of the data if requested
+ auto& ownedData = _ownedData.emplace();
+ ownedData.reserve(data.size());
+ ownedData.insert(ownedData.end(), data.begin(), data.end());
+ _data = Span<T>(ownedData.data(), ownedData.size());
+ } else {
+ // Otherwise just reference the provided data directly
+ _data = data;
+ }
+ }
+
+ ManagedVector(const ManagedVector& other) {
+ if (other._ownedData.has_value()) {
+ // Deep-copy the owned data so each instance manages its own allocation
+ _ownedData = other._ownedData;
+ auto& ownedData = _ownedData.value();
+ _data = Span<T>(ownedData.data(), ownedData.size());
+ } else {
+ // Share the same external data without taking ownership
+ _data = other._data;
+ }
+ }
+
+ ManagedVector(ManagedVector&& other) noexcept: _ownedData(std::move(other._ownedData)) {
+ if (_ownedData.has_value()) {
+ auto& ownedData = _ownedData.value();
+ _data = Span<T>(ownedData.data(), ownedData.size());
+ } else {
+ _data = other._data;
+ }
+ other._data = Span<T>();
+ }
+
+ ManagedVector& operator=(const ManagedVector& other) {
+ if (this != &other) {
+ // Copy into temporaries first, to leave *this in a valid state if the vector copy fails
+ std::optional<std::vector<T>> newOwnedData;
+ Span<T> newData;
+
+ if (other._ownedData.has_value()) {
+ newOwnedData = other._ownedData;
+ auto& ownedData = newOwnedData.value();
+ newData = Span<T>(ownedData.data(), ownedData.size());
+ } else {
+ newData = other._data;
+ }
+
+ // Move the data from the temporaries into *this
+ _ownedData = std::move(newOwnedData);
+ _data = newData;
+ }
+ return *this;
+ }
+
+ ManagedVector& operator=(ManagedVector&& other) noexcept {
+ if (this != &other) {
+ _ownedData = std::move(other._ownedData);
+ if (_ownedData.has_value()) {
+ auto& ownedData = _ownedData.value();
+ _data = Span<T>(ownedData.data(), ownedData.size());
+ } else {
+ _data = other._data;
+ }
+ other._data = Span<T>();
+ }
+ return *this;
+ }
+
+ ~ManagedVector() = default;
+
+ /// Returns true if this ManagedVector owns its data, false if it is just referencing external data
+ bool isOwned() const {
+ return _ownedData.has_value();
+ }
+
+ /// Returns a Span representing the elements in the vector
+ Span<const T> get() const {
+ return Span<const T>(_data.begin(), _data.size());
+ }
+
+ /// Returns a Span representing the elements in the vector
+ Span<T> get() {
+ return _data;
+ }
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/network_description.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/network_description.hpp
new file mode 100644
index 00000000000..9ac2e737b93
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/network_description.hpp
@@ -0,0 +1,173 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+
+#include <openvino/core/partial_shape.hpp>
+#include <openvino/core/type/element_type.hpp>
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+namespace intel_npu::vm {
+
+/**
+ * @brief A helper structure used for storing metadata corresponding to one input/output entry.
+ */
+struct IODescriptor {
+ /**
+ * @brief The name of the input/output assigned by the compiler.
+ * @details This value may differ from other name attributes:
+ * - The compiler could have created additional inputs/outputs (e.g. for representing states). These are not
+ * found in the original IR model.
+ * - The compiler may append indices to names in the case where duplicate names are found.
+ * @note The prefixes introduced by the compiler in order to differentiate the special cases (e.g. states and shape
+ * tensors) were removed prior to initializing this field.
+ */
+ std::string nameFromCompiler;
+
+ ov::element::Type precision;
+
+ std::string layout;
+
+ ov::PartialShape shapeFromCompiler;
+
+ /**
+ * @brief If set to "true", the current object describes a buffer which may be used for altering a state tensor.
+ * @details This flag is set if the compiler prefixed the name using a "read value" prefix. The state input and
+ * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isStateInput = false;
+
+ /**
+ * @brief If set to "true", the current object describes a buffer which reflects the value of a state tensor.
+ * @details This flag is set if the compiler prefixed the name using an "assign" prefix. The state input and
+ * state output descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isStateOutput = false;
+
+ /**
+ * @brief If set to "true", the buffer of the tensor described here contains as value the shape of the referenced
+ * tensor.
+ * @details This flag is set if the compiler prefixed the name using a "shape" prefix.
+ *
+ * The referenced tensor bears the same name ("nameFromCompiler"), but its "isShapeTensor" value is set to
+ * "false". The two descriptors are also tied using the "relatedDescriptorIndex" attribute.
+ */
+ bool isShapeTensor = false;
+
+ /**
+ * @brief If "true", the current object describes an input for an init schedule (weights separation).
+ */
+ bool isInitInputWeights = false;
+
+ /**
+ * @brief If "true", the current object describes an output for an init schedule (weights separation).
+ */
+ bool isInitOutputWeights = false;
+
+ /**
+ * @brief If "true", the current object describes a weights input for the main schedule (weights separation).
+ *
+ * @details If weights separation is enabled, a significant amount of weights are cut off from the compiled model
+ * and then corresponding placeholders are created as inputs. These inputs are meant to be obtained by running the
+ * init schedule(s).
+ */
+ bool isMainInputWeights = false;
+
+ /**
+ * @brief Points towards a related descriptor.
+ * @details The related descriptors are defined by (state input, state output) or (dynamic tensor, shape tensor)
+ * pairs.
+ */
+ std::optional<size_t> relatedDescriptorIndex;
+
+ /**
+ * @brief The friendly name of the node extracted from the IR model.
+ * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
+ * metadata as the original IR model.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
+ * compiler).
+ */
+ std::string nodeFriendlyName;
+
+ /**
+ * @brief The names of the output tensors extracted from the IR model.
+ * @details In some cases, this field is required for constructing a dummy model which uses the same input/output
+ * metadata as the original IR model.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added by the
+ * compiler).
+ */
+ std::unordered_set<std::string> outputTensorNames;
+
+ /**
+ * @brief The shape extracted from the IR model.
+ * @details The values may differ from the ones found in "shapeFromCompiler" if batching is to be handled by the
+ * plugin.
+ *
+ * This field may be empty if the I/O entry is not found in the original IR model (i.e. the entry was added
+ * by the compiler).
+ */
+ std::optional<ov::PartialShape> shapeFromIRModel = std::nullopt;
+
+ /**
+ * @brief The driver index of the descriptor.
+ * @details This value is used by the driver to identify the input/output buffer. Driver indices for inputs and
+ * outputs are assigned in the same vector and could have different indexing.
+ */
+ uint32_t indexUsedByDriver = 0;
+
+ /**
+ * @brief Indicates whether strided memory layout is supported for this tensor.
+ * @details When set to true, this tensor can use non-contiguous memory layout with custom strides,
+ * allowing for more flexible memory access patterns. Strided tensors enable efficient representation of sliced or
+ * transposed data without copying.
+ */
+ bool supportsStridedLayout = false;
+};
+
+struct NetworkMetadata final {
+ std::string name;
+
+ std::vector<IODescriptor> inputs;
+ std::vector<IODescriptor> outputs;
+ std::vector<IODescriptor> profilingOutputs;
+
+ size_t numStreams = 1;
+
+ size_t numCmdLists = 1;
+
+ /**
+ * @brief Binds the (state input, state output) and (dynamic tensor, shape tensor) pairs using the
+ * "relatedDescriptorIndex" attribute.
+ * @details For state inputs, the "relatedDescriptorIndex" value is set to the index of the output which bears the
+ * same name. The reverse is also applied.
+ *
+ * For shape tensors, the lookup is performed in the same container (inputs or outputs). The value is once again set
+ * to the index of the entry which bears the same name.
+ */
+ void bindRelatedDescriptors();
+};
+
+enum class MetadataRecordKind : uint8_t {
+ Network = 0,
+ Input = 1,
+ Output = 2,
+ ProfilingOutput = 3,
+};
+
+std::optional<NetworkMetadata> parseNetworkMetadata(const uint8_t* bytecodePtr, size_t bytecodeSize);
+std::optional<NetworkMetadata> parseNetworkMetadata(BytecodeReader& reader);
+
+void printMetadataEntry(Span<uint8_t> metadata);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/print_utils.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/print_utils.hpp
new file mode 100644
index 00000000000..448cdb27501
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/print_utils.hpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+namespace intel_npu::vm {
+
+inline void printIndent(size_t indentLevel) {
+ constexpr auto numSpaces = 2;
+ for (size_t i = 0; i < indentLevel * numSpaces; ++i) {
+ std::cout << " ";
+ }
+}
+
+std::string toHex(uint8_t byte);
+
+template <typename T>
+std::string formatVector(const std::vector<T>& values) {
+ std::ostringstream stream;
+ stream << "[";
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (i != 0) {
+ stream << ", ";
+ }
+ stream << values.at(i);
+ }
+ stream << "]";
+ return stream.str();
+}
+
+std::string formatPtrVectorContent(const std::vector<int64_t*>& values);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/section_header_table.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/section_header_table.hpp
new file mode 100644
index 00000000000..5ce4931887b
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/section_header_table.hpp
@@ -0,0 +1,182 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace intel_npu::vm {
+
+namespace details {
+
+// Base class for section-specific metadata stored within a SectionHeader.
+// Each section type (function, constant, etc.) carries its own layout description that is serialized immediately after
+// the common header fields.
+struct SectionInfo {
+ SectionInfo() = default;
+ SectionInfo(const SectionInfo&) = default;
+ SectionInfo& operator=(const SectionInfo&) = default;
+ SectionInfo(SectionInfo&&) = default;
+ SectionInfo& operator=(SectionInfo&&) = default;
+ virtual ~SectionInfo() = default;
+
+ // Returns the total number of bytes this metadata occupies when serialized
+ virtual size_t getBinarySize() const = 0;
+
+ // Serializes the section-specific metadata and appends it to buffer
+ virtual void appendTo(std::vector<uint8_t>& buffer) const = 0;
+
+ // Deserializes function section metadata from the buffer.
+ // Returns false and logs an error on malformed input. The buffer is advanced past the consumed bytes.
+ virtual bool parseFrom(vm::Span<uint8_t>& buffer) = 0;
+
+ // Prints a human-readable representation of the metadata to stdout
+ virtual void print(size_t indentLevel = 0) const = 0;
+};
+
+// Metadata for a function section. Describes all compiled functions including their names, type signatures, register
+// requirements, and the byte range of each function body within the section payload.
+struct FunctionSectionInfo : public SectionInfo {
+ struct FunctionInfo {
+ uint64_t nameIndex; // Index into the string section for the function name
+ uint64_t functionTypeIndex; // Index into the type section for the function signature
+ uint64_t numGeneralRegisters; // Number of general registers used by the function
+ uint64_t bodyOffset; // Byte offset of the function body relative to the section start
+ uint64_t bodySize; // Size of the function body in bytes
+ };
+
+ uint64_t numFunctions{}; // Total number of functions described in this section
+ uint64_t entrypointFunctionIndex{}; // Index of the entry-point function within the function list
+ std::vector<FunctionInfo> functionInfos; // List of metadata entries for each function in the section
+
+ size_t getBinarySize() const override;
+
+ void appendTo(std::vector<uint8_t>& buffer) const override;
+
+ bool parseFrom(vm::Span<uint8_t>& buffer) override;
+
+ void print(size_t indentLevel = 0) const override;
+};
+
+// Metadata for data-oriented sections (constants, strings, types).
+// Each entry is described by its offset and size within the section payload, allowing random access to individual data
+// items.
+struct DataSectionInfo : public SectionInfo {
+ struct DataInfo {
+ uint64_t offset; // Byte offset of the data entry relative to the section start
+ uint64_t size; // Size of the data entry in bytes
+ };
+
+ uint64_t numData{}; // Total number of data entries in this section
+ std::vector<DataInfo> dataInfos; // List of metadata entries for each data item in the section
+
+ size_t getBinarySize() const override;
+
+ void appendTo(std::vector<uint8_t>& buffer) const override;
+
+ bool parseFrom(vm::Span<uint8_t>& buffer) override;
+
+ void print(size_t indentLevel = 0) const override;
+};
+
+} // namespace details
+
+/// Identifies the kind of payload a section carries.
+/// @details The section type determines which SectionInfo subclass is used to describe the section layout.
+enum class SectionType : uint8_t {
+ FuncSection = 0x00, // Contains compiled function bodies
+ ConstantSection = 0x01, // Contains constant data blobs (weights, biases, etc.)
+ StringSection = 0x02, // Contains null-terminated strings referenced by index
+ KernelSection = 0x03, // Contains kernel binaries referenced by index
+ TypeSection = 0x04, // Contains type descriptors (function signatures, buffer types, primitive types, etc.)
+ MetadataSection = 0x05 // Contains serialized network/input/output metadata entries
+};
+
+std::string getSectionTypeString(SectionType type);
+
+// Represents an entry in the section header table.
+// Combines common fields (type, name, file offset, size) with a polymorphic
+// SectionInfo pointer that holds section-type-specific metadata.
+struct SectionHeader {
+ SectionType type{}; // Discriminator for the section payload kind
+ uint64_t nameIndex{}; // Index into the string section for the section name
+ uint64_t offset{}; // Absolute byte offset of the section payload in the file
+ uint64_t size{}; // Size of the section payload in bytes
+ std::unique_ptr<details::SectionInfo> info; // Section-type-specific descriptor
+
+ SectionHeader() = default;
+ SectionHeader(SectionType type, uint64_t nameIndex, uint64_t offset, uint64_t size,
+ std::unique_ptr<details::SectionInfo> info)
+ : type(type), nameIndex(nameIndex), offset(offset), size(size), info(std::move(info)) {
+ }
+ SectionHeader(const SectionHeader&) = delete;
+ SectionHeader& operator=(const SectionHeader&) = delete;
+ SectionHeader(SectionHeader&&) = default;
+ SectionHeader& operator=(SectionHeader&&) = default;
+ ~SectionHeader() = default;
+
+ // Returns the total serialized size of this header including its SectionInfo
+ size_t getBinarySize() const;
+
+ // Serializes the header fields and section-specific info into buffer
+ void appendTo(std::vector<uint8_t>& buffer) const;
+
+ // Deserializes a section header from buffer, including the appropriate SectionInfo subclass based on the parsed
+ // section type.
+ // Returns false and logs an error on failure. The buffer is advanced past the consumed bytes.
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+
+ // Prints a human-readable representation of the header and its metadata to stdout
+ void print(size_t indentLevel = 0) const;
+};
+
+// Manages the collection of section headers that form the bytecode file's table of contents
+class SectionHeaderTable {
+ uint64_t _numSections = 0;
+ std::vector<SectionHeader> _sectionHeaders;
+
+public:
+ SectionHeaderTable() = default;
+ SectionHeaderTable(const SectionHeaderTable&) = delete;
+ SectionHeaderTable& operator=(const SectionHeaderTable&) = delete;
+ SectionHeaderTable(SectionHeaderTable&&) = default;
+ SectionHeaderTable& operator=(SectionHeaderTable&&) = default;
+ ~SectionHeaderTable() = default;
+
+ // Returns a reference to the internal section header list
+ const std::vector<SectionHeader>& getSectionHeaders() const;
+ std::vector<SectionHeader>& getSectionHeaders();
+
+ // Appends a section header to the table
+ void addSectionHeader(SectionHeader header);
+
+ // Returns the total serialized size of the table
+ size_t getBinarySize() const;
+
+ // Assigns absolute file offsets to each section's payload. Offsets are
+ // calculated assuming sections are laid out immediately after the file
+ // header in a fixed order: functions, constants, strings, types.
+ void computeOffsets();
+
+ // Serializes the section count and all headers into buffer.
+ // Headers are written grouped by section type in a deterministic order:
+ // functions, constants, strings, types.
+ void appendTo(std::vector<uint8_t>& buffer) const;
+
+ // Deserializes the section header table from buffer.
+ // Returns false and logs an error if parsing fails. The buffer is advanced past the consumed bytes.
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+
+ // Prints the entire section header table to stdout
+ void print(size_t indentLevel = 0) const;
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/serialization_utils.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/serialization_utils.hpp
new file mode 100644
index 00000000000..2287f9dc63e
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/serialization_utils.hpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <array>
+#include <cstdint>
+#include <cstring>
+#include <vector>
+
+namespace intel_npu::vm {
+
+template <typename T>
+void appendValueTo(std::vector<uint8_t>& buffer, const T& value) {
+ std::array<uint8_t, sizeof(T)> bytes{};
+ std::memcpy(bytes.data(), &value, sizeof(T));
+ buffer.insert(buffer.end(), bytes.begin(), bytes.end());
+}
+
+template <typename T>
+bool parseValueFrom(vm::Span<uint8_t>& buffer, T& value) {
+ if (buffer.begin() == nullptr) {
+ return false;
+ }
+ if (buffer.size() < sizeof(T)) {
+ return false;
+ }
+ memcpy(&value, buffer.begin(), sizeof(T));
+ buffer = buffer.subspan(sizeof(T));
+ return true;
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/span.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/span.hpp
new file mode 100644
index 00000000000..c66b004edf6
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/span.hpp
@@ -0,0 +1,216 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <array>
+#include <cassert>
+#include <cstddef>
+#include <iterator>
+#include <stdexcept>
+#include <type_traits>
+
+namespace intel_npu::vm {
+
+// NOLINTNEXTLINE(readability-identifier-naming) - keep std::span-compatible naming
+inline constexpr size_t dynamic_extent = static_cast<size_t>(-1);
+
+// Represents a contiguous sequence of objects, with the first element of the sequence at position zero
+template <typename T>
+class Span {
+public:
+ using element_type = T;
+ using value_type = std::remove_cv_t<T>;
+ using size_type = size_t;
+ using difference_type = std::ptrdiff_t;
+ using pointer = T*;
+ using const_pointer = const T*;
+ using reference = T&;
+ using const_reference = const T&;
+ using iterator = pointer;
+ using reverse_iterator = std::reverse_iterator<iterator>;
+ using const_iterator = const_pointer;
+ using const_reverse_iterator = std::reverse_iterator<const_iterator>;
+ // NOLINTNEXTLINE(readability-identifier-naming) - keep std::span-compatible naming
+ static constexpr size_t extent = dynamic_extent;
+
+private:
+ T* _data{};
+ size_t _size{};
+
+public:
+ // Constructs an empty span
+ constexpr Span() noexcept = default;
+
+ // Constructs a span over [data, data + size)
+ constexpr Span(pointer data, size_type size) noexcept: _data{data}, _size{size} {
+ assert((data != nullptr || size == 0) && "Span cannot have a null data pointer if size is greater than zero");
+ }
+
+ // Constructs a span over [first, last)
+ constexpr Span(pointer first, pointer last) noexcept: Span(first, static_cast<size_type>(last - first)) {
+ assert((first != nullptr || last == first) &&
+ "Span cannot have a null data pointer if size is greater than zero");
+ assert((last >= first) && "Span cannot be constructed from an invalid [first, last) range");
+ }
+
+ template <size_t N>
+ // Constructs a span over all elements in a C-style array
+ constexpr Span(element_type (&arr)[N]) noexcept // NOLINT(cppcoreguidelines-avoid-c-arrays)
+ : Span(arr, N) {
+ }
+
+ // Constructs a span over all elements in a mutable std::array
+ template <typename U, size_t N, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
+ constexpr Span(std::array<U, N>& arr) noexcept: Span(arr.data(), arr.size()) {
+ }
+
+ // Constructs a span over all elements in a const std::array
+ template <typename U, size_t N, typename = std::enable_if_t<std::is_convertible_v<const U*, T*>>>
+ constexpr Span(const std::array<U, N>& arr) noexcept: Span(arr.data(), arr.size()) {
+ }
+
+ // Constructs a span from another span when element pointers are convertible
+ template <typename U, typename = std::enable_if_t<std::is_convertible_v<U*, T*>>>
+ constexpr Span(const Span<U>& other) noexcept: Span(other.data(), other.size()) {
+ }
+
+ // Returns a reference to the element at index i, with bounds checking. Throws std::out_of_range if i >= size()
+ constexpr reference at(size_type i) const {
+ if (i >= size()) {
+ throw std::out_of_range("Span index out of bounds");
+ }
+ return *std::next(_data, static_cast<difference_type>(i));
+ }
+
+ // Returns a reference to the element at index i
+ constexpr reference operator[](size_type i) const noexcept {
+ assert(i < size() && "Span index out of bounds");
+ return *std::next(begin(), static_cast<difference_type>(i));
+ }
+
+ // Returns a reference to the first element
+ constexpr reference front() const noexcept {
+ assert(!empty() && "Span::front called on an empty span");
+ return *begin();
+ }
+
+ // Returns a reference to the last element
+ constexpr reference back() const noexcept {
+ assert(!empty() && "Span::back called on an empty span");
+ return *(end() - 1);
+ }
+
+ // Returns a pointer to the first element, or nullptr for a default-constructed empty span
+ constexpr pointer data() const noexcept {
+ return _data;
+ }
+
+ // Returns the number of elements
+ constexpr size_type size() const noexcept {
+ return _size;
+ }
+
+ // Returns the number of bytes in the view
+ constexpr size_type size_bytes() const noexcept { // NOLINT(readability-identifier-naming)
+ return _size * sizeof(element_type);
+ }
+
+ // Returns true if the span has zero elements
+ constexpr bool empty() const noexcept {
+ return _size == 0;
+ }
+
+ // Returns an iterator to the first element
+ constexpr iterator begin() const noexcept {
+ return _data;
+ }
+
+ // Returns an iterator one past the last element
+ constexpr iterator end() const noexcept {
+ return (_data == nullptr) ? nullptr : std::next(_data, static_cast<difference_type>(_size));
+ }
+
+ // Returns a const iterator to the first element
+ constexpr const_iterator cbegin() const noexcept {
+ return _data;
+ }
+
+ // Returns a const iterator one past the last element
+ constexpr const_iterator cend() const noexcept {
+ return (_data == nullptr) ? nullptr : std::next(_data, static_cast<difference_type>(_size));
+ }
+
+ // Returns a reverse iterator to the first element of the reversed view
+ constexpr reverse_iterator rbegin() const noexcept {
+ return reverse_iterator(end());
+ }
+
+ // Returns a reverse iterator one past the last element of the reversed view
+ constexpr reverse_iterator rend() const noexcept {
+ return reverse_iterator(begin());
+ }
+
+ // Returns a const reverse iterator to the first element of the reversed view
+ constexpr const_reverse_iterator crbegin() const noexcept {
+ return const_reverse_iterator(cend());
+ }
+
+ // Returns a const reverse iterator one past the last element of the reversed view
+ constexpr const_reverse_iterator crend() const noexcept {
+ return const_reverse_iterator(cbegin());
+ }
+
+ // Returns a subview of the first count elements
+ constexpr Span<T> first(size_type count) const noexcept {
+ assert(count <= _size && "Span::first count exceeds span size");
+ return Span<T>(_data, count);
+ }
+
+ // Returns a subview of the last count elements
+ constexpr Span<T> last(size_type count) const noexcept {
+ assert(count <= _size && "Span::last count exceeds span size");
+ return Span<T>(std::next(_data, static_cast<difference_type>(_size - count)), count);
+ }
+
+ // Returns a subview with compile-time offset/count
+ // If Count is dynamic_extent, the subview extends to the end
+ template <size_t Offset, size_t Count = dynamic_extent>
+ constexpr Span<T> subspan() const noexcept {
+ assert(Offset <= _size && "Span::subspan offset exceeds span size");
+ if constexpr (Count == dynamic_extent) {
+ return Span<T>(std::next(_data, static_cast<difference_type>(Offset)), _size - Offset);
+ }
+
+ assert(Count <= _size - Offset && "Span::subspan count exceeds available range");
+ return Span<T>(std::next(_data, static_cast<difference_type>(Offset)), Count);
+ }
+
+ // Returns a subview with runtime offset/count
+ // If count is dynamic_extent, the subview extends to the end
+ constexpr Span<T> subspan(size_type offset, size_type count = dynamic_extent) const noexcept {
+ assert(offset <= _size && "Span::subspan offset exceeds span size");
+ if (count == dynamic_extent) {
+ return Span<T>(std::next(_data, static_cast<difference_type>(offset)), _size - offset);
+ }
+
+ assert(count <= _size - offset && "Span::subspan count exceeds available range");
+ return Span<T>(std::next(_data, static_cast<difference_type>(offset)), count);
+ }
+};
+
+// Returns a read-only byte view over the same memory.
+template <typename T>
+constexpr Span<const std::byte> as_bytes(Span<T> span) noexcept { // NOLINT(readability-identifier-naming)
+ return Span<const std::byte>(static_cast<const std::byte*>(static_cast<const void*>(span.data())),
+ span.size_bytes());
+}
+
+// Returns a writable byte view over the same memory.
+template <typename T, typename = std::enable_if_t<!std::is_const_v<T>>>
+constexpr Span<std::byte> as_writable_bytes(Span<T> span) noexcept { // NOLINT(readability-identifier-naming)
+ return Span<std::byte>(static_cast<std::byte*>(static_cast<void*>(span.data())), span.size_bytes());
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/type_section.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/type_section.hpp
new file mode 100644
index 00000000000..1ab16345797
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/type_section.hpp
@@ -0,0 +1,145 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <optional>
+#include <variant>
+#include <vector>
+
+namespace intel_npu::vm {
+
+class SectionHeaderTable;
+
+enum class TypeCode : uint8_t {
+ INTEGER = 0x01,
+ FLOAT = 0x02,
+ OPAQUE = 0x03,
+ BUFFER = 0x04,
+ FUNCTION = 0x05,
+};
+
+enum class FloatTypeFormat : uint8_t {
+ IEEE754 = 0x00,
+ BFloat = 0x01,
+ TFloat = 0x02,
+ E4M3 = 0x03,
+ E5M2 = 0x04,
+ E2M1 = 0x05,
+ E8M0 = 0x06,
+ NF4 = 0x07
+};
+
+struct IntegerType {
+ uint8_t bitWidth; // The bit width of the integer type (e.g. 32 for i32, 64 for i64)
+ uint8_t isSigned; // Whether the integer type is signed (1) or unsigned (0)
+ TypeCode getTypeCode() const {
+ return TypeCode::INTEGER;
+ }
+
+ uint8_t getBitWidth() const {
+ return bitWidth;
+ }
+
+ uint8_t getSigned() const {
+ return isSigned;
+ }
+
+ void appendTo(std::vector<uint8_t>& buffer) const;
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+ void print(size_t indentLevel = 0) const;
+};
+
+struct FloatType {
+ uint8_t bitWidth; // The bit width of the float type (e.g. 32 for f32, 64 for f64)
+ FloatTypeFormat format; // The specific format of the float type (e.g. IEEE754, BFloat, etc.)
+
+ TypeCode getTypeCode() const {
+ return TypeCode::FLOAT;
+ }
+
+ uint8_t getBitWidth() const {
+ return bitWidth;
+ }
+
+ void appendTo(std::vector<uint8_t>& buffer) const;
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+ void print(size_t indentLevel = 0) const;
+};
+
+struct OpaqueType {
+ uint8_t bitWidth; // The bit width of the opaque type
+
+ TypeCode getTypeCode() const {
+ return TypeCode::OPAQUE;
+ }
+
+ uint8_t getBitWidth() const {
+ return bitWidth;
+ }
+
+ void appendTo(std::vector<uint8_t>& buffer) const;
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+ void print(size_t indentLevel = 0) const;
+};
+
+struct BufferType {
+ using RankType = uint8_t;
+ static constexpr int64_t MAX_RANK = std::numeric_limits<RankType>::max();
+
+ uint64_t dataTypeIndex; // Index into the type section for the data type of the buffer
+ RankType rank; // The rank of the buffer (number of dimensions)
+ std::vector<int64_t> shape; // The shape of the buffer, with -1 representing dynamic dimensions
+ std::vector<int64_t> strides; // The strides of the buffer, with -1 representing dynamic strides
+
+ TypeCode getTypeCode() const {
+ return TypeCode::BUFFER;
+ }
+
+ void appendTo(std::vector<uint8_t>& buffer) const;
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+ void print(size_t indentLevel = 0) const;
+};
+
+struct FunctionType {
+ std::vector<uint64_t> paramTypeIndices; // Indices into the type section for the parameter types of the function
+ std::vector<uint64_t> resultTypeIndices; // Indices into the type section for the result types of the function
+
+ TypeCode getTypeCode() const {
+ return TypeCode::FUNCTION;
+ }
+
+ void appendTo(std::vector<uint8_t>& buffer) const;
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+ void print(size_t indentLevel = 0) const;
+};
+
+struct Type {
+ // Note: FunctionType is currently excluded, as the current uses of Type only involve primitive types (such as for a
+ // function's parameters or return types). If FunctionType is added in the future, it might be a good idea to keep
+ // the differentiation between function and non-function types
+ std::variant<IntegerType, FloatType, OpaqueType, BufferType> data{IntegerType{}};
+};
+
+TypeCode getTypeCode(const Type& type);
+
+uint8_t getBitWidth(const intel_npu::vm::Type& type);
+
+bool isTypeSigned(const intel_npu::vm::Type& type);
+
+// Returns the rounded-up byte size for the type at `typeIndex` in the parsed type section.
+// Returns 0 if the index is out of range or the type does not represent a primitive element type.
+uint16_t lookupTypeByteSize(const std::vector<uint16_t>& typeByteSizes, int64_t typeIndex);
+
+// Extracts rounded-up primitive byte sizes from the Type section. Non-primitive entries are returned as 0.
+// Returns std::nullopt and prints an error if the type section layout is malformed.
+std::optional<std::vector<uint16_t>> extractTypeByteSizes(const SectionHeaderTable& sectionHeaderTable,
+ const std::vector<Span<uint8_t>>& sections);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/version.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/version.hpp
new file mode 100644
index 00000000000..1e6041343c5
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/include/npu_bytecode_utils/version.hpp
@@ -0,0 +1,88 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <ostream>
+#include <vector>
+
+namespace intel_npu::vm {
+
+constexpr uint8_t VERSION_SIZE = 3;
+
+class Version {
+private:
+ std::array<uint16_t, VERSION_SIZE> _version{0, 0, 0};
+
+public:
+ Version() = default;
+ Version(uint16_t major, uint16_t minor, uint16_t patch): _version{major, minor, patch} {
+ }
+
+ static Version getMinSupportedVersion() {
+ return Version(1, 0, 0);
+ }
+
+ uint16_t getMajor() const {
+ return _version.at(0);
+ }
+ uint16_t getMinor() const {
+ return _version.at(1);
+ }
+ uint16_t getPatch() const {
+ return _version.at(2);
+ }
+
+ const std::array<uint16_t, VERSION_SIZE>& getFullVersion() const {
+ return _version;
+ }
+
+ Version resetPatchNumber() const {
+ return Version(getMajor(), getMinor(), 0);
+ }
+
+ bool operator<(const Version& other) const {
+ return _version < other._version;
+ };
+ bool operator>(const Version& other) const {
+ return _version > other._version;
+ };
+ bool operator<=(const Version& other) const {
+ return _version <= other._version;
+ };
+ bool operator>=(const Version& other) const {
+ return _version >= other._version;
+ };
+ bool operator==(const Version& other) const {
+ return _version == other._version;
+ };
+ bool operator!=(const Version& other) const {
+ return _version != other._version;
+ };
+
+ // Returns the total number of bytes used to represent the version
+ static size_t getBinarySize();
+
+ // Appends the version bytes to the provided buffer
+ void appendTo(std::vector<uint8_t>& buffer) const;
+
+ // Parses version bytes from the given buffer and populates the version fields.
+ // Returns false and logs an error on malformed input. The buffer is advanced past the consumed bytes on success.
+ bool parseFrom(vm::Span<uint8_t>& buffer);
+
+ // Prints the version in "major.minor.patch" format to stdout
+ void print(size_t indentLevel = 0) const;
+
+ friend std::ostream& operator<<(std::ostream& os, const Version& v) {
+ os << v.getMajor() << "." << v.getMinor() << "." << v.getPatch();
+ return os;
+ }
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/bytecode_reader.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/bytecode_reader.cpp
new file mode 100644
index 00000000000..b89b4bc9b60
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/bytecode_reader.cpp
@@ -0,0 +1,1167 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/network_description.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "npu_bytecode_utils/version.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace {
+
+bool checkInstructionInBounds(intel_npu::vm::Span<uint8_t> functionBody, intel_npu::vm::OpCode opcode) {
+ const auto instructionSize = intel_npu::vm::getInstructionSize(opcode, functionBody.begin(), functionBody.size());
+ if (!instructionSize.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to decode instruction size for opcode {}: unknown opcode or malformed instruction body",
+ static_cast<uint16_t>(opcode));
+ return false;
+ }
+ if (functionBody.size() < instructionSize.value()) {
+ NPU_VM_LOG_ERROR(
+ "Reached end of function body while decoding an instruction. This likely means the function body "
+ "is malformed");
+ return false;
+ }
+ return true;
+}
+
+void printFunctionBody(intel_npu::vm::Span<uint8_t> body, size_t indentLevel = 0) {
+ using namespace intel_npu::vm;
+
+ const auto printInstruction = [&](std::string_view opcode, const std::vector<int64_t>& operands = {}) {
+ printIndent(indentLevel);
+ std::cout << opcode;
+ for (size_t i = 0; i < operands.size(); ++i) {
+ std::cout << " " << operands.at(i);
+ if (i < operands.size() - 1) {
+ std::cout << ",";
+ }
+ }
+ std::cout << std::endl;
+ };
+
+ while (body.begin() != nullptr && !body.empty()) {
+ if (body.size() < intel_npu::vm::OPCODE_SIZE) {
+ NPU_VM_LOG_ERROR(
+ "Reached end of function body while decoding an opcode. This likely means the function body "
+ "is malformed.");
+ break;
+ }
+ const auto opcode = intel_npu::vm::getOpcode(body.begin());
+ if (!checkInstructionInBounds(body, opcode)) {
+ break;
+ }
+ switch (opcode) {
+ case OpCode::ADD_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("add.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MUL_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("mul.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MIN_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("min.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MAX_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("max.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::CMP_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ const auto flag = getOperand(body.begin(), 3);
+ printInstruction("cmp.i64", {dstRegNum, srcReg1Num, srcReg2Num, flag});
+ break;
+ }
+ case OpCode::CMP_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ const auto flag = getOperand(body.begin(), 3);
+ printInstruction("cmp.f64", {dstRegNum, srcReg1Num, srcReg2Num, flag});
+ break;
+ }
+ case OpCode::SUB_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("sub.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::DIV_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("div.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::DIV_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("div.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MIN_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("min.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::ADD_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("add.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MAX_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("max.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MUL_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("mul.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::REM_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("rem.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::SUB_U64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("sub.u64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::REM_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("rem.i64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::ABS_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("abs.i64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::AND_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("and.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::NOT_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("not.64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::OR_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("or.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::XOR_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("xor.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::SLL_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("sll.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::SRL_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("srl.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::SRA_64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("sra.64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::CMD_LIST_CREATE: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ printInstruction("cmd_list.create", {dstRegNum});
+ break;
+ }
+ case OpCode::CMD_LIST_CLOSE: {
+ const auto srcRegNum = getOperand(body.begin(), 0);
+ printInstruction("cmd_list.close", {srcRegNum});
+ break;
+ }
+ case OpCode::CMD_LIST_EXEC: {
+ const auto srcRegNum = getOperand(body.begin(), 0);
+ const auto hostSync = getOperand(body.begin(), 1);
+ printInstruction("cmd_list.exec", {srcRegNum, hostSync});
+ break;
+ }
+ case OpCode::CMD_LIST_ADD_KERNEL: {
+ // Instruction layout: `cmd_list.add_kernel rs1, rs2, N, rN..., M, rM...`
+ // rs1 - command list handle register
+ // rs2 - kernel handle register
+ // N - immediate: number of signal-event registers
+ // rN... - N signal-event registers
+ // M - immediate: number of wait-event registers
+ // rM... - M wait-event registers
+ const auto cmdListRegNum = getOperand(body.begin(), 0);
+ const auto kernelRegNum = getOperand(body.begin(), 1);
+ const auto numSignalEvents = getOperand(body.begin(), 2);
+ if (numSignalEvents < 0) {
+ NPU_VM_LOG_ERROR("Malformed cmd_list.add_kernel instruction: negative signal-event count");
+ return;
+ }
+
+ std::vector<int64_t> operands = {cmdListRegNum, kernelRegNum, static_cast<int64_t>(numSignalEvents)};
+ for (int16_t i = 0; i < numSignalEvents; ++i) {
+ operands.push_back(getOperand(body.begin(), 3 + i));
+ }
+
+ const auto numWaitEvents = getOperand(body.begin(), 3 + numSignalEvents);
+ if (numWaitEvents < 0) {
+ NPU_VM_LOG_ERROR("Malformed cmd_list.add_kernel instruction: negative wait-event count");
+ return;
+ }
+
+ operands.push_back(static_cast<int64_t>(numWaitEvents));
+ for (int16_t i = 0; i < numWaitEvents; ++i) {
+ operands.push_back(getOperand(body.begin(), 4 + numSignalEvents + i));
+ }
+
+ printInstruction("cmd_list.add_kernel", operands);
+ break;
+ }
+ case OpCode::KERNEL_CREATE: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto kidxImm = getOperand(body.begin(), 1);
+ const auto kNameIdxImm = getOperand(body.begin(), 2);
+ const auto numInputs = getOperand(body.begin(), 3);
+ if (numInputs < 0) {
+ NPU_VM_LOG_ERROR("Malformed kernel.create instruction: negative input count {}", numInputs);
+ return;
+ }
+ std::vector<int64_t> operands = {dstRegNum, kidxImm, kNameIdxImm, numInputs};
+ constexpr auto inputsOffset = 4;
+ for (size_t i = 0; i < static_cast<size_t>(numInputs); ++i) {
+ operands.push_back(getOperand(body.begin(), inputsOffset + i));
+ }
+ const auto outputsCountOffset = inputsOffset + static_cast<size_t>(numInputs);
+ const auto numOutputs = getOperand(body.begin(), outputsCountOffset);
+ if (numOutputs < 0) {
+ NPU_VM_LOG_ERROR("Malformed kernel.create instruction: negative output count {}", numOutputs);
+ return;
+ }
+ operands.push_back(numOutputs);
+ const auto outputsOffset = outputsCountOffset + 1;
+ for (size_t i = 0; i < static_cast<size_t>(numOutputs); ++i) {
+ operands.push_back(getOperand(body.begin(), outputsOffset + i));
+ }
+ printInstruction("kernel.create", operands);
+ break;
+ }
+ case OpCode::SELECT: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto condRegNum = getOperand(body.begin(), 1);
+ const auto trueRegNum = getOperand(body.begin(), 2);
+ const auto falseRegNum = getOperand(body.begin(), 3);
+ printInstruction("select", {dstRegNum, condRegNum, trueRegNum, falseRegNum});
+ break;
+ }
+ case OpCode::CALL: {
+ // Instruction layout: `call rs, N, rN..., M, rM...`
+ // rs - register holding the callee function index
+ // N - immediate: number of destination registers that will receive the return values
+ // rN... - N destination register operands (in call order; mapped by `retv` on return)
+ // M - immediate: number of argument registers passed to the callee
+ // rM... - M argument register operands; loaded into callee parameter registers [G, G+M)
+ const auto funcIdxReg = getOperand(body.begin(), 0);
+ const auto n = getOperand(body.begin(), 1);
+ if (n < 0) {
+ NPU_VM_LOG_ERROR("Malformed call instruction: negative destination register count");
+ return;
+ }
+
+ std::vector<int64_t> operands = {funcIdxReg, static_cast<int64_t>(n)};
+ // Collect N destination registers (indices 2..2+N-1)
+ for (int16_t i = 0; i < n; ++i) {
+ operands.push_back(getOperand(body.begin(), 2 + i));
+ }
+ // M is stored immediately after the N destination registers (index 2+N)
+ const auto m = getOperand(body.begin(), 2 + n);
+ if (m < 0) {
+ NPU_VM_LOG_ERROR("Malformed call instruction: negative argument register count");
+ return;
+ }
+
+ operands.push_back(static_cast<int64_t>(m));
+ // Collect M argument registers (indices 3+N..3+N+M-1)
+ for (int16_t i = 0; i < m; ++i) {
+ operands.push_back(getOperand(body.begin(), 3 + n + i));
+ }
+ printInstruction("call", operands);
+ break;
+ }
+ case OpCode::RET: {
+ printInstruction("ret");
+ break;
+ }
+ case OpCode::RETV: {
+ const auto numOperandsRegNum = getOperand(body.begin(), 0);
+ constexpr auto variadicOperandsOffset = 1;
+ std::vector<int64_t> operands = {numOperandsRegNum};
+ for (size_t i = 0; i < static_cast<size_t>(numOperandsRegNum); ++i) {
+ operands.push_back(getOperand(body.begin(), variadicOperandsOffset + i));
+ }
+ printInstruction("retv", operands);
+ break;
+ }
+ case OpCode::SET: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("set", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::SET_IMM: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto immValue = get64BitImm(body.begin(), 1);
+ printInstruction("set.imm", {dstRegNum, immValue});
+ break;
+ }
+ case OpCode::ASSERT: {
+ const auto conditionRegNum = getOperand(body.begin(), 0);
+ const auto msgSymIndex = getOperand(body.begin(), 1);
+ printInstruction("assert", {conditionRegNum, msgSymIndex});
+ break;
+ }
+ case OpCode::BUFFER_CREATE: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // dst
+ operands.push_back(getOperand(body.begin(), 1)); // elem_type
+ const auto rank = getOperand(body.begin(), 2);
+ operands.push_back(rank);
+ for (int64_t i = 0; i < 2 * rank; ++i) {
+ operands.push_back(getOperand(body.begin(), 3 + i));
+ }
+ printInstruction("buffer.create", operands);
+ break;
+ }
+ case OpCode::BUFFER_FROM_CONST: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // dst
+ operands.push_back(getOperand(body.begin(), 1)); // constant index
+ operands.push_back(getOperand(body.begin(), 2)); // elem type
+ const auto rank = getOperand(body.begin(), 3);
+ operands.push_back(rank);
+ for (int64_t i = 0; i < 2 * rank; ++i) {
+ operands.push_back(getOperand(body.begin(), 4 + i));
+ }
+ printInstruction("buffer.from_const", operands);
+ break;
+ }
+ case OpCode::BUFFER_GET_DIM: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto bufRegNum = getOperand(body.begin(), 1);
+ const auto dimRegNum = getOperand(body.begin(), 2);
+ printInstruction("buffer.get_dim", {dstRegNum, bufRegNum, dimRegNum});
+ break;
+ }
+ case OpCode::BUFFER_LOAD: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // dst
+ operands.push_back(getOperand(body.begin(), 1)); // buffer
+ const auto rank = getOperand(body.begin(), 2);
+ operands.push_back(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ operands.push_back(getOperand(body.begin(), 3 + i));
+ }
+ printInstruction("buffer.load", operands);
+ break;
+ }
+ case OpCode::BUFFER_SUBVIEW: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // dst
+ operands.push_back(getOperand(body.begin(), 1)); // src
+ const auto rank = getOperand(body.begin(), 2);
+ operands.push_back(rank);
+ constexpr auto offsetsStartIndex = 3;
+ for (int64_t i = 0; i < 3 * rank; ++i) {
+ operands.push_back(getOperand(body.begin(), offsetsStartIndex + i));
+ }
+ printInstruction("buffer.subview", operands);
+ break;
+ }
+ case OpCode::BUFFER_VIEW: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // dst
+ operands.push_back(getOperand(body.begin(), 1)); // src
+ operands.push_back(getOperand(body.begin(), 2)); // byte_offset
+ operands.push_back(getOperand(body.begin(), 3)); // elem_type
+ const auto rank = getOperand(body.begin(), 4);
+ operands.push_back(rank);
+ constexpr auto shapeStartIndex = 5;
+ for (int64_t i = 0; i < 2 * rank; ++i) {
+ operands.push_back(getOperand(body.begin(), shapeStartIndex + i));
+ }
+ printInstruction("buffer.view", operands);
+ break;
+ }
+ case OpCode::BUFFER_STORE: {
+ std::vector<int64_t> operands;
+ operands.push_back(getOperand(body.begin(), 0)); // buffer
+ operands.push_back(getOperand(body.begin(), 1)); // value
+ const auto rank = getOperand(body.begin(), 2);
+ operands.push_back(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ operands.push_back(getOperand(body.begin(), 3 + i));
+ }
+ printInstruction("buffer.store", operands);
+ break;
+ }
+ case OpCode::BUFFER_COPY: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("buffer.copy", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::ADD_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("add.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::SUB_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("sub.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MUL_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("mul.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::DIV_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("div.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::REM_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("rem.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MAX_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("max.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::MIN_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcReg1Num = getOperand(body.begin(), 1);
+ const auto srcReg2Num = getOperand(body.begin(), 2);
+ printInstruction("min.f64", {dstRegNum, srcReg1Num, srcReg2Num});
+ break;
+ }
+ case OpCode::ABS_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("abs.f64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::NEG_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("neg.f64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CEIL_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("ceil.f64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::FLOOR_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("floor.f64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::ROUND_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ const auto immValue = getOperand(body.begin(), 2);
+ printInstruction("round.f64", {dstRegNum, srcRegNum, immValue});
+ break;
+ }
+ case OpCode::JMP: {
+ const auto offset = get64BitImm(body.begin(), 0);
+ printInstruction("jmp", {offset});
+ break;
+ }
+ case OpCode::JE: {
+ const auto offset = get64BitImm(body.begin(), 0);
+ const auto lhs = getAsOperand<int16_t>(body.begin(), OPCODE_SIZE + sizeof(int64_t));
+ const auto rhs = getAsOperand<int16_t>(body.begin(), OPCODE_SIZE + sizeof(int64_t) + sizeof(int16_t));
+ printInstruction("je", {offset, lhs, rhs});
+ break;
+ }
+ case OpCode::JNE: {
+ const auto offset = get64BitImm(body.begin(), 0);
+ const auto lhs = getAsOperand<int16_t>(body.begin(), OPCODE_SIZE + sizeof(int64_t));
+ const auto rhs = getAsOperand<int16_t>(body.begin(), OPCODE_SIZE + sizeof(int64_t) + sizeof(int16_t));
+ printInstruction("jne", {offset, lhs, rhs});
+ break;
+ }
+ case OpCode::CONVERT_I8_TO_F32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i8tof32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I8_TO_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i8tof64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_I8: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i16toi8", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_F32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i16tof32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i16tof64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_I8: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i32toi8", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_I16: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i32toi16", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_F32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i32tof32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i32tof64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I8: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i64toi8", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I16: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i64toi16", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i64toi32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_F32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i64tof32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.i64tof64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I8: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f32toi8", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I16: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f32toi16", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f32toi32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f32toi64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_F64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f32tof64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I8: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f64toi8", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I16: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f64toi16", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f64toi32", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I64: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f64toi64", {dstRegNum, srcRegNum});
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_F32: {
+ const auto dstRegNum = getOperand(body.begin(), 0);
+ const auto srcRegNum = getOperand(body.begin(), 1);
+ printInstruction("convert.f64tof32", {dstRegNum, srcRegNum});
+ break;
+ }
+ default:
+ NPU_VM_LOG_ERROR("Unknown opcode {}", static_cast<uint16_t>(opcode));
+ return;
+ }
+ const auto instructionSize = getInstructionSize(opcode, body.begin(), body.size());
+ if (!instructionSize.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to decode instruction size for opcode {}. This likely means the instruction encoding "
+ "is malformed",
+ static_cast<uint16_t>(opcode));
+ return;
+ }
+ body = body.subspan(instructionSize.value());
+ }
+}
+
+void printConstant(intel_npu::vm::Span<uint8_t> constant, bool printFull) {
+ const auto printEntireConstant = [&]() {
+ for (const auto& byte : constant) {
+ std::cout << intel_npu::vm::toHex(byte);
+ }
+ };
+
+ const auto printPartialConstant = [&]() {
+ constexpr size_t numBytesToPrintBeforeAndAfter = 4;
+ if (constant.size() <= numBytesToPrintBeforeAndAfter * 2) {
+ printEntireConstant();
+ return;
+ }
+ for (size_t i = 0; i < numBytesToPrintBeforeAndAfter; ++i) {
+ std::cout << intel_npu::vm::toHex(constant.at(i));
+ }
+ std::cout << "...";
+ for (size_t i = constant.size() - numBytesToPrintBeforeAndAfter; i < constant.size(); ++i) {
+ std::cout << intel_npu::vm::toHex(constant.at(i));
+ }
+ };
+
+ if (constant.empty()) {
+ std::cout << "(empty)";
+ return;
+ }
+ std::cout << "0x";
+ if (printFull) {
+ printEntireConstant();
+ } else {
+ // Only print the first and last few elements when printFull is disabled
+ printPartialConstant();
+ }
+}
+
+void printString(intel_npu::vm::Span<uint8_t> string) {
+ if (string.empty()) {
+ std::cout << "\"\"";
+ return;
+ }
+ for (const auto& byte : string) {
+ if (byte == '\0') {
+ // Ensure the null terminator character is printed as well
+ std::cout << "\\0";
+ continue;
+ }
+ std::cout << byte;
+ }
+}
+
+void printType(intel_npu::vm::Span<uint8_t> type) {
+ if (type.empty()) {
+ std::cout << "(empty)";
+ return;
+ }
+ auto typeCode = static_cast<intel_npu::vm::TypeCode>(type.at(0));
+ auto typeData = type.subspan(1);
+
+ switch (typeCode) {
+ case intel_npu::vm::TypeCode::INTEGER: {
+ intel_npu::vm::IntegerType intType{};
+ if (!intType.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse integer type from type data");
+ std::cout << "i<invalid>";
+ return;
+ }
+ intType.print();
+ break;
+ }
+ case intel_npu::vm::TypeCode::FLOAT: {
+ intel_npu::vm::FloatType floatType{};
+ if (!floatType.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse float type from type data");
+ std::cout << "f<invalid>";
+ return;
+ }
+ floatType.print();
+ break;
+ }
+ case intel_npu::vm::TypeCode::OPAQUE: {
+ intel_npu::vm::OpaqueType opaqueType{};
+ if (!opaqueType.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse opaque type from type data");
+ std::cout << "opaque<invalid>";
+ return;
+ }
+ opaqueType.print();
+ break;
+ }
+ case intel_npu::vm::TypeCode::BUFFER: {
+ intel_npu::vm::BufferType bufferType{};
+ if (!bufferType.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse buffer type from type data");
+ std::cout << "buffer<invalid>";
+ return;
+ }
+ bufferType.print();
+ break;
+ }
+ case intel_npu::vm::TypeCode::FUNCTION: {
+ intel_npu::vm::FunctionType funcType{};
+ if (!funcType.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse function type from type data");
+ std::cout << "function<invalid>";
+ return;
+ }
+ funcType.print();
+ break;
+ }
+ default: {
+ std::cout << "Unknown type code: " << intel_npu::vm::toHex(static_cast<uint8_t>(typeCode));
+ break;
+ }
+ }
+}
+
+} // namespace
+
+intel_npu::vm::Version intel_npu::vm::BytecodeReader::getMinSupportedVersion() {
+ return Version{1, 0, 0};
+}
+
+intel_npu::vm::Version intel_npu::vm::BytecodeReader::getMaxSupportedVersion() {
+ return Version{1, 2, 0};
+}
+
+intel_npu::vm::SectionHeaderTable& intel_npu::vm::BytecodeReader::getSectionHeaderTable() {
+ return _sectionHeaderTable;
+}
+
+const std::vector<intel_npu::vm::Span<uint8_t>>& intel_npu::vm::BytecodeReader::getSections() const {
+ return _sections;
+}
+
+intel_npu::vm::Span<uint8_t> intel_npu::vm::BytecodeReader::getDataSectionEntry(intel_npu::vm::SectionType sectionType,
+ size_t entryIndex) const {
+ const auto& sectionHeaders = _sectionHeaderTable.getSectionHeaders();
+ const auto& sections = getSections();
+ for (size_t i = 0; i < sectionHeaders.size(); ++i) {
+ const auto& header = sectionHeaders.at(i);
+ if (header.type != sectionType) {
+ continue;
+ }
+ auto dataSectionInfo = dynamic_cast<const intel_npu::vm::details::DataSectionInfo*>(header.info.get());
+ if (dataSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Section header for section of type {} does not contain data section info",
+ static_cast<int>(sectionType));
+ return {};
+ }
+ if (entryIndex >= dataSectionInfo->numData) {
+ NPU_VM_LOG_ERROR("Entry index {} out of bounds for section with {} entries", entryIndex,
+ dataSectionInfo->numData);
+ return {};
+ }
+ if (entryIndex >= dataSectionInfo->dataInfos.size()) {
+ NPU_VM_LOG_ERROR("Entry index {} out of bounds for section with {} data infos", entryIndex,
+ dataSectionInfo->dataInfos.size());
+ return {};
+ }
+ if (i >= sections.size()) {
+ NPU_VM_LOG_ERROR("Could not find associated section with section header {}", i);
+ return {};
+ }
+ const auto& dataInfo = dataSectionInfo->dataInfos.at(entryIndex);
+ auto& sectionContent = sections.at(i);
+ if (dataInfo.offset > sectionContent.size() || dataInfo.size > sectionContent.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("Entry with offset {} and size {} exceeds section bounds", dataInfo.offset, dataInfo.size);
+ return {};
+ }
+ return sectionContent.subspan(dataInfo.offset, dataInfo.size);
+ }
+ return {};
+}
+
+std::optional<std::string> intel_npu::vm::BytecodeReader::getString(size_t stringIndex) const {
+ auto stringEntry = getDataSectionEntry(SectionType::StringSection, stringIndex);
+ if (stringEntry.empty()) {
+ return std::nullopt;
+ }
+ auto stringSize = stringEntry.size();
+ // Remove the null terminator from the end of the string, since std::string does not require a null terminator
+ if (stringSize > 0 && stringEntry.at(stringSize - 1) == '\0') {
+ --stringSize;
+ }
+ auto subString = stringEntry.subspan(0, stringSize);
+ return std::string(subString.begin(), subString.end());
+}
+
+std::optional<intel_npu::vm::FunctionType> intel_npu::vm::BytecodeReader::getFunctionType(size_t typeIndex) const {
+ auto typeEntry = getDataSectionEntry(SectionType::TypeSection, typeIndex);
+ if (typeEntry.empty()) {
+ return std::nullopt;
+ }
+ intel_npu::vm::FunctionType funcType{};
+ const auto typeCode = static_cast<TypeCode>(typeEntry.at(0));
+ if (typeCode != TypeCode::FUNCTION) {
+ NPU_VM_LOG_ERROR("Type entry at index {} has invalid type code {}, expected FUNCTION type code", typeIndex,
+ static_cast<uint8_t>(typeCode));
+ return std::nullopt;
+ }
+ typeEntry = typeEntry.subspan(sizeof(intel_npu::vm::TypeCode));
+ if (!funcType.parseFrom(typeEntry)) {
+ NPU_VM_LOG_ERROR("Failed to parse function type at index {}", typeIndex);
+ return std::nullopt;
+ }
+ return funcType;
+}
+
+bool intel_npu::vm::BytecodeReader::isVersionSupported(intel_npu::vm::Span<uint8_t> bytecode, Version minVersion,
+ Version maxVersion) {
+ MagicNumber magicNumber{};
+ if (!magicNumber.parseFrom(bytecode)) {
+ NPU_VM_LOG_ERROR("Failed to parse magic number");
+ return false;
+ }
+ Version version{};
+ if (!version.parseFrom(bytecode)) {
+ NPU_VM_LOG_ERROR("Failed to parse version");
+ return false;
+ }
+
+ // Patch version is ignored for compatibility checking
+ maxVersion = maxVersion.resetPatchNumber();
+ minVersion = minVersion.resetPatchNumber();
+ const auto bytecodeVersion = version.resetPatchNumber();
+
+ // Bytecode version must not exceed the VM's current version
+ // A higher version means the bytecode uses features the VM does not yet support
+ if (bytecodeVersion > maxVersion) {
+ NPU_VM_LOG_ERROR(
+ "Bytecode version {} exceeds VM version {}. The bytecode requires a newer VM than the one available",
+ version, maxVersion);
+ return false;
+ }
+
+ // Bytecode version must not be below the minimum supported version
+ // The runtime maintains backward compatibility, but deprecated formats may be dropped
+ if (bytecodeVersion < minVersion) {
+ NPU_VM_LOG_ERROR("Bytecode version {} is below the minimum supported version {}. This bytecode format has been "
+ "deprecated",
+ version, minVersion);
+ return false;
+ }
+
+ return true;
+}
+
+bool intel_npu::vm::BytecodeReader::isVersionSupported() const {
+ return isVersionSupported(_bytecode);
+}
+
+bool intel_npu::vm::BytecodeReader::parseFileHeader() {
+ // Wrap the raw bytecode in a Span that tracks the current read position.
+ // Each parseFrom() call advances the span past the consumed bytes.
+ auto bytecodeBuffer = _bytecode;
+
+ if (!_magicNumber.parseFrom(bytecodeBuffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse magic number");
+ return false;
+ }
+
+ if (!_version.parseFrom(bytecodeBuffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse version");
+ return false;
+ }
+
+ if (!_sectionHeaderTable.parseFrom(bytecodeBuffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse section header table");
+ return false;
+ }
+
+ return true;
+}
+
+bool intel_npu::vm::BytecodeReader::parseSections() {
+ auto bytecodeBuffer = _bytecode;
+
+ for (const auto& header : _sectionHeaderTable.getSectionHeaders()) {
+ const auto sectionType = header.type;
+ const auto offset = header.offset;
+ const auto size = header.size;
+ if (offset > bytecodeBuffer.size() || size > bytecodeBuffer.size() - offset) {
+ NPU_VM_LOG_ERROR(
+ "Section of type {} has invalid offset {} and size {} that exceed bytecode buffer (size {})",
+ static_cast<uint64_t>(sectionType), offset, size, bytecodeBuffer.size());
+ return false;
+ }
+ _sections.push_back(bytecodeBuffer.subspan(offset, size));
+ }
+
+ return true;
+}
+
+void intel_npu::vm::BytecodeReader::printFunctionSection(const intel_npu::vm::SectionHeader& sectionHeader,
+ intel_npu::vm::Span<uint8_t> sectionContent, size_t sectionIdx,
+ size_t indentLevel) {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Function section " << sectionIdx << std::endl;
+ const auto funcSectionInfo =
+ dynamic_cast<const intel_npu::vm::details::FunctionSectionInfo*>(sectionHeader.info.get());
+ if (funcSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Function section header has invalid info type");
+ return;
+ }
+ for (const auto& funcInfo : funcSectionInfo->functionInfos) {
+ intel_npu::vm::printIndent(indentLevel + 1);
+ auto functionName = getString(funcInfo.nameIndex);
+ if (!functionName.has_value()) {
+ NPU_VM_LOG_ERROR("Failed to retrieve function name string for function with name index {}",
+ funcInfo.nameIndex);
+ }
+ std::cout << "Function name: " << functionName.value_or("<unknown>") << std::endl;
+ if (funcInfo.bodyOffset > sectionContent.size() ||
+ funcInfo.bodySize > sectionContent.size() - funcInfo.bodyOffset) {
+ NPU_VM_LOG_ERROR("Function {} has invalid body offset {} and size {} that exceed section buffer (size {})",
+ functionName.value_or("<unknown>"), funcInfo.bodyOffset, funcInfo.bodySize,
+ sectionContent.size());
+ continue;
+ }
+ const auto body = sectionContent.subspan(funcInfo.bodyOffset, funcInfo.bodySize);
+ printFunctionBody(body, indentLevel + 2);
+ }
+}
+
+void intel_npu::vm::BytecodeReader::printDataSection(const intel_npu::vm::SectionHeader& sectionHeader,
+ intel_npu::vm::Span<uint8_t> sectionContent, size_t sectionIdx,
+ intel_npu::vm::SectionType sectionType, bool printFull,
+ size_t indentLevel) {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << intel_npu::vm::getSectionTypeString(sectionType) << " section " << sectionIdx << std::endl;
+
+ const auto dataSectionInfo = dynamic_cast<intel_npu::vm::details::DataSectionInfo*>(sectionHeader.info.get());
+ if (dataSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Section header has invalid info type");
+ return;
+ }
+ for (size_t cstIdx = 0; cstIdx < dataSectionInfo->dataInfos.size(); ++cstIdx) {
+ const auto& dataInfo = dataSectionInfo->dataInfos.at(cstIdx);
+ intel_npu::vm::printIndent(indentLevel + 1);
+ std::cout << intel_npu::vm::getSectionTypeString(sectionType) << " " << cstIdx << ": ";
+ if (dataInfo.offset > sectionContent.size() || dataInfo.size > sectionContent.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("Entry with offset {} and size {} exceeds section bounds", dataInfo.offset, dataInfo.size);
+ continue;
+ }
+ const auto content = sectionContent.subspan(dataInfo.offset, dataInfo.size);
+ if (sectionType == intel_npu::vm::SectionType::ConstantSection ||
+ sectionType == intel_npu::vm::SectionType::KernelSection) {
+ printConstant(content, printFull);
+ } else if (sectionType == intel_npu::vm::SectionType::StringSection) {
+ printString(content);
+ } else if (sectionType == intel_npu::vm::SectionType::TypeSection) {
+ printType(content);
+ } else if (sectionType == intel_npu::vm::SectionType::MetadataSection) {
+ intel_npu::vm::printMetadataEntry(content);
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported section type for body section printing: {}",
+ static_cast<uint64_t>(sectionType));
+ }
+ std::cout << std::endl;
+ }
+}
+
+bool intel_npu::vm::BytecodeReader::parseFile() {
+ if (!isVersionSupported()) {
+ return false;
+ }
+ if (!parseFileHeader()) {
+ NPU_VM_LOG_ERROR("Failed to parse file header");
+ return false;
+ }
+ if (!parseSections()) {
+ NPU_VM_LOG_ERROR("Failed to parse sections");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::BytecodeReader::printFileHeader(size_t indentLevel) {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Magic Number: ";
+ _magicNumber.print();
+ std::cout << std::endl;
+
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Version: ";
+ _version.print();
+ std::cout << std::endl;
+
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Section Header Table:" << std::endl;
+ _sectionHeaderTable.print(indentLevel + 1);
+}
+
+void intel_npu::vm::BytecodeReader::printFile(bool printFull, size_t indentLevel) {
+ printFileHeader(indentLevel);
+
+ size_t functionSectionIdx = 0;
+ size_t constantSectionIdx = 0;
+ size_t kernelSectionIdx = 0;
+ size_t stringSectionIdx = 0;
+ size_t typeSectionIdx = 0;
+ size_t metadataSectionIdx = 0;
+
+ auto& sectionHeaders = _sectionHeaderTable.getSectionHeaders();
+ for (size_t i = 0; i < sectionHeaders.size(); ++i) {
+ if (i >= _sections.size()) {
+ NPU_VM_LOG_ERROR("Could not find associated section with section header {}", i);
+ continue;
+ }
+ auto sectionContent = _sections.at(i);
+ const auto& header = sectionHeaders.at(i);
+ if (header.type == SectionType::FuncSection) {
+ printFunctionSection(header, sectionContent, functionSectionIdx++, indentLevel + 1);
+ } else if (header.type == SectionType::ConstantSection) {
+ printDataSection(header, sectionContent, constantSectionIdx++, header.type, printFull, indentLevel + 1);
+ } else if (header.type == SectionType::StringSection) {
+ printDataSection(header, sectionContent, stringSectionIdx++, header.type, printFull, indentLevel + 1);
+ } else if (header.type == SectionType::KernelSection) {
+ printDataSection(header, sectionContent, kernelSectionIdx++, header.type, printFull, indentLevel + 1);
+ } else if (header.type == SectionType::TypeSection) {
+ printDataSection(header, sectionContent, typeSectionIdx++, header.type, printFull, indentLevel + 1);
+ } else if (header.type == SectionType::MetadataSection) {
+ printDataSection(header, sectionContent, metadataSectionIdx++, header.type, printFull, indentLevel + 1);
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported section type for printing: {}", static_cast<uint64_t>(header.type));
+ }
+ }
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/except.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/except.cpp
new file mode 100644
index 00000000000..38023f6cf68
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/except.cpp
@@ -0,0 +1,20 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/except.hpp"
+
+#include <sstream>
+#include <stdexcept>
+#include <string>
+
+[[noreturn]] void intel_npu::vm::detail::throwRuntimeError([[maybe_unused]] const char* file, [[maybe_unused]] int line,
+ const std::string& message) {
+ std::ostringstream stream;
+ stream
+#ifdef NPU_PLUGIN_DEVELOPER_BUILD
+ << file << ":" << line << ": "
+#endif
+ << message;
+ throw std::runtime_error(stream.str());
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/format.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/format.cpp
new file mode 100644
index 00000000000..3385f2ef69d
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/format.cpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/format.hpp"
+
+#include <cstddef>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
+
+std::string intel_npu::vm::formatString(std::string_view format, const std::vector<std::string>& args) {
+ std::ostringstream stream;
+ size_t formatOffset = 0;
+ size_t argIndex = 0;
+
+ while (true) {
+ const auto placeholderPos = format.find("{}", formatOffset);
+ if (placeholderPos == std::string_view::npos) {
+ stream << format.substr(formatOffset);
+ break;
+ }
+
+ stream << format.substr(formatOffset, placeholderPos - formatOffset);
+ if (argIndex < args.size()) {
+ stream << args.at(argIndex++);
+ } else {
+ stream << "{}";
+ }
+ formatOffset = placeholderPos + 2;
+ }
+
+ while (argIndex < args.size()) {
+ stream << ' ' << args.at(argIndex++);
+ }
+
+ return stream.str();
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/instructions.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/instructions.cpp
new file mode 100644
index 00000000000..83fbdcab576
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/instructions.cpp
@@ -0,0 +1,299 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/instructions.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <optional>
+#include <unordered_map>
+
+namespace intel_npu::vm {
+
+namespace {
+
+std::optional<size_t> getInstructionSizeForOperandCount(size_t operandCount) {
+ if (operandCount > (std::numeric_limits<size_t>::max() - OPCODE_SIZE) / OPERAND_SIZE) {
+ return std::nullopt;
+ }
+ return OPCODE_SIZE + operandCount * OPERAND_SIZE;
+}
+
+std::optional<size_t> decodeRankBasedVariadicInstructionSize(const uint8_t* instructionBegin, size_t baseOperands,
+ size_t operandsPerDim, size_t rankOperandIndex) {
+ const auto rank = getOperand(instructionBegin, rankOperandIndex);
+ if (rank < 0) {
+ return std::nullopt;
+ }
+ const auto checkedRank = static_cast<size_t>(rank);
+ if (checkedRank > (std::numeric_limits<size_t>::max() - baseOperands) / operandsPerDim) {
+ return std::nullopt;
+ }
+ return getInstructionSizeForOperandCount(baseOperands + checkedRank * operandsPerDim);
+}
+
+} // namespace
+
+std::optional<size_t> getStaticInstructionSize(OpCode opcode) {
+ static const std::unordered_map<OpCode, size_t> staticInstructionSizes = {
+ {OpCode::ADD_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::RET, OPCODE_SIZE}, // opcode
+ {OpCode::SET, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::SET_IMM,
+ OPCODE_SIZE + OPERAND_SIZE + sizeof(int64_t)}, // opcode + 1 16-bit operand + 1 64-bit operand
+ {OpCode::ASSERT, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::MUL_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MIN_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MAX_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::CMP_I64, OPCODE_SIZE + 4 * OPERAND_SIZE}, // opcode + 3 operands + 1 imm flag
+ {OpCode::CMP_F64, OPCODE_SIZE + 4 * OPERAND_SIZE}, // opcode + 3 operands + 1 imm flag
+ {OpCode::SUB_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::DIV_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::REM_I64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::ABS_I64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::AND_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::NOT_64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::OR_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::XOR_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SLL_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SRL_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SRA_64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SELECT, OPCODE_SIZE + 4 * OPERAND_SIZE}, // opcode + 4 operands
+ {OpCode::BUFFER_GET_DIM, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::CMD_LIST_CREATE, OPCODE_SIZE + OPERAND_SIZE}, // opcode + 1 operand
+ {OpCode::CMD_LIST_CLOSE, OPCODE_SIZE + OPERAND_SIZE}, // opcode + 1 operand
+ {OpCode::CMD_LIST_EXEC, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operand
+ {OpCode::ADD_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SUB_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MUL_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::DIV_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::REM_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MAX_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MIN_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::ABS_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::NEG_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::CEIL_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::FLOOR_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + 2 operands
+ {OpCode::ROUND_F64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 2 operands + 1 imm flag
+ {OpCode::JMP, OPCODE_SIZE + sizeof(int64_t)}, // opcode + imm64(8)
+ {OpCode::JE, OPCODE_SIZE + sizeof(int64_t) + 2 * OPERAND_SIZE}, // opcode + imm64(8) + lhs(2) + rhs(2)
+ {OpCode::JNE, OPCODE_SIZE + sizeof(int64_t) + 2 * OPERAND_SIZE}, // opcode + imm64(8) + lhs(2) + rhs(2)
+ {OpCode::DIV_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MIN_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::ADD_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MAX_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::MUL_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::REM_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::SUB_U64, OPCODE_SIZE + 3 * OPERAND_SIZE}, // opcode + 3 operands
+ {OpCode::CONVERT_I8_TO_F32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I8_TO_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I16_TO_I8, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I16_TO_F32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I16_TO_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I32_TO_I8, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I32_TO_I16, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I32_TO_F32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I32_TO_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I64_TO_I8, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I64_TO_I16, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I64_TO_I32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I64_TO_F32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_I64_TO_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F32_TO_I8, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F32_TO_I16, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F32_TO_I32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F32_TO_I64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F32_TO_F64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F64_TO_I8, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F64_TO_I16, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F64_TO_I32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F64_TO_I64, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::CONVERT_F64_TO_F32, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ {OpCode::BUFFER_COPY, OPCODE_SIZE + 2 * OPERAND_SIZE}, // opcode + dst + src
+ };
+
+ const auto it = staticInstructionSizes.find(opcode);
+ if (it != staticInstructionSizes.end()) {
+ return it->second;
+ }
+ return std::nullopt;
+}
+
+namespace {
+
+std::optional<size_t> getInstructionSizeDecodeByteSize(OpCode opcode) {
+ switch (opcode) {
+ case OpCode::RETV:
+ return OPCODE_SIZE + OPERAND_SIZE;
+ case OpCode::BUFFER_CREATE:
+ case OpCode::BUFFER_FROM_CONST:
+ case OpCode::BUFFER_LOAD:
+ case OpCode::BUFFER_SUBVIEW:
+ case OpCode::BUFFER_STORE: {
+ constexpr auto baseOperands = 3; // dst + src + rank
+ return OPCODE_SIZE + baseOperands * OPERAND_SIZE;
+ }
+ case OpCode::BUFFER_VIEW: {
+ constexpr auto baseOperands = 5; // dst + src + offset + elem type + rank
+ return OPCODE_SIZE + baseOperands * OPERAND_SIZE;
+ }
+ case OpCode::KERNEL_CREATE: {
+ constexpr auto baseOperands = 4; // dst + kidx + kNameIdx + N
+ return OPCODE_SIZE + baseOperands * OPERAND_SIZE;
+ }
+ case OpCode::CMD_LIST_ADD_KERNEL: {
+ constexpr auto baseOperands = 3; // dst + src + N
+ return OPCODE_SIZE + baseOperands * OPERAND_SIZE;
+ }
+ case OpCode::CALL: {
+ constexpr auto baseOperands = 2; // rs + N
+ return OPCODE_SIZE + baseOperands * OPERAND_SIZE;
+ }
+ default:
+ return std::nullopt;
+ }
+}
+
+std::optional<size_t> getVariadicInstructionSize(OpCode opcode, const uint8_t* instructionBegin,
+ size_t availableBytes) {
+ const auto decodeByteSize = getInstructionSizeDecodeByteSize(opcode);
+ if (!decodeByteSize.has_value() || availableBytes < decodeByteSize.value()) {
+ return std::nullopt;
+ }
+
+ switch (opcode) {
+ case OpCode::RETV: {
+ const auto numResults = getOperand(instructionBegin, 0);
+ if (numResults < 0) {
+ return std::nullopt;
+ }
+ return getInstructionSizeForOperandCount(1 + static_cast<size_t>(numResults));
+ }
+ case OpCode::BUFFER_CREATE: {
+ constexpr auto baseOperands = 3; // dst + size + rank
+ constexpr auto operandsPerDim = 2; // size + stride per dimension
+ constexpr auto rankOperandIndex = 2;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::BUFFER_FROM_CONST: {
+ constexpr auto baseOperands = 4; // dst + constant index + element type + rank
+ constexpr auto operandsPerDim = 2; // size + stride per dimension
+ constexpr auto rankOperandIndex = 3;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::BUFFER_LOAD: {
+ constexpr auto baseOperands = 3; // dst + buffer + rank
+ constexpr auto operandsPerDim = 1; // index per dimension
+ constexpr auto rankOperandIndex = 2;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::BUFFER_SUBVIEW: {
+ constexpr auto baseOperands = 3; // dst + src + rank
+ constexpr auto operandsPerDim = 3; // offset + size + stride per dimension
+ constexpr auto rankOperandIndex = 2;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::BUFFER_VIEW: {
+ constexpr auto baseOperands = 5; // dst + src + offset + elem type + rank
+ constexpr auto operandsPerDim = 2; // size + stride per dimension
+ constexpr auto rankOperandIndex = 4;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::BUFFER_STORE: {
+ constexpr auto baseOperands = 3; // dst + src + rank
+ constexpr auto operandsPerDim = 1; // offset per dimension
+ constexpr auto rankOperandIndex = 2;
+ return decodeRankBasedVariadicInstructionSize(instructionBegin, baseOperands, operandsPerDim, rankOperandIndex);
+ }
+ case OpCode::KERNEL_CREATE: {
+ // Binary layout: [opcode:2] [dst:2] [kidx:2] [kNameIdx:2] [N:2] [N×input:2] [M:2] [M×output:2]
+ // The header check at the top of this function guarantees opcode+dst+kidx+kNameIdx+N (10 bytes) are readable.
+ const auto n = getOperand(instructionBegin, 3);
+ if (n < 0) {
+ return std::nullopt;
+ }
+ const auto nChecked = static_cast<size_t>(n);
+ // M is at operand index (4 + N); verify it fits within the available buffer.
+ const auto mByteOffset = OPCODE_SIZE + (4 + nChecked) * OPERAND_SIZE;
+ if (availableBytes < mByteOffset + OPERAND_SIZE) {
+ return std::nullopt;
+ }
+ const auto m = getOperand(instructionBegin, 4 + nChecked);
+ if (m < 0) {
+ return std::nullopt;
+ }
+ const auto mChecked = static_cast<size_t>(m);
+ // Overflow-safe total: (6 + N + M) * sizeof(int16_t)
+ constexpr size_t fixedOperands = 6; // opcode word + dst + kidx + kNameIndex + N + M
+ if (nChecked > std::numeric_limits<size_t>::max() - mChecked ||
+ nChecked + mChecked > std::numeric_limits<size_t>::max() - fixedOperands) {
+ return std::nullopt;
+ }
+ return (fixedOperands + nChecked + mChecked) * sizeof(int16_t);
+ }
+ case OpCode::CMD_LIST_ADD_KERNEL: {
+ // Layout: rs1, rs2, N, rN..., M, rM...
+ const auto numSignalEvents = getOperand(instructionBegin, 2);
+ if (numSignalEvents < 0) {
+ return std::nullopt;
+ }
+
+ const auto checkedNumSignalEvents = static_cast<size_t>(numSignalEvents);
+ if (checkedNumSignalEvents > std::numeric_limits<size_t>::max() - 4) {
+ return std::nullopt;
+ }
+
+ const auto waitEventsCountOperandIndex = static_cast<size_t>(3) + checkedNumSignalEvents;
+ // Verify we can read the numWaitEvents operand
+ const auto mByteOffset = OPCODE_SIZE + waitEventsCountOperandIndex * OPERAND_SIZE;
+ if (availableBytes < mByteOffset + OPERAND_SIZE) {
+ return std::nullopt;
+ }
+ const auto numWaitEvents = getOperand(instructionBegin, waitEventsCountOperandIndex);
+ if (numWaitEvents < 0) {
+ return std::nullopt;
+ }
+
+ const auto checkedNumWaitEvents = static_cast<size_t>(numWaitEvents);
+ if (checkedNumWaitEvents > std::numeric_limits<size_t>::max() - (4 + checkedNumSignalEvents)) {
+ return std::nullopt;
+ }
+
+ const auto totalOperandCount = static_cast<size_t>(4) + checkedNumSignalEvents + checkedNumWaitEvents;
+ return getInstructionSizeForOperandCount(totalOperandCount);
+ }
+ case OpCode::CALL: {
+ // Binary layout: [opcode:2] [rs:2] [N:2] [N*dst:2] [M:2] [M*arg:2]
+ // N is the destination register count and M is the argument register count.
+ // The header check at the top of this function guarantees opcode+rs+N (6 bytes) are readable.
+ const auto n = static_cast<size_t>(static_cast<uint16_t>(getOperand(instructionBegin, 1)));
+ // M is at operand index (2 + N); verify it fits within the available buffer.
+ const auto mByteOffset = OPCODE_SIZE + (2 + n) * OPERAND_SIZE;
+ if (availableBytes < mByteOffset + OPERAND_SIZE) {
+ return std::nullopt;
+ }
+ const auto m = static_cast<size_t>(static_cast<uint16_t>(getOperand(instructionBegin, 2 + n)));
+ // Overflow-safe total: (4 + N + M) * sizeof(int16_t)
+ constexpr size_t fixedOperands = 4; // opcode word + rs + N + M
+ if (n > std::numeric_limits<size_t>::max() - m || n + m > std::numeric_limits<size_t>::max() - fixedOperands) {
+ return std::nullopt;
+ }
+ return (fixedOperands + n + m) * sizeof(int16_t);
+ }
+ default:
+ return std::nullopt;
+ }
+}
+
+} // namespace
+
+std::optional<size_t> getInstructionSize(OpCode opcode, const uint8_t* instructionBegin, size_t availableBytes) {
+ if (const auto staticInstructionSize = getStaticInstructionSize(opcode); staticInstructionSize.has_value()) {
+ return staticInstructionSize;
+ }
+ return getVariadicInstructionSize(opcode, instructionBegin, availableBytes);
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/logger.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/logger.cpp
new file mode 100644
index 00000000000..3740b56f060
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/logger.cpp
@@ -0,0 +1,311 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/format.hpp"
+
+#include <chrono>
+#include <cstdlib>
+#include <ctime>
+#include <iomanip>
+#include <iostream>
+#include <mutex>
+#include <new>
+#include <optional>
+#include <regex>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
+
+using namespace intel_npu::vm;
+
+namespace {
+
+constexpr std::string_view ANSI_RESET = "\x1b[0m";
+constexpr std::string_view ANSI_MAGENTA_BOLD = "\033[1;35m";
+constexpr std::string_view ANSI_RED_BOLD = "\033[1;31m";
+constexpr std::string_view ANSI_YELLOW_BOLD = "\033[1;33m";
+constexpr std::string_view ANSI_BLUE = "\033[0;34m";
+constexpr std::string_view ANSI_GREEN = "\033[0;32m";
+constexpr std::string_view ANSI_CYAN = "\033[0;36m";
+constexpr std::string_view ANSI_WHITE = "\033[0;37m";
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+
+std::optional<std::string_view> isEnvVarSet(std::string_view envVar) {
+ const auto env = std::getenv(envVar.data());
+ if (env != nullptr && *env != '\0') {
+ return std::string_view(env);
+ }
+ return std::nullopt;
+}
+
+struct LogFilterState {
+ std::optional<std::regex> compiledRegex;
+ bool hasFilter{false};
+};
+
+// Cached values for environment variables to avoid performance overhead of getenv() and regex matching in hot code
+// paths. These are mutable globals but are set once. They are not made constant for unit tests, as they need to be able
+// to reset these globals in between tests.
+// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
+static std::once_flag filterStateFlag;
+static std::once_flag areColorsActiveFlag;
+static std::once_flag showFullFilePathFlag;
+static std::once_flag logLevelFlag;
+static std::optional<LogFilterState> cachedFilterState;
+static std::optional<bool> cachedAreColorsActive;
+static std::optional<bool> cachedShowFullFilePath;
+static std::optional<LogLevel> cachedLogLevel;
+// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
+
+const LogFilterState& getLogFilterState() {
+ // Cache once to avoid getenv() and regex compilation overhead in hot logging call sites.
+ // std::call_once ensures thread-safe one-time initialization with minimal overhead on reads.
+ std::call_once(filterStateFlag, []() {
+ std::optional<std::string_view> filter;
+ if (auto logFilterStr = isEnvVarSet("NPU_VM_LOG_FILTER"); logFilterStr.has_value()) {
+ filter = logFilterStr;
+ } else if (auto logFilterStr = isEnvVarSet("IE_NPU_LOG_FILTER"); logFilterStr.has_value()) {
+ filter = logFilterStr;
+ }
+
+ LogFilterState state;
+ if (filter.has_value()) {
+ state.hasFilter = true;
+ try {
+ // std::regex can throw if the provided filter is not a valid regex. In that case, we consider all logs
+ // as filtered out
+ state.compiledRegex.emplace(filter.value().data());
+ } catch (const std::regex_error&) {
+ // Invalid regex disables all filtered logs.
+ state.compiledRegex.reset();
+ }
+ }
+
+ cachedFilterState.emplace(state);
+ });
+ return cachedFilterState.value();
+}
+
+LogLevel parseLogLevelString(std::string_view logLevelStr) {
+ if (logLevelStr == "LOG_TRACE") {
+ return LogLevel::Trace;
+ }
+ if (logLevelStr == "LOG_DEBUG") {
+ return LogLevel::Debug;
+ }
+ if (logLevelStr == "LOG_INFO") {
+ return LogLevel::Info;
+ }
+ if (logLevelStr == "LOG_WARN") {
+ return LogLevel::Warn;
+ }
+ if (logLevelStr == "LOG_ERROR") {
+ return LogLevel::Error;
+ }
+ if (logLevelStr == "LOG_FATAL") {
+ return LogLevel::Fatal;
+ }
+ return LogLevel::None;
+}
+
+#endif // defined(NPU_PLUGIN_DEVELOPER_BUILD)
+
+// Check whether terminal colors are enabled. By default, colors are enabled. For developer builds, the user can disable
+// colors by setting the NPU_VM_LOG_COLORS environment variable to "0"
+bool areColorsActive() {
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ // std::call_once ensures thread-safe one-time initialization with minimal overhead on reads.
+ std::call_once(areColorsActiveFlag, []() {
+ bool value = true;
+ if (const auto logColorsStr = isEnvVarSet("NPU_VM_LOG_COLORS"); logColorsStr.has_value()) {
+ value = logColorsStr.value() != "0";
+ }
+ cachedAreColorsActive.emplace(value);
+ });
+ return cachedAreColorsActive.value();
+#endif
+ return true;
+}
+
+// Check whether the logs should include the full file path or just the file name. By default, only the file name is
+// shown. For developer builds, the user can enable full file paths by setting the NPU_VM_LOG_FULL_PATH environment
+// variable to a value that is not "0"
+bool showFullFilePath() {
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ // std::call_once ensures thread-safe one-time initialization with minimal overhead on reads.
+ std::call_once(showFullFilePathFlag, []() {
+ bool value = false;
+ if (const auto logFullPathStr = isEnvVarSet("NPU_VM_LOG_FULL_PATH"); logFullPathStr.has_value()) {
+ value = logFullPathStr.value() != "0";
+ }
+ cachedShowFullFilePath.emplace(value);
+ });
+ return cachedShowFullFilePath.value();
+#endif
+ return false;
+}
+
+// Extracts the file name from a full file path, or returns the full path based on the showFullFilePath() setting
+std::string filePath(const char* file) {
+ if (file == nullptr) {
+ return {};
+ }
+ std::string filePath(file);
+ if (showFullFilePath()) {
+ return filePath;
+ }
+ const auto separatorPos = filePath.find_last_of("/\\");
+ if (separatorPos == std::string::npos) {
+ return filePath;
+ }
+ return filePath.substr(separatorPos + 1);
+}
+
+std::string getLogSource(const char* file, int line) {
+ return filePath(file) + ":" + std::to_string(line);
+}
+
+const char* levelPrefix(LogLevel level) {
+ switch (level) {
+ case LogLevel::Trace:
+ return "[TRCE]";
+ case LogLevel::Debug:
+ return "[DEBG]";
+ case LogLevel::Info:
+ return "[INFO]";
+ case LogLevel::Warn:
+ return "[WARN]";
+ case LogLevel::Error:
+ return "[ERRO]";
+ case LogLevel::Fatal:
+ return "[FATL]";
+ default:
+ return "[UNKN]";
+ }
+}
+
+std::string_view color(std::string_view colorCode) {
+ if (areColorsActive()) {
+ return colorCode;
+ }
+ return {};
+}
+
+std::string_view colorLevel(LogLevel level) {
+ switch (level) {
+ case LogLevel::Trace:
+ return color(ANSI_CYAN);
+ case LogLevel::Debug:
+ return color(ANSI_GREEN);
+ case LogLevel::Info:
+ return color(ANSI_BLUE);
+ case LogLevel::Warn:
+ return color(ANSI_YELLOW_BOLD);
+ case LogLevel::Error:
+ return color(ANSI_RED_BOLD);
+ case LogLevel::Fatal:
+ return color(ANSI_MAGENTA_BOLD);
+ default:
+ return {};
+ }
+}
+
+// Generate a timestamp string in the format "YYYY-MM-DD HH:MM:SS.mmm"
+std::string makeTimestamp() {
+ const auto localTimeFromTimeT = [](std::time_t secondsSinceEpoch) -> std::tm {
+ std::tm nowTm{};
+#if defined(_WIN32)
+ localtime_s(&nowTm, &secondsSinceEpoch);
+#else
+ localtime_r(&secondsSinceEpoch, &nowTm);
+#endif
+ return nowTm;
+ };
+
+ const auto now = std::chrono::system_clock::now();
+ const auto secondsTimePoint = std::chrono::time_point_cast<std::chrono::seconds>(now);
+ const auto secondsSinceEpoch = std::chrono::system_clock::to_time_t(secondsTimePoint);
+ const auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - secondsTimePoint).count();
+ const auto nowTm = localTimeFromTimeT(secondsSinceEpoch);
+
+ std::ostringstream stream;
+ stream << std::put_time(&nowTm, "%Y-%m-%d %H:%M:%S") << '.' << std::setfill('0') << std::setw(3) << millis;
+ return stream.str();
+}
+
+} // namespace
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+
+void intel_npu::vm::detail::resetLoggingCache() {
+ // Reset cached values and reinitialize once_flags for testing.
+ // Note: std::once_flag cannot be reset, so we destroy and recreate them using placement new.
+ cachedLogLevel.reset();
+ cachedAreColorsActive.reset();
+ cachedShowFullFilePath.reset();
+ cachedFilterState.reset();
+ logLevelFlag.~once_flag();
+ new (&logLevelFlag) std::once_flag();
+ areColorsActiveFlag.~once_flag();
+ new (&areColorsActiveFlag) std::once_flag();
+ showFullFilePathFlag.~once_flag();
+ new (&showFullFilePathFlag) std::once_flag();
+ filterStateFlag.~once_flag();
+ new (&filterStateFlag) std::once_flag();
+}
+
+#endif // defined(NPU_PLUGIN_DEVELOPER_BUILD)
+
+// For developer builds, the effective log level can be set by the user through the NPU_VM_LOG_LEVEL or OV_NPU_LOG_LEVEL
+// environment variables. For non-developer builds, the log level is Info by default
+LogLevel intel_npu::vm::detail::getEffectiveLogLevel() {
+#if !defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ return LogLevel::Info;
+#else
+ // std::call_once ensures thread-safe one-time initialization with minimal overhead on reads.
+ std::call_once(logLevelFlag, []() {
+ LogLevel value = LogLevel::Info;
+ if (auto logLevelStr = isEnvVarSet("NPU_VM_LOG_LEVEL"); logLevelStr.has_value()) {
+ value = parseLogLevelString(logLevelStr.value());
+ } else if (auto logLevelStr = isEnvVarSet("OV_NPU_LOG_LEVEL"); logLevelStr.has_value()) {
+ value = parseLogLevelString(logLevelStr.value());
+ }
+ cachedLogLevel.emplace(value);
+ });
+ return cachedLogLevel.value();
+#endif
+}
+
+// Check whether the log message should be printed based on the log filter. Only developer builds support log filtering,
+// which is done by matching the log source (file name / path and line) against a regex specified in the
+// NPU_VM_LOG_FILTER or IE_NPU_LOG_FILTER environment variables. For non-developer builds, all messages are printed
+bool intel_npu::vm::detail::isLogIncludedInFilter([[maybe_unused]] const char* file, [[maybe_unused]] int line) {
+#if !defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ return true;
+#else
+ const auto& filterState = getLogFilterState();
+ if (!filterState.hasFilter) {
+ return true;
+ }
+ if (!filterState.compiledRegex.has_value()) {
+ return false;
+ }
+ const auto logSource = getLogSource(file, line);
+ return std::regex_search(logSource.begin(), logSource.end(), *filterState.compiledRegex);
+#endif
+}
+
+// Print the log message to the appropriate stream with the specified formatting and colors based on the log level
+void intel_npu::vm::detail::dispatchLogMessage(LogLevel level, const char* file, int line, std::string_view format,
+ const std::vector<std::string>& args) {
+ static std::mutex logMutex;
+ std::lock_guard<std::mutex> lock(logMutex);
+ std::ostringstream stream;
+ stream << color(ANSI_WHITE) << "[" << makeTimestamp() << "] " << colorLevel(level) << levelPrefix(level) << ' '
+ << getLogSource(file, line) << color(ANSI_RESET) << ' ' << formatString(format, args) << '\n';
+ std::cerr << stream.str();
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/magic_number.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/magic_number.cpp
new file mode 100644
index 00000000000..5e0a411a6dc
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/magic_number.cpp
@@ -0,0 +1,47 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/span.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <vector>
+
+const std::array<uint8_t, intel_npu::vm::MAGIC_NUMBER_SIZE>& intel_npu::vm::MagicNumber::value() const {
+ return _value;
+}
+
+size_t intel_npu::vm::MagicNumber::getBinarySize() {
+ return MAGIC_NUMBER_SIZE * sizeof(uint8_t);
+}
+
+void intel_npu::vm::MagicNumber::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, _value);
+}
+
+bool intel_npu::vm::MagicNumber::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, _value)) {
+ NPU_VM_LOG_ERROR("Failed to parse magic number from buffer");
+ return false;
+ }
+ if (!std::equal(MAGIC_NUMBER.begin(), MAGIC_NUMBER.end(), _value.begin(), _value.end())) {
+ NPU_VM_LOG_ERROR("Magic number does not match expected value");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::MagicNumber::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ for (const auto& byte : _value) {
+ std::cout << intel_npu::vm::toHex(byte) << " ";
+ }
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/network_description.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/network_description.cpp
new file mode 100644
index 00000000000..3d5472dad17
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/network_description.cpp
@@ -0,0 +1,502 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/network_description.hpp"
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/except.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <iterator>
+#include <limits>
+#include <optional>
+#include <vector>
+
+#include <openvino/core/dimension.hpp>
+#include <openvino/core/partial_shape.hpp>
+#include <openvino/core/type/element_type.hpp>
+
+namespace intel_npu::vm {
+void NetworkMetadata::bindRelatedDescriptors() {
+ size_t ioIndex = 0;
+
+ for (IODescriptor& input : inputs) {
+ if (input.relatedDescriptorIndex.has_value()) {
+ ++ioIndex;
+ continue;
+ }
+
+ if (input.isStateInput) {
+ const auto relatedDescriptorIterator =
+ std::find_if(outputs.begin(), outputs.end(), [&](const IODescriptor& output) {
+ return output.isStateOutput && (output.nameFromCompiler == input.nameFromCompiler);
+ });
+
+ if (relatedDescriptorIterator != outputs.end()) {
+ input.relatedDescriptorIndex = std::distance(outputs.begin(), relatedDescriptorIterator);
+ outputs.at(*input.relatedDescriptorIndex).relatedDescriptorIndex = ioIndex;
+ }
+ } else if (input.isShapeTensor) {
+ const auto relatedDescriptorIterator =
+ std::find_if(inputs.begin(), inputs.end(), [&](const IODescriptor& candidate) {
+ return !candidate.isShapeTensor && (candidate.nameFromCompiler == input.nameFromCompiler);
+ });
+
+ if (relatedDescriptorIterator != inputs.end()) {
+ input.relatedDescriptorIndex = std::distance(inputs.begin(), relatedDescriptorIterator);
+ inputs.at(*input.relatedDescriptorIndex).relatedDescriptorIndex = ioIndex;
+ }
+ }
+
+ ++ioIndex;
+ }
+
+ ioIndex = 0;
+
+ for (IODescriptor& output : outputs) {
+ if (output.relatedDescriptorIndex.has_value()) {
+ ++ioIndex;
+ continue;
+ }
+
+ if (output.isShapeTensor) {
+ const auto relatedDescriptorIterator =
+ std::find_if(outputs.begin(), outputs.end(), [&](const IODescriptor& candidate) {
+ return !candidate.isShapeTensor && (candidate.nameFromCompiler == output.nameFromCompiler);
+ });
+
+ if (relatedDescriptorIterator != outputs.end()) {
+ output.relatedDescriptorIndex = std::distance(outputs.begin(), relatedDescriptorIterator);
+ outputs.at(*output.relatedDescriptorIndex).relatedDescriptorIndex = ioIndex;
+ }
+ }
+
+ ++ioIndex;
+ }
+}
+
+namespace {
+ov::element::Type parsePrecision(const BytecodeReader& reader, size_t typeIndex) {
+ constexpr uint8_t int4Bitwidth = 4;
+ constexpr uint8_t int8Bitwidth = 8;
+ constexpr uint8_t int16Bitwidth = 16;
+ constexpr uint8_t int32Bitwidth = 32;
+ constexpr uint8_t int64Bitwidth = 64;
+ constexpr uint8_t fp16Bitwidth = 16;
+ constexpr uint8_t fp32Bitwidth = 32;
+ constexpr uint8_t fp64Bitwidth = 64;
+
+ auto typeEntry = reader.getDataSectionEntry(SectionType::TypeSection, typeIndex);
+ NPU_VM_THROW_WHEN(typeEntry.empty(), "Type entry at index {} is not found", typeIndex);
+
+ TypeCode typeCode = TypeCode::OPAQUE;
+ NPU_VM_THROW_UNLESS(parseValueFrom(typeEntry, typeCode), "Failed to parse type code for type index {}", typeIndex);
+
+ switch (typeCode) {
+ case TypeCode::FLOAT: {
+ FloatType floatType{};
+ NPU_VM_THROW_UNLESS(floatType.parseFrom(typeEntry), "Failed to parse float type for type index {}", typeIndex);
+
+ if (floatType.bitWidth == 4 && floatType.format == FloatTypeFormat::NF4) {
+ return ov::element::nf4;
+ }
+
+ // Map float types using both bitwidth and format
+ if (floatType.bitWidth == fp16Bitwidth) {
+ switch (floatType.format) {
+ case FloatTypeFormat::IEEE754:
+ return ov::element::f16;
+ case FloatTypeFormat::BFloat:
+ return ov::element::bf16;
+ case FloatTypeFormat::TFloat:
+ case FloatTypeFormat::E4M3:
+ case FloatTypeFormat::E5M2:
+ case FloatTypeFormat::E2M1:
+ case FloatTypeFormat::E8M0:
+ case FloatTypeFormat::NF4:
+ // Extended formats not yet supported in OV element types; preserve exact format awareness
+ // by returning dynamic for now. This prevents silent misinterpretation.
+ NPU_VM_LOG_WARN("Type index {}: extended float format {} not yet supported in OV element types, "
+ "falling back to dynamic",
+ typeIndex, static_cast<int>(floatType.format));
+ return ov::element::dynamic;
+ }
+ }
+ if (floatType.bitWidth == fp32Bitwidth) {
+ return ov::element::f32;
+ }
+ if (floatType.bitWidth == fp64Bitwidth) {
+ return ov::element::f64;
+ }
+ NPU_VM_LOG_WARN("Type index {}: unsupported float bitwidth {}, falling back to dynamic", typeIndex,
+ floatType.bitWidth);
+ return ov::element::dynamic;
+ }
+ case TypeCode::INTEGER: {
+ IntegerType intType{};
+ NPU_VM_THROW_UNLESS(intType.parseFrom(typeEntry), "Failed to parse integer type for type index {}", typeIndex);
+
+ // Map common integer bit-widths. NOTE: signedness (signed vs unsigned) is NOT preserved in bytecode
+ // metadata; only bitWidth is stored during serialization. We use conservative signed mappings
+ // (i8, i16, i32, i64). If the actual signedness is critical, it must be inferred from context
+ // (e.g., operations using the value) or preserved separately.
+ switch (intType.bitWidth) {
+ case int4Bitwidth:
+ return (intType.isSigned) ? ov::element::i4 : ov::element::u4;
+ case int8Bitwidth:
+ return (intType.isSigned) ? ov::element::i8 : ov::element::u8;
+ case int16Bitwidth:
+ return (intType.isSigned) ? ov::element::i16 : ov::element::u16;
+ case int32Bitwidth:
+ return (intType.isSigned) ? ov::element::i32 : ov::element::u32;
+ case int64Bitwidth:
+ return (intType.isSigned) ? ov::element::i64 : ov::element::u64;
+ default:
+ NPU_VM_LOG_WARN("Type index {}: unsupported integer bitwidth {}, signed {}, falling back to dynamic",
+ typeIndex, intType.bitWidth, intType.isSigned);
+ return ov::element::dynamic;
+ }
+ }
+ case TypeCode::OPAQUE:
+ case TypeCode::BUFFER:
+ case TypeCode::FUNCTION:
+ // OPAQUE, BUFFER, and FUNCTION types lack well-defined OV element mappings.
+ NPU_VM_LOG_WARN("Type index {}: type code {} lacks well-defined OV element mapping, falling back to dynamic",
+ typeIndex, static_cast<int>(typeCode));
+ return ov::element::dynamic;
+ }
+
+ return ov::element::dynamic;
+}
+
+ov::PartialShape parseShape(const BytecodeReader& reader, size_t shapeIndex) {
+ auto shapeEntry = reader.getDataSectionEntry(SectionType::ConstantSection, shapeIndex);
+ NPU_VM_THROW_WHEN(shapeEntry.empty(), "Shape entry at index {} is not found", shapeIndex);
+
+ NPU_VM_THROW_UNLESS(shapeEntry.size() % sizeof(int64_t) == 0,
+ "Shape entry at index {} has invalid size {}, expected multiple of {}", shapeIndex,
+ shapeEntry.size(), sizeof(int64_t));
+
+ const auto numDims = shapeEntry.size() / sizeof(int64_t);
+ ov::PartialShape shape;
+ shape.reserve(numDims);
+
+ auto isDynamicDim = [](int64_t value) {
+ constexpr std::array<int64_t, 2> dynamicDimMarkers = {
+ std::numeric_limits<int64_t>::min(), // Legacy marker
+ -1 // MLIR sentinel (mlir::ShapedType::kDynamic)
+ };
+ return std::find(dynamicDimMarkers.begin(), dynamicDimMarkers.end(), value) != dynamicDimMarkers.end();
+ };
+
+ for (size_t i = 0; i < numDims; ++i) {
+ int64_t dimValue = 0;
+ NPU_VM_THROW_UNLESS(parseValueFrom(shapeEntry, dimValue),
+ "Failed to parse shape dimension {} for shape entry {}", i, shapeIndex);
+ if (isDynamicDim(dimValue)) {
+ shape.push_back(ov::Dimension::dynamic());
+ } else {
+ shape.push_back(ov::Dimension(dimValue));
+ }
+ }
+
+ return shape;
+}
+
+IODescriptor parseDescriptor(const BytecodeReader& reader, Span<uint8_t>& entry) {
+ uint64_t nameIndex = 0;
+ uint64_t typeIndex = 0;
+ uint64_t shapeIndex = 0;
+ uint32_t indexUsedByDriver = 0;
+ uint8_t hasDynamicStrides = 0;
+ uint8_t tensorNameCount = 0;
+ uint8_t hasShapeFromIRModel = 0;
+ uint64_t shapeFromIRModelIndex = 0;
+ uint8_t hasNodeFriendlyName = 0;
+ uint64_t nodeFriendlyNameIndex = 0;
+
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, nameIndex), "Failed to parse descriptor name index");
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, typeIndex), "Failed to parse descriptor type index");
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, shapeIndex), "Failed to parse descriptor shape index");
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, indexUsedByDriver), "Failed to parse descriptor index used by driver");
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, hasDynamicStrides), "Failed to parse descriptor dynamic strides flag");
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, tensorNameCount), "Failed to parse descriptor tensor name count");
+ auto name = reader.getString(nameIndex);
+ NPU_VM_THROW_UNLESS(name.has_value(), "String entry for descriptor name at index {} is not found", nameIndex);
+
+ IODescriptor descriptor;
+ descriptor.nameFromCompiler = name.value();
+ descriptor.precision = parsePrecision(reader, typeIndex);
+ descriptor.shapeFromCompiler = parseShape(reader, shapeIndex);
+ descriptor.indexUsedByDriver = indexUsedByDriver;
+ descriptor.supportsStridedLayout = hasDynamicStrides != 0;
+
+ for (uint8_t i = 0; i < tensorNameCount; ++i) {
+ uint64_t tensorNameIndex = 0;
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, tensorNameIndex),
+ "Failed to parse tensor name index {} for descriptor", i);
+ auto tensorName = reader.getString(tensorNameIndex);
+ NPU_VM_THROW_UNLESS(tensorName.has_value(), "String entry for tensor name at index {} is not found",
+ tensorNameIndex);
+ descriptor.outputTensorNames.insert(tensorName.value());
+ }
+
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, hasShapeFromIRModel), "Failed to parse hasShapeFromIRModel");
+ if (hasShapeFromIRModel != 0) {
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, shapeFromIRModelIndex), "Failed to parse shape from IR model index");
+ descriptor.shapeFromIRModel = parseShape(reader, shapeFromIRModelIndex);
+ }
+
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, hasNodeFriendlyName), "Failed to parse hasNodeFriendlyName");
+ if (hasNodeFriendlyName != 0) {
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, nodeFriendlyNameIndex),
+ "Failed to parse descriptor friendly name index");
+ auto nodeFriendlyName = reader.getString(nodeFriendlyNameIndex);
+ NPU_VM_THROW_UNLESS(nodeFriendlyName.has_value(), "String entry for descriptor name at index {} is not found",
+ nodeFriendlyNameIndex);
+ descriptor.nodeFriendlyName = nodeFriendlyName.value();
+ }
+
+ if (!entry.empty()) {
+ uint64_t layoutIndex = 0;
+ NPU_VM_THROW_UNLESS(parseValueFrom(entry, layoutIndex), "Failed to parse descriptor layout index");
+ auto layout = reader.getString(layoutIndex);
+ NPU_VM_THROW_UNLESS(layout.has_value(), "String entry for descriptor layout at index {} is not found",
+ layoutIndex);
+ descriptor.layout = layout.value();
+ }
+
+ return descriptor;
+}
+
+const details::DataSectionInfo* getMetadataSectionInfo(BytecodeReader& reader) {
+ const auto& headers = reader.getSectionHeaderTable().getSectionHeaders();
+ for (const auto& header : headers) {
+ if (header.type == SectionType::MetadataSection) {
+ return dynamic_cast<const details::DataSectionInfo*>(header.info.get());
+ }
+ }
+ return nullptr;
+}
+
+void dumpDescriptors([[maybe_unused]] const char* kind, const std::vector<IODescriptor>& descriptors) {
+ NPU_VM_LOG_TRACE("{} count: {}", kind, descriptors.size());
+ [[maybe_unused]] size_t index = 0;
+ for ([[maybe_unused]] const auto& descriptor : descriptors) {
+ NPU_VM_LOG_TRACE("{}[{}] name='{}', precision={}, shape={}, layout='{}', driver_index={}, "
+ "dynamic_strides={}, state_in={}, state_out={}, shape_tensor={}",
+ kind, index, descriptor.nameFromCompiler, descriptor.precision.get_type_name(),
+ descriptor.shapeFromCompiler.to_string(), descriptor.layout, descriptor.indexUsedByDriver,
+ descriptor.supportsStridedLayout ? "true" : "false",
+ descriptor.isStateInput ? "true" : "false", descriptor.isStateOutput ? "true" : "false",
+ descriptor.isShapeTensor ? "true" : "false");
+ ++index;
+ }
+}
+
+void dumpNetworkMetadata(const NetworkMetadata& network) {
+ NPU_VM_LOG_TRACE("deserialized metadata: name='{}', numStreams={}, numCmdLists={}", network.name,
+ network.numStreams, network.numCmdLists);
+ dumpDescriptors("input", network.inputs);
+ dumpDescriptors("output", network.outputs);
+ dumpDescriptors("profiling_output", network.profilingOutputs);
+}
+
+} // namespace
+
+std::optional<NetworkMetadata> parseNetworkMetadata(const uint8_t* bytecodePtr, size_t bytecodeSize) {
+ if (bytecodePtr == nullptr || bytecodeSize == 0) {
+ return std::nullopt;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - function receives pointer to const
+ Span<uint8_t> bytecodeView(const_cast<uint8_t*>(bytecodePtr), bytecodeSize);
+ BytecodeReader reader(bytecodeView);
+ if (!reader.parseFile()) {
+ return std::nullopt;
+ }
+ return parseNetworkMetadata(reader);
+}
+
+std::optional<NetworkMetadata> parseNetworkMetadata(BytecodeReader& reader) {
+ NetworkMetadata network{};
+
+ const auto* metadataInfo = getMetadataSectionInfo(reader);
+ if (metadataInfo == nullptr) {
+ NPU_VM_LOG_DEBUG("Bytecode blob does not contain metadata section");
+ return std::nullopt;
+ }
+
+ for (size_t i = 0; i < metadataInfo->dataInfos.size(); ++i) {
+ auto entry = reader.getDataSectionEntry(SectionType::MetadataSection, i);
+ if (entry.empty()) {
+ NPU_VM_LOG_WARN("Metadata entry at index {} is empty", i);
+ return std::nullopt;
+ }
+
+ MetadataRecordKind recordKind = MetadataRecordKind::Network;
+ if (!parseValueFrom(entry, recordKind)) {
+ NPU_VM_LOG_WARN("Failed to parse metadata record kind for entry {}", i);
+ return std::nullopt;
+ }
+
+ switch (recordKind) {
+ case MetadataRecordKind::Network: {
+ uint64_t nameIndex = 0;
+ uint64_t numStreams = 0;
+ uint64_t numCmdLists = 0;
+ if (!parseValueFrom(entry, nameIndex)) {
+ NPU_VM_LOG_WARN("Failed to parse network metadata name field for entry {}", i);
+ return std::nullopt;
+ }
+ if (!parseValueFrom(entry, numStreams)) {
+ NPU_VM_LOG_WARN("Failed to parse network metadata numStreams field for entry {}", i);
+ return std::nullopt;
+ }
+ if (!parseValueFrom(entry, numCmdLists)) {
+ NPU_VM_LOG_WARN("Failed to parse network metadata numCmdLists field for entry {}", i);
+ return std::nullopt;
+ }
+
+ auto name = reader.getString(nameIndex);
+ if (!name.has_value()) {
+ NPU_VM_LOG_WARN("String entry for network name at index {} is not found", nameIndex);
+ return std::nullopt;
+ }
+ network.name = name.value();
+ network.numStreams = static_cast<size_t>(numStreams);
+ network.numCmdLists = static_cast<size_t>(numCmdLists);
+ break;
+ }
+ case MetadataRecordKind::Input:
+ network.inputs.push_back(parseDescriptor(reader, entry));
+ break;
+ case MetadataRecordKind::Output:
+ network.outputs.push_back(parseDescriptor(reader, entry));
+ break;
+ case MetadataRecordKind::ProfilingOutput:
+ network.profilingOutputs.push_back(parseDescriptor(reader, entry));
+ break;
+ default:
+ NPU_VM_LOG_WARN("Unknown metadata record kind {} for entry {}", static_cast<uint8_t>(recordKind), i);
+ return std::nullopt;
+ }
+
+ if (!entry.empty()) {
+ NPU_VM_LOG_WARN("Trailing bytes are present in metadata entry {} after parsing expected fields", i);
+ return std::nullopt;
+ }
+ }
+
+ network.bindRelatedDescriptors();
+ dumpNetworkMetadata(network);
+ return network;
+}
+
+void printMetadataEntry(Span<uint8_t> metadata) {
+ if (metadata.empty()) {
+ std::cout << "(empty)";
+ return;
+ }
+
+ MetadataRecordKind kind{};
+ if (!parseValueFrom(metadata, kind)) {
+ NPU_VM_LOG_ERROR("Failed to parse metadata record kind");
+ return;
+ }
+
+ switch (kind) {
+ case MetadataRecordKind::Network: {
+ uint64_t nameIndex = 0;
+ uint64_t numStreams = 0;
+ uint64_t numCmdlists = 0;
+ if (!parseValueFrom(metadata, nameIndex) || !parseValueFrom(metadata, numStreams) ||
+ !parseValueFrom(metadata, numCmdlists)) {
+ NPU_VM_LOG_ERROR("Failed to parse network_metadata fields");
+ return;
+ }
+ std::cout << "networkMetadata<nameIndex=" << nameIndex << ", numStreams=" << numStreams
+ << ", numCmdlists=" << numCmdlists << ">";
+ break;
+ }
+ case MetadataRecordKind::Input:
+ case MetadataRecordKind::Output:
+ case MetadataRecordKind::ProfilingOutput: {
+ uint64_t nameIndex = 0;
+ uint64_t typeIndex = 0;
+ uint64_t shapeIndex = 0;
+ uint32_t indexUsedByDriver = 0;
+ uint8_t hasDynamicStrides = 0;
+ uint8_t tensorNameCount = 0;
+ if (!parseValueFrom(metadata, nameIndex) || !parseValueFrom(metadata, typeIndex) ||
+ !parseValueFrom(metadata, shapeIndex) || !parseValueFrom(metadata, indexUsedByDriver) ||
+ !parseValueFrom(metadata, hasDynamicStrides) || !parseValueFrom(metadata, tensorNameCount)) {
+ NPU_VM_LOG_ERROR("Failed to parse metadata descriptor fields");
+ return;
+ }
+
+ const char* kindStr = (kind == MetadataRecordKind::Input) ? "inputMetadata"
+ : (kind == MetadataRecordKind::Output) ? "outputMetadata"
+ : "profilingOutputMetadata";
+ std::cout << kindStr << "<nameIndex=" << nameIndex << ", typeIndex=" << typeIndex
+ << ", shapeIndex=" << shapeIndex << ", driverIdx=" << indexUsedByDriver
+ << ", dynamicStrides=" << (hasDynamicStrides ? "true" : "false")
+ << ", tensorNameCount=" << static_cast<uint32_t>(tensorNameCount);
+
+ for (uint8_t i = 0; i < tensorNameCount; ++i) {
+ uint64_t tensorNameIndex = 0;
+ if (!parseValueFrom(metadata, tensorNameIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse tensor name index at position {}", static_cast<uint32_t>(i));
+ return;
+ }
+ std::cout << ", tensorName[" << static_cast<uint32_t>(i) << "]=" << tensorNameIndex;
+ }
+
+ uint8_t hasShapeFromIRModel = 0;
+ if (!parseValueFrom(metadata, hasShapeFromIRModel)) {
+ NPU_VM_LOG_ERROR("Failed to parse hasShapeFromIRModel field");
+ return;
+ }
+ std::cout << ", hasShapeFromIRModel=" << (hasShapeFromIRModel ? "true" : "false");
+ if (hasShapeFromIRModel) {
+ uint64_t shapeFromIRModelIndex = 0;
+ if (!parseValueFrom(metadata, shapeFromIRModelIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse shapeFromIRModelIndex field");
+ return;
+ }
+ std::cout << ", shapeFromIRModelIndex=" << shapeFromIRModelIndex;
+ }
+
+ uint8_t hasNodeFriendlyName = 0;
+ if (!parseValueFrom(metadata, hasNodeFriendlyName)) {
+ NPU_VM_LOG_ERROR("Failed to parse hasNodeFriendlyName field");
+ return;
+ }
+ std::cout << ", hasNodeFriendlyName=" << (hasNodeFriendlyName ? "true" : "false");
+ if (hasNodeFriendlyName) {
+ uint64_t nodeFriendlyNameIndex = 0;
+ if (!parseValueFrom(metadata, nodeFriendlyNameIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse nodeFriendlyNameIndex field");
+ return;
+ }
+ std::cout << ", nodeFriendlyNameIndex=" << nodeFriendlyNameIndex;
+ }
+
+ std::cout << ">";
+ break;
+ }
+ default:
+ NPU_VM_LOG_ERROR("Unknown metadata kind: {}", static_cast<uint8_t>(kind));
+ break;
+ }
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/print_utils.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/print_utils.cpp
new file mode 100644
index 00000000000..8d57149e8eb
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/print_utils.cpp
@@ -0,0 +1,32 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/print_utils.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <iomanip>
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+std::string intel_npu::vm::toHex(uint8_t byte) {
+ std::stringstream ss;
+ ss << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast<int>(byte);
+ return ss.str();
+};
+
+std::string intel_npu::vm::formatPtrVectorContent(const std::vector<int64_t*>& values) {
+ std::ostringstream stream;
+ stream << "[";
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (i != 0) {
+ stream << ", ";
+ }
+ stream << *values.at(i);
+ }
+ stream << "]";
+ return stream.str();
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/section_header_table.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/section_header_table.cpp
new file mode 100644
index 00000000000..ec3b1191d7e
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/section_header_table.cpp
@@ -0,0 +1,297 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/version.hpp"
+
+#include <cstdint>
+#include <cstring>
+#include <iostream>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+size_t intel_npu::vm::details::FunctionSectionInfo::getBinarySize() const {
+ const auto functionInfoSize = sizeof(FunctionInfo::nameIndex) + sizeof(FunctionInfo::functionTypeIndex) +
+ sizeof(FunctionInfo::numGeneralRegisters) + sizeof(FunctionInfo::bodyOffset) +
+ sizeof(FunctionInfo::bodySize);
+ return sizeof(numFunctions) + sizeof(entrypointFunctionIndex) + functionInfos.size() * functionInfoSize;
+}
+
+void intel_npu::vm::details::FunctionSectionInfo::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, numFunctions);
+ appendValueTo(buffer, entrypointFunctionIndex);
+ for (const auto& functionInfo : functionInfos) {
+ appendValueTo(buffer, functionInfo.nameIndex);
+ appendValueTo(buffer, functionInfo.functionTypeIndex);
+ appendValueTo(buffer, functionInfo.numGeneralRegisters);
+ appendValueTo(buffer, functionInfo.bodyOffset);
+ appendValueTo(buffer, functionInfo.bodySize);
+ }
+}
+
+bool intel_npu::vm::details::FunctionSectionInfo::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, numFunctions)) {
+ NPU_VM_LOG_ERROR("Failed to parse numFunctions from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, entrypointFunctionIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse entrypointFunctionIndex from buffer");
+ return false;
+ }
+ for (uint64_t i = 0; i < numFunctions; ++i) {
+ FunctionSectionInfo::FunctionInfo functionInfo{};
+ if (!parseValueFrom(buffer, functionInfo.nameIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse nameIndex from buffer, for function {}", i);
+ return false;
+ }
+ if (!parseValueFrom(buffer, functionInfo.functionTypeIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse functionTypeIndex from buffer, for function {}", i);
+ return false;
+ }
+ if (!parseValueFrom(buffer, functionInfo.numGeneralRegisters)) {
+ NPU_VM_LOG_ERROR("Failed to parse numGeneralRegisters from buffer, for function {}", i);
+ return false;
+ }
+ if (!parseValueFrom(buffer, functionInfo.bodyOffset)) {
+ NPU_VM_LOG_ERROR("Failed to parse bodyOffset from buffer, for function {}", i);
+ return false;
+ }
+ if (!parseValueFrom(buffer, functionInfo.bodySize)) {
+ NPU_VM_LOG_ERROR("Failed to parse bodySize from buffer {} {}, for function {}",
+ static_cast<const void*>(buffer.begin()), buffer.size(), i);
+ return false;
+ }
+ functionInfos.push_back(functionInfo);
+ }
+ return true;
+}
+
+void intel_npu::vm::details::FunctionSectionInfo::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Number of functions: " << numFunctions << ", entrypoint function index: " << entrypointFunctionIndex
+ << std::endl;
+ for (const auto& functionInfo : functionInfos) {
+ intel_npu::vm::printIndent(indentLevel + 1);
+ // TODO: Replace name index and type index with actual entries from string / type sections
+ std::cout << "Name index: " << functionInfo.nameIndex
+ << ", function type index: " << functionInfo.functionTypeIndex
+ << ", num general registers: " << functionInfo.numGeneralRegisters
+ << ", body offset: " << functionInfo.bodyOffset << ", body size: " << functionInfo.bodySize
+ << std::endl;
+ }
+}
+
+size_t intel_npu::vm::details::DataSectionInfo::getBinarySize() const {
+ const auto dataInfoSize = sizeof(DataInfo::offset) + sizeof(DataInfo::size);
+ return sizeof(numData) + dataInfos.size() * dataInfoSize;
+}
+
+void intel_npu::vm::details::DataSectionInfo::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, numData);
+ for (const auto& dataInfo : dataInfos) {
+ appendValueTo(buffer, dataInfo.offset);
+ appendValueTo(buffer, dataInfo.size);
+ }
+}
+
+bool intel_npu::vm::details::DataSectionInfo::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, numData)) {
+ NPU_VM_LOG_ERROR("Failed to parse numData from buffer");
+ return false;
+ }
+ for (uint64_t i = 0; i < numData; ++i) {
+ DataSectionInfo::DataInfo dataInfo{};
+ if (!parseValueFrom(buffer, dataInfo.offset)) {
+ NPU_VM_LOG_ERROR("Failed to parse offset from buffer, for data {}", i);
+ return false;
+ }
+ if (!parseValueFrom(buffer, dataInfo.size)) {
+ NPU_VM_LOG_ERROR("Failed to parse size from buffer, for data {}", i);
+ return false;
+ }
+ dataInfos.push_back(dataInfo);
+ }
+ return true;
+}
+
+void intel_npu::vm::details::DataSectionInfo::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Number of entries: " << numData << std::endl;
+ for (uint64_t i = 0; i < dataInfos.size(); ++i) {
+ const auto& dataInfo = dataInfos.at(i);
+ intel_npu::vm::printIndent(indentLevel + 1);
+ std::cout << "Entry " << i << " offset: " << dataInfo.offset << ", size: " << dataInfo.size << std::endl;
+ }
+}
+
+std::string intel_npu::vm::getSectionTypeString(intel_npu::vm::SectionType type) {
+ switch (type) {
+ case SectionType::FuncSection:
+ return "Function";
+ case SectionType::ConstantSection:
+ return "Constant";
+ case SectionType::StringSection:
+ return "String";
+ case SectionType::KernelSection:
+ return "Kernel";
+ case SectionType::TypeSection:
+ return "Type";
+ case SectionType::MetadataSection:
+ return "Metadata";
+ default:
+ return "Unknown";
+ }
+}
+
+size_t intel_npu::vm::SectionHeader::getBinarySize() const {
+ return sizeof(type) + sizeof(nameIndex) + sizeof(offset) + sizeof(size) + info->getBinarySize();
+}
+
+void intel_npu::vm::SectionHeader::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(type));
+ appendValueTo(buffer, nameIndex);
+ appendValueTo(buffer, offset);
+ appendValueTo(buffer, size);
+ info->appendTo(buffer);
+}
+
+bool intel_npu::vm::SectionHeader::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, type)) {
+ NPU_VM_LOG_ERROR("Failed to parse type from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, nameIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse nameIndex from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, offset)) {
+ NPU_VM_LOG_ERROR("Failed to parse offset from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, size)) {
+ NPU_VM_LOG_ERROR("Failed to parse size from buffer");
+ return false;
+ }
+ if (type == SectionType::FuncSection) {
+ auto functionSectionInfo = details::FunctionSectionInfo{};
+ if (!functionSectionInfo.parseFrom(buffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse function section info from buffer");
+ return false;
+ }
+ info = std::make_unique<details::FunctionSectionInfo>(functionSectionInfo);
+ } else if (type == SectionType::ConstantSection || type == SectionType::KernelSection ||
+ type == SectionType::StringSection || type == SectionType::TypeSection ||
+ type == SectionType::MetadataSection) {
+ auto dataSectionInfo = details::DataSectionInfo{};
+ if (!dataSectionInfo.parseFrom(buffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse data section info from buffer");
+ return false;
+ }
+ info = std::make_unique<details::DataSectionInfo>(dataSectionInfo);
+ } else {
+ NPU_VM_LOG_ERROR("Unknown section type {}", static_cast<uint8_t>(type));
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::SectionHeader::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Section type: " << getSectionTypeString(type) << ", name index: " << nameIndex
+ << ", offset: " << offset << ", size: " << size << std::endl;
+ info->print(indentLevel + 1);
+}
+
+const std::vector<intel_npu::vm::SectionHeader>& intel_npu::vm::SectionHeaderTable::getSectionHeaders() const {
+ return _sectionHeaders;
+}
+
+std::vector<intel_npu::vm::SectionHeader>& intel_npu::vm::SectionHeaderTable::getSectionHeaders() {
+ return _sectionHeaders;
+}
+
+void intel_npu::vm::SectionHeaderTable::addSectionHeader(SectionHeader header) {
+ _sectionHeaders.push_back(std::move(header));
+ ++_numSections;
+}
+
+size_t intel_npu::vm::SectionHeaderTable::getBinarySize() const {
+ size_t size = sizeof(_numSections);
+ for (const auto& header : _sectionHeaders) {
+ size += header.getBinarySize();
+ }
+ return size;
+}
+
+void intel_npu::vm::SectionHeaderTable::computeOffsets() {
+ // Section payloads start immediately after the file header, which consists of magic number, version, and
+ // the section header table itself
+ uint64_t currentOffset = MagicNumber::getBinarySize() + Version::getBinarySize() + getBinarySize();
+ // Assign offsets in a deterministic order so that the file layout is predictable: functions first, then constants,
+ // strings, and finally types
+ const auto updateOffsets = [&](SectionType sectionType) {
+ for (auto& header : _sectionHeaders) {
+ if (header.type == sectionType) {
+ header.offset = currentOffset;
+ currentOffset += header.size;
+ }
+ }
+ };
+ updateOffsets(SectionType::FuncSection);
+ updateOffsets(SectionType::ConstantSection);
+ updateOffsets(SectionType::KernelSection);
+ updateOffsets(SectionType::StringSection);
+ updateOffsets(SectionType::TypeSection);
+ updateOffsets(SectionType::MetadataSection);
+}
+
+void intel_npu::vm::SectionHeaderTable::appendTo(std::vector<uint8_t>& buffer) const {
+ // Serialize headers grouped by section type to match the offset assignment order used in computeOffsets()
+ const auto appendSection = [&](SectionType sectionType) {
+ for (const auto& header : _sectionHeaders) {
+ if (header.type == sectionType) {
+ header.appendTo(buffer);
+ }
+ }
+ };
+ appendValueTo(buffer, _numSections);
+ appendSection(SectionType::FuncSection);
+ appendSection(SectionType::ConstantSection);
+ appendSection(SectionType::KernelSection);
+ appendSection(SectionType::StringSection);
+ appendSection(SectionType::TypeSection);
+ appendSection(SectionType::MetadataSection);
+}
+
+bool intel_npu::vm::SectionHeaderTable::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ uint64_t fileNumSections = 0;
+ if (!parseValueFrom(buffer, fileNumSections)) {
+ NPU_VM_LOG_ERROR("Failed to parse numSections from buffer");
+ return false;
+ }
+ for (uint64_t i = 0; i < fileNumSections; ++i) {
+ SectionHeader header{};
+ if (!header.parseFrom(buffer)) {
+ NPU_VM_LOG_ERROR("Failed to parse section header {} from buffer", i);
+ return false;
+ }
+ addSectionHeader(std::move(header));
+ }
+ return true;
+}
+
+void intel_npu::vm::SectionHeaderTable::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "Number of sections: " << _numSections << std::endl;
+ for (const auto& header : _sectionHeaders) {
+ header.print(indentLevel + 1);
+ }
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/type_section.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/type_section.cpp
new file mode 100644
index 00000000000..34d4491b234
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/type_section.cpp
@@ -0,0 +1,350 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/type_section.hpp"
+#include "npu_bytecode_utils/except.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/span.hpp"
+
+#include <algorithm>
+#include <climits>
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <optional>
+#include <variant>
+#include <vector>
+
+namespace {
+
+std::optional<uint16_t> extractPrimitiveTypeByteSize(intel_npu::vm::TypeCode typeCode,
+ intel_npu::vm::Span<uint8_t> typeData, size_t typeIndex) {
+ switch (typeCode) {
+ case intel_npu::vm::TypeCode::INTEGER: {
+ intel_npu::vm::IntegerType type{};
+ if (!type.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse integer type entry {}", typeIndex);
+ return std::nullopt;
+ }
+ return (type.bitWidth + (CHAR_BIT - 1)) / CHAR_BIT;
+ }
+ case intel_npu::vm::TypeCode::FLOAT: {
+ intel_npu::vm::FloatType type{};
+ if (!type.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse float type entry {}", typeIndex);
+ return std::nullopt;
+ }
+ return (type.bitWidth + (CHAR_BIT - 1)) / CHAR_BIT;
+ }
+ case intel_npu::vm::TypeCode::OPAQUE: {
+ intel_npu::vm::OpaqueType type{};
+ if (!type.parseFrom(typeData)) {
+ NPU_VM_LOG_ERROR("Failed to parse opaque type entry {}", typeIndex);
+ return std::nullopt;
+ }
+ return (type.bitWidth + (CHAR_BIT - 1)) / CHAR_BIT;
+ }
+ default:
+ return 0;
+ }
+}
+
+} // namespace
+
+void intel_npu::vm::IntegerType::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(TypeCode::INTEGER));
+ appendValueTo(buffer, bitWidth);
+ appendValueTo(buffer, isSigned);
+}
+
+bool intel_npu::vm::IntegerType::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, bitWidth)) {
+ NPU_VM_LOG_ERROR("Failed to parse IntegerType bitWidth from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, isSigned)) {
+ NPU_VM_LOG_ERROR("Failed to parse IntegerType isSigned from buffer");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::IntegerType::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << (isSigned ? "i" : "u") << static_cast<int>(bitWidth);
+}
+
+void intel_npu::vm::FloatType::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(TypeCode::FLOAT));
+ appendValueTo(buffer, bitWidth);
+ appendValueTo(buffer, static_cast<uint8_t>(format));
+}
+
+bool intel_npu::vm::FloatType::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, bitWidth)) {
+ NPU_VM_LOG_ERROR("Failed to parse FloatType bitWidth from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, format)) {
+ NPU_VM_LOG_ERROR("Failed to parse FloatType format from buffer");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::FloatType::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "float" << static_cast<int>(bitWidth);
+ switch (format) {
+ case FloatTypeFormat::IEEE754:
+ std::cout << " (IEEE754)";
+ break;
+ case FloatTypeFormat::BFloat:
+ std::cout << " (BFloat)";
+ break;
+ case FloatTypeFormat::TFloat:
+ std::cout << " (TFloat)";
+ break;
+ case FloatTypeFormat::E4M3:
+ std::cout << " (E4M3)";
+ break;
+ case FloatTypeFormat::E5M2:
+ std::cout << " (E5M2)";
+ break;
+ case FloatTypeFormat::E2M1:
+ std::cout << " (E2M1)";
+ break;
+ case FloatTypeFormat::E8M0:
+ std::cout << " (E8M0)";
+ break;
+ case FloatTypeFormat::NF4:
+ std::cout << " (NF4)";
+ break;
+ default:
+ std::cout << " (Unknown format)";
+ break;
+ }
+}
+
+void intel_npu::vm::OpaqueType::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(TypeCode::OPAQUE));
+ appendValueTo(buffer, bitWidth);
+}
+
+bool intel_npu::vm::OpaqueType::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, bitWidth)) {
+ NPU_VM_LOG_ERROR("Failed to parse OpaqueType bitWidth from buffer");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::OpaqueType::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "opaque<" << static_cast<int>(bitWidth) << ">";
+}
+
+void intel_npu::vm::BufferType::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(TypeCode::BUFFER));
+ appendValueTo(buffer, dataTypeIndex);
+ appendValueTo(buffer, rank);
+ for (const auto& dim : shape) {
+ appendValueTo(buffer, dim);
+ }
+ for (const auto& stride : strides) {
+ appendValueTo(buffer, stride);
+ }
+}
+
+bool intel_npu::vm::BufferType::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, dataTypeIndex)) {
+ NPU_VM_LOG_ERROR("Failed to parse BufferType dataTypeIndex from buffer");
+ return false;
+ }
+ if (!parseValueFrom(buffer, rank)) {
+ NPU_VM_LOG_ERROR("Failed to parse BufferType rank from buffer");
+ return false;
+ }
+ shape.resize(rank);
+ strides.resize(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ if (!parseValueFrom(buffer, shape.at(i))) {
+ NPU_VM_LOG_ERROR("Failed to parse BufferType shape dimension {}", i);
+ return false;
+ }
+ }
+ for (int64_t i = 0; i < rank; ++i) {
+ if (!parseValueFrom(buffer, strides.at(i))) {
+ NPU_VM_LOG_ERROR("Failed to parse BufferType stride dimension {}", i);
+ return false;
+ }
+ }
+ return true;
+}
+
+void intel_npu::vm::BufferType::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "buffer<typeIndex=" << dataTypeIndex << ", rank=" << static_cast<unsigned>(rank) << ", shape=[";
+ for (size_t i = 0; i < shape.size(); ++i) {
+ std::cout << shape.at(i);
+ if (i < shape.size() - 1) {
+ std::cout << ",";
+ }
+ }
+ std::cout << "], strides=[";
+ for (size_t i = 0; i < strides.size(); ++i) {
+ std::cout << strides.at(i);
+ if (i < strides.size() - 1) {
+ std::cout << ",";
+ }
+ }
+ std::cout << "]>";
+}
+
+void intel_npu::vm::FunctionType::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, static_cast<uint8_t>(TypeCode::FUNCTION));
+ appendValueTo(buffer, static_cast<uint16_t>(paramTypeIndices.size()));
+ for (const auto& paramTypeIndex : paramTypeIndices) {
+ appendValueTo(buffer, paramTypeIndex);
+ }
+ appendValueTo(buffer, static_cast<uint16_t>(resultTypeIndices.size()));
+ for (const auto& resultTypeIndex : resultTypeIndices) {
+ appendValueTo(buffer, resultTypeIndex);
+ }
+}
+
+bool intel_npu::vm::FunctionType::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ uint16_t numParams = 0;
+ if (!parseValueFrom(buffer, numParams)) {
+ NPU_VM_LOG_ERROR("Failed to parse FunctionType numParams from buffer");
+ return false;
+ }
+ paramTypeIndices.resize(numParams);
+ for (uint16_t i = 0; i < numParams; ++i) {
+ if (!parseValueFrom(buffer, paramTypeIndices.at(i))) {
+ NPU_VM_LOG_ERROR("Failed to parse FunctionType paramTypeIndex {}", i);
+ return false;
+ }
+ }
+ uint16_t numResults = 0;
+ if (!parseValueFrom(buffer, numResults)) {
+ NPU_VM_LOG_ERROR("Failed to parse FunctionType numResults from buffer");
+ return false;
+ }
+ resultTypeIndices.resize(numResults);
+ for (uint16_t i = 0; i < numResults; ++i) {
+ if (!parseValueFrom(buffer, resultTypeIndices.at(i))) {
+ NPU_VM_LOG_ERROR("Failed to parse FunctionType resultTypeIndex {}", i);
+ return false;
+ }
+ }
+ return true;
+}
+
+void intel_npu::vm::FunctionType::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << "function<params=[";
+ for (size_t i = 0; i < paramTypeIndices.size(); ++i) {
+ std::cout << paramTypeIndices.at(i);
+ if (i < paramTypeIndices.size() - 1) {
+ std::cout << ",";
+ }
+ }
+ std::cout << "], results=[";
+ for (size_t i = 0; i < resultTypeIndices.size(); ++i) {
+ std::cout << resultTypeIndices.at(i);
+ if (i < resultTypeIndices.size() - 1) {
+ std::cout << ",";
+ }
+ }
+ std::cout << "]>";
+}
+
+intel_npu::vm::TypeCode intel_npu::vm::getTypeCode(const Type& type) {
+ return std::visit(
+ [](const auto& t) {
+ return t.getTypeCode();
+ },
+ type.data);
+}
+
+uint8_t intel_npu::vm::getBitWidth(const intel_npu::vm::Type& type) {
+ switch (getTypeCode(type)) {
+ case TypeCode::INTEGER:
+ return std::get<IntegerType>(type.data).bitWidth;
+ case TypeCode::FLOAT:
+ return std::get<FloatType>(type.data).bitWidth;
+ case TypeCode::OPAQUE:
+ return std::get<OpaqueType>(type.data).bitWidth;
+ default:
+ NPU_VM_THROW("Unsupported type code for getBitWidth: {}", static_cast<uint64_t>(getTypeCode(type)));
+ }
+}
+
+bool intel_npu::vm::isTypeSigned(const intel_npu::vm::Type& type) {
+ NPU_VM_THROW_UNLESS(getTypeCode(type) == TypeCode::INTEGER,
+ "isTypeSigned is only applicable to integer types, but got type code: {}",
+ static_cast<uint64_t>(getTypeCode(type)));
+ return std::get<IntegerType>(type.data).isSigned;
+}
+
+uint16_t intel_npu::vm::lookupTypeByteSize(const std::vector<uint16_t>& typeByteSizes, int64_t typeIndex) {
+ if (typeIndex < 0 || static_cast<size_t>(typeIndex) >= typeByteSizes.size()) {
+ return 0;
+ }
+ return typeByteSizes.at(static_cast<size_t>(typeIndex));
+}
+
+std::optional<std::vector<uint16_t>> intel_npu::vm::extractTypeByteSizes(
+ const intel_npu::vm::SectionHeaderTable& sectionHeaderTable,
+ const std::vector<intel_npu::vm::Span<uint8_t>>& sections) {
+ const auto& sectionHeaders = sectionHeaderTable.getSectionHeaders();
+ const auto numTypeSections = std::count_if(sectionHeaders.begin(), sectionHeaders.end(), [](const auto& header) {
+ return header.type == intel_npu::vm::SectionType::TypeSection;
+ });
+ if (numTypeSections > 1) {
+ NPU_VM_LOG_ERROR("Expected at most one Type section, but found {}", numTypeSections);
+ return std::nullopt;
+ }
+
+ std::vector<uint16_t> typeByteSizes;
+ for (size_t headerIdx = 0; headerIdx < sectionHeaders.size(); ++headerIdx) {
+ const auto& header = sectionHeaders.at(headerIdx);
+ if (header.type != intel_npu::vm::SectionType::TypeSection) {
+ continue;
+ }
+ auto typeSectionInfo = dynamic_cast<intel_npu::vm::details::DataSectionInfo*>(header.info.get());
+ if (typeSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Type section header does not contain data section info");
+ return std::nullopt;
+ }
+ if (headerIdx >= sections.size()) {
+ NPU_VM_LOG_ERROR("Type section header has no payload");
+ return std::nullopt;
+ }
+ const auto& section = sections.at(headerIdx);
+ for (size_t typeIndex = 0; typeIndex < typeSectionInfo->dataInfos.size(); ++typeIndex) {
+ const auto& dataInfo = typeSectionInfo->dataInfos.at(typeIndex);
+ if (dataInfo.size == 0 || dataInfo.offset > section.size() ||
+ dataInfo.size > section.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("Type entry {} exceeds section bounds", typeIndex);
+ return std::nullopt;
+ }
+
+ const auto typeSpan = section.subspan(dataInfo.offset, dataInfo.size);
+ const auto typeCode = static_cast<intel_npu::vm::TypeCode>(typeSpan.at(0));
+ auto typeData = typeSpan.subspan(sizeof(uint8_t), typeSpan.size() - 1);
+ auto byteSize = extractPrimitiveTypeByteSize(typeCode, typeData, typeIndex);
+ if (!byteSize.has_value()) {
+ return std::nullopt;
+ }
+ typeByteSizes.push_back(byteSize.value());
+ }
+ }
+
+ return typeByteSizes;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/version.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/version.cpp
new file mode 100644
index 00000000000..b84b4ab0e4b
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/npu_bytecode_utils/src/version.cpp
@@ -0,0 +1,37 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/version.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/span.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <iostream>
+#include <utility>
+#include <vector>
+
+size_t intel_npu::vm::Version::getBinarySize() {
+ using VersionType = decltype(std::declval<intel_npu::vm::Version>().getFullVersion());
+ return sizeof(VersionType);
+}
+
+void intel_npu::vm::Version::appendTo(std::vector<uint8_t>& buffer) const {
+ appendValueTo(buffer, _version);
+}
+
+bool intel_npu::vm::Version::parseFrom(intel_npu::vm::Span<uint8_t>& buffer) {
+ if (!parseValueFrom(buffer, _version)) {
+ NPU_VM_LOG_ERROR("Failed to parse version from buffer");
+ return false;
+ }
+ return true;
+}
+
+void intel_npu::vm::Version::print(size_t indentLevel) const {
+ intel_npu::vm::printIndent(indentLevel);
+ std::cout << getMajor() << "." << getMinor() << "." << getPatch();
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/CMakeLists.txt b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/CMakeLists.txt
new file mode 100644
index 00000000000..92a864b6422
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/CMakeLists.txt
@@ -0,0 +1,70 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+
+set(TARGET_NAME "openvino_intel_npu_vm_runtime")
+
+set(SOURCES
+ src/npu_vm_runtime.cpp
+ src/virtual_machine.cpp
+ src/utils/buffer.cpp
+ src/utils/buffer_metadata.cpp
+ src/utils/call_frame.cpp
+ src/utils/function.cpp
+ src/utils/host_allocator.cpp
+ src/utils/kernel_execution.cpp
+ src/utils/level_zero_allocator.cpp
+ src/utils/math.cpp
+ src/utils/parameters.cpp
+)
+
+source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})
+
+add_library(${TARGET_NAME} SHARED ${SOURCES})
+add_library(openvino::intel_npu_vm_runtime ALIAS ${TARGET_NAME})
+set_target_properties(${TARGET_NAME} PROPERTIES EXPORT_NAME intel_npu_vm_runtime)
+ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})
+
+# To fix BinSkim scan issues in the CID package test nightly job
+# Limit LTCG to this library to avoid changing linker flags for other targets in the directory scope.
+if(MSVC)
+ target_link_options(${TARGET_NAME}
+ PRIVATE
+ $<$<CONFIG:Release>:/LTCG>
+ )
+endif()
+
+target_link_libraries(${TARGET_NAME}
+ PUBLIC
+ openvino::intel_npu_bytecode_utils
+ PRIVATE
+ openvino::zero_loader
+ openvino::npu_zero_utils
+ openvino::util
+ openvino::npu_al
+)
+
+# Prevents warning about unused parameters in NPU plugin logger header:
+# include/openvino/core/attribute_adapter.hpp:38:44: error: unused parameter 'x' [-Werror=unused-parameter]
+if(NOT MSVC)
+ target_compile_options(${TARGET_NAME}
+ PRIVATE
+ -Wno-error=unused-parameter
+ )
+endif()
+
+if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT ENABLE_DEVELOPER_BUILD)
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=4)
+else()
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=6)
+endif()
+
+target_include_directories(${TARGET_NAME}
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
+)
+
+install(TARGETS ${TARGET_NAME}
+ RUNTIME DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT ${NPU_PLUGIN_COMPONENT}
+ LIBRARY DESTINATION ${OV_CPACK_PLUGINSDIR} COMPONENT ${NPU_PLUGIN_COMPONENT})
+
\ No newline at end of file
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/npu_vm_runtime.hpp
similarity index 75%
rename from src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp
rename to src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/npu_vm_runtime.hpp
index 7bbbff61f75..a5d515c34dc 100644
--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/vm/npu_vm_runtime.hpp
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/npu_vm_runtime.hpp
@@ -6,20 +6,20 @@
#define NPU_VM_RUNTIME_H
#if defined(__cplusplus)
-# pragma once
+#pragma once
#endif
#include <level_zero/ze_api.h>
-#include <ze_command_queue_npu_ext.h>
+#include <ze_command_queue_npu_ext.h>
#include "ze_graph_ext.h"
#if defined(__cplusplus)
-# include <cstdint>
-# include <cstdlib>
+#include <cstdint>
+#include <cstdlib>
#else
-# include <stdint.h>
-# include <stdlib.h>
+#include <stdint.h>
+#include <stdlib.h>
#endif
#if defined(__cplusplus)
@@ -28,40 +28,40 @@ extern "C" {
///////////////////////////////////////////////////////////////////////////////
#ifndef NPU_VM_RUNTIME_APICALL
-# if defined(_WIN32)
+#if defined(_WIN32)
/// @brief Calling convention for all API functions
-# define NPU_VM_RUNTIME_APICALL __cdecl
-# else
-# define NPU_VM_RUNTIME_APICALL
-# endif // defined(_WIN32)
-#endif // NPU_VM_RUNTIME_APICALL
+#define NPU_VM_RUNTIME_APICALL __cdecl
+#else
+#define NPU_VM_RUNTIME_APICALL
+#endif // defined(_WIN32)
+#endif // NPU_VM_RUNTIME_APICALL
///////////////////////////////////////////////////////////////////////////////
#ifndef NPU_VM_RUNTIME_APIEXPORT
-# if defined(_WIN32)
+#if defined(_WIN32)
/// @brief Windows-specific dllexport storage-class attribute
-# define NPU_VM_RUNTIME_APIEXPORT __declspec(dllexport)
-# else
-# define NPU_VM_RUNTIME_APIEXPORT
-# endif // defined(_WIN32)
-#endif // NPU_VM_RUNTIME_APIEXPORT
+#define NPU_VM_RUNTIME_APIEXPORT __declspec(dllexport)
+#else
+#define NPU_VM_RUNTIME_APIEXPORT
+#endif // defined(_WIN32)
+#endif // NPU_VM_RUNTIME_APIEXPORT
///////////////////////////////////////////////////////////////////////////////
#ifndef NPU_VM_RUNTIME_MAKE_VERSION
/// @brief Generates generic API versions
-# define NPU_VM_RUNTIME_MAKE_VERSION(_major, _minor) ((_major << 16) | (_minor & 0x0000ffff))
+#define NPU_VM_RUNTIME_MAKE_VERSION(_major, _minor) ((_major << 16) | (_minor & 0x0000ffff))
#endif // NPU_VM_RUNTIME_MAKE_VERSION
///////////////////////////////////////////////////////////////////////////////
#ifndef NPU_VM_RUNTIME_MAJOR_VERSION
/// @brief Extracts API major version
-# define NPU_VM_RUNTIME_MAJOR_VERSION(_ver) (_ver >> 16)
+#define NPU_VM_RUNTIME_MAJOR_VERSION(_ver) (_ver >> 16)
#endif // NPU_VM_RUNTIME_MAJOR_VERSION
///////////////////////////////////////////////////////////////////////////////
#ifndef NPU_VM_RUNTIME_MINOR_VERSION
/// @brief Extracts API minor version
-# define NPU_VM_RUNTIME_MINOR_VERSION(_ver) (_ver & 0x0000ffff)
+#define NPU_VM_RUNTIME_MINOR_VERSION(_ver) (_ver & 0x0000ffff)
#endif // NPU_VM_RUNTIME_MINOR_VERSION
///////////////////////////////////////////////////////////////////////////////
@@ -97,6 +97,7 @@ typedef enum _npu_vm_runtime_result_t {
NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER = 0x80000001,
NPU_VM_RUNTIME_RESULT_ERROR_UNSUPPORTED_DIM_COUNT = 0x80000002,
NPU_VM_RUNTIME_RESULT_ERROR_UNSUPPORTED_VERSION = 0x80000003,
+ NPU_VM_RUNTIME_RESULT_ERROR_INVALID_VALUE = 0x80000004,
NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN = 0x8ffffffe,
NPU_VM_RUNTIME_RESULT_FORCE_UINT32 = 0x8fffffff,
} npu_vm_runtime_result_t;
@@ -147,45 +148,45 @@ typedef struct _npu_vm_runtime_predict_output_shape_params_t {
///////////////////////////////////////////////////////////////////////////////
/// @brief Returns the API version
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeGetAPIVersion(
- npu_vm_runtime_version_t* pVersion ///< [out] pointer to version information
+ npu_vm_runtime_version_t* pVersion ///< [out] pointer to version information
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Init VM runtime instance and return handle
-/// @details The handle borrows desc->pInput without copying it. Keep the buffer alive until npuVMRuntimeDestroy.
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreate(
- const npu_vm_runtime_blob_desc_t* desc, ///< [in] pointer to graph descriptor
- npu_vm_runtime_handle_t* phRuntime, ///< [out] pointer to handle of VM runtime object created
- npu_vm_runtime_properties_t* pProperties ///< [out] pointer to properties of the runtime
+ const npu_vm_runtime_blob_desc_t* desc, ///< [in] pointer to graph descriptor
+ npu_vm_runtime_handle_t* phRuntime, ///< [out] pointer to handle of VM runtime object created
+ npu_vm_runtime_properties_t* pProperties ///< [out] pointer to properties of the runtime
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Destroy VM runtime instance
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeDestroy(
- npu_vm_runtime_handle_t hRuntime ///< [in][release] handle of VM runtime object to destroy
+ npu_vm_runtime_handle_t hRuntime ///< [in][release] handle of VM runtime object to destroy
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Get metadata from VM runtime instance
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeGetMetadata(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- uint32_t argIndex, ///< [in] index of the argument
- ze_graph_argument_properties_3_t* pGraphArgumentProperties, ///< [out] query result for graph argument properties
- ze_graph_argument_metadata_t* pGraphArgumentMetadata, ///< [out] query result for graph argument metadata
- int64_t* upperBound);
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ uint32_t argIndex, ///< [in] index of the argument
+ ze_graph_argument_properties_3_t*
+ pGraphArgumentProperties, ///< [out] query result for graph argument properties
+ ze_graph_argument_metadata_t* pGraphArgumentMetadata, ///< [out] query result for graph argument metadata
+ int64_t* upperBound);
///////////////////////////////////////////////////////////////////////////////
/// @brief Execute VM runtime with params
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeExecute(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_execute_params_t* pParams ///< [in] pointer to execution parameters
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params_t* pParams ///< [in] pointer to execution parameters
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Predict output shape based on input shape
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimePredictOutputShape(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_predict_output_shape_params_t* pParams ///< [in] pointer to predict output shape parameters
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_predict_output_shape_params_t* pParams ///< [in] pointer to predict output shape parameters
);
///////////////////////////////////////////////////////////////////////////////
@@ -224,25 +225,25 @@ npuVMRuntimeParseMemRef(npu_vm_runtime_mem_ref_handle_t hMemRef, ///< [in] hand
///////////////////////////////////////////////////////////////////////////////
/// @brief Init VM runtime instance and return handle
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreateExecutionContext(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_execution_context_handle_t*
- phExecutionHandle ///< [out] pointer to handle of VM runtime execution context created
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execution_context_handle_t*
+ phExecutionHandle ///< [out] pointer to handle of VM runtime execution context created
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Destroy VM runtime instance
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeDestroyExecutionContext(
- npu_vm_runtime_execution_context_handle_t
- phExecutionHandle ///< [in][release] handle of execution context object to destroy
+ npu_vm_runtime_execution_context_handle_t
+ phExecutionHandle ///< [in][release] handle of execution context object to destroy
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Update mutable command list used in execution and execute
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeUpdateMutableCommandList(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_execute_params_t* pParams, ///< [in] pointer to execution parameters
- uint64_t* argIndexArray, ///< [in] pointer to argument index list
- uint64_t argIndexArraySize); ///< [in] size of argument index list
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params_t* pParams, ///< [in] pointer to execution parameters
+ uint64_t* argIndexArray, ///< [in] pointer to argument index list
+ uint64_t argIndexArraySize); ///< [in] size of argument index list
///////////////////////////////////////////////////////////////////////////////
/// @brief Version 1.1
@@ -260,8 +261,8 @@ typedef struct _npu_vm_runtime_predict_output_shape_params_t2 {
///////////////////////////////////////////////////////////////////////////////
/// @brief Predict output shape based on input shape
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimePredictOutputShape2(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_predict_output_shape_params_t2* pParams ///< [in] pointer to predict output shape parameters
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_predict_output_shape_params_t2* pParams ///< [in] pointer to predict output shape parameters
);
///////////////////////////////////////////////////////////////////////////////
@@ -290,10 +291,10 @@ typedef struct _npu_vm_runtime_config_desc_t {
const struct _npu_vm_runtime_config_desc_t* pNext;
} npu_vm_runtime_config_desc_t;
-#define NPU_VM_RUNTIME_CONFIG_TYPE_INVALID 0ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_INVALID 0ULL
#define NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY 2ULL
-#define NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE 3ULL
-#define NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS 4ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE 3ULL
+#define NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS 4ULL
///////////////////////////////////////////////////////////////////////////////
/// @brief Init VM runtime instance with initial runtime configuration and return handle (v2.0)
@@ -305,27 +306,24 @@ typedef struct _npu_vm_runtime_config_desc_t {
/// As with npuVMRuntimeCreate, the handle borrows desc->pInput without copying it. Keep the buffer alive
/// until npuVMRuntimeDestroy.
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreate2(
- const npu_vm_runtime_blob_desc_t* desc, ///< [in] pointer to graph descriptor
- const npu_vm_runtime_config_desc_t*
- pConfig, ///< [in][optional] pointer to initial runtime configuration descriptors
- npu_vm_runtime_handle_t* phRuntime, ///< [out] pointer to handle of VM runtime object created
- npu_vm_runtime_properties_t* pProperties ///< [out] pointer to properties of the runtime
+ const npu_vm_runtime_blob_desc_t* desc, ///< [in] pointer to graph descriptor
+ const npu_vm_runtime_config_desc_t*
+ pConfig, ///< [in][optional] pointer to initial runtime configuration descriptors
+ npu_vm_runtime_handle_t* phRuntime, ///< [out] pointer to handle of VM runtime object created
+ npu_vm_runtime_properties_t* pProperties ///< [out] pointer to properties of the runtime
);
///////////////////////////////////////////////////////////////////////////////
/// @brief Init VM runtime execution context with Level Zero handles (v2.0)
typedef struct _npu_vm_runtime_create_execution_context_params_t {
- /// @brief Level Zero context. Used by interpreter to create internal CLs.
+ /// @brief Level Zero context. Used by interpreter to create command lists in vm runtime.
ze_context_handle_t ctx;
- /// @brief Level Zero device. Used by interpreter to create internal CLs.
+ /// @brief Level Zero device. Used by interpreter to create command lists in vm runtime.
ze_device_handle_t device;
/// @brief Initial Level Zero command queue. Used by interpreter to create a fence for host synchronization.
/// Later npuVMRuntimeExecute2 calls may provide a different commandQueue.
- /// Lifetime: this queue must remain valid until a subsequent npuVMRuntimeExecute2 with a different
- /// commandQueue has succeeded. The interpreter keeps a fence bound to this queue and destroys it only
- /// during that migration, so freeing the queue earlier causes a use-after-free inside the runtime.
ze_command_queue_handle_t commandQueue;
/// @brief Graph DDI table extension pointer.
@@ -335,11 +333,11 @@ typedef struct _npu_vm_runtime_create_execution_context_params_t {
} npu_vm_runtime_create_execution_context_params_t;
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreateExecutionContext2(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_create_execution_context_params_t*
- pParams, ///< [in] pointer to execution context creation parameters
- npu_vm_runtime_execution_context_handle_t*
- phExecutionHandle ///< [out] pointer to handle of VM runtime execution context created
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_create_execution_context_params_t*
+ pParams, ///< [in] pointer to execution context creation parameters
+ npu_vm_runtime_execution_context_handle_t*
+ phExecutionHandle ///< [out] pointer to handle of VM runtime execution context created
);
///////////////////////////////////////////////////////////////////////////////
@@ -353,11 +351,6 @@ NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRun
/// If commandQueue differs from the one currently stored in executionContext,
/// runtime updates queue-dependent internal objects as needed.
/// Plugin never creates or manages command lists directly in this path.
-/// Queue lifetime: every commandQueue passed here (and to npuVMRuntimeCreateExecutionContext2) must stay
-/// valid until a later npuVMRuntimeExecute2 with a different commandQueue succeeds; a failed call may
-/// return before the migration. On a queue change the
-/// interpreter destroys the fence bound to the previously stored queue and rebuilds it on the new one;
-/// if the caller already freed the old queue, that destroy is a use-after-free the runtime cannot detect.
typedef struct _npu_vm_runtime_execute_params2_t {
/// @brief Command queue for submitting command lists or configuring internal command lists.
ze_command_queue_handle_t commandQueue;
@@ -373,7 +366,7 @@ typedef struct _npu_vm_runtime_execute_params2_t {
npu_vm_runtime_mem_ref_handle_t* pOutputs;
uint32_t numOfOutputs;
- /// @brief Execution context. Interpreter stores its internal CLs here
+ /// @brief Execution context. Interpreter stores its command lists created in vm_runtime here
/// and reuses them across Execute2 calls.
npu_vm_runtime_execution_context_handle_t executionContext;
} npu_vm_runtime_execute_params2_t;
@@ -389,8 +382,8 @@ typedef struct _npu_vm_runtime_execute_params2_t {
/// until the inference completes. The interpreter uses pParams->executionContext
/// to access the underlying synchronization primitive.
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeExecute2(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
);
///////////////////////////////////////////////////////////////////////////////
@@ -400,8 +393,8 @@ NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRun
/// pParams->executionContext. Other pParams fields are ignored by this call.
/// Output buffers are safe to read after this returns.
NPU_VM_RUNTIME_APIEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeHostSync(
- npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
- npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
+ npu_vm_runtime_handle_t hRuntime, ///< [in] handle of VM runtime object
+ npu_vm_runtime_execute_params2_t* pParams ///< [in] pointer to v2 execution parameters
);
#if defined(__cplusplus)
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/virtual_machine.h b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/virtual_machine.h
new file mode 100644
index 00000000000..ac2c6ef0063
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/include/vm_runtime/virtual_machine.h
@@ -0,0 +1,276 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#ifndef NPU_VIRTUAL_MACHINE_H
+#define NPU_VIRTUAL_MACHINE_H
+
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#if defined(__cplusplus)
+#include <cstdint>
+#else
+#include <stdint.h>
+#endif
+
+#ifndef NPU_VM_APICALL
+#if defined(_WIN32)
+#define NPU_VM_APICALL __cdecl
+#else
+#define NPU_VM_APICALL
+#endif // defined(_WIN32)
+#endif // NPU_VM_APICALL
+
+#ifndef NPU_VM_EXPORT
+#if defined(_WIN32)
+#define NPU_VM_EXPORT __declspec(dllexport)
+#else
+#define NPU_VM_EXPORT __attribute__((visibility("default")))
+#endif // defined(_WIN32)
+#endif // NPU_VM_EXPORT
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// NOLINTBEGIN
+
+typedef enum _npu_vm_result {
+ NPU_VM_SUCCESS = 0,
+ NPU_VM_ERROR_INVALID_NULL_POINTER = 0x80000001,
+ NPU_VM_ERROR_MODULE_NOT_FOUND = 0x80000002,
+ NPU_VM_ERROR_FUNCTION_NOT_FOUND = 0x80000003,
+ NPU_VM_ERROR_FUNCTION_NAME_TOO_LONG = 0x80000004,
+ NPU_VM_ERROR_FUNCTION_CALL_FAILED = 0x80000005,
+ NPU_VM_ERROR_INFERENCE_FAILED = 0x80000006,
+ NPU_VM_ERROR_OUTPUT_SHAPE_PREDICTION_FAILED = 0x80000007,
+ NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED = 0x80000008,
+ NPU_VM_ERROR_UNKNOWN = 0x8ffffffe,
+} npu_vm_result;
+
+typedef enum _npu_vm_type {
+ npu_vm_type_int8 = 0,
+ npu_vm_type_int16 = 1,
+ npu_vm_type_int32 = 2,
+ npu_vm_type_int64 = 3,
+ npu_vm_type_uint8 = 4,
+ npu_vm_type_uint16 = 5,
+ npu_vm_type_uint32 = 6,
+ npu_vm_type_uint64 = 7,
+ npu_vm_type_float32 = 8,
+ npu_vm_type_float64 = 9,
+ npu_vm_type_buffer = 10
+} npu_vm_type;
+
+typedef enum _npu_vm_batch_mode {
+ npu_vm_batch_mode_none = 0,
+ npu_vm_batch_mode_static = 1,
+ npu_vm_batch_mode_dynamic = 2,
+} npu_vm_batch_mode;
+
+typedef union _npu_vm_value {
+ int8_t i8;
+ int16_t i16;
+ int32_t i32;
+ int64_t i64;
+ uint8_t u8;
+ uint16_t u16;
+ uint32_t u32;
+ uint64_t u64;
+ float f32;
+ double f64;
+ struct {
+ uint8_t* data;
+ uint32_t size;
+ } buffer;
+} npu_vm_value;
+
+typedef struct _npu_vm_function_info {
+ char* name; // Null-terminated function name string
+ uint32_t num_params;
+ npu_vm_type* param_types;
+ uint32_t num_results;
+ npu_vm_type* result_types;
+} npu_vm_function_info;
+
+typedef struct _npu_vm_command_queue_desc {
+ ze_command_queue_priority_t priority;
+ ze_command_queue_workload_type_t workload_type;
+ uint32_t option_flags;
+} npu_vm_command_queue_desc;
+
+typedef struct _npu_vm_module_load_params {
+ npu_vm_runtime_create_execution_context_params_t* create_execution_context_params;
+ /// Stores the number concurrent command lists that can be executed in parallel.
+ /// If the value is 1, the runtime will consider that the compiled schedule uses
+ /// the max number of tiles
+ uint32_t concurrentJobCount;
+
+ // If true, the runtime will create an internal command queue for the engine to use.
+ // If false, the runtime will use the command queue provided in create_execution_context_params
+ bool internalCommandQueue;
+
+ // If true, the runtime will use counter-based events for synchronization between subgraphs.
+ bool counterBasedEventSupported;
+
+ // Specifies the batch mode of the module
+ npu_vm_batch_mode batchMode;
+
+ // Specifies batch size;
+ uint64_t batchSize;
+} npu_vm_module_load_params;
+
+typedef struct _npu_vm_module npu_vm_module;
+typedef struct _npu_vm_engine npu_vm_engine;
+
+#define NPU_VM_MAIN_INFERENCE_FUNCTION_NAME "main"
+#define NPU_VM_OUTPUT_SHAPE_PREDICTION_FUNCTION_NAME "output_shape"
+
+/// Print the bytecode binary in a human-readable format. The output is printed to stdout
+/// @param bytecode Pointer to the bytecode binary data
+/// @param bytecode_size Size of the bytecode binary in bytes
+/// @param print_full If true, large constants are printed in full. Non-zero values are treated as true
+/// @param indent_level The indentation level for pretty-printing nested structures
+/// @return NPU_VM_SUCCESS if printing succeeded, or an appropriate error code if parsing the bytecode failed
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_print(const uint8_t* bytecode, uint32_t bytecode_size, int print_full,
+ uint32_t indent_level);
+
+/// Deserializes a bytecode binary and stores this information inside a `npu_vm_module` for later execution. The
+/// resulting module instance references the provided bytecode data, so the caller must ensure that the bytecode data
+/// remains valid for the lifetime of the module.
+/// @param bytecode Pointer to the bytecode binary data
+/// @param bytecode_size Size of the bytecode binary in bytes
+/// @param module_out Output parameter where to store the deserialized module. The caller is responsible for freeing the
+/// memory allocated for the output module, by calling `npu_vm_destroy_module()`
+/// @return NPU_VM_SUCCESS if parsing succeeded, or an appropriate error code if parsing failed
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_parse_module(const uint8_t* bytecode, uint32_t bytecode_size,
+ npu_vm_module** module_out);
+
+/// Destroy an instance of `npu_vm_module` and free the memory allocated for its fields
+/// @param module The `npu_vm_module` structure to free
+/// @return NPU_VM_SUCCESS if the memory was successfully freed, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_module(npu_vm_module* module);
+
+/// Returns information about a function by name. The information is stored in the info_out parameter
+/// @param module The module instance
+/// @param name The name of the function to query
+/// @param info_out Output parameter where to store the function information. The caller is responsible for freeing the
+/// memory allocated for the output structure, by calling `npu_vm_destroy_function_info()`
+/// @return NPU_VM_SUCCESS if the function was found and the information was successfully stored in `info_out`, or an
+/// appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_get_function_info(npu_vm_module* module, const char* name,
+ npu_vm_function_info** info_out);
+
+/// Destroy an instance of `npu_vm_function_info` and free the memory allocated for its fields
+/// @param info The `npu_vm_function_info` structure to free
+/// @return NPU_VM_SUCCESS if the memory was successfully freed, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_function_info(npu_vm_function_info* info);
+
+/// Creates a new engine instance. This instance can be used to load a module and execute its functions. The caller is
+/// responsible for destroying the created engine instance by calling `npu_vm_destroy_engine()`
+/// @param engine_out Output parameter where to store the created engine instance
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_new_engine(npu_vm_engine** engine_out);
+
+/// Destroys an engine instance
+/// @param engine The engine instance to destroy
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_engine(npu_vm_engine* engine);
+
+/// Load a module into the engine instance. The loaded module can then be executed by calling its functions through the
+/// engine. The state of the engine is reset when a new module is loaded
+/// @param engine The engine instance where to load the module
+/// @param module The module to load into the engine
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_load_module(npu_vm_engine* engine, npu_vm_module_load_params* params,
+ npu_vm_module* module);
+
+/// Resets the internal state of the engine, to prepare for a new inference execution
+/// @param engine The engine instance to reset
+/// @param resetExecutionContext Whether to reset the execution context. Non-zero values are treated as true
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_reset_state(npu_vm_engine* engine, int resetExecutionContext);
+
+/// Calls the function with the given name and the specified arguments
+/// @param engine The engine instance
+/// @param name The name of the function to call
+/// @param num_arguments The number of arguments provided in the `arguments` array. This must match the function's
+/// parameter count, and the types of the provided arguments must match the function's parameter types
+/// @param arguments The argument values to pass to the function
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+/// @details The called function must not return any values; otherwise use `vm_call_with_results`.
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_call(npu_vm_engine* engine, const char* name, uint32_t num_arguments,
+ const npu_vm_value* arguments);
+
+/// Calls the function with the given name and the specified arguments, then returns the results in the provided results
+/// storage
+/// @param engine The engine instance
+/// @param name The name of the function to call
+/// @param num_arguments The number of arguments provided in the `arguments` array. This must match the function's
+/// parameter count, and the types of the provided arguments must match the function's parameter types
+/// @param arguments The argument values to pass to the function
+/// @param num_results The number of results expected from the function, and the size of the `results` array. This must
+/// match the function's result count, and the types of the expected results must match the function's result types
+/// @param results The storage where to write the function's result values
+/// @details In case the result types include buffers, the VM can either use the provided buffers, or allocate memory
+/// internally and set the `data` and `size` fields in the corresponding `npu_vm_value` entries. If the data pointer of
+/// a buffer is null and the size is zero, the VM will allocate the buffer internally; if the data pointer is not null,
+/// the VM will write the result to the provided buffer, and the caller is responsible for ensuring that the buffer has
+/// sufficient size to hold the result. In case the VM allocates the buffer internally, the caller is responsible for
+/// freeing the allocated memory after the call, by using `free()`
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_call_with_results(npu_vm_engine* engine, const char* name,
+ uint32_t num_arguments,
+ const npu_vm_value* arguments, uint32_t num_results,
+ npu_vm_value* results);
+
+/// Calls the main inference function with the specified execution parameters
+/// @param engine The engine instance
+/// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+/// @details The main inference function is expected to have the name 'main' and to have the same number and types of
+/// parameters as specified in the execution parameters (i.e. buffers)
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_infer(npu_vm_engine* engine, npu_vm_runtime_execute_params_t* params);
+
+/// Calls the main inference function with the specified execution parameters
+/// @param engine The engine instance
+/// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+/// @details The main inference function is expected to have the name 'main' and to have the same number and types of
+/// parameters as specified in the execution parameters (i.e. buffers)
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_infer2(npu_vm_engine* engine,
+ npu_vm_runtime_execute_params2_t* params);
+
+/// Calls the output shape prediction function with the specified execution parameters
+/// @param engine The engine instance
+/// @param params The execution parameters from the VM Runtime API, specifying the model's input buffer information
+/// needed for output shape prediction, and the result buffers where to store the predicted output shapes
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+/// @details The output shape prediction function is expected to have the name 'output_shape' and to have the
+/// same number and types of parameters as specified in the output shape prediction execution parameters (i.e. buffers)
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL
+npu_vm_predict_output_shape(npu_vm_engine* engine, npu_vm_runtime_predict_output_shape_params_t2* params);
+
+/// Returns true if host code execution is required for the given execution parameters
+/// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT bool NPU_VM_APICALL npu_vm_host_code_execution_required(npu_vm_engine* engine,
+ npu_vm_runtime_execute_params2_t* params);
+
+/// Submit recorded command lists
+/// @param engine The engine instance
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL
+npu_vm_submit_recorded_command_lists(npu_vm_engine* engine, npu_vm_runtime_execute_params2_t* params);
+
+/// Host synchronizes the engine, blocking until all previously submitted commands have completed execution.
+/// @param engine The engine instance
+/// @return NPU_VM_SUCCESS if the function executed and finalized successfully, or an appropriate error code otherwise
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_host_sync(npu_vm_engine* engine);
+
+// NOLINTEND
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // NPU_VIRTUAL_MACHINE_H
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/npu_vm_runtime.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/npu_vm_runtime.cpp
new file mode 100644
index 00000000000..32349ff1146
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/npu_vm_runtime.cpp
@@ -0,0 +1,975 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "vm_runtime/npu_vm_runtime.hpp"
+#include "intel_npu/config/config.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/network_description.hpp"
+#include "utils/network_metadata.hpp"
+#include "utils/parameters.hpp"
+#include "vm_runtime/virtual_machine.h"
+
+#include <ze_command_queue_npu_ext.h>
+#include <openvino/core/layout.hpp>
+#include <openvino/core/type/element_type.hpp>
+
+#include <ze_graph_ext.h>
+#include <intel_npu/utils/zero/zero_utils.hpp>
+#include <openvino/zero_api.hpp>
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <exception>
+#include <limits>
+#include <memory>
+#include <mutex>
+#include <new>
+#include <string>
+#include <utility>
+#include <vector>
+
+/// Opaque runtime object holding the VirtualMachine instance.
+struct _npu_vm_runtime_handle_t {
+ intel_npu::vm::NetworkMetadata metadata;
+ npu_vm_module* module{};
+ // Ze command queue handle for executing the graph.
+ // A command queue will be created when npuVMRuntimeCreateExecutionContext2 is called with
+ // a null command queue
+ ze_device_handle_t device{};
+ ze_context_handle_t context{};
+ npu_vm_command_queue_desc commandQueueDesc{};
+ ze_command_queue_handle_t commandQueue{};
+ std::vector<ze_command_queue_handle_t> commandQueues;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt{nullptr};
+ npu_vm_batch_mode batchMode = npu_vm_batch_mode_none;
+ uint64_t batchSize = 1;
+ std::mutex mutex;
+};
+
+namespace {
+constexpr uint32_t MAX_COMMAND_QUEUE_PRIORITIES = 3;
+constexpr uint32_t MAX_GRAPH_ARG_DIMS = ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE;
+constexpr uint32_t MAX_GRAPH_TENSOR_REF_DIMS = ZE_MAX_GRAPH_TENSOR_REF_DIMS;
+
+ze_graph_argument_precision_t toZeGraphPrecision(const ov::element::Type& precision) {
+ static const std::vector<std::pair<ov::element::Type, ze_graph_argument_precision_t>> precisions = {
+ {ov::element::f64, ZE_GRAPH_ARGUMENT_PRECISION_FP64},
+ {ov::element::f32, ZE_GRAPH_ARGUMENT_PRECISION_FP32},
+ {ov::element::f16, ZE_GRAPH_ARGUMENT_PRECISION_FP16},
+ {ov::element::bf16, ZE_GRAPH_ARGUMENT_PRECISION_BF16},
+ {ov::element::u64, ZE_GRAPH_ARGUMENT_PRECISION_UINT64},
+ {ov::element::u32, ZE_GRAPH_ARGUMENT_PRECISION_UINT32},
+ {ov::element::u16, ZE_GRAPH_ARGUMENT_PRECISION_UINT16},
+ {ov::element::u8, ZE_GRAPH_ARGUMENT_PRECISION_UINT8},
+ {ov::element::u4, ZE_GRAPH_ARGUMENT_PRECISION_UINT4},
+ {ov::element::u1, ZE_GRAPH_ARGUMENT_PRECISION_BIN},
+ {ov::element::i64, ZE_GRAPH_ARGUMENT_PRECISION_INT64},
+ {ov::element::i32, ZE_GRAPH_ARGUMENT_PRECISION_INT32},
+ {ov::element::i16, ZE_GRAPH_ARGUMENT_PRECISION_INT16},
+ {ov::element::i8, ZE_GRAPH_ARGUMENT_PRECISION_INT8},
+ {ov::element::i4, ZE_GRAPH_ARGUMENT_PRECISION_INT4},
+ {ov::element::nf4, ZE_GRAPH_ARGUMENT_PRECISION_NF4},
+ {ov::element::boolean, ZE_GRAPH_ARGUMENT_PRECISION_BOOLEAN},
+ };
+
+ const auto it = std::find_if(precisions.begin(), precisions.end(), [&](const auto& entry) {
+ return entry.first == precision;
+ });
+ return it != precisions.end() ? it->second : ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN;
+}
+
+void copyString(char* dst, size_t dstSize, const std::string& src) {
+ if (dst == nullptr || dstSize == 0) {
+ return;
+ }
+
+ std::strncpy(dst, src.c_str(), dstSize - 1);
+ dst[dstSize - 1] = '\0'; // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
+}
+
+ze_result_t createCmdQueue(npu_vm_runtime_handle_t hRuntime, ze_command_queue_handle_t* commandQueue) {
+ auto context = hRuntime->context;
+ auto device = hRuntime->device;
+ auto& desc = hRuntime->commandQueueDesc;
+ auto commandQueueDdiTableExt = hRuntime->commandQueueDdiTableExt;
+
+ if (context == nullptr || device == nullptr) {
+ return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ if (desc.workload_type != ZE_WORKLOAD_TYPE_DEFAULT) {
+ if (commandQueueDdiTableExt == nullptr || commandQueueDdiTableExt->pfnSetWorkloadType == nullptr) {
+ return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ }
+
+ auto groupOrdinal =
+ intel_npu::zeroUtils::findCommandQueueGroupOrdinal(device, ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);
+
+ ze_command_queue_desc_t ze_queue_desc = {ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC, nullptr, groupOrdinal, 0, 0,
+ ZE_COMMAND_QUEUE_MODE_DEFAULT, desc.priority};
+ ze_command_queue_desc_npu_ext_2_t command_queue_desc = {};
+
+ if (desc.option_flags) {
+ command_queue_desc.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC_NPU_EXT_2;
+ command_queue_desc.options = desc.option_flags;
+ ze_queue_desc.pNext = &command_queue_desc;
+ }
+
+ auto handle = ::intel_npu::zeCommandQueueCreate(context, device, &ze_queue_desc, commandQueue);
+
+ if (desc.workload_type != ZE_WORKLOAD_TYPE_DEFAULT) {
+ auto result = commandQueueDdiTableExt->pfnSetWorkloadType(
+ *commandQueue, static_cast<ze_command_queue_workload_type_t>(desc.workload_type));
+
+ if (ZE_RESULT_SUCCESS != result) {
+ ::intel_npu::zeCommandQueueDestroy(*commandQueue);
+ *commandQueue = nullptr;
+ return result;
+ }
+ }
+
+ return handle;
+}
+
+ze_result_t configCmdQueue(npu_vm_runtime_handle_t hRuntime, const npu_vm_runtime_config_desc_t* pConfig) {
+ const npu_vm_runtime_config_desc_t* config = pConfig;
+ auto& desc = hRuntime->commandQueueDesc;
+
+ ze_command_queue_priority_t priority = desc.priority;
+ auto workloadType = desc.workload_type;
+ while (config) {
+ if (config->type == NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY) {
+ if (config->value >= MAX_COMMAND_QUEUE_PRIORITIES) {
+ NPU_VM_LOG_ERROR("Invalid queue priority value: {}", config->value);
+ return ZE_RESULT_ERROR_INVALID_ARGUMENT;
+ }
+ priority = static_cast<ze_command_queue_priority_t>(config->value);
+ } else if (config->type == NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE) {
+ workloadType = static_cast<ze_command_queue_workload_type_t>(config->value);
+ } else if (config->type == NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS) {
+ NPU_VM_LOG_ERROR("NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS is not supported");
+ return ZE_RESULT_ERROR_INVALID_ARGUMENT;
+ } else {
+ NPU_VM_LOG_WARN("Unknown config type: {}", config->type);
+ }
+
+ config = config->pNext;
+ }
+
+ if (priority != desc.priority || workloadType != desc.workload_type) {
+ std::lock_guard<std::mutex> lock(hRuntime->mutex);
+ if (priority != desc.priority) {
+ desc.priority = priority;
+ if (hRuntime->commandQueues[static_cast<uint32_t>(priority)] != nullptr) {
+ hRuntime->commandQueue = hRuntime->commandQueues[static_cast<uint32_t>(priority)];
+ } else {
+ // Create an internal command queue if none is provided in the parameters and none is stored in
+ // the runtime handle
+ ze_command_queue_handle_t commandQueue = nullptr;
+ auto result = createCmdQueue(hRuntime, &commandQueue);
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ // Stores the command queue according to priority [0..2]
+ hRuntime->commandQueues[static_cast<uint32_t>(hRuntime->commandQueueDesc.priority)] = commandQueue;
+ hRuntime->commandQueue = commandQueue;
+ }
+ }
+ if (hRuntime->commandQueue == nullptr) {
+ NPU_VM_LOG_ERROR("Invalid null command queue pointer");
+ return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ if (workloadType != desc.workload_type) {
+ auto commandQueueDdiTableExt = hRuntime->commandQueueDdiTableExt;
+ if (commandQueueDdiTableExt == nullptr || commandQueueDdiTableExt->pfnSetWorkloadType == nullptr) {
+ NPU_VM_LOG_ERROR("pfnSetWorkloadType is not supported");
+ return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ auto commandQueue = hRuntime->commandQueue;
+ desc.workload_type = workloadType;
+ auto result = commandQueueDdiTableExt->pfnSetWorkloadType(commandQueue, workloadType);
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to set workload type: {}", result);
+ return result;
+ }
+ }
+ }
+
+ return ZE_RESULT_SUCCESS;
+}
+
+std::pair<npu_vm_batch_mode, uint64_t> getBatchMode(const npu_vm_runtime_handle_t hRuntime) {
+ if (hRuntime == nullptr) {
+ return {npu_vm_batch_mode_none, 1};
+ }
+
+ uint64_t batchSize = 1;
+ npu_vm_batch_mode batchMode = npu_vm_batch_mode_none;
+ auto updateBatchMode = [&](const auto& descriptors) {
+ for (const auto& descriptor : descriptors) {
+ if (!descriptor.shapeFromIRModel.has_value()) {
+ continue;
+ }
+
+ const auto& shape = descriptor.shapeFromIRModel.value();
+ if (!descriptor.layout.empty()) {
+ const ov::Layout layout(descriptor.layout);
+ if (!ov::layout::has_batch(layout)) {
+ continue;
+ }
+ auto batchIndex = ov::layout::batch_idx(layout);
+
+ const auto& batchDim = shape[batchIndex];
+ if (batchDim.is_dynamic()) {
+ return true;
+ }
+ if (batchDim.get_length() > 1) {
+ batchMode = npu_vm_batch_mode_static;
+ batchSize = std::max(batchSize, static_cast<uint64_t>(batchDim.get_length()));
+ }
+ }
+ }
+ return false;
+ };
+
+ if (updateBatchMode(hRuntime->metadata.inputs) || updateBatchMode(hRuntime->metadata.outputs)) {
+ return {npu_vm_batch_mode_dynamic, std::numeric_limits<uint64_t>::max()};
+ }
+
+ return {batchMode, batchSize};
+}
+} // namespace
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(_WIN32)
+#define DLLEXPORT __declspec(dllexport)
+#else
+#define DLLEXPORT __attribute__((visibility("default")))
+#endif
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeGetAPIVersion(npu_vm_runtime_version_t* pVersion) {
+ if (pVersion == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ npu_vm_runtime_version_t version = NPU_VM_RUNTIME_VERSION_CURRENT;
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD) || !defined(NDEBUG)
+ // Debug purpose to verify old version of runtime interfaces
+ // The env variable can be set to "V1.1" to force the runtime to use the old version.
+ const char* envVar = std::getenv("NPU_VM_RUNTIME_VERSION");
+ if (envVar != nullptr) {
+ std::string modeStr(envVar);
+ if (modeStr == "V1.1") {
+ version = NPU_VM_RUNTIME_VERSION_1_1;
+ }
+ }
+#endif
+ NPU_VM_LOG_INFO("VMRuntime APIVersion {}_{}", NPU_VM_RUNTIME_MAJOR_VERSION(version),
+ NPU_VM_RUNTIME_MINOR_VERSION(version));
+
+ *pVersion = version;
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreate(const npu_vm_runtime_blob_desc_t* desc,
+ npu_vm_runtime_handle_t* phRuntime,
+ npu_vm_runtime_properties_t* pProperties) {
+ if (desc == nullptr || phRuntime == nullptr || pProperties == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ if (desc->pInput == nullptr || desc->inputSize == 0) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ const auto bytecodePtr = desc->pInput;
+ const auto bytecodeSize = desc->inputSize;
+
+ auto handle = std::make_unique<_npu_vm_runtime_handle_t>();
+
+ if (npu_vm_parse_module(bytecodePtr, static_cast<uint32_t>(bytecodeSize), &handle->module) != NPU_VM_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ auto metadata = intel_npu::vm::getNetworkMetadata(handle->module);
+ if (metadata.has_value()) {
+ handle->metadata = std::move(metadata.value());
+ if (handle->metadata.numCmdLists == 0 ||
+ (handle->metadata.inputs.size() + handle->metadata.outputs.size()) == 0) {
+ npu_vm_destroy_module(handle->module);
+ handle->module = nullptr;
+ NPU_VM_LOG_ERROR(
+ "Metadata section is present but contains invalid data (numCmdLists or inputs/outputs)");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ pProperties->numOfSubGraphs = static_cast<uint32_t>(handle->metadata.numCmdLists);
+ pProperties->numOfGraphArgs =
+ static_cast<uint32_t>(handle->metadata.inputs.size() + handle->metadata.outputs.size());
+ const auto [batchMode, batchSize] = getBatchMode(handle.get());
+ handle->batchMode = batchMode;
+ handle->batchSize = batchSize;
+ } else {
+ NPU_VM_LOG_WARN("Bytecode blob does not contain metadata section. Set conservatively "
+ "numOfGraphArgs=2 and numOfSubGraphs=1 to allow for basic functionality.");
+ // if metadata is missing, assume a single subgraph with all inputs and outputs
+ pProperties->numOfSubGraphs = 1;
+ pProperties->numOfGraphArgs = 2; // at least one input and one output
+ handle->batchMode = npu_vm_batch_mode_none;
+ handle->batchSize = 1;
+ }
+ *phRuntime = handle.release();
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while creating runtime: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeDestroy(npu_vm_runtime_handle_t hRuntime) {
+ if (hRuntime == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ auto result = NPU_VM_RUNTIME_RESULT_SUCCESS;
+ if (hRuntime->module != nullptr) {
+ if (npu_vm_destroy_module(hRuntime->module) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy module");
+ result = NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ } else {
+ hRuntime->module = nullptr;
+ }
+ }
+
+ for (auto& commandQueue : hRuntime->commandQueues) {
+ if (commandQueue != nullptr) {
+ auto cmdQueueDestroyResult = ::intel_npu::zeCommandQueueDestroy(commandQueue);
+ if (cmdQueueDestroyResult != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy command queue: {}", cmdQueueDestroyResult);
+ result = NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ } else {
+ commandQueue = nullptr;
+ }
+ }
+ }
+
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
+ delete hRuntime;
+ return result;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeGetMetadata(
+ npu_vm_runtime_handle_t hRuntime, uint32_t argIndex, ze_graph_argument_properties_3_t* pGraphArgumentProperties,
+ ze_graph_argument_metadata_t* pGraphArgumentMetadata, int64_t* upperBound) {
+ if (hRuntime == nullptr || pGraphArgumentProperties == nullptr || pGraphArgumentMetadata == nullptr ||
+ upperBound == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ const intel_npu::vm::IODescriptor* descriptor = nullptr;
+ ze_graph_argument_type_t argType = ZE_GRAPH_ARGUMENT_TYPE_INPUT;
+
+ const auto inputCount = hRuntime->metadata.inputs.size();
+ const auto outputCount = hRuntime->metadata.outputs.size();
+
+ if (argIndex < inputCount) {
+ descriptor = &hRuntime->metadata.inputs.at(argIndex);
+ argType = ZE_GRAPH_ARGUMENT_TYPE_INPUT;
+ } else if (argIndex < inputCount + outputCount) {
+ descriptor = &hRuntime->metadata.outputs.at(argIndex - inputCount);
+ argType = ZE_GRAPH_ARGUMENT_TYPE_OUTPUT;
+ } else {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ *pGraphArgumentProperties = {};
+ pGraphArgumentProperties->stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES_3;
+ pGraphArgumentProperties->pNext = nullptr;
+ pGraphArgumentProperties->type = argType;
+ pGraphArgumentProperties->networkPrecision = toZeGraphPrecision(descriptor->precision);
+ pGraphArgumentProperties->devicePrecision = toZeGraphPrecision(descriptor->precision);
+ pGraphArgumentProperties->networkLayout = ZE_GRAPH_ARGUMENT_LAYOUT_ANY;
+ pGraphArgumentProperties->deviceLayout = ZE_GRAPH_ARGUMENT_LAYOUT_ANY;
+ pGraphArgumentProperties->quantReverseScale = 1.0f;
+ pGraphArgumentProperties->quantZeroPoint = 0;
+ pGraphArgumentProperties->associated_tensor_names_count = 0;
+
+ // The ze_graph_* properties expose fixed-size C arrays and `upperBound` is a raw pointer parameter, so
+ // array-to-pointer decay and indexed access are unavoidable when populating them.
+ // NOLINTBEGIN
+ copyString(pGraphArgumentProperties->name, ZE_MAX_GRAPH_ARGUMENT_NAME, descriptor->nameFromCompiler);
+ copyString(pGraphArgumentProperties->debug_friendly_name, ZE_MAX_GRAPH_ARGUMENT_NAME,
+ descriptor->nodeFriendlyName.empty() ? descriptor->nameFromCompiler : descriptor->nodeFriendlyName);
+
+ for (uint32_t i = 0; i < MAX_GRAPH_ARG_DIMS; ++i) {
+ pGraphArgumentProperties->dims[i] = 0;
+ upperBound[i] = 0;
+ }
+
+ const auto rank = descriptor->shapeFromCompiler.rank();
+ if (rank.is_static()) {
+ const auto rankLength = static_cast<size_t>(rank.get_length());
+ const auto cappedRank = std::min(rankLength, static_cast<size_t>(MAX_GRAPH_ARG_DIMS));
+ pGraphArgumentProperties->dims_count = static_cast<uint32_t>(cappedRank);
+
+ uint32_t dimIdx = 0;
+ for (const auto& dim : descriptor->shapeFromCompiler) {
+ if (dimIdx >= pGraphArgumentProperties->dims_count) {
+ break;
+ }
+ if (!dim.is_dynamic() && dim.get_length() >= 0 &&
+ static_cast<uint64_t>(dim.get_length()) <= std::numeric_limits<uint32_t>::max()) {
+ const auto dimVal = static_cast<uint32_t>(dim.get_length());
+ pGraphArgumentProperties->dims[dimIdx] = dimVal;
+ upperBound[dimIdx] = static_cast<int64_t>(dimVal);
+ }
+ ++dimIdx;
+ }
+ } else {
+ pGraphArgumentProperties->dims_count = 0;
+ }
+ // NOLINTEND
+
+ *pGraphArgumentMetadata = {};
+ pGraphArgumentMetadata->stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_METADATA;
+ pGraphArgumentMetadata->pNext = nullptr;
+ pGraphArgumentMetadata->type = argType;
+ pGraphArgumentMetadata->data_type = ZE_GRAPH_METADATA_TYPE_UNDEFINED;
+
+ std::vector<std::string> tensorNames(descriptor->outputTensorNames.begin(),
+ descriptor->outputTensorNames.end());
+ std::sort(tensorNames.begin(), tensorNames.end());
+
+ const auto tensorNameCount = static_cast<uint32_t>(
+ std::min(tensorNames.size(), static_cast<size_t>(ZE_MAX_GRAPH_TENSOR_NAMES_SIZE)));
+ pGraphArgumentMetadata->tensor_names_count = tensorNameCount;
+ // The ze_graph_* metadata exposes fixed-size C arrays, so array-to-pointer decay and indexed access are
+ // unavoidable when populating them.
+ // NOLINTBEGIN
+ for (uint32_t i = 0; i < tensorNameCount; ++i) {
+ copyString(pGraphArgumentMetadata->tensor_names[i], ZE_MAX_GRAPH_ARGUMENT_NAME, tensorNames.at(i));
+ }
+
+ // copy tensors names to associated_tensor_names
+ pGraphArgumentProperties->associated_tensor_names_count = pGraphArgumentMetadata->tensor_names_count;
+ for (uint32_t i = 0; i < tensorNameCount; i++) {
+ copyString(pGraphArgumentProperties->associated_tensor_names[i], ZE_MAX_GRAPH_ARGUMENT_NAME,
+ tensorNames.at(i));
+ }
+
+ const auto friendlyName =
+ descriptor->nodeFriendlyName.empty() ? descriptor->nameFromCompiler : descriptor->nodeFriendlyName;
+ copyString(pGraphArgumentMetadata->friendly_name, ZE_MAX_GRAPH_ARGUMENT_NAME, friendlyName);
+ copyString(pGraphArgumentMetadata->input_name, ZE_MAX_GRAPH_ARGUMENT_NAME, descriptor->nameFromCompiler);
+
+ for (uint32_t i = 0; i < MAX_GRAPH_TENSOR_REF_DIMS; ++i) {
+ pGraphArgumentMetadata->shape[i] = 0;
+ }
+
+ const auto& metadataShape = descriptor->shapeFromIRModel.has_value() ? descriptor->shapeFromIRModel.value()
+ : descriptor->shapeFromCompiler;
+ const auto metadataRank = metadataShape.rank();
+ if (metadataRank.is_static()) {
+ const auto rankLength = static_cast<size_t>(metadataRank.get_length());
+ const auto cappedRank = std::min(rankLength, static_cast<size_t>(MAX_GRAPH_TENSOR_REF_DIMS));
+ pGraphArgumentMetadata->shape_size = static_cast<uint32_t>(cappedRank);
+
+ uint32_t shapeIdx = 0;
+ for (const auto& dim : metadataShape) {
+ if (shapeIdx >= pGraphArgumentMetadata->shape_size) {
+ break;
+ }
+ pGraphArgumentMetadata->shape[shapeIdx] = dim.is_dynamic() ? std::numeric_limits<uint64_t>::max()
+ : static_cast<uint64_t>(dim.get_length());
+ ++shapeIdx;
+ }
+ } else {
+ pGraphArgumentMetadata->shape_size = 0;
+ }
+ // NOLINTEND
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while getting metadata: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ } catch (...) {
+ NPU_VM_LOG_ERROR("Unknown exception while getting metadata");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeExecute(npu_vm_runtime_handle_t hRuntime,
+ npu_vm_runtime_execute_params_t* pParams) {
+ if (hRuntime == nullptr || pParams == nullptr || pParams->executionContext == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto engine = reinterpret_cast<npu_vm_engine*>(pParams->executionContext);
+ if (npu_vm_reset_state(engine, /*resetExecutionContext=*/true) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to reset engine state before inference");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ if (npu_vm_infer(engine, pParams) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Inference failed for the given parameters");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while executing model: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimePredictOutputShape(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_predict_output_shape_params_t* pParams) {
+ if (hRuntime == nullptr || hRuntime->module == nullptr || pParams == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ // Note: Create a temporary instance of the engine to call the output shape prediction function, since this
+ // function is called before the execution context is created. Ideally, the execution context should be created
+ // before output shape prediction, but it requires changes in NPU plugin flow, so this temporary instance is
+ // used. If the execution engine creation is moved before output shape prediction in the future, this code can
+ // be simplified by reusing the same engine instance (via npu_vm_runtime_handle_t)
+ npu_vm_engine* engine = nullptr;
+ if (npu_vm_new_engine(&engine) != NPU_VM_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ if (npu_vm_load_module(engine, /*moduleParams*/ nullptr, hRuntime->module) != NPU_VM_SUCCESS) {
+ npu_vm_destroy_engine(engine);
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ npu_vm_runtime_predict_output_shape_params_t2 params2 = {};
+ params2.pInputs = pParams->pInputs;
+ params2.numOfInputs = pParams->numOfInputs;
+ params2.pOutputs = pParams->pOutputs;
+ params2.numOfOutputs = pParams->numOfOutputs;
+ // Execution context is not available at this point, and the output shape prediction function should not require
+ // it
+ params2.executionContext = nullptr;
+ if (npu_vm_predict_output_shape(engine, &params2) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Output shape prediction failed for the given parameters");
+ npu_vm_destroy_engine(engine);
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ if (npu_vm_destroy_engine(engine) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy engine after output shape prediction");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while executing output shape prediction: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimePredictOutputShape2(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_predict_output_shape_params_t2* pParams) {
+ if (hRuntime == nullptr || pParams == nullptr || pParams->executionContext == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto* engine = reinterpret_cast<npu_vm_engine*>(pParams->executionContext);
+ // Note: The execution context state is not reset, as it will be reset when the main inference takes place (i.e.
+ // when npuVMRuntimeExecute is called)
+ if (npu_vm_reset_state(engine, /*resetExecutionContext=*/false) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to reset engine state before output shape prediction");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ if (npu_vm_predict_output_shape(engine, pParams) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Output shape prediction failed for the given parameters");
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while executing output shape prediction: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeCreateMemRef(int64_t dimsCount, npu_vm_runtime_mem_ref_handle_t* phMemRef) {
+ if (phMemRef == nullptr || dimsCount <= 0) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
+ auto handle = new (std::nothrow) npu_vm_runtime_mem_ref(dimsCount);
+ if (handle == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ *phMemRef = reinterpret_cast<npu_vm_runtime_mem_ref_handle_t>(handle);
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeDestroyMemRef(npu_vm_runtime_mem_ref_handle_t hMemRef) {
+ if (hMemRef == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto memRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(hMemRef);
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
+ delete memRef;
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeSetMemRef(npu_vm_runtime_mem_ref_handle_t hMemRef,
+ const void* basePtr, const void* data,
+ int64_t offset, int64_t* pSizes,
+ int64_t* pStrides, int64_t dimsCount) {
+ if (hMemRef == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto memRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(hMemRef);
+ if (dimsCount != memRef->dimsCount) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNSUPPORTED_DIM_COUNT;
+ }
+
+ memRef->dirtyFlags = static_cast<uint32_t>(intel_npu::vm::MemRef::DirtyFlag::NONE);
+ if (memRef->basePtr != basePtr || memRef->data != data) {
+ memRef->basePtr = basePtr;
+ memRef->data = data;
+ memRef->dirtyFlags |= static_cast<uint32_t>(intel_npu::vm::MemRef::DirtyFlag::BUFFER_PTR);
+ }
+
+ if (memRef->offset != offset) {
+ memRef->offset = offset;
+ memRef->dirtyFlags |= static_cast<uint32_t>(intel_npu::vm::MemRef::DirtyFlag::OFFSET);
+ }
+
+ // NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)
+ if (pSizes == nullptr) {
+ if (memRef->sizes.size() != static_cast<size_t>(dimsCount)) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ } else {
+ std::copy(pSizes, pSizes + dimsCount, memRef->sizes.begin());
+ memRef->dirtyFlags |= static_cast<uint32_t>(intel_npu::vm::MemRef::DirtyFlag::SIZES);
+ }
+
+ if (pStrides == nullptr) {
+ if (memRef->strides.size() != static_cast<size_t>(dimsCount)) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ } else {
+ std::copy(pStrides, pStrides + dimsCount, memRef->strides.begin());
+ memRef->dirtyFlags |= static_cast<uint32_t>(intel_npu::vm::MemRef::DirtyFlag::STRIDES);
+ }
+ // NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeParseMemRef(npu_vm_runtime_mem_ref_handle_t hMemRef, const void** pBasePtr, const void** pData,
+ int64_t* pOffset, int64_t* pSizes, int64_t* pStrides, int64_t* pDimsCount) {
+ if (hMemRef == nullptr || pBasePtr == nullptr || pData == nullptr || pOffset == nullptr || pSizes == nullptr ||
+ pStrides == nullptr || pDimsCount == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto memRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(hMemRef);
+ *pBasePtr = memRef->basePtr;
+ *pData = memRef->data;
+ *pOffset = memRef->offset;
+ std::copy(memRef->sizes.begin(), memRef->sizes.end(), pSizes);
+ std::copy(memRef->strides.begin(), memRef->strides.end(), pStrides);
+ *pDimsCount = memRef->dimsCount;
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreateExecutionContext(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execution_context_handle_t* phExecutionHandle) {
+ if (hRuntime == nullptr || hRuntime->module == nullptr || phExecutionHandle == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ // The execution context is represented by an instance of the VM engine, whose lifetime is managed by the
+ // npuVMRuntimeCreateExecutionContext and npuVMRuntimeDestroyExecutionContext functions. In the end-to-end flow, the
+ // engine is created once per inference request, then reused for subsequent inferences
+ npu_vm_engine* engine = nullptr;
+ if (npu_vm_new_engine(&engine) != NPU_VM_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ if (npu_vm_load_module(engine, /*moduleParams*/ nullptr, hRuntime->module) != NPU_VM_SUCCESS) {
+ npu_vm_destroy_engine(engine);
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ *phExecutionHandle = reinterpret_cast<npu_vm_runtime_execution_context_handle_t>(engine);
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeDestroyExecutionContext(npu_vm_runtime_execution_context_handle_t phExecutionHandle) {
+ if (phExecutionHandle == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto engine = reinterpret_cast<npu_vm_engine*>(phExecutionHandle);
+ if (npu_vm_destroy_engine(engine) != NPU_VM_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeUpdateMutableCommandList(npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execute_params_t* pParams,
+ uint64_t* argIndexArray, uint64_t /*argIndexArraySize*/) {
+ if (hRuntime == nullptr || pParams == nullptr || argIndexArray == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ // TODO: implement mutable command list update
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeCreate2(const npu_vm_runtime_blob_desc_t* desc, const npu_vm_runtime_config_desc_t* pConfig,
+ npu_vm_runtime_handle_t* phRuntime, npu_vm_runtime_properties_t* pProperties) {
+ if (npuVMRuntimeCreate(desc, phRuntime, pProperties) != NPU_VM_RUNTIME_RESULT_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ const npu_vm_runtime_config_desc_t* curConfig = pConfig;
+ auto& cmdQueueDesc = (*phRuntime)->commandQueueDesc;
+ (*phRuntime)->commandQueues.resize(MAX_COMMAND_QUEUE_PRIORITIES);
+ while (curConfig) {
+ switch (curConfig->type) {
+ case NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY: {
+ if (curConfig->value >= MAX_COMMAND_QUEUE_PRIORITIES) {
+ NPU_VM_LOG_ERROR("Invalid queue priority value: {}", curConfig->value);
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_VALUE;
+ }
+ cmdQueueDesc.priority = static_cast<ze_command_queue_priority_t>(curConfig->value);
+ break;
+ };
+ case NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE: {
+ cmdQueueDesc.workload_type = static_cast<ze_command_queue_workload_type_t>(curConfig->value);
+ break;
+ };
+ case NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_OPTIONS: {
+ cmdQueueDesc.option_flags = static_cast<uint32_t>(curConfig->value);
+ break;
+ };
+ default:
+ NPU_VM_LOG_WARN("Unknown config type: {}", curConfig->type);
+ break;
+ }
+ curConfig = curConfig->pNext;
+ }
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL npuVMRuntimeCreateExecutionContext2(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_create_execution_context_params_t* pParams,
+ npu_vm_runtime_execution_context_handle_t* phExecutionHandle) {
+ if (hRuntime == nullptr || hRuntime->module == nullptr || pParams == nullptr || phExecutionHandle == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ hRuntime->device = pParams->device;
+ hRuntime->context = pParams->ctx;
+ hRuntime->commandQueueDdiTableExt = pParams->commandQueueDdiTableExt;
+
+ if (pParams->commandQueue == nullptr && hRuntime->commandQueue == nullptr) {
+ std::lock_guard<std::mutex> lock(hRuntime->mutex);
+ // check if command queue was created again
+ if (hRuntime->commandQueue == nullptr) {
+ // Create an internal command queue if none is provided in the parameters and none is stored in the runtime
+ // handle
+ ze_command_queue_handle_t commandQueue = nullptr;
+ if (createCmdQueue(hRuntime, &commandQueue) != ZE_RESULT_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ // Stores the command queue according to priority [0..2]
+ hRuntime->commandQueues[static_cast<uint32_t>(hRuntime->commandQueueDesc.priority)] = commandQueue;
+ hRuntime->commandQueue = commandQueue;
+ }
+ }
+
+ bool counterBasedEventSupported = false;
+ // The counter based event is supported only on Windows platform for now.
+ // Once all function calls replaced with openvino::zero_loader functions,
+ // the counter based event will be supported on Linux platform as well.
+ auto graphDdiTableExt = pParams->graphDdiTableExt;
+ if (graphDdiTableExt != nullptr && graphDdiTableExt->pfnCompilerIsOptionSupported != nullptr) {
+ counterBasedEventSupported = graphDdiTableExt->pfnCompilerIsOptionSupported(
+ pParams->device, ZE_NPU_DRIVER_OPTIONS, "COUNTER_BASED_EVENTS",
+ nullptr) == ZE_RESULT_SUCCESS;
+ }
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ const char* envVar = std::getenv("NPU_VM_RUNTIME_DISABLE_COUNTER_BASED_EVENT");
+ if (envVar != nullptr && counterBasedEventSupported) {
+ counterBasedEventSupported = !::intel_npu::OptionParser<bool>::parse(envVar);
+ }
+#endif
+
+ // The execution context is represented by an instance of the VM engine, whose lifetime is managed by the
+ // npuVMRuntimeCreateExecutionContext and npuVMRuntimeDestroyExecutionContext functions. In the end-to-end flow, the
+ // engine is created once per inference request, then reused for subsequent inferences
+ npu_vm_engine* engine = nullptr;
+ if (npu_vm_new_engine(&engine) != NPU_VM_SUCCESS) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ npu_vm_result result = {};
+ npu_vm_module_load_params module_load_params = {};
+ module_load_params.concurrentJobCount = 1;
+ // The reason for checking numStream != 0, there was a bug to set numStream to 0 in the metadata,
+ // which is not correct. The correct value should be 1 for single tile and >1 for multi-tile.
+ if (hRuntime->metadata.numStreams != 0) {
+ // Checks whether a blob is compiled for single tile.
+ ze_device_properties_t deviceProperties{};
+ ::intel_npu::zeDeviceGetProperties(pParams->device, &deviceProperties);
+ if (deviceProperties.numSlices > 1 && hRuntime->metadata.numStreams == 1) {
+ // The blob is compiled for single tile, but the device has multiple slices.
+ // In this case, we need to set the number of tiles to concurrentJobCount
+ // for concurrent execution.
+ module_load_params.concurrentJobCount = deviceProperties.numSlices;
+
+ NPU_VM_LOG_INFO("Concurrent job count: {}", module_load_params.concurrentJobCount);
+ }
+ }
+
+ module_load_params.counterBasedEventSupported = counterBasedEventSupported;
+ module_load_params.batchMode = hRuntime->batchMode;
+ module_load_params.batchSize = hRuntime->batchSize;
+ if (pParams->commandQueue == nullptr) {
+ // need to use an internally created command queue.
+ npu_vm_runtime_create_execution_context_params_t params = *pParams;
+ params.commandQueue = hRuntime->commandQueue;
+ module_load_params.create_execution_context_params = &params;
+ module_load_params.internalCommandQueue = true;
+ result = npu_vm_load_module(engine, &module_load_params, hRuntime->module);
+ } else {
+ // when command queue is shared, npu plugin will pass a valid command queue in pParams,
+ // so we can use it directly.
+ module_load_params.create_execution_context_params = pParams;
+ module_load_params.internalCommandQueue = false;
+ result = npu_vm_load_module(engine, &module_load_params, hRuntime->module);
+ }
+
+ if (result != NPU_VM_SUCCESS) {
+ npu_vm_destroy_engine(engine);
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ *phExecutionHandle = reinterpret_cast<npu_vm_runtime_execution_context_handle_t>(engine);
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeExecute2(npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execute_params2_t* pParams) {
+ if (hRuntime == nullptr || pParams == nullptr || pParams->executionContext == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ bool recordingRequired = true;
+ try {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ const bool useInternalCmdQueue = pParams->commandQueue == nullptr;
+ if (useInternalCmdQueue) {
+ if (pParams->pConfig) {
+ // update configuration of an internal command queue
+ configCmdQueue(hRuntime, pParams->pConfig);
+ }
+
+ pParams->commandQueue = hRuntime->commandQueue;
+ }
+
+ auto engine = reinterpret_cast<npu_vm_engine*>(pParams->executionContext);
+ // checks whether the command list needs to be recorded or not.
+ // If the command list is already recorded, we can skip the recording step
+ // and directly submit the recorded command list for execution.
+ recordingRequired = npu_vm_host_code_execution_required(engine, pParams);
+ auto result = NPU_VM_RUNTIME_RESULT_SUCCESS;
+ if (recordingRequired) {
+ if (npu_vm_reset_state(engine, /*resetExecutionContext=*/true) == NPU_VM_SUCCESS) {
+ if (npu_vm_infer2(engine, pParams) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Inference failed for the given parameters");
+ result = NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ } else {
+ NPU_VM_LOG_ERROR("Failed to reset engine state before inference");
+ result = NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ } else {
+ // submit recorded command lists
+ if (npu_vm_submit_recorded_command_lists(engine, pParams) != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to submit recorded command lists for the given parameters");
+ result = NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+ }
+
+ if (useInternalCmdQueue) {
+ // reset command queue handle
+ pParams->commandQueue = nullptr;
+ }
+
+ if (result != NPU_VM_RUNTIME_RESULT_SUCCESS) {
+ return result;
+ }
+
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Exception while executing model: {}", e.what());
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ if (recordingRequired) {
+ // Reset dirty bits for all input and output memrefs after execution
+ // for avoiding unnecessary commandlist recording
+ for (uint32_t i = 0; i < pParams->numOfInputs; ++i) {
+ auto memRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(pParams->pInputs[i]);
+ memRef->resetDirtyBits();
+ }
+
+ for (uint32_t i = 0; i < pParams->numOfOutputs; ++i) {
+ auto memRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(pParams->pOutputs[i]);
+ memRef->resetDirtyBits();
+ }
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+DLLEXPORT npu_vm_runtime_result_t NPU_VM_RUNTIME_APICALL
+npuVMRuntimeHostSync(npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execute_params2_t* pParams) {
+ if (hRuntime == nullptr || pParams == nullptr || pParams->executionContext == nullptr) {
+ return NPU_VM_RUNTIME_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+
+ auto engine = reinterpret_cast<npu_vm_engine*>(pParams->executionContext);
+
+ const auto result = npu_vm_host_sync(engine);
+ if (result != NPU_VM_SUCCESS) {
+ NPU_VM_LOG_ERROR("Host sync failed for the given parameters: {}", result);
+ return NPU_VM_RUNTIME_RESULT_ERROR_UNKNOWN;
+ }
+
+ return NPU_VM_RUNTIME_RESULT_SUCCESS;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/allocator_core.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/allocator_core.hpp
new file mode 100644
index 00000000000..7c9c3ef9887
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/allocator_core.hpp
@@ -0,0 +1,121 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "vm_export.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <type_traits>
+#include <utility>
+
+// Core allocator abstraction. `Block` is the currency every allocator hands out; `AnyAllocator` is the
+// type-erased handle BufferManager holds over any value type modeling the Allocator concept:
+// Block allocate(size_t bytes); // null Block on failure; on success Block.size == bytes exactly --
+// // BufferManager budgets and bounds buffers by it, so never round up
+// void deallocate(Block block); // noexcept; per-block release (may be a no-op)
+// bool owns(Block block); // noexcept (const); true if this allocator would release the block
+// void recycle(); // noexcept; reclaim everything for reuse, keeping memory
+// void release(); // noexcept; free all underlying memory
+//
+// composable_allocators.hpp splits this into two roles so neither carries a no-op release(): a Backing owns
+// OS/device memory and hands out whole chunks (HostAllocator, LevelZeroAllocator); a SubAllocator carves one
+// borrowed chunk into sub-blocks for routing but no release(). GrowingArena ties a Backing to a per-chunk
+// SubAllocator into a full Allocator, and routes deallocations through SubAllocator::owns(). Each role
+// advertises a `static constexpr size_t ALIGNMENT`: a Backing's chunk-base guarantee, a SubAllocator's
+// sub-block stride.
+
+namespace intel_npu::vm {
+
+struct Block {
+ uint8_t* ptr = nullptr;
+ size_t size = 0;
+ explicit operator bool() const noexcept {
+ return ptr != nullptr;
+ }
+};
+
+// Type-erased, move-only owning handle for any Allocator value type, modeled on std::any/std::function:
+// the concrete allocator is stored behind a private interface so BufferManager need not be templated.
+class NPU_VM_EXPORT AnyAllocator {
+ class Concept {
+ public:
+ Concept() = default;
+ Concept(const Concept&) = delete;
+ Concept& operator=(const Concept&) = delete;
+ Concept(Concept&&) = delete;
+ Concept& operator=(Concept&&) = delete;
+ virtual ~Concept() = default;
+ virtual Block allocate(size_t bytes) = 0;
+ virtual void deallocate(Block block) noexcept = 0;
+ virtual bool owns(Block block) const noexcept = 0;
+ virtual void recycle() noexcept = 0;
+ virtual void release() noexcept = 0;
+ };
+
+ template <class A>
+ class Model final : public Concept {
+ A _allocator;
+
+ public:
+ explicit Model(A allocator): _allocator(std::move(allocator)) {
+ }
+ Block allocate(size_t bytes) override {
+ return _allocator.allocate(bytes);
+ }
+ void deallocate(Block block) noexcept override {
+ _allocator.deallocate(block);
+ }
+ bool owns(Block block) const noexcept override {
+ return _allocator.owns(block);
+ }
+ void recycle() noexcept override {
+ _allocator.recycle();
+ }
+ void release() noexcept override {
+ _allocator.release();
+ }
+ };
+
+ std::unique_ptr<Concept> _impl;
+
+public:
+ // Empty handle; converts to false. BufferManager rejects an empty allocator.
+ AnyAllocator() = default;
+
+ // Constrained so this never shadows the move constructor.
+ template <class A, class = std::enable_if_t<!std::is_same_v<std::decay_t<A>, AnyAllocator>>>
+ AnyAllocator(A allocator): _impl(std::make_unique<Model<std::decay_t<A>>>(std::move(allocator))) {
+ }
+
+ Block allocate(size_t bytes) {
+ return _impl ? _impl->allocate(bytes) : Block{};
+ }
+ void deallocate(Block block) noexcept {
+ if (_impl) {
+ _impl->deallocate(block);
+ }
+ }
+ bool owns(Block block) const noexcept {
+ return _impl ? _impl->owns(block) : false;
+ }
+ void recycle() noexcept {
+ if (_impl) {
+ _impl->recycle();
+ }
+ }
+ void release() noexcept {
+ if (_impl) {
+ _impl->release();
+ }
+ }
+
+ explicit operator bool() const noexcept {
+ return _impl != nullptr;
+ }
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.cpp
new file mode 100644
index 00000000000..62fcd0f41b8
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.cpp
@@ -0,0 +1,248 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "buffer.hpp"
+#include "allocator_core.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <iterator>
+#include <new>
+#include <stdexcept>
+#include <utility>
+
+intel_npu::vm::Buffer::Buffer(uint8_t* data, size_t size, Permission permission, Ownership ownership)
+ : _data(data), _size(size), _permission(permission), _ownership(ownership) {
+}
+
+const uint8_t* intel_npu::vm::Buffer::getData() const {
+ return _data;
+}
+
+size_t intel_npu::vm::Buffer::getSize() const {
+ return _size;
+}
+
+intel_npu::vm::Permission intel_npu::vm::Buffer::getPermission() const {
+ return _permission;
+}
+
+intel_npu::vm::Ownership intel_npu::vm::Buffer::getOwnership() const {
+ return _ownership;
+}
+
+void intel_npu::vm::Buffer::readData(size_t offset, uint8_t* data, size_t size) const {
+ if (size == 0) {
+ return;
+ }
+ if (_data == nullptr) {
+ throw std::runtime_error("Buffer data pointer is null");
+ }
+ if (_permission != Permission::ReadWrite && _permission != Permission::Read) {
+ throw std::runtime_error("Buffer does not have read permission");
+ }
+ if (offset > _size || size > _size - offset) {
+ throw std::out_of_range("Read exceeds buffer bounds");
+ }
+ std::memcpy(data, std::next(_data, static_cast<std::ptrdiff_t>(offset)), size);
+}
+
+void intel_npu::vm::Buffer::writeData(size_t offset, const uint8_t* data, size_t size) {
+ // std::memcpy takes size_t, so copies whose size does not fit in size_t cannot be performed on this host.
+ static_assert(sizeof(size_t) >= sizeof(int64_t), "Bytecode buffer copies require a 64-bit size_t");
+ if (size == 0) {
+ return;
+ }
+ if (_data == nullptr) {
+ throw std::runtime_error("Buffer data pointer is null");
+ }
+ if (_permission != Permission::ReadWrite) {
+ throw std::runtime_error("Buffer does not have write permission");
+ }
+ if (offset > _size || size > _size - offset) {
+ throw std::out_of_range("Write exceeds buffer bounds");
+ }
+ std::memcpy(std::next(_data, static_cast<std::ptrdiff_t>(offset)), data, size);
+}
+
+void intel_npu::vm::Buffer::copyDataFrom(const Buffer& source) {
+ if (_permission != Permission::ReadWrite) {
+ throw std::runtime_error("Destination buffer does not have write permission");
+ }
+ if (source._permission != Permission::ReadWrite && source._permission != Permission::Read) {
+ throw std::runtime_error("Source buffer does not have read permission");
+ }
+ if (_size != source._size) {
+ throw std::invalid_argument("Buffer copy requires equal buffer sizes");
+ }
+ if (_size == 0) {
+ return;
+ }
+ if (_data == nullptr || source._data == nullptr) {
+ throw std::runtime_error("Buffer data pointer is null");
+ }
+ std::memmove(_data, source._data, _size);
+}
+
+intel_npu::vm::BufferHandle intel_npu::vm::BufferManager::BufferHandleManager::getNextHandle() {
+ return ++_lastHandle;
+}
+
+intel_npu::vm::BufferHandle intel_npu::vm::BufferManager::generateBufferHandle() {
+ return _handleManager.getNextHandle();
+}
+
+void intel_npu::vm::BufferManager::deallocateOwnedBuffers() noexcept {
+ if (!_allocator) {
+ return; // moved-from manager: _buffers is empty, nothing to free
+ }
+ for (auto& entry : _buffers) {
+ auto& buffer = entry.second;
+ if (buffer.getOwnership() == Ownership::Owned) {
+ _allocator.deallocate(Block{buffer.rawData(), buffer.getSize()});
+ }
+ }
+}
+
+void intel_npu::vm::BufferManager::recycle() noexcept {
+ // Free the Owned-buffer storage, then let the allocator reclaim its pool (see recycle() in buffer.hpp).
+ deallocateOwnedBuffers();
+ if (_allocator) {
+ _allocator.recycle();
+ }
+ _buffers.clear();
+ _derivedBuffers.clear();
+ _currentMemorySize = 0;
+}
+
+intel_npu::vm::BufferManager::BufferManager(size_t maximumMemorySize, AnyAllocator allocator)
+ : _maximumMemorySize(maximumMemorySize), _allocator(std::move(allocator)) {
+ if (!_allocator) {
+ throw std::invalid_argument("BufferManager: allocator must not be null");
+ }
+}
+
+intel_npu::vm::BufferManager& intel_npu::vm::BufferManager::operator=(BufferManager&& other) noexcept {
+ if (this != &other) {
+ // Free our current Owned buffers before overwriting members: deallocateOwnedBuffers() reads the
+ // current _allocator/_buffers, so it must run before _allocator is moved out.
+ deallocateOwnedBuffers();
+ _maximumMemorySize = other._maximumMemorySize;
+ _currentMemorySize = other._currentMemorySize;
+ _handleManager = other._handleManager;
+ _allocator = std::move(other._allocator);
+ // Moving the maps destroys the just-freed view entries (no double free) and adopts other's buffers.
+ _buffers = std::move(other._buffers);
+ _derivedBuffers = std::move(other._derivedBuffers);
+ }
+ return *this;
+}
+
+intel_npu::vm::BufferManager::~BufferManager() {
+ // Free the storage of any Owned buffers still held (see deallocateOwnedBuffers).
+ deallocateOwnedBuffers();
+}
+
+intel_npu::vm::BufferHandle intel_npu::vm::BufferManager::create(size_t size, Permission permission,
+ bool zeroInitialized) {
+ if (size == 0) {
+ throw std::invalid_argument("Buffer size must be greater than 0");
+ }
+ if (size > _maximumMemorySize || _currentMemorySize > _maximumMemorySize - size) {
+ throw std::bad_alloc();
+ }
+
+ const auto block = _allocator.allocate(size);
+ if (!block) {
+ throw std::bad_alloc();
+ }
+
+ // By default, owned buffers are zero-initialized so recycled memory never exposes bytes from a previous execution.
+ // Zeroing out the allocated memory causes significant performance overhead for large buffers.
+ // Callers may opt out (zeroInitialized=true) only when the buffer is guaranteed to be initialized
+ if (!zeroInitialized) {
+ std::memset(block.ptr, 0, block.size);
+ }
+
+ const auto bufferHandle = generateBufferHandle();
+ try {
+ _buffers.emplace(bufferHandle, Buffer(block.ptr, block.size, permission, Ownership::Owned));
+ } catch (...) {
+ _allocator.deallocate(block);
+ throw;
+ }
+ _currentMemorySize += size;
+ return bufferHandle;
+}
+
+intel_npu::vm::BufferHandle intel_npu::vm::BufferManager::createFromMemory(uint8_t* externalData, size_t size,
+ Permission permission) {
+ if (externalData == nullptr) {
+ throw std::invalid_argument("External data pointer cannot be null");
+ }
+ if (size == 0) {
+ throw std::invalid_argument("Buffer size must be greater than 0");
+ }
+ const auto handle = generateBufferHandle();
+ _buffers.emplace(handle, Buffer(externalData, size, permission, Ownership::Unowned));
+ return handle;
+}
+
+intel_npu::vm::BufferHandle intel_npu::vm::BufferManager::createFromBuffer(intel_npu::vm::BufferHandle handle,
+ size_t offset, size_t size) {
+ auto& buffer = this->getBuffer(handle);
+ const auto bufferSize = buffer.getSize();
+ if (offset > bufferSize || size > bufferSize - offset) {
+ throw std::out_of_range("Requested offset and size exceeds buffer bounds");
+ }
+ const auto newData = std::next(buffer.rawData(), static_cast<std::ptrdiff_t>(offset));
+ const auto newHandle = generateBufferHandle();
+ _buffers.emplace(newHandle, Buffer(newData, size, buffer.getPermission(), Ownership::Unowned));
+ _derivedBuffers[handle].push_back(newHandle);
+ return newHandle;
+}
+
+void intel_npu::vm::BufferManager::deleteBuffer(intel_npu::vm::BufferHandle handle) {
+ // Recursively delete all buffers derived from this one via createFromBuffer.
+ // Children that were already explicitly deleted are skipped.
+ auto childrenIt = _derivedBuffers.find(handle);
+ if (childrenIt != _derivedBuffers.end()) {
+ // Copy the children list before iterating, as each recursive call modifies _derivedBuffers
+ const auto children = childrenIt->second;
+ for (const auto child : children) {
+ if (exists(child)) {
+ deleteBuffer(child);
+ }
+ }
+ _derivedBuffers.erase(handle);
+ }
+
+ auto& buffer = this->getBuffer(handle);
+ if (buffer.getOwnership() == Ownership::Owned) {
+ _currentMemorySize -= buffer.getSize();
+ _allocator.deallocate(Block{buffer.rawData(), buffer.getSize()});
+ }
+ _buffers.erase(handle);
+}
+
+bool intel_npu::vm::BufferManager::exists(intel_npu::vm::BufferHandle handle) const {
+ return _buffers.find(handle) != _buffers.end();
+}
+
+intel_npu::vm::Buffer& intel_npu::vm::BufferManager::getBuffer(intel_npu::vm::BufferHandle handle) {
+ return const_cast<Buffer&>(std::as_const(*this).getBuffer(handle));
+}
+
+const intel_npu::vm::Buffer& intel_npu::vm::BufferManager::getBuffer(intel_npu::vm::BufferHandle handle) const {
+ auto it = _buffers.find(handle);
+ if (it == _buffers.end()) {
+ throw std::invalid_argument("Invalid buffer handle");
+ }
+ return it->second;
+}
+
+size_t intel_npu::vm::BufferManager::getCurrentMemorySize() const {
+ return _currentMemorySize;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.hpp
new file mode 100644
index 00000000000..f78a52754d3
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer.hpp
@@ -0,0 +1,177 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "allocator_core.hpp"
+#include "vm_export.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+namespace intel_npu::vm {
+
+using BufferHandle = uint64_t;
+
+// Logical budget cap enforced by BufferManager (sum of owned-buffer sizes), not an eager allocation.
+inline constexpr uint64_t DEFAULT_BUFFER_MEMORY_LIMIT_BYTES = uint64_t{1} << 32; // 4 GiB
+
+enum class NPU_VM_EXPORT Permission : uint8_t {
+ Read = 0,
+ ReadWrite = 1,
+};
+
+enum class NPU_VM_EXPORT Ownership : uint8_t {
+ Owned = 0,
+ Unowned = 1,
+};
+
+class NPU_VM_EXPORT Buffer {
+ // BufferManager owns the storage of Owned buffers and needs a mutable pointer to free the block and to carve
+ // derived views. Granting it friendship keeps that mutable access internal -- teardown does not go through
+ // const_cast -- while the public API stays read-only (getData() returns const).
+ friend class BufferManager;
+
+ uint8_t* _data = nullptr;
+ size_t _size = 0;
+ Permission _permission;
+ Ownership _ownership;
+
+ // Mutable view of the storage, for BufferManager-only teardown and derivation (see the friend declaration).
+ uint8_t* rawData() noexcept {
+ return _data;
+ }
+
+public:
+ // Construct a view over an already-allocated region. BufferManager owns and releases storage for
+ // buffers tagged Ownership::Owned.
+ Buffer(uint8_t* data, size_t size, Permission permission, Ownership ownership = Ownership::Unowned);
+
+ // Disable copy operations to prevent unintended shallow copies.
+ Buffer(const Buffer&) = delete;
+ Buffer& operator=(const Buffer&) = delete;
+
+ // A Buffer is a non-owning view (BufferManager releases owned storage), so the destructor has nothing to release.
+ // Moves transfer the view and clear the source, so moved-from objects are explicit empty views.
+ // The moves and destructor are written out (rather than `= default`) so all five special members are explicitly
+ // user-provided -- Coverity's rule-of-three/five checker does not count a `= default`ed member as
+ // user-provided, so leaving them defaulted alongside the deleted copies trips it.
+ Buffer(Buffer&& other) noexcept
+ : _data(std::exchange(other._data, nullptr)),
+ _size(std::exchange(other._size, 0)),
+ _permission(other._permission),
+ _ownership(other._ownership) {
+ }
+ Buffer& operator=(Buffer&& other) noexcept {
+ if (this != &other) {
+ _data = std::exchange(other._data, nullptr);
+ _size = std::exchange(other._size, 0);
+ _permission = other._permission;
+ _ownership = other._ownership;
+ }
+ return *this;
+ }
+ ~Buffer() { // NOLINT(modernize-use-equals-default): user-provided, not `= default`, per the note above
+ }
+
+ const uint8_t* getData() const;
+
+ size_t getSize() const;
+
+ Permission getPermission() const;
+
+ Ownership getOwnership() const;
+
+ void readData(size_t offset, uint8_t* data, size_t size) const;
+
+ void writeData(size_t offset, const uint8_t* data, size_t size);
+
+ void copyDataFrom(const Buffer& source);
+};
+
+class NPU_VM_EXPORT BufferManager {
+ class BufferHandleManager {
+ BufferHandle _lastHandle = 0;
+
+ public:
+ BufferHandle getNextHandle();
+ };
+
+ size_t _maximumMemorySize{};
+ size_t _currentMemorySize{};
+ BufferHandleManager _handleManager{};
+ AnyAllocator _allocator;
+ std::unordered_map<BufferHandle, Buffer> _buffers;
+ std::unordered_map<BufferHandle, std::vector<BufferHandle>> _derivedBuffers;
+
+ BufferHandle generateBufferHandle();
+
+ // Deallocates every Owned buffer's storage through _allocator. Unowned buffers (external memory and
+ // derived views) are left untouched. Does not modify the buffer maps or the budget; callers do that.
+ void deallocateOwnedBuffers() noexcept;
+
+public:
+ // Create a buffer manager, which manages the creation, deletion and access for buffers
+ // The buffer manager keeps track of the total allocated memory size, and does not allow creation of new buffers if
+ // the total size exceeds the given maximum memory size. Owned buffers are obtained from the given allocator.
+ //
+ // Allocator contract: the manager reclaims Owned-buffer storage by calling allocator.deallocate() on every owned
+ // block and then allocator.recycle() (in recycle()); it tracks no storage of its own. The allocator must therefore
+ // release every outstanding block through that sequence. A per-block leaf reclaims each block in deallocate(); an
+ // arena whose deallocate() only pops the most recent block must reclaim the remainder in recycle(). An allocator
+ // that does neither would leak the dropped buffers.
+ BufferManager(size_t maximumMemorySize, AnyAllocator allocator);
+ BufferManager(const BufferManager&) = delete;
+ BufferManager& operator=(const BufferManager&) = delete;
+ // Move assignment and the destructor must first free this object's own Owned buffers (the move
+ // constructor leaves the source empty, so its later destruction frees nothing), hence they are
+ // user-defined rather than defaulted.
+ BufferManager(BufferManager&&) = default;
+ BufferManager& operator=(BufferManager&&) noexcept;
+ ~BufferManager();
+
+ // Allocates a buffer of the given size. Returns a handle to the buffer
+ // Throws std::invalid_argument if the requested size is zero
+ // Throws std::bad_alloc if the requested size exceeds the maximum memory size
+ BufferHandle create(size_t size, Permission permission = Permission::ReadWrite, bool zeroInitialized = false);
+
+ // Create a buffer from external memory. Returns a handle to the created buffer
+ // This buffer does not contribute to the memory size tracked by the buffer manager, as the memory
+ // is external
+ // Throws std::invalid_argument if the external data pointer is null or if the size is zero
+ BufferHandle createFromMemory(uint8_t* externalData, size_t size, Permission permission);
+
+ // Create a buffer from another buffer that references a subset of the original buffer's memory. Returns a handle to
+ // the new buffer. The new buffer does not own the memory, and its permission is the same as the original buffer
+ // Throws std::invalid_argument if the original handle is invalid
+ // Throws std::out_of_range if the offset and size exceed the bounds of the original buffer
+ BufferHandle createFromBuffer(BufferHandle handle, size_t offset, size_t size);
+
+ // Deletes the buffer associated with the given handle. Does not deallocate memory for unowned buffers.
+ // If the buffer has derived buffers created via createFromBuffer, those are recursively deleted first.
+ // Throws std::invalid_argument if the handle is invalid
+ void deleteBuffer(BufferHandle handle);
+
+ // Returns true if a buffer with the given handle exists, false otherwise
+ bool exists(BufferHandle handle) const;
+
+ // Returns a reference to the buffer associated with the given handle
+ // Throws std::invalid_argument if the handle is invalid
+ Buffer& getBuffer(BufferHandle handle);
+
+ const Buffer& getBuffer(BufferHandle handle) const;
+
+ // Drops every buffer and rewinds the allocator's pool for reuse WITHOUT releasing it, so the next
+ // inference reuses the same memory. (With an arena the per-buffer frees are no-ops and the rewind keeps
+ // the memory; with a leaf the frees reclaim and the rewind is a no-op.) The handle counter stays
+ // monotonic, so stale handles are not reused.
+ void recycle() noexcept;
+
+ size_t getCurrentMemorySize() const;
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.cpp
new file mode 100644
index 00000000000..08ad6f9c79c
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.cpp
@@ -0,0 +1,122 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "buffer_metadata.hpp"
+#include "math.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <optional>
+#include <string_view>
+#include <vector>
+
+std::optional<uint64_t> intel_npu::vm::computeMaxLinearOffset(const intel_npu::vm::BufferMetadata& meta) {
+ if (meta.shape.size() != meta.strides.size()) {
+ return std::nullopt;
+ }
+ uint64_t offset = 0;
+ for (size_t i = 0; i < meta.shape.size(); ++i) {
+ if (meta.shape.at(i) <= 0 || meta.strides.at(i) < 0) {
+ return std::nullopt;
+ }
+ const auto extent = static_cast<uint64_t>(meta.shape.at(i) - 1);
+ const auto stride = static_cast<uint64_t>(meta.strides.at(i));
+ if (!checkedAddProduct(extent, stride, offset)) {
+ return std::nullopt;
+ }
+ }
+ return offset;
+}
+
+std::optional<uint64_t> intel_npu::vm::computeLogicalByteSize(const intel_npu::vm::BufferMetadata& meta) {
+ const auto maxLinearOffset = computeMaxLinearOffset(meta);
+ if (!maxLinearOffset.has_value() || meta.elemByteSize == 0) {
+ return std::nullopt;
+ }
+ if (*maxLinearOffset == std::numeric_limits<uint64_t>::max()) {
+ return std::nullopt;
+ }
+ const auto elementCount = *maxLinearOffset + 1;
+ uint64_t byteSize = 0;
+ if (!checkedMultiply(elementCount, static_cast<uint64_t>(meta.elemByteSize), byteSize)) {
+ return std::nullopt;
+ }
+ return byteSize;
+}
+
+std::optional<uint64_t> intel_npu::vm::computeSubviewStartElement(const intel_npu::vm::BufferMetadata& srcMeta,
+ const std::vector<int64_t>& offsets,
+ const std::vector<int64_t>& sizes,
+ const std::vector<int64_t>& strides) {
+ const auto rank = offsets.size();
+ if (sizes.size() != rank || strides.size() != rank) {
+ NPU_VM_LOG_ERROR("buffer.subview expected offsets, sizes and strides to have the same rank, got {} for "
+ "offsets, {} for sizes and {} for strides",
+ rank, sizes.size(), strides.size());
+ return std::nullopt;
+ }
+ if (srcMeta.shape.size() != rank || srcMeta.strides.size() != rank) {
+ NPU_VM_LOG_ERROR("buffer.subview source metadata rank mismatch: subview rank={}, source shape rank={}, source "
+ "stride rank={}",
+ rank, srcMeta.shape.size(), srcMeta.strides.size());
+ return std::nullopt;
+ }
+
+ uint64_t startElem = 0;
+ for (size_t dimIdx = 0; dimIdx < rank; ++dimIdx) {
+ if (offsets.at(dimIdx) < 0 || sizes.at(dimIdx) <= 0 || strides.at(dimIdx) < 0 ||
+ srcMeta.strides.at(dimIdx) < 0 || offsets.at(dimIdx) >= srcMeta.shape.at(dimIdx)) {
+ NPU_VM_LOG_ERROR("buffer.subview invalid offsets/sizes/strides at dim {}: offset={}, size={}, stride={}, "
+ "source shape={}, source stride={}",
+ dimIdx, offsets.at(dimIdx), sizes.at(dimIdx), strides.at(dimIdx), srcMeta.shape.at(dimIdx),
+ srcMeta.strides.at(dimIdx));
+ return std::nullopt;
+ }
+ uint64_t stridedExtent = 0;
+ if (!checkedMultiply(static_cast<uint64_t>(sizes.at(dimIdx) - 1), static_cast<uint64_t>(strides.at(dimIdx)),
+ stridedExtent) ||
+ static_cast<uint64_t>(offsets.at(dimIdx)) > std::numeric_limits<uint64_t>::max() - stridedExtent) {
+ NPU_VM_LOG_ERROR("buffer.subview index overflows at dim {}: offset={}, size={}, stride={}", dimIdx,
+ offsets.at(dimIdx), sizes.at(dimIdx), strides.at(dimIdx));
+ return std::nullopt;
+ }
+ const auto lastIndex = static_cast<uint64_t>(offsets.at(dimIdx)) + stridedExtent;
+ if (lastIndex >= static_cast<uint64_t>(srcMeta.shape.at(dimIdx))) {
+ NPU_VM_LOG_ERROR("buffer.subview exceeds source shape at dim {}: last index={}, source shape={}", dimIdx,
+ lastIndex, srcMeta.shape.at(dimIdx));
+ return std::nullopt;
+ }
+ const auto srcStride = static_cast<uint64_t>(srcMeta.strides.at(dimIdx));
+ if (!checkedAddProduct(static_cast<uint64_t>(offsets.at(dimIdx)), srcStride, startElem)) {
+ NPU_VM_LOG_ERROR("buffer.subview byte offset overflows at dim {}: offset={}, source stride={}", dimIdx,
+ offsets.at(dimIdx), srcStride);
+ return std::nullopt;
+ }
+ }
+ return startElem;
+}
+
+bool intel_npu::vm::validateShapeAndStrides(std::string_view opName, const intel_npu::vm::BufferMetadata& meta) {
+ if (meta.shape.size() != meta.strides.size()) {
+ NPU_VM_LOG_ERROR("{} metadata rank mismatch: shape rank={}, stride rank={}", opName, meta.shape.size(),
+ meta.strides.size());
+ return false;
+ }
+ if (meta.shape.size() > static_cast<size_t>(std::numeric_limits<int64_t>::max())) {
+ NPU_VM_LOG_ERROR("{} metadata rank exceeds int64_t range: rank={}", opName, meta.shape.size());
+ return false;
+ }
+ const auto rank = static_cast<int64_t>(meta.shape.size());
+ for (int64_t dim = 0; dim < rank; ++dim) {
+ const auto dimIdx = static_cast<size_t>(dim);
+ if (meta.shape.at(dimIdx) <= 0 || meta.strides.at(dimIdx) < 0) {
+ NPU_VM_LOG_ERROR("{} requires positive shape and non-negative strides, got dim {}: shape={}, stride={}",
+ opName, dim, meta.shape.at(dimIdx), meta.strides.at(dimIdx));
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.hpp
new file mode 100644
index 00000000000..492d5400b66
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/buffer_metadata.hpp
@@ -0,0 +1,33 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "vm_export.hpp"
+
+#include <cstdint>
+#include <optional>
+#include <string_view>
+#include <vector>
+
+namespace intel_npu::vm {
+
+// Bytecode-level metadata for a buffer handle. The underlying memory is owned by the BufferManager;
+// this struct tracks the rank, shape, strides and element-type index that the bytecode operates on.
+struct NPU_VM_EXPORT BufferMetadata {
+ int64_t elemTypeIndex{}; // Index into the type section
+ std::vector<int64_t> shape; // Shape per dimension (rank == shape.size())
+ std::vector<int64_t> strides; // Stride (in elements) per dimension; same length as shape
+ uint16_t elemByteSize{}; // Element size in bytes, derived from elemTypeIndex on creation
+};
+
+std::optional<uint64_t> NPU_VM_EXPORT computeMaxLinearOffset(const BufferMetadata& meta);
+std::optional<uint64_t> NPU_VM_EXPORT computeLogicalByteSize(const BufferMetadata& meta);
+std::optional<uint64_t> NPU_VM_EXPORT computeSubviewStartElement(const BufferMetadata& srcMeta,
+ const std::vector<int64_t>& offsets,
+ const std::vector<int64_t>& sizes,
+ const std::vector<int64_t>& strides);
+bool NPU_VM_EXPORT validateShapeAndStrides(std::string_view opName, const BufferMetadata& meta);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.cpp
new file mode 100644
index 00000000000..fad5c3ac2a4
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.cpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "call_frame.hpp"
+#include "function.hpp"
+#include "npu_bytecode_utils/except.hpp"
+
+#include <cstdint>
+#include <cstring>
+#include <utility>
+#include <vector>
+
+intel_npu::vm::CallFrame::CallFrame(const Function& function, const uint8_t* returnAddress,
+ std::vector<int64_t*> results)
+ : _function(&function),
+ _registers(function.getNumGeneralRegisters(), 0),
+ _returnAddress(returnAddress),
+ _results(std::move(results)) {
+}
+
+const intel_npu::vm::Function& intel_npu::vm::CallFrame::getFunction() const {
+ return *_function;
+}
+
+int64_t& intel_npu::vm::CallFrame::getReg(int16_t index) {
+ if (index < 0 || static_cast<size_t>(index) >= _registers.size()) {
+ NPU_VM_THROW("Register index {} is out of bounds for register count {}", index, _registers.size());
+ }
+ return _registers.at(index);
+}
+
+void intel_npu::vm::CallFrame::setReg(int16_t index, int64_t value) {
+ if (index < 0 || static_cast<size_t>(index) >= _registers.size()) {
+ NPU_VM_THROW("Register index {} is out of bounds for register count {}", index, _registers.size());
+ }
+ _registers.at(index) = value;
+}
+
+const uint8_t* intel_npu::vm::CallFrame::getReturnAddress() const {
+ return _returnAddress;
+}
+
+std::vector<int64_t*>& intel_npu::vm::CallFrame::getResults() {
+ return _results;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.hpp
new file mode 100644
index 00000000000..4c62fec80a4
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/call_frame.hpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "function.hpp"
+#include "vm_export.hpp"
+
+#include <cstdint>
+#include <vector>
+
+namespace intel_npu::vm {
+
+constexpr const uint8_t* EXIT_RETURN_ADDR = nullptr;
+
+class NPU_VM_EXPORT CallFrame {
+ const Function* _function; // The function executing in this call frame
+ std::vector<int64_t> _registers; // The register set for the current function call, indexed by register number
+ const uint8_t* _returnAddress; // The return address to jump to after this function call completes
+ std::vector<int64_t*> _results; // Sinks that RETV writes its return values into (owned by the caller)
+
+public:
+ CallFrame(const Function& function, const uint8_t* returnAddress, std::vector<int64_t*> results);
+
+ // Returns the function executing in this call frame
+ const Function& getFunction() const;
+
+ // Returns a mutable reference to the register at the given index.
+ // Throws a runtime error if the index exceeds the register count.
+ int64_t& getReg(int16_t index);
+
+ // Sets the register at the given index to the specified value.
+ // Throws a runtime error if the index exceeds the register count.
+ void setReg(int16_t index, int64_t value);
+
+ // Returns the address to return to after the function call completes
+ const uint8_t* getReturnAddress() const;
+
+ // Returns the result sinks that RETV writes its return values into
+ std::vector<int64_t*>& getResults();
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/composable_allocators.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/composable_allocators.hpp
new file mode 100644
index 00000000000..eb877820678
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/composable_allocators.hpp
@@ -0,0 +1,219 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "allocator_core.hpp"
+
+#include <algorithm>
+#include <cstddef>
+#include <iterator>
+#include <limits>
+#include <utility>
+#include <vector>
+
+namespace intel_npu::vm {
+
+// Rounds up to the next multiple of `alignment`: sizes a block's footprint so the next block starts aligned.
+// Returns 0 to signal overflow (no multiple of `alignment` is representable >= `value`), so callers refuse the
+// allocation instead of proceeding with a footprint that wrapped to a smaller multiple (which would walk the
+// bump cursor backwards). Callers guard `bytes == 0` before calling, so a 0 result is unambiguously the sentinel.
+inline size_t alignUp(size_t value, size_t alignment) noexcept {
+ if (alignment <= 1) {
+ return value;
+ }
+ if (value > std::numeric_limits<size_t>::max() - (alignment - 1)) {
+ return 0; // overflow: no representable aligned footprint; callers treat 0 as failure
+ }
+ return (value + alignment - 1) / alignment * alignment;
+}
+
+// Carves aligned sub-blocks out of one fixed chunk it does NOT own. `Alignment` is the sub-block alignment,
+// advertised as a `static constexpr` so a composing parent (GrowingArena) can size chunks to it.
+template <size_t Alignment>
+class BumpRegion {
+ static_assert(Alignment >= 1, "BumpRegion: Alignment must be at least 1");
+
+ Block _chunk; // borrowed; the arena owns this chunk and frees it
+ size_t _high{}; // next free offset
+public:
+ static constexpr size_t ALIGNMENT = Alignment;
+
+ explicit BumpRegion(Block chunk): _chunk(chunk) {
+ }
+
+ Block allocate(size_t bytes) {
+ if (bytes == 0 || !_chunk) {
+ return Block{};
+ }
+ const size_t start = _high;
+ // Reserve the aligned footprint so the next block starts aligned. alignUp returns 0 if that footprint
+ // overflows size_t; refusing it (rather than clamping to the chunk end) keeps `_high` on a footprint
+ // boundary, so deallocate() can pop even the last block in the chunk. A non-zero footprint is never
+ // < bytes, so the same bound check covers the raw-size check too.
+ const size_t footprint = alignUp(bytes, Alignment);
+ if (footprint == 0 || footprint > _chunk.size - start) {
+ return Block{};
+ }
+ _high = start + footprint;
+ return Block{std::next(_chunk.ptr, static_cast<std::ptrdiff_t>(start)), bytes};
+ }
+
+ // Pops a block only if it is the most recent hand-out: its footprint reaches the cursor.
+ void deallocate(Block block) noexcept {
+ if (!owns(block)) {
+ return;
+ }
+ const auto start = static_cast<size_t>(block.ptr - _chunk.ptr);
+ if (start + alignUp(block.size, Alignment) == _high) {
+ _high = start;
+ }
+ }
+
+ bool owns(Block block) const noexcept {
+ return block.ptr != nullptr && _chunk.ptr != nullptr && block.ptr >= _chunk.ptr &&
+ block.ptr < std::next(_chunk.ptr, static_cast<std::ptrdiff_t>(_chunk.size));
+ }
+
+ void recycle() noexcept {
+ _high = 0; // rewind; the chunk is kept for reuse next inference
+ }
+};
+
+// Grows a set of sub-allocators, each carving one chunk from a single `Backing`. `InitialSlabBytes`/
+// `MaxSlabBytes` tune slab growth; alignment comes from `SubAllocator::ALIGNMENT`, not a parameter.
+template <class Backing, class SubAllocator, size_t InitialSlabBytes, size_t MaxSlabBytes>
+class GrowingArena {
+ static_assert(InitialSlabBytes > 0, "GrowingArena: InitialSlabBytes must be greater than 0");
+
+ // The only alignment the arena needs: to size each chunk to the sub-allocator's footprint. The chunk
+ // base alignment is the backing's responsibility.
+ static constexpr size_t ALIGNMENT = SubAllocator::ALIGNMENT;
+
+ // Sub-block offsets are multiples of SubAllocator::ALIGNMENT, but absolute alignment holds only if every
+ // chunk base is too -- so Backing::ALIGNMENT must be a multiple of it, else carved blocks are silently
+ // under-aligned.
+ static_assert(Backing::ALIGNMENT % SubAllocator::ALIGNMENT == 0,
+ "GrowingArena: Backing::ALIGNMENT must be a multiple of SubAllocator::ALIGNMENT, "
+ "otherwise carved sub-blocks are not aligned to SubAllocator::ALIGNMENT");
+
+public:
+ explicit GrowingArena(Backing backing): _backing(std::move(backing)), _nextSlabBytes(InitialSlabBytes) {
+ }
+
+ // Move-only and non-reassignable. AnyAllocator stores the arena by value, so it must be move-constructible;
+ // the move constructor is written out (rather than `= default`) so all five special members are explicitly
+ // user-provided. Assignment is deleted because a memberwise move would overwrite `_slabs` without first
+ // freeing the destination's chunks, leaking them; copying an owning arena is meaningless.
+ GrowingArena(GrowingArena&& other) noexcept
+ : _backing(std::move(other._backing)),
+ _nextSlabBytes(other._nextSlabBytes),
+ _slabs(std::move(other._slabs)) {
+ }
+ GrowingArena(const GrowingArena&) = delete;
+ GrowingArena& operator=(GrowingArena&&) = delete;
+ GrowingArena& operator=(const GrowingArena&) = delete;
+
+ ~GrowingArena() {
+ freeChunks(); // the arena owns the chunks; nothing else frees them
+ }
+
+ Block allocate(size_t bytes) {
+ if (bytes == 0) {
+ return Block{};
+ }
+ // First-fit so a small request can reuse the tail of an earlier slab a larger one skipped.
+ for (auto& slab : _slabs) {
+ if (Block block = slab.subAllocator.allocate(bytes)) {
+ return block;
+ }
+ }
+ // Size the chunk to the aligned footprint, not raw `bytes`: the sub-allocator reserves that footprint
+ // and would refuse a chunk merely `bytes` long when `bytes` is not a multiple of the alignment.
+ const size_t footprint = alignUp(bytes, ALIGNMENT);
+ if (footprint == 0) {
+ return Block{}; // footprint overflowed size_t; no chunk can satisfy the request
+ }
+ const size_t want = std::max(footprint, _nextSlabBytes);
+ Block chunk = _backing.allocate(want);
+ if (!chunk) {
+ return Block{};
+ }
+ try {
+ SubAllocator subAllocator{chunk};
+ Block block = subAllocator.allocate(bytes);
+ if (!block) {
+ _backing.deallocate(chunk); // a fresh chunk could not satisfy the request
+ return Block{};
+ }
+ _slabs.push_back(Slab{chunk, std::move(subAllocator)});
+ growNextSlabBytes();
+ return block;
+ } catch (...) {
+ _backing.deallocate(chunk); // don't leak the chunk if the bookkeeping push throws
+ return Block{};
+ }
+ }
+
+ void deallocate(Block block) noexcept {
+ for (auto& slab : _slabs) {
+ if (slab.subAllocator.owns(block)) {
+ slab.subAllocator.deallocate(block);
+ return;
+ }
+ }
+ }
+
+ // True if the block was carved from one of this arena's chunks (i.e. some sub-allocator owns it).
+ bool owns(Block block) const noexcept {
+ for (const auto& slab : _slabs) {
+ if (slab.subAllocator.owns(block)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void recycle() noexcept {
+ for (auto& slab : _slabs) {
+ slab.subAllocator.recycle(); // rewind, keep the chunk for reuse
+ }
+ }
+
+ void release() noexcept {
+ freeChunks();
+ _slabs.clear();
+ _nextSlabBytes = InitialSlabBytes;
+ }
+
+private:
+ struct Slab {
+ Block chunk; // allocated from _backing
+ SubAllocator subAllocator; // carves `chunk`; owns no memory of its own
+ };
+
+ void freeChunks() noexcept {
+ for (auto& slab : _slabs) {
+ _backing.deallocate(slab.chunk);
+ }
+ }
+
+ void growNextSlabBytes() noexcept {
+ if (MaxSlabBytes != 0 && _nextSlabBytes >= MaxSlabBytes) {
+ _nextSlabBytes = MaxSlabBytes;
+ return;
+ }
+ if (_nextSlabBytes > std::numeric_limits<size_t>::max() / 2) {
+ return; // overflow guard: keep the current size
+ }
+ const size_t doubled = _nextSlabBytes * 2;
+ _nextSlabBytes = (MaxSlabBytes != 0) ? std::min(doubled, MaxSlabBytes) : doubled;
+ }
+
+ Backing _backing; // sole owner of chunk memory; chunks are allocated and freed through it
+ size_t _nextSlabBytes; // next slab size; starts at InitialSlabBytes, grows toward MaxSlabBytes
+ std::vector<Slab> _slabs; // chunk + the sub-allocator carving it, in growth order
+};
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.cpp
new file mode 100644
index 00000000000..7d9c44f699b
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.cpp
@@ -0,0 +1,144 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "function.hpp"
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+intel_npu::vm::Function::Function(std::string name, uint64_t numGeneralRegisters, bool isEntrypoint,
+ std::vector<FuncParamResType> paramTypes, std::vector<FuncParamResType> resultTypes,
+ intel_npu::vm::Span<uint8_t> body, bool copyBody)
+ : _name(std::move(name)),
+ _numGeneralRegisters(numGeneralRegisters),
+ _isEntrypoint(isEntrypoint),
+ _paramTypes(std::move(paramTypes)),
+ _resultTypes(std::move(resultTypes)),
+ _body(body, copyBody) {
+}
+
+bool intel_npu::vm::Function::ownsBody() const {
+ return _body.isOwned();
+}
+
+std::string intel_npu::vm::Function::getName() const {
+ return _name;
+}
+
+uint64_t intel_npu::vm::Function::getNumGeneralRegisters() const {
+ return _numGeneralRegisters;
+}
+
+bool intel_npu::vm::Function::isEntrypoint() const {
+ return _isEntrypoint;
+}
+
+const std::vector<intel_npu::vm::FuncParamResType>& intel_npu::vm::Function::getParamTypes() const {
+ return _paramTypes;
+}
+
+const std::vector<intel_npu::vm::FuncParamResType>& intel_npu::vm::Function::getResultTypes() const {
+ return _resultTypes;
+}
+
+intel_npu::vm::Span<const uint8_t> intel_npu::vm::Function::getBody() const {
+ return _body.get();
+}
+
+bool intel_npu::vm::Function::parseInstructionOffsets() {
+ _instructionOffsets.clear();
+ const auto body = _body.get();
+ const auto begin = body.begin();
+ const auto totalSize = body.size();
+
+ size_t offset = 0;
+ while (offset < totalSize) {
+ const auto remaining = totalSize - offset;
+ if (remaining < intel_npu::vm::OPCODE_SIZE) {
+ NPU_VM_LOG_ERROR("Function '{}' body is malformed: cannot read opcode at offset {}", _name, offset);
+ return false;
+ }
+ const auto* instructionBegin = std::next(begin, static_cast<std::ptrdiff_t>(offset));
+ const auto opcode = intel_npu::vm::getOpcode(instructionBegin);
+
+ const auto instructionSize = intel_npu::vm::getInstructionSize(opcode, instructionBegin, remaining);
+ if (!instructionSize.has_value() || instructionSize.value() == 0) {
+ NPU_VM_LOG_ERROR(
+ "Function '{}' body is malformed: failed to determine instruction size at offset {} (unknown "
+ "opcode {} or truncated instruction)",
+ _name, offset, static_cast<uint16_t>(opcode));
+ return false;
+ }
+ if (remaining < instructionSize.value()) {
+ NPU_VM_LOG_ERROR("Function '{}' body is malformed: instruction at offset {} exceeds body bounds", _name,
+ offset);
+ return false;
+ }
+
+ _instructionOffsets.insert(offset);
+ offset += instructionSize.value();
+ }
+ return true;
+}
+
+bool intel_npu::vm::Function::isValidInstructionOffset(size_t offset) const {
+ return _instructionOffsets.count(offset) != 0;
+}
+
+std::optional<intel_npu::vm::FuncParamResType> intel_npu::vm::extractFuncParamResType(
+ intel_npu::vm::BytecodeReader& reader, size_t typeIndex) {
+ auto typeEntry = reader.getDataSectionEntry(intel_npu::vm::SectionType::TypeSection, typeIndex);
+ if (typeEntry.empty()) {
+ NPU_VM_LOG_ERROR("Failed to retrieve type entry for type index {}", typeIndex);
+ return std::nullopt;
+ }
+
+ const auto typeCode = static_cast<intel_npu::vm::TypeCode>(typeEntry.at(0));
+ if (typeCode == intel_npu::vm::TypeCode::INTEGER) {
+ intel_npu::vm::IntegerType intType{};
+ typeEntry = typeEntry.subspan(sizeof(intel_npu::vm::TypeCode));
+ if (!intType.parseFrom(typeEntry)) {
+ NPU_VM_LOG_ERROR("Failed to parse IntegerType from type entry for type index {}", typeIndex);
+ return std::nullopt;
+ }
+ return FuncParamResType{intel_npu::vm::Type{intType}, static_cast<int64_t>(typeIndex)};
+ } else if (typeCode == intel_npu::vm::TypeCode::FLOAT) {
+ intel_npu::vm::FloatType floatType{};
+ typeEntry = typeEntry.subspan(sizeof(intel_npu::vm::TypeCode));
+ if (!floatType.parseFrom(typeEntry)) {
+ NPU_VM_LOG_ERROR("Failed to parse FloatType from type entry for type index {}", typeIndex);
+ return std::nullopt;
+ }
+ return FuncParamResType{intel_npu::vm::Type{floatType}, static_cast<int64_t>(typeIndex)};
+ } else if (typeCode == intel_npu::vm::TypeCode::OPAQUE) {
+ intel_npu::vm::OpaqueType opaqueType{};
+ typeEntry = typeEntry.subspan(sizeof(intel_npu::vm::TypeCode));
+ if (!opaqueType.parseFrom(typeEntry)) {
+ NPU_VM_LOG_ERROR("Failed to parse OpaqueType from type entry for type index {}", typeIndex);
+ return std::nullopt;
+ }
+ return FuncParamResType{intel_npu::vm::Type{opaqueType}, static_cast<int64_t>(typeIndex)};
+ } else if (typeCode == intel_npu::vm::TypeCode::BUFFER) {
+ intel_npu::vm::BufferType bufferType{};
+ typeEntry = typeEntry.subspan(sizeof(intel_npu::vm::TypeCode));
+ if (!bufferType.parseFrom(typeEntry)) {
+ NPU_VM_LOG_ERROR("Failed to parse BufferType from type entry for type index {}", typeIndex);
+ return std::nullopt;
+ }
+ return FuncParamResType{intel_npu::vm::Type{bufferType}, static_cast<int64_t>(typeIndex)};
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported type code {} for type index {}", static_cast<uint64_t>(typeCode), typeIndex);
+ return std::nullopt;
+ }
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.hpp
new file mode 100644
index 00000000000..ae8d394bc3b
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/function.hpp
@@ -0,0 +1,82 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/managed_vector.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "vm_export.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+namespace intel_npu::vm {
+
+struct NPU_VM_EXPORT FuncParamResType {
+ intel_npu::vm::Type type{};
+ int64_t typeSectionIndex{};
+};
+
+class NPU_VM_EXPORT Function {
+ std::string _name; // Human-readable function name
+ uint64_t _numGeneralRegisters; // Number of general-purpose registers used by the function
+ bool _isEntrypoint; // True if this function is the bytecode entry point
+ std::vector<FuncParamResType> _paramTypes; // Types of the function parameters
+ std::vector<FuncParamResType> _resultTypes; // Types of the function result values
+ ManagedVector<uint8_t> _body; // Raw instruction bytes representing the function body
+ std::unordered_set<size_t> _instructionOffsets; // Body-relative offsets where each instruction starts
+
+public:
+ /// Constructs a Function object with the given name, register count, entrypoint flag, parameter and result types,
+ /// and instruction body. If copyBody is true, the Function object will make an owned copy of the body bytes;
+ /// otherwise, it will reference the provided body bytes directly. The body bytes must remain valid for the lifetime
+ /// of the Function object if copyBody is false.
+ Function(std::string name, uint64_t numGeneralRegisters, bool isEntrypoint,
+ std::vector<FuncParamResType> paramTypes, std::vector<FuncParamResType> resultTypes, Span<uint8_t> body,
+ bool copyBody = false);
+
+ /// Returns true if the Function object owns the body bytes (i.e., it made a copy of them), false otherwise
+ bool ownsBody() const;
+
+ /// Get the name of the function
+ std::string getName() const;
+
+ /// Get the number of general-purpose registers that the function uses
+ uint64_t getNumGeneralRegisters() const;
+
+ /// Returns true if this function is the bytecode entry point (i.e. the function that should be called externally to
+ /// execute the bytecode)
+ bool isEntrypoint() const;
+
+ /// Get the parameter types of the function
+ const std::vector<FuncParamResType>& getParamTypes() const;
+
+ /// Get the result types of the function
+ const std::vector<FuncParamResType>& getResultTypes() const;
+
+ /// Get the raw instruction bytes representing the function body
+ Span<const uint8_t> getBody() const;
+
+ /// Walks the function body once and records the body-relative byte offset of every instruction start.
+ /// Populates the internal instruction-offset table used by jump-target validation. Must be called before
+ /// executing the function. Returns false if the body is malformed and cannot be fully decoded.
+ bool parseInstructionOffsets();
+
+ /// Returns true if the given body-relative byte offset corresponds to the start of an instruction.
+ bool isValidInstructionOffset(size_t offset) const;
+};
+
+// Extracts a function parameter or result type from the type section given its index. The type is expected to be a
+// primitive type (integer, float, opaque or buffer). The return value contains the extracted type and its original
+// index in the type section
+std::optional<FuncParamResType> NPU_VM_EXPORT extractFuncParamResType(intel_npu::vm::BytecodeReader& reader,
+ size_t typeIndex);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.cpp
new file mode 100644
index 00000000000..8c466c060bf
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.cpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "host_allocator.hpp"
+#include "allocator_core.hpp"
+#include "composable_allocators.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <new>
+
+intel_npu::vm::Block intel_npu::vm::HostAllocator::allocate(size_t bytes) {
+ // operator new[] takes size_t, so buffers whose size does not fit in size_t cannot be allocated on this host.
+ static_assert(sizeof(size_t) >= sizeof(int64_t), "Bytecode buffer allocation requires a 64-bit size_t");
+ // Reject empty requests up front: new[] may hand back a unique non-null pointer for a zero-size
+ // allocation, which would make the returned Block evaluate true. Mirror BumpRegion/LevelZeroAllocator
+ // and report a null Block so `if (block)` stays a reliable success check.
+ if (bytes == 0) {
+ return Block{};
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
+ auto* ptr = new (std::nothrow) uint8_t[bytes];
+ if (ptr == nullptr) {
+ return Block{};
+ }
+ return Block{ptr, bytes};
+}
+
+void intel_npu::vm::HostAllocator::deallocate(Block block) noexcept {
+ if (block.ptr == nullptr) {
+ return;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
+ delete[] block.ptr;
+}
+
+intel_npu::vm::AnyAllocator intel_npu::vm::makeHostAllocator() {
+ // GrowingArena of BumpRegions over the host heap. No device-visibility requirement, so sub-blocks need
+ // only natural alignment.
+ return AnyAllocator{
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, DEFAULT_HOST_ARENA_INITIAL_SLAB_BYTES,
+ DEFAULT_HOST_ARENA_MAX_SLAB_BYTES>(HostAllocator{})};
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.hpp
new file mode 100644
index 00000000000..12c48c816a2
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/host_allocator.hpp
@@ -0,0 +1,37 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "allocator_core.hpp"
+#include "vm_export.hpp"
+
+#include <cstddef>
+#include <cstdint>
+
+namespace intel_npu::vm {
+
+// Leaf over the host heap (new[]/delete[]), used as a GrowingArena backing by makeHostAllocator.
+// recycle()/release() are no-ops: the heap retains nothing and frees per-block in deallocate().
+class NPU_VM_EXPORT HostAllocator {
+public:
+ // Chunk-base alignment this backing guarantees: new[] returns max_align_t-aligned storage.
+ static constexpr size_t ALIGNMENT = alignof(std::max_align_t);
+
+ Block allocate(size_t bytes);
+ void deallocate(Block block) noexcept;
+};
+
+// Tuning for the default host GrowingArena. It grows on demand (doubling each slab toward the cap) and reuses
+// slabs, so the initial size need not match the working set. Kept small so a first allocation of a few small
+// buffers (e.g. output-shape prediction / metadata) does not eagerly reserve tens of MiB; a larger first
+// request still gets a chunk sized to it.
+inline constexpr uint64_t DEFAULT_HOST_ARENA_INITIAL_SLAB_BYTES = uint64_t{1} << 20; // 1 MiB
+inline constexpr uint64_t DEFAULT_HOST_ARENA_MAX_SLAB_BYTES = uint64_t{64} << 20; // 64 MiB
+
+// Host allocator: a GrowingArena of BumpRegions over the host heap, mirroring makeLevelZeroAllocator's
+// shape. Used on the no-device path (output-shape prediction / offline execute) and by the unit tests.
+NPU_VM_EXPORT AnyAllocator makeHostAllocator();
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.cpp
new file mode 100644
index 00000000000..216085a22bf
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.cpp
@@ -0,0 +1,1334 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "kernel_execution.hpp"
+#include <ze_api.h>
+#include <ze_graph_ext.h>
+#include <ze_graph_profiling_ext.h>
+#include "intel_npu/config/config.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <cstdlib>
+#include <iterator>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+using namespace intel_npu::vm;
+
+namespace {
+result_t success() {
+ return ZE_RESULT_SUCCESS;
+}
+
+template <typename... Args>
+void failureLogImpl(std::string_view format, Args... args) {
+ NPU_VM_LOG_ERROR(format, args...);
+}
+
+template <typename... Args>
+result_t failure(result_t errorCode, const std::string& format, Args... args) {
+ failureLogImpl(format + ": {}", args..., errorCode);
+ return errorCode;
+}
+
+int32_t setArguments(uint32_t index, const BufferMapperItem& desc, ze_graph_handle_t graphHandle,
+ ze_graph_dditable_ext_t* graphDdiTable, bool supportsDynamicStrides) {
+ ze_result_t result = ZE_RESULT_SUCCESS;
+
+ auto buffer = desc.first;
+ auto bufferMetadata = desc.second;
+
+ // where to get buffer offset
+ uint64_t offsetInElements = 0;
+ const auto byteOffset = static_cast<std::ptrdiff_t>(bufferMetadata->elemByteSize * offsetInElements);
+ auto address = std::next(buffer->getData(), byteOffset);
+
+ if (ZE_GRAPH_EXT_VERSION_CURRENT >= ZE_GRAPH_EXT_VERSION_1_15) {
+ // Below is an example implementation.
+ // When a new graph ext is available in master, this will be finalized.
+
+ ze_graph_argument_value_tensor_t tensorValue{ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_TENSOR, nullptr, address};
+
+ // Only attach strides when the driver reported this graph argument expects dynamic strides;
+ // otherwise the argument is bound without stride metadata.
+ // tensorStrides must be declared here, outside the `if` below, so it stays alive until
+ // pfnSetArgumentValue2 is called
+ ze_graph_argument_value_strides_t tensorStrides = {};
+ if (supportsDynamicStrides) {
+ tensorStrides.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_STRIDES;
+ tensorStrides.pNext = nullptr;
+ auto& strides = bufferMetadata->strides;
+ if (strides.size() > ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE) {
+ return failure(ZE_RESULT_ERROR_INVALID_SIZE,
+ "Buffer rank {} for argument {} exceeds ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE ({})",
+ strides.size(), index, ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE);
+ }
+ const size_t dimCount = strides.size();
+ for (size_t dim = 0; dim < dimCount; dim++) {
+ // store strides in reverse order
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) - index values are guaranteed above
+ tensorStrides.userStrides[dim] =
+ static_cast<uint32_t>(bufferMetadata->strides.at((dimCount - 1) - dim));
+ }
+ tensorValue.pNext = static_cast<void*>(&tensorStrides);
+ }
+ result = graphDdiTable->pfnSetArgumentValue2(graphHandle, index, &tensorValue);
+ } else {
+ result = graphDdiTable->pfnSetArgumentValue(graphHandle, index, address);
+ }
+
+ NPU_VM_LOG_TRACE("setArguments index={}, address={}, buffer={}, metadata={}, elemByteSize={}, "
+ "supportsDynamicStrides={}",
+ index, address, static_cast<void*>(buffer), static_cast<void*>(bufferMetadata),
+ bufferMetadata->elemByteSize, supportsDynamicStrides);
+ return result;
+}
+
+template <typename CmdListCreateImmediateT>
+result_t createImmediateCmdList(ze_context_handle_t context, ze_device_handle_t device, uint32_t groupOrdinal,
+ CmdListCreateImmediateT cmdListCreateFunc, ze_command_list_handle_t& handle) {
+ // currently, it is an experimental feature.
+ // Use specified command queue configuration will be ignored,
+ // and the command queue will be created with default configuration.
+ const ze_command_queue_mode_t mode = ZE_COMMAND_QUEUE_MODE_ASYNCHRONOUS;
+ const ze_command_queue_priority_t priority = ZE_COMMAND_QUEUE_PRIORITY_NORMAL;
+ ze_command_queue_desc_t queueDesc = {
+ ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC, nullptr, groupOrdinal, 0, /*flags*/ 0, mode, priority};
+ return cmdListCreateFunc(context, device, &queueDesc, &handle);
+}
+
+result_t executeGraphImmediate(ExecutionContext& executionContext, ze_graph_handle_t graphHandle, void* kernelName) {
+ if (graphHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid graph handle");
+ }
+
+ auto graphDdiTable = executionContext.getGraphDdiTable();
+ auto cmdListIndex = executionContext.getCurrentCmdListIndex();
+ auto cmdList = executionContext.getCmdList(cmdListIndex);
+ if (kernelName == nullptr) {
+ NPU_VM_LOG_TRACE("Executing graph for unnamed kernel at handle {}", graphHandle);
+ } else {
+ NPU_VM_LOG_TRACE("Executing graph for kernel {} at handle {} in cmdList {} and execContext {}",
+ static_cast<const char*>(kernelName), graphHandle, cmdList, &executionContext);
+ }
+
+ ze_pfnAppendGraphExecute_ext_t pfnAppendGraphExecute = graphDdiTable->pfnAppendGraphExecute;
+ ze_result_t result = ZE_RESULT_SUCCESS;
+ auto& eventPool = executionContext.getEventPool();
+ auto& waitEvents = eventPool.getWaitEvents();
+ auto signalEvent = eventPool.getSignalEvent();
+ result = pfnAppendGraphExecute(cmdList, graphHandle, nullptr, signalEvent, static_cast<uint32_t>(waitEvents.size()),
+ const_cast<ze_event_handle_t*>(waitEvents.data()));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append graph execute in command list: {}, kern: {}, numWaits: {}", cmdList,
+ graphHandle, waitEvents.size());
+ }
+
+ NPU_VM_LOG_TRACE("Executed graph for kernel: {}", graphHandle);
+
+ return success();
+}
+
+result_t executeGraphCmdListPool(ExecutionContext& executionContext, ze_graph_handle_t graphHandle, void* kernelName) {
+ if (graphHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid graph handle");
+ }
+ auto ddiTable = executionContext.getDdiTable();
+ auto graphDdiTable = executionContext.getGraphDdiTable();
+ auto cmdListIndex = executionContext.getCurrentCmdListIndex();
+ auto cmdList = executionContext.getCmdList(cmdListIndex);
+ if (kernelName == nullptr) {
+ NPU_VM_LOG_TRACE("Executing graph for unnamed kernel at handle {}", graphHandle);
+ } else {
+ NPU_VM_LOG_TRACE("Executing graph for kernel {} at handle {} in cmdList {} and execContext {}",
+ static_cast<const char*>(kernelName), graphHandle, cmdList, &executionContext);
+ }
+
+ ze_pfnAppendGraphExecute_ext_t pfnAppendGraphExecute = graphDdiTable->pfnAppendGraphExecute;
+ ze_result_t result = ZE_RESULT_SUCCESS;
+ auto& eventPool = executionContext.getEventPool();
+ auto& waitEvents = eventPool.getWaitEvents();
+ auto signalEvent = eventPool.getSignalEvent();
+
+ auto pfnCommandListReset = ddiTable->zeCommandListReset;
+ auto pfnCommandListClose = ddiTable->zeCommandListClose;
+ auto pfnCommandQueueExecuteCommandLists = ddiTable->zeCommandQueueExecuteCommandLists;
+ result = pfnCommandListReset(cmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to zeCommandListReset");
+ }
+ result = pfnAppendGraphExecute(cmdList, graphHandle, nullptr, signalEvent, static_cast<uint32_t>(waitEvents.size()),
+ const_cast<ze_event_handle_t*>(waitEvents.data()));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append graph execute in command list: {}, kern: {}, numWaits: {}", cmdList,
+ graphHandle, waitEvents.size());
+ }
+ result = pfnCommandListClose(cmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to close a command list");
+ }
+
+ result = pfnCommandQueueExecuteCommandLists(executionContext.getCommandQueue(), 1, &cmdList, nullptr);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result,
+ "Failed to zeCommandQueueExecuteCommandList with command queue: {}, command "
+ "list: {}",
+ executionContext.getCommandQueue(), cmdList);
+ }
+
+ NPU_VM_LOG_TRACE("Executed graph for kernel: {}", graphHandle);
+
+ return success();
+}
+
+result_t submitCmdListPool(ExecutionContext& executionContext, ze_command_list_handle_t, bool needHostSync) {
+ ze_fence_handle_t fence = nullptr;
+ ze_event_handle_t event = nullptr;
+ if (needHostSync) {
+ event = executionContext.getHostSyncEvent();
+ fence = executionContext.getHostSyncFence();
+
+ if (event != nullptr && fence != nullptr) {
+ // Both event and fence are provided, which is not expected
+ // as they serve similar synchronization purposes.
+ return failure(ZE_RESULT_ERROR_INVALID_ARGUMENT,
+ "Both event and fence are not nullptr(event: {}, fence: {})", event, fence);
+ }
+ }
+
+ auto commandQueue = executionContext.getCommandQueue();
+ // executionContext.in
+ // note command queue is null when immediate command list is used
+ auto& eventPool = executionContext.getEventPool();
+ eventPool.increaseSignalEventsArrayIndex();
+
+ auto ddiTable = executionContext.getDdiTable();
+ auto pfnCommandListReset = ddiTable->zeCommandListReset;
+ auto pfnCommandListAppendBarrier = ddiTable->zeCommandListAppendBarrier;
+ auto pfnCommandListClose = ddiTable->zeCommandListClose;
+ auto pfnCommandQueueExecuteCommandLists = ddiTable->zeCommandQueueExecuteCommandLists;
+ if (commandQueue != nullptr && event) {
+ auto cmdList = executionContext.getCmdList(executionContext.getCurrentCmdListIndex());
+ NPU_VM_LOG_TRACE("Submitting command list: {}, fence: {}, event: {}", cmdList, fence, event);
+ if (cmdList == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE,
+ "Invalid commandListHandle for submission, command queue: {}, fence: {}, event: {}",
+ commandQueue, fence, event);
+ }
+
+ auto& waitEvents = eventPool.getWaitEvents();
+ auto result = pfnCommandListReset(cmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to reset command list");
+ }
+
+ // For the last command list, event or fence will be not nullptr when host synchronization is needed
+ if (event != nullptr) {
+ // host sync with an event given by npu-plugin
+ result = pfnCommandListAppendBarrier(cmdList, event, static_cast<uint32_t>(waitEvents.size()),
+ const_cast<ze_event_handle_t*>(waitEvents.data()));
+
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to zeCommandListAppendBarrier");
+ }
+ }
+ result = pfnCommandListClose(cmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to zeCommandListClose");
+ }
+
+ result = pfnCommandQueueExecuteCommandLists(commandQueue, 1, &cmdList, fence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(
+ result,
+ "Failed to zeCommandQueueExecuteCommandList with event: {}, fence: {}, command queue: {}, command "
+ "list: {}",
+ event, fence, commandQueue, cmdList);
+ }
+ NPU_VM_LOG_TRACE("Submitted command list: {}", cmdList);
+ }
+ return success();
+}
+
+result_t submitCmdListImmediate(ExecutionContext& executionContext, ze_command_list_handle_t, bool needHostSync) {
+ ze_fence_handle_t fence = nullptr;
+ ze_event_handle_t event = nullptr;
+ if (needHostSync) {
+ event = executionContext.getHostSyncEvent();
+ fence = executionContext.getHostSyncFence();
+
+ if (event != nullptr && fence != nullptr) {
+ // Both event and fence are provided, which is not expected
+ // as they serve similar synchronization purposes.
+ return failure(ZE_RESULT_ERROR_INVALID_ARGUMENT,
+ "Both event and fence are not nullptr(event: {}, fence: {})", event, fence);
+ }
+ }
+
+ // make all signal events as wait events
+ auto& eventPool = executionContext.getEventPool();
+ eventPool.increaseSignalEventsArrayIndex();
+ result_t result = ZE_RESULT_SUCCESS;
+ if (event) {
+ auto ddiTable = executionContext.getDdiTable();
+ auto pfnCommandListAppendBarrier = ddiTable->zeCommandListAppendBarrier;
+ auto cmdList = executionContext.getCmdList(executionContext.getCurrentCmdListIndex());
+ auto& waitEvents = eventPool.getWaitEvents();
+ result =
+ pfnCommandListAppendBarrier(cmdList, event, static_cast<uint32_t>(waitEvents.size()), waitEvents.data());
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to zeCommandListAppendBarrier");
+ }
+
+ NPU_VM_LOG_TRACE("Submitted command list: {}", cmdList);
+ }
+
+ return success();
+}
+} // namespace
+
+namespace intel_npu::vm {
+result_t ExecutionContext::EventPool::initialize(ze_device_handle_t deviceHandle, ze_context_handle_t context,
+ uint32_t cmdListCount, ExecutionContext::ExecutionMode executionMode,
+ bool isCounterBasedEventSupported, bool hostSyncWithEventRequired,
+ npu_vm_batch_mode batchMode, uint32_t concurrentJobCount,
+ ov::ZeroApi* ddiTable) {
+ if (ddiTable == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid ddiTable pointer");
+ }
+
+ _ddiTable = ddiTable;
+ _device = deviceHandle;
+ _context = context;
+ _hostSyncWithEventRequired = hostSyncWithEventRequired;
+ _executionMode = executionMode;
+
+ // counter based event will be used only for TILE_AGNOSTIC execution mode
+ _eventType = (isCounterBasedEventSupported &&
+ (executionMode != ExecutionMode::TILE_BOUND || batchMode != npu_vm_batch_mode_dynamic))
+ ? EventPool::EventType::COUNTER_BASED
+ : EventPool::EventType::DEFAULT;
+
+ _eventResetRequired = (_eventType == EventType::COUNTER_BASED) ? false : true;
+
+ // event will be used for host sync, so need to create an additional event
+ auto eventCount = [&]() -> uint32_t {
+ uint32_t eventCount = hostSyncWithEventRequired ? 1 : 0;
+ if (executionMode == ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL ||
+ executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST) {
+ if (_eventType == EventPool::EventType::DEFAULT) {
+ eventCount = MAX_EVENT_POOL_SIZE;
+ _dynamicEventCount = true;
+ _eventGroupSize = EVENT_GROUP_SIZE;
+ } else {
+ eventCount += cmdListCount;
+ _eventGroupSize = cmdListCount;
+ }
+ } else {
+ // if counter based event is supported, we only need one signal event per subgraph
+ // as the target count will increase for each signal event set
+ uint32_t synEventCountPerSubgraph = (_eventType == EventType::COUNTER_BASED) ? 1 : concurrentJobCount;
+
+ if (_eventType == EventPool::EventType::DEFAULT && !_hostSyncWithEventRequired &&
+ batchMode != npu_vm_batch_mode_dynamic) {
+ // if there is one subgraph, no sync event is required
+ eventCount += (cmdListCount > 1) ? (cmdListCount - 1) * synEventCountPerSubgraph : 0;
+ _eventGroupSize = 1;
+ _dynamicEventCount = false;
+ } else {
+ eventCount += cmdListCount * synEventCountPerSubgraph;
+ _eventGroupSize = cmdListCount * synEventCountPerSubgraph;
+ _dynamicEventCount = batchMode == npu_vm_batch_mode_dynamic;
+ }
+ }
+ return eventCount;
+ }();
+
+ auto pfnEventCounterBasedCreate = _ddiTable->zeEventCounterBasedCreate;
+
+ auto createCounterBasedEvents = [&]() -> result_t {
+ ze_event_pool_counter_based_exp_flags_t flag = executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST
+ ? ZE_EVENT_POOL_COUNTER_BASED_EXP_FLAG_IMMEDIATE
+ : ZE_EVENT_POOL_COUNTER_BASED_EXP_FLAG_NON_IMMEDIATE;
+
+ ze_event_counter_based_desc_t desc = {ZE_STRUCTURE_TYPE_EVENT_COUNTER_BASED_DESC, nullptr, flag, 0, 0};
+
+ if (pfnEventCounterBasedCreate == nullptr) {
+ return failure(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, "Counter based event is not supported");
+ }
+
+ for (uint32_t i = 0; i < eventCount; i++) {
+ auto result = pfnEventCounterBasedCreate(context, deviceHandle, &desc, &_events.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create event");
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+ };
+
+ auto pfnEventPoolCreate = _ddiTable->zeEventPoolCreate;
+ auto pfnEventCreate = _ddiTable->zeEventCreate;
+ auto createEvents = [&]() -> result_t {
+ uint32_t eventPoolSize = _dynamicEventCount ? MAX_EVENT_POOL_SIZE : eventCount;
+ ze_event_pool_desc_t eventPoolDesc = {ZE_STRUCTURE_TYPE_EVENT_POOL_DESC, nullptr,
+ ZE_EVENT_POOL_FLAG_HOST_VISIBLE, eventPoolSize};
+
+ auto result = pfnEventPoolCreate(context, &eventPoolDesc, /*numDevices*/ 1, &deviceHandle, &_eventPool);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create event pool for execution context");
+ }
+
+ for (uint32_t i = 0; i < eventCount; i++) {
+ ze_event_desc_t eventDesc = {ZE_STRUCTURE_TYPE_EVENT_DESC, nullptr, i, 0, 0};
+ auto result = pfnEventCreate(_eventPool, &eventDesc, &_events.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create event");
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+ };
+
+ result_t result = ZE_RESULT_SUCCESS;
+ if (eventCount > 0) {
+ _events.resize(eventCount);
+ if (_eventType == EventType::COUNTER_BASED) {
+ result = createCounterBasedEvents();
+ } else {
+ result = createEvents();
+ }
+ }
+
+ return result;
+}
+
+ze_event_handle_t ExecutionContext::EventPool::getSignalEvent() {
+ if (_events.empty()) {
+ return nullptr;
+ }
+
+ if (_dynamicEventCount) {
+ auto pfnEventCounterBasedCreate = _ddiTable->zeEventCounterBasedCreate;
+ auto pfnEventCreate = _ddiTable->zeEventCreate;
+ // increase the event pool size if the current event index exceeds the current max event count
+ if (_curEventIndex >= _events.size() && _events.size() < MAX_EVENT_POOL_SIZE) {
+ uint32_t startIndex = static_cast<uint32_t>(_events.size());
+ _events.resize(std::min(static_cast<uint32_t>(_events.size()) + _eventGroupSize, MAX_EVENT_POOL_SIZE));
+ if (_eventType == EventType::COUNTER_BASED) {
+ ze_event_pool_counter_based_exp_flags_t flag =
+ _executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST
+ ? ZE_EVENT_POOL_COUNTER_BASED_EXP_FLAG_IMMEDIATE
+ : ZE_EVENT_POOL_COUNTER_BASED_EXP_FLAG_NON_IMMEDIATE;
+
+ if (pfnEventCounterBasedCreate == nullptr) {
+ NPU_VM_LOG_ERROR("Counter based event is not supported");
+ return nullptr;
+ }
+ ze_event_counter_based_desc_t desc = {ZE_STRUCTURE_TYPE_EVENT_COUNTER_BASED_DESC, nullptr, flag, 0, 0};
+
+ for (uint32_t i = startIndex; i < _events.size(); i++) {
+ auto result = pfnEventCounterBasedCreate(_context, _device, &desc, &_events.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to create event");
+ return nullptr;
+ }
+ }
+ } else {
+ for (uint32_t i = startIndex; i < _events.size(); ++i) {
+ ze_event_desc_t eventDesc = {ZE_STRUCTURE_TYPE_EVENT_DESC, nullptr, i, 0, 0};
+ auto result = pfnEventCreate(_eventPool, &eventDesc, &_events.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to create event during dynamic event pool expansion");
+ return nullptr;
+ }
+ }
+ }
+ }
+ }
+
+ if (_curEventIndex < _events.size()) {
+ ze_event_handle_t eventHandle = _events.at(_curEventIndex);
+
+ if (_signalEventsArrayIndex == _signalEvents.size()) {
+ _signalEvents.push_back(std::vector<ze_event_handle_t>());
+ } else if (_signalEventsArrayIndex > _signalEvents.size()) {
+ _signalEvents.resize(_signalEventsArrayIndex + 1);
+ }
+
+ if (_eventType == EventType::DEFAULT) {
+ _curEventIndex++;
+
+ // stores the signal event handle to the signal events array for synchronization
+ _signalEvents[_signalEventsArrayIndex].push_back(eventHandle);
+ } else {
+ // note that for counter based events, we don't need to increase the event index
+ // as the target count will be increased for each signal event set
+ if (_signalEvents[_signalEventsArrayIndex].size() == 0) {
+ _signalEvents[_signalEventsArrayIndex].push_back(eventHandle);
+ }
+ }
+ return eventHandle;
+ }
+
+ return nullptr;
+}
+
+std::vector<ze_event_handle_t>& ExecutionContext::EventPool::getWaitEvents() {
+ if (_signalEventsArrayIndex == 1) {
+ if (_signalEventsArrayIndex >= _signalEvents.size()) {
+ _signalEvents.push_back(std::vector<ze_event_handle_t>());
+ }
+ }
+
+ if (_signalEventsArrayIndex > 0 && _signalEventsArrayIndex < _signalEvents.size()) {
+ // returns the signal events from the previous signal events array index
+ // as wait events for synchronization
+ return _signalEvents[_signalEventsArrayIndex - 1];
+ }
+
+ return _signalEvents.back();
+}
+
+bool ExecutionContext::EventPool::destroy() {
+ bool success = true;
+ if (_ddiTable != nullptr) {
+ auto pfnEventDestroy = _ddiTable->zeEventDestroy;
+ auto pfnEventPoolDestroy = _ddiTable->zeEventPoolDestroy;
+ for (auto& event : _events) {
+ if (event == nullptr) {
+ continue;
+ }
+
+ auto result = pfnEventDestroy(event);
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy event during destruction: {}", result);
+ success = false;
+ } else {
+ event = nullptr;
+ }
+ }
+
+ _events.clear();
+
+ if (_eventPool != nullptr) {
+ auto result = pfnEventPoolDestroy(_eventPool);
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy event pool during destruction: {}", result);
+ success = false;
+ } else {
+ _eventPool = nullptr;
+ }
+ }
+ }
+ return success;
+}
+
+result_t ExecutionContext::CmdListPool::createCmdList(ze_context_handle_t context, ze_device_handle_t device,
+ uint32_t groupOrdinal, ze_command_list_handle_t& handle) {
+ ze_mutable_command_list_exp_desc_t mutable_desc = {ZE_STRUCTURE_TYPE_MUTABLE_COMMAND_LIST_EXP_DESC, nullptr, 0};
+ ze_command_list_desc_t desc = {ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC, &mutable_desc, groupOrdinal, 0};
+
+ auto pfnCommandListCreate = _ddiTable->zeCommandListCreate;
+ return pfnCommandListCreate(context, device, &desc, &handle);
+}
+
+result_t ExecutionContext::CmdListPool::initialize(ze_context_handle_t context, ze_device_handle_t device,
+ uint32_t cmdListCount, uint32_t groupOrdinal,
+ uint32_t concurrentJobCount,
+ bool dynamicCmdListCount, ExecutionMode executionMode,
+ ov::ZeroApi* ddiTable) {
+ if (ddiTable == nullptr) {
+ return failure(ZE_RESULT_ERROR_UNINITIALIZED, "Level Zero DDI table is not initialized");
+ }
+ _executionMode = executionMode;
+ _ddiTable = ddiTable;
+ auto pfnCommandListDestroy = ddiTable->zeCommandListDestroy;
+ for (uint32_t i = 0; i < _cmdLists.size(); ++i) {
+ if (_cmdLists.at(i) != nullptr) {
+ auto result = pfnCommandListDestroy(_cmdLists.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to destroy command lists");
+ } else {
+ _cmdLists.at(i) = nullptr;
+ }
+ }
+ }
+ _cmdLists.clear();
+
+ _groupOrdinal = groupOrdinal;
+ _context = context;
+ _device = device;
+ _dynamicCmdListCount = dynamicCmdListCount;
+ if (dynamicCmdListCount && (_executionMode == ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL ||
+ _executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST)) {
+ if (cmdListCount > MAX_CMDLIST_POOL_SIZE) {
+ return failure(ZE_RESULT_ERROR_INVALID_SIZE,
+ "Requested command list count {} exceeds maximum command list pool size {}", cmdListCount,
+ MAX_CMDLIST_POOL_SIZE);
+ }
+ _cmdLists.reserve(MAX_CMDLIST_POOL_SIZE);
+ _cmdLists.resize(CMDLIST_GROUP_SIZE);
+ _cmdListGroupSize = CMDLIST_GROUP_SIZE;
+ } else {
+ _cmdLists.resize(cmdListCount, nullptr);
+ if (dynamicCmdListCount) {
+ _cmdListGroupSize = cmdListCount;
+ }
+ else {
+ _cmdListGroupSize = 1;
+ }
+
+ _inferenceCmdIds.assign(_cmdLists.size(), DEFAULT_INFERENCE_ID);
+ }
+
+ for (uint32_t i = 0; i < _cmdLists.size(); ++i) {
+ auto result = createCmdList(context, device, groupOrdinal, _cmdLists.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create a command list");
+ }
+ }
+
+ return success();
+}
+
+bool ExecutionContext::CmdListPool::destroy() {
+ bool success = true;
+ for (auto cmdList : _cmdLists) {
+ if (cmdList != nullptr && _ddiTable != nullptr) {
+ auto pfnCommandListDestroy = _ddiTable->zeCommandListDestroy;
+ auto result = pfnCommandListDestroy(cmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy command list during destruction: {}", result);
+ success = false;
+ }
+ }
+ }
+
+ _cmdLists.clear();
+
+ return success;
+}
+
+result_t ExecutionContext::createCmdList(ze_command_list_handle_t& cmdListHandle) {
+ switch (_executionMode) {
+ case ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST: {
+ cmdListHandle = _immediateCmdList;
+ break;
+ };
+ case ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL: {
+ // For command list pool, we don't need to return a command list handle
+ cmdListHandle = nullptr;
+ break;
+ };
+ case ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST:
+ case ExecutionMode::TILE_BOUND: {
+ // reset the round index to 0 for the next execution
+ _cmdListRoundIndex = 0;
+
+ uint32_t currentCmdListIndex = _nextCmdListIndex;
+ // If the concurrent job count is greater than 1,
+ // we need to create multiple command lists for concurrent execution.
+ for (uint32_t i = 0; i < _concurrentJobCount; ++i) {
+ // The round index is used internally to determine which command list
+ // to use for the current execution
+ auto handle = getCmdList(currentCmdListIndex);
+ if (handle == nullptr) {
+ return ZE_RESULT_ERROR_INVALID_NULL_HANDLE;
+ }
+
+ // reset cmdlists for V2 execution context,
+ // as they are created internally and need to be reset
+ if (_executionContextType == ExecutionContextType::V2) {
+ auto result = _levelZeroDdiTable->zeCommandListReset(handle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to reset command list");
+ }
+ }
+ }
+
+ // updates the current command list index to the next command list index
+ _currentCmdListIndex = _nextCmdListIndex;
+
+ if (_concurrentJobCount > 1) {
+ // return nullptr here
+ // the caller should use getCmdList() to get the command list handle for execution
+ cmdListHandle = nullptr;
+
+ // specifies that all command lists in the current group have not been used for execution
+ _allCmdListsUsedInGroup = false;
+ } else {
+ cmdListHandle = getCmdList(_currentCmdListIndex);
+ }
+
+ // increases the next command list index
+ _nextCmdListIndex += _concurrentJobCount;
+ break;
+ }
+ }
+
+ return success();
+}
+
+bool ExecutionContext::destroySyncObjects() {
+ bool success = true;
+ if (!_eventPool.destroy()) {
+ success = false;
+ }
+
+ if (_levelZeroDdiTable != nullptr && _internalHostSyncObjectType == HostSyncOjbectType::FENCE && _hostSyncFence != nullptr) {
+ auto pfnFenceDestroy = _levelZeroDdiTable->zeFenceDestroy;
+ auto result = pfnFenceDestroy(_hostSyncFence);
+ if (result != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to destroy host sync fence during destruction: {}", result);
+ success = false;
+ } else {
+ _hostSyncFence = nullptr;
+ }
+ }
+
+ return success;
+}
+
+ExecutionContext::~ExecutionContext() {
+ (void)destroySyncObjects();
+ if (!_cmdListPool.destroy()) {
+ NPU_VM_LOG_ERROR("Failed to destroy command list pool during execution context destruction");
+ }
+ if (_levelZeroDdiTable != nullptr && _immediateCmdList != nullptr) {
+ _levelZeroDdiTable->zeCommandListDestroy(_immediateCmdList);
+ _immediateCmdList = nullptr;
+ }
+}
+
+bool ExecutionContext::initialize(ExecutionContextType type, uint32_t cmdListCount, uint32_t /*numNetworkArgs*/,
+ uint32_t concurrentJobCount, bool isCounterBasedEventSupported,
+ npu_vm_batch_mode batchMode, uint64_t batchSize) {
+ _executionObjectsInitialized = false;
+
+ // release resources
+ if (!destroySyncObjects()) {
+ NPU_VM_LOG_ERROR("Failed to destroy sync objects during execution context initialization");
+ return false;
+ }
+ if (!_cmdListPool.destroy()) {
+ NPU_VM_LOG_ERROR("Failed to destroy command list pool during execution context initialization");
+ return false;
+ }
+
+ _executionContextType = type;
+ _cmdListCount = cmdListCount;
+ _concurrentJobCount = concurrentJobCount;
+ _executionMode =
+ (_concurrentJobCount > 1) ? ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST : ExecutionMode::TILE_BOUND;
+ _isCounterBasedEventSupported = isCounterBasedEventSupported;
+ _batchMode = batchMode;
+ _batchSize = (batchSize > 0) ? batchSize : 1;
+ return true;
+}
+
+result_t ExecutionContext::initializeExecutionObjects(ze_context_handle_t context, ze_device_handle_t device,
+ ze_command_queue_handle_t commandQueue,
+ ze_graph_dditable_ext_t* graphDdiTable,
+ ze_command_queue_npu_dditable_ext_t* cmdQueueDdiTable,
+ bool useInternalCmdQueue) {
+ if (_levelZeroDdiTable == nullptr) {
+ _ddiTable = ov::ZeroApi::get_instance();
+ if (_ddiTable == nullptr) {
+ NPU_VM_LOG_ERROR("Failed to get Level Zero DDI table");
+ throw std::runtime_error("Failed to get Level Zero DDI table");
+ }
+ _levelZeroDdiTable = _ddiTable.get();
+ }
+
+ if (graphDdiTable == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid null pointer for ddi table");
+ }
+ if (device == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid null pointer for device handle");
+ }
+
+ _optimizedDynamicStridesSupported =
+ (graphDdiTable->pfnCompilerIsOptionSupported != nullptr) &&
+ (graphDdiTable->pfnCompilerIsOptionSupported(device, ZE_NPU_DRIVER_OPTIONS, "OPTIMIZED_DYNAMIC_STRIDES",
+ nullptr) == ZE_RESULT_SUCCESS);
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD) || !defined(NDEBUG)
+ auto updateExecutionModeFromEnvVariable = [&]() {
+ if (_executionContextType == ExecutionContextType::V2) {
+ const char* envVar = std::getenv("NPU_VM_RUNTIME_EXECUTION_MODE");
+ if (envVar != nullptr) {
+ std::string modeStr(envVar);
+ auto mode = _executionMode;
+ if (_concurrentJobCount > 1 && useInternalCmdQueue) {
+ if (modeStr == "TILE_AGNOSTIC_CMDLIST_POOL") {
+ mode = ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL;
+ } else if (modeStr == "TILE_AGNOSTIC_IMMEDIATE_CMD_LIST") {
+ mode = ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST;
+ }
+
+ if (mode != _executionMode) {
+ NPU_VM_LOG_WARN("Execution mode changed from {} to {} based on environment variable",
+ static_cast<int>(_executionMode), static_cast<int>(mode));
+ _executionMode = mode;
+ }
+ }
+ }
+ }
+ };
+
+ updateExecutionModeFromEnvVariable();
+#endif
+
+ // Initialize the execution context with the provided context, device, command queue, and DDI tables.
+ _graphDdiTable = graphDdiTable;
+ _commandQueueDdiTableExt = cmdQueueDdiTable;
+ _device = device;
+ _context = context;
+ _commandQueue = commandQueue;
+
+ // recorded command list can be reused for execution
+ // if the tensor shapes do not change between executions
+ // If command list pool or immediate command list are used
+ // it will be false
+ _recordedCmdListReusable = [&]() -> bool {
+ if (_executionContextType == ExecutionContextType::V2) {
+ if (_executionMode == ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL ||
+ _executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST) {
+ return false;
+ }
+ }
+
+ return true;
+ }();
+
+ // Set the internal host synchronization object type based on the execution context type.
+ // It should be set before creating the event pool, as the event pool creation may depend on the host sync object
+ // type.
+ if (_executionContextType == ExecutionContextType::V2) {
+ _internalHostSyncObjectType =
+ (_recordedCmdListReusable) ? HostSyncOjbectType::FENCE : HostSyncOjbectType::EVENT;
+ }
+
+#if defined(NPU_PLUGIN_DEVELOPER_BUILD)
+ // forcing command list recording should not change _internalHostSyncObjectType
+ const char* envVar = std::getenv("NPU_VM_RUNTIME_FORCE_CMD_LIST_RECORDING");
+ if (envVar != nullptr && ::intel_npu::OptionParser<bool>::parse(envVar)) {
+ _recordedCmdListReusable = false;
+ }
+#endif
+
+ auto result = createEventPool(device, context);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create event pool for execution context");
+ }
+
+ // V2 requires to create command lists and sync objects internally
+ auto initializeCmdListsAndCmdListPool = [&]() -> result_t {
+ if (_executionMode == ExecutionMode::TILE_BOUND ||
+ _executionMode == ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST) {
+ auto totalCmdLists = _cmdListCount * _concurrentJobCount;
+ if (_batchMode == npu_vm_batch_mode_static) {
+ totalCmdLists *= static_cast<uint32_t>(_batchSize);
+ }
+ const bool dynamicCmdListCount = _batchMode == npu_vm_batch_mode_dynamic ? true : false;
+ result = _cmdListPool.initialize(context, device, totalCmdLists, 0, _concurrentJobCount,
+ dynamicCmdListCount, _executionMode, _levelZeroDdiTable);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to initialize command list pool");
+ }
+ _cmdListPool.getInferenceCmdIds().assign(totalCmdLists, DEFAULT_INFERENCE_ID);
+ } else if (_executionMode == ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL) {
+ const bool dynamicCmdListCount = true;
+ result = _cmdListPool.initialize(context, device, MAX_CMDLIST_POOL_SIZE, 0,
+ _concurrentJobCount, dynamicCmdListCount, _executionMode, _levelZeroDdiTable);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to initialize command list pool");
+ }
+ } else if (_executionMode == ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST) {
+ _cmdListPool.destroy();
+ auto pfnCommandListCreateImmediate = _levelZeroDdiTable->zeCommandListCreateImmediate;
+ result = createImmediateCmdList(context, device, 0, pfnCommandListCreateImmediate, _immediateCmdList);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create an immediate command list");
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+ };
+
+ if (_executionContextType == ExecutionContextType::V2) {
+ if (initializeCmdListsAndCmdListPool() != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+
+ result = createHostSyncObject(commandQueue);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create host sync object for execution context");
+ }
+ } else {
+ // internal command lists for V1 execution context is not required, so destroy the command list pool
+ _cmdListPool.destroy();
+ _cmdListPool.getInferenceCmdIds().assign(_cmdListCount, DEFAULT_INFERENCE_ID);
+ }
+ _executionObjectsInitialized = true;
+
+ return success();
+}
+
+result_t ExecutionContext::createEventPool(ze_device_handle_t deviceHandle, ze_context_handle_t context) {
+ auto totalCmdListCount = _cmdListCount;
+ if (_batchMode == npu_vm_batch_mode_static) {
+ totalCmdListCount *= static_cast<uint32_t>(_batchSize);
+ }
+ return _eventPool.initialize(
+ deviceHandle, context, totalCmdListCount, _executionMode, _isCounterBasedEventSupported,
+ _internalHostSyncObjectType == HostSyncOjbectType::EVENT, _batchMode, _concurrentJobCount, _levelZeroDdiTable);
+}
+
+result_t ExecutionContext::prepareSubmission(ze_command_list_handle_t commandListHandle, bool needHostSync,
+ uint32_t& cmdListCountToBeSubmitted) {
+ result_t result = ZE_RESULT_SUCCESS;
+
+ auto pfnCommandListAppendBarrier = _levelZeroDdiTable->zeCommandListAppendBarrier;
+ auto pfnCommandListClose = _levelZeroDdiTable->zeCommandListClose;
+ if (commandListHandle == nullptr) {
+ auto cmdListIndex = getCurrentCmdListIndex();
+
+ const bool hostEventSyncRequired = needHostSync && _hostSyncEvent != nullptr;
+ cmdListCountToBeSubmitted =
+ _allCmdListsUsedInGroup ? _concurrentJobCount : std::min(_cmdListRoundIndex, _concurrentJobCount);
+
+ // No host sync means add sync objects to make sure that execution of the current command lists completes.
+ if (_concurrentJobCount > 1) {
+ // Need to reset the command list round index to 0
+ // This is because we are starting a new submission and need to use the first command list
+ _cmdListRoundIndex = 0;
+
+ if (!needHostSync || _hostSyncFence == nullptr) {
+ for (uint32_t i = 0; i < cmdListCountToBeSubmitted; ++i) {
+ auto cmdListHandle = getCmdList(cmdListIndex);
+ if (cmdListHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid commandListHandle for submission");
+ }
+
+ // Need to add signal event to the command list to ensure that the host sync event is signaled
+ // after all command lists complete execution
+ auto signalEvent = _eventPool.getSignalEvent();
+ if (signalEvent == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_SIZE, "No synchronization event is available");
+ }
+ result = pfnCommandListAppendBarrier(cmdListHandle, signalEvent, 0, nullptr);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append barrier to command list");
+ }
+
+ if (!hostEventSyncRequired) {
+ // no additional record required
+ auto result = pfnCommandListClose(cmdListHandle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to close a command list");
+ }
+ }
+ }
+
+ // requires to add a barrier to the command lists to ensure that the host sync event is signaled
+ // after all command lists complete execution
+ if (hostEventSyncRequired) {
+ // increase the signal events array index to ensure the current submission uses
+ // a set of signal events as wait events
+ _eventPool.increaseSignalEventsArrayIndex();
+
+ auto& waitEvents = _eventPool.getWaitEvents();
+ auto cmdListHandle = getCmdList(cmdListIndex);
+ if (cmdListHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid commandListHandle for submission");
+ }
+
+ result = pfnCommandListAppendBarrier(cmdListHandle, _hostSyncEvent,
+ static_cast<uint32_t>(waitEvents.size()), waitEvents.data());
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append barrier to command list");
+ }
+
+ result = pfnCommandListClose(cmdListHandle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to close a command list");
+ }
+ }
+ } else {
+ // need to close command lists
+ for (uint32_t i = 0; i < _concurrentJobCount; ++i) {
+ auto cmdListHandle = getCmdList(cmdListIndex);
+ if (cmdListHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid commandListHandle for submission");
+ }
+
+ result = pfnCommandListClose(cmdListHandle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to close a command list");
+ }
+ }
+ }
+ }
+ } else {
+ cmdListCountToBeSubmitted = 1;
+ if (!needHostSync) {
+ // Need to add signal event to the command list to ensure that the host sync event is signaled
+ // after all commands complete execution
+ auto signalEvent = _eventPool.getSignalEvent();
+ if (signalEvent == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_SIZE, "No synchronization event is available");
+ }
+ result = pfnCommandListAppendBarrier(commandListHandle, signalEvent, 0, nullptr);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append barrier to command list");
+ }
+ } else if (_hostSyncEvent != nullptr) {
+ result = pfnCommandListAppendBarrier(commandListHandle, _hostSyncEvent, 0, nullptr);
+ }
+
+ auto result = pfnCommandListClose(commandListHandle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to close a command list");
+ }
+ }
+
+ // increase the signal events array index to ensure the current submission uses
+ // a set of signal events as wait events
+ _eventPool.increaseSignalEventsArrayIndex();
+
+ return result;
+}
+
+result_t ExecutionContext::hostSync() {
+ // No need to synchronize host with fence or event if the execution parameters V1 are set
+ if (_executeParamsV2) {
+ if (_hostSyncFence != nullptr) {
+ auto pfnFenceHostSynchronize = _levelZeroDdiTable->zeFenceHostSynchronize;
+ auto result = pfnFenceHostSynchronize(_hostSyncFence, UINT64_MAX);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to synchronize host with fence");
+ }
+ } else if (_hostSyncEvent != nullptr) {
+ auto pfnEventHostSynchronize = _levelZeroDdiTable->zeEventHostSynchronize;
+ auto result = pfnEventHostSynchronize(_hostSyncEvent, UINT64_MAX);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to synchronize host with event");
+ }
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+}
+
+result_t createKernel(ExecutionContext& executionContext, uint8_t* kernelBlob, size_t kernelBlobSize,
+ const std::string& kernelName, ze_graph_handle_t& graphHandle, KernelInfo& graphInfo) {
+ NPU_VM_LOG_TRACE("Creating graph for kernel {} at address {} of size {}", kernelName, kernelBlob, kernelBlobSize);
+
+ const uint32_t flag = ZE_GRAPH_FLAG_OPTIMIZE_FOR_DYNAMIC_SHAPES;
+ ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_2,
+ nullptr,
+ ZE_GRAPH_FORMAT_NATIVE,
+ static_cast<size_t>(kernelBlobSize),
+ kernelBlob,
+ nullptr /* build flag */,
+ flag};
+
+ auto graphDdiTable = executionContext.getGraphDdiTable();
+ auto context = executionContext.getContext();
+ auto device = executionContext.getDevice();
+
+ if (graphDdiTable == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid null pointer for graph ddi table");
+ }
+ if (context == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid null pointer for context");
+ }
+ if (device == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid null pointer for device");
+ }
+
+ auto pfnCreate = graphDdiTable->pfnCreate2;
+ auto result = pfnCreate(context, device, &desc, &graphHandle);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to create graph, kern: {}, size: {}", kernelBlob, kernelBlobSize);
+ }
+
+ ze_graph_properties_t props{};
+ props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
+ result = graphDdiTable->pfnGetProperties(graphHandle, &props);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to get graph properties");
+ }
+ auto numInputArguments = 0;
+ std::vector<bool> supportsDynamicStrides(props.numGraphArgs, false);
+
+ NPU_VM_LOG_TRACE("Get properties of graph arguments: {}, kernel: {}, size: {}", props.numGraphArgs, kernelBlob,
+ kernelBlobSize);
+
+ for (uint32_t index = 0; index < props.numGraphArgs; ++index) {
+ ze_graph_argument_properties_3_t arg3{};
+ arg3.stype = ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTIES_3;
+
+ ze_graph_argument_property_strides_t strides{ZE_STRUCTURE_TYPE_GRAPH_ARGUMENT_PROPERTY_STRIDES, nullptr, false};
+ arg3.pNext = static_cast<void*>(&strides);
+ result = graphDdiTable->pfnGetArgumentProperties3(graphHandle, index, &arg3);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to get properties of arg: {}, kern: {}, size: {}", index, kernelBlob,
+ kernelBlobSize);
+ }
+
+ if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ numInputArguments++;
+ }
+
+ supportsDynamicStrides[index] = strides.supportsDynamicStrides;
+ NPU_VM_LOG_DEBUG("Graph arg {} of kernel {} supportsDynamicStrides={}", index, kernelName,
+ strides.supportsDynamicStrides);
+ }
+
+ graphInfo = KernelInfo(graphHandle, props.numGraphArgs, numInputArguments, kernelName,
+ std::move(supportsDynamicStrides));
+
+ NPU_VM_LOG_TRACE("Created graph for kernel: {}, size: {}, graph_handle: {}", kernelBlob, kernelBlobSize,
+ graphHandle);
+
+ return success();
+}
+
+result_t setBindings(ExecutionContext& executionContext, ze_graph_handle_t graphHandle,
+ const std::vector<BufferMapperItem>& inputs, const std::vector<BufferMapperItem>& outputs,
+ KernelInfo& graphInfo) {
+ if (graphHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid graph handle");
+ }
+
+ auto context = executionContext.getContext();
+ auto device = executionContext.getDevice();
+ auto ddiTable = executionContext.getGraphDdiTable();
+ auto cmdQueue = executionContext.getCommandQueue();
+ if (!executionContext.executionObjectsInitialized()) {
+ // Initialization will be done here for VM runtime V1
+ NPU_VM_LOG_TRACE("Creating event pool for execution context");
+ // V1 does not support internal command queue, so we set useInternalCmdQueue to false
+ const bool useInternalCmdQueue = false;
+ auto result = executionContext.initializeExecutionObjects(context, device, cmdQueue, ddiTable, nullptr,
+ useInternalCmdQueue);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to initialize an execution context");
+ }
+ }
+
+ if (inputs.empty() || outputs.empty()) {
+ return failure(ZE_RESULT_ERROR_INVALID_SIZE, "Invalid size, inputs: {}, outputs: {}", inputs.size(),
+ outputs.size());
+ }
+
+ if ((inputs.size() + outputs.size()) != graphInfo.getNumArgs()) {
+ return failure(
+ ZE_RESULT_ERROR_INVALID_SIZE,
+ "The total number of inputs and outputs does not match the number of graph arguments, numInputs: "
+ "{} , numOutputs: {} , numGraphArgs: {}",
+ inputs.size(), outputs.size(), graphInfo.getNumArgs());
+ }
+
+ NPU_VM_LOG_TRACE("Begin setting arguments: {} of kern: {} and kern name: {}", graphInfo.getNumArgs(), graphHandle,
+ graphInfo.getKernelName());
+
+ for (uint32_t index = 0; index < graphInfo.getNumArgs(); ++index) {
+ // Process inputs
+ if (index < graphInfo.getNumInputArgs()) {
+ auto result = setArguments(index, inputs.at(index), graphHandle, ddiTable,
+ graphInfo.supportsDynamicStrides(index));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to set input argument [{}/{}] for kern: {}", index,
+ graphInfo.getNumArgs(), graphHandle);
+ }
+ } else {
+ auto result = setArguments(index, outputs.at(index - graphInfo.getNumInputArgs()), graphHandle, ddiTable,
+ graphInfo.supportsDynamicStrides(index));
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to set output argument [{}/{}] for kern: {}", index,
+ graphInfo.getNumArgs(), graphHandle);
+ }
+ }
+ }
+
+ return success();
+}
+
+result_t executeGraph(ExecutionContext& executionContext, ze_command_list_handle_t commandListHandle,
+ ze_graph_handle_t graphHandle, void* kernelName) {
+ auto executionMode = executionContext.getExecutionMode();
+ if (executionMode == ExecutionContext::ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL) {
+ return executeGraphCmdListPool(executionContext, graphHandle, kernelName);
+ } else if (executionMode == ExecutionContext::ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST) {
+ return executeGraphImmediate(executionContext, graphHandle, kernelName);
+ }
+
+ if (graphHandle == nullptr) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_HANDLE, "Invalid graph handle");
+ }
+
+ auto ddiTable = executionContext.getDdiTable();
+ auto graphDdiTable = executionContext.getGraphDdiTable();
+ auto cmdListIndex = executionContext.getCurrentCmdListIndex();
+ auto cmdListRoundIndex = executionContext.getCmdListRoundIndex();
+ if (commandListHandle == nullptr) {
+ commandListHandle = executionContext.getCmdList(cmdListIndex);
+ }
+ if (executionContext.getExecutionMode() == ExecutionContext::ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST) {
+ // actually, the command list index is the round robin index, so we need to add the round index to get the
+ // actual command list index
+ cmdListIndex += cmdListRoundIndex;
+ }
+
+ if (kernelName == nullptr) {
+ NPU_VM_LOG_TRACE("Executing graph for unnamed kernel at handle {}", graphHandle);
+ } else {
+ NPU_VM_LOG_TRACE("Executing graph for kernel {} at handle {} in cmdList {} and execContext {}",
+ static_cast<const char*>(kernelName), graphHandle, commandListHandle, &executionContext);
+ }
+
+ ze_pfnAppendGraphExecute_ext_t pfnAppendGraphExecute = graphDdiTable->pfnAppendGraphExecute;
+ auto& eventPool = executionContext.getEventPool();
+ std::vector<ze_event_handle_t>& waitEvents = eventPool.getWaitEvents();
+ auto& inferenceCmdIds = executionContext.getInferenceCmdIds();
+ const auto inferenceCmdCount = inferenceCmdIds.size();
+ bool waitSyncRequired = false;
+ if (static_cast<size_t>(cmdListIndex) < inferenceCmdCount) {
+ auto id = inferenceCmdIds.at(cmdListIndex);
+ if (id == DEFAULT_INFERENCE_ID) {
+ // For the first inference execution in the command list,
+ // wait events need to be added to ensure that the execution of the current command list start
+ // after the previous command list execution
+ waitSyncRequired = waitEvents.size() > 0;
+ }
+ } else {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER, "Invalid commandList Index: {}, got: {}", cmdListIndex,
+ inferenceCmdCount);
+ }
+
+ auto pfnCommandListAppendEventReset = ddiTable->zeCommandListAppendEventReset;
+ ze_result_t result = ZE_RESULT_SUCCESS;
+ if (waitSyncRequired == true) {
+ result = pfnAppendGraphExecute(commandListHandle, graphHandle, nullptr, nullptr, static_cast<uint32_t>(waitEvents.size()),
+ waitEvents.data());
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append graph execute in command list: {}, kern: {}, numWaits: {}",
+ commandListHandle, graphHandle, waitEvents.size());
+ }
+ if (executionContext.getConcurrentJobCount() == 1 && waitEvents.size() == 1 &&
+ executionContext.getEventPool().getEventType() == ExecutionContext::EventPool::EventType::DEFAULT) {
+ result = pfnCommandListAppendEventReset(commandListHandle, waitEvents[0]);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append an event reset in command list: {}", commandListHandle);
+ }
+ }
+ } else {
+ result = pfnAppendGraphExecute(commandListHandle, graphHandle, nullptr, nullptr, 0, nullptr);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to append graph execute in command list: {}, kern: {}, numWaits: {}",
+ commandListHandle, graphHandle, waitEvents.size());
+ }
+ }
+
+ executionContext.increaseInferenceCmdId(cmdListIndex);
+
+ NPU_VM_LOG_TRACE("Executed graph for kernel: {}", graphHandle);
+
+ return success();
+}
+
+
+result_t submitCmdList(ExecutionContext& executionContext, ze_command_list_handle_t commandListHandle,
+ bool needHostSync) {
+ auto executionMode = executionContext.getExecutionMode();
+ if (executionMode == ExecutionContext::ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL) {
+ return submitCmdListPool(executionContext, commandListHandle, needHostSync);
+ } else if (executionMode == ExecutionContext::ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST) {
+ return submitCmdListImmediate(executionContext, commandListHandle, needHostSync);
+ }
+
+ auto commandQueueHandle = executionContext.getCommandQueue();
+ ze_fence_handle_t fence = nullptr;
+ ze_event_handle_t event = nullptr;
+
+ if (needHostSync) {
+ fence = executionContext.getHostSyncFence();
+ event = executionContext.getHostSyncEvent();
+
+ if (event != nullptr && fence != nullptr) {
+ // Both event and fence are provided, which is not expected
+ // as they serve similar synchronization purposes.
+ return failure(ZE_RESULT_ERROR_INVALID_ARGUMENT,
+ "Both event and fence are not nullptr(event: {}, fence: {})", event, fence);
+ }
+ }
+
+ NPU_VM_LOG_TRACE("Submitting command list: {}, fence: {}, event: {}", commandListHandle, fence, event);
+
+ // prepare for submission
+ uint32_t cmdListCountToBeSubmitted = 0;
+ auto result = executionContext.prepareSubmission(commandListHandle, needHostSync, cmdListCountToBeSubmitted);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result, "Failed to prepare command list submission");
+ }
+
+ auto commandQueue = executionContext.getCommandQueue();
+
+ // note command queue is null when immediate command list is used
+ if (commandQueueHandle != nullptr) {
+ auto ddiTable = executionContext.getDdiTable();
+ auto pfnCommandQueueExecuteCommandLists = ddiTable->zeCommandQueueExecuteCommandLists;
+ auto result = ZE_RESULT_SUCCESS;
+ if (commandListHandle) {
+ // tile bound execution will pass not null commandListHandle
+ result = pfnCommandQueueExecuteCommandLists(commandQueueHandle, 1, &commandListHandle, fence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result,
+ "Failed to zeCommandQueueExecuteCommandList with event: {}, fence: {}, command queue: "
+ "{}, command "
+ "list: {}",
+ event, fence, commandQueue, commandListHandle);
+ }
+
+ // stores it to the recorded command lists for reuse in future executions
+ // when no tensor shape changes are detected and the recorded command lists
+ // can be reused for execution.
+ if (!executionContext.appendRecordedCmdLists(&commandListHandle, 1)) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER,
+ "Failed to add command lists handles to a recorded command list");
+ }
+ } else {
+ // tile agnostic execution will pass null commandListHandle
+ // need to get the command list array from the execution context
+ result = pfnCommandQueueExecuteCommandLists(commandQueueHandle, cmdListCountToBeSubmitted,
+ executionContext.getCmdListArrayPtr(), fence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return failure(result,
+ "Failed to zeCommandQueueExecuteCommandList with event: {}, fence: {}, command queue: "
+ "{}, command ",
+ event, fence, commandQueue);
+ }
+
+ // stores it to the recorded command lists for reuse in future executions
+ // when no tensor shape changes are detected and the recorded command lists
+ // can be reused for execution.
+ if (!executionContext.appendRecordedCmdLists(executionContext.getCmdListArrayPtr(),
+ cmdListCountToBeSubmitted)) {
+ return failure(ZE_RESULT_ERROR_INVALID_NULL_POINTER,
+ "Failed to add command lists handles to a recorded command list");
+ }
+ }
+ }
+
+ NPU_VM_LOG_TRACE("Submitted command list: {}", commandListHandle);
+
+ return success();
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.hpp
new file mode 100644
index 00000000000..529c27c7251
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/kernel_execution.hpp
@@ -0,0 +1,801 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <openvino/zero_api.hpp>
+
+#include "buffer.hpp"
+#include "buffer_metadata.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+#include "vm_runtime/virtual_machine.h"
+
+#include <cstddef>
+#include <cstdint>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace intel_npu::vm {
+
+constexpr size_t HOST_SYNC_EVENT_INDEX = 0U;
+constexpr uint32_t MAX_EVENT_POOL_SIZE = 1000;
+constexpr uint32_t EVENT_GROUP_SIZE = 100;
+constexpr uint32_t MAX_CMDLIST_POOL_SIZE = 1000;
+constexpr uint32_t CMDLIST_GROUP_SIZE = 100;
+
+// Opaque handle representing the execution context for a function call, can be extended in the future to hold more
+// information if needed
+using result_t = int32_t;
+using BufferMapperItem = std::pair<Buffer*, BufferMetadata*>;
+
+#if defined(_WIN32)
+constexpr uint32_t DEFAULT_INFERENCE_ID = 1;
+#else
+constexpr uint32_t DEFAULT_INFERENCE_ID = 0;
+#endif
+
+// Structure to hold graph information
+class KernelInfo {
+ // Graph handle created by L0 UMD, used for setting arguments and executing the graph
+ ze_graph_handle_t _graphHandle;
+
+ // Total number of arguments (inputs + outputs) for the graph, used for validating the number of arguments
+ uint32_t _numArgs;
+
+ // Number of input arguments for the graph, used for validating the number of input arguments and output arguments
+ uint32_t _numInputArgs;
+
+ // Kernel symbol name
+ std::string _kernelName;
+
+ // Per graph-argument flag reported by the driver, indexed by graph argument index.
+ std::vector<bool> _supportsDynamicStrides;
+
+public:
+ KernelInfo(): _graphHandle(nullptr), _numArgs(0), _numInputArgs(0) {
+ }
+
+ KernelInfo(ze_graph_handle_t handle, uint32_t numArgs, uint32_t numInputArgs, const std::string& kernelName,
+ std::vector<bool> supportsDynamicStrides = {})
+ : _graphHandle(handle),
+ _numArgs(numArgs),
+ _numInputArgs(numInputArgs),
+ _kernelName(kernelName),
+ _supportsDynamicStrides(std::move(supportsDynamicStrides)) {
+ }
+
+ uint32_t getNumArgs() const {
+ return _numArgs;
+ }
+
+ uint32_t getNumInputArgs() const {
+ return _numInputArgs;
+ }
+
+ ze_graph_handle_t getGraphHandle() const {
+ return _graphHandle;
+ }
+
+ std::string& getKernelName() {
+ return _kernelName;
+ }
+
+ const std::string& getKernelName() const {
+ return _kernelName;
+ }
+
+ bool supportsDynamicStrides(uint32_t index) const {
+ if (index >= _supportsDynamicStrides.size()) {
+ return false;
+ }
+ return _supportsDynamicStrides[index];
+ }
+};
+
+class ExecutionContext {
+public:
+ enum class HostSyncOjbectType : uint32_t { NONE, FENCE, EVENT, COUNTER_BASED_EVENT };
+ enum class ExecutionContextType : uint32_t { V1, V2 };
+ enum class ExecutionMode : uint32_t {
+ TILE_BOUND,
+ TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST,
+ TILE_AGNOSTIC_CMDLIST_POOL,
+ TILE_AGNOSTIC_IMMEDIATE_CMD_LIST
+ };
+
+ class EventPool {
+ public :
+ enum class EventType : uint32_t { DEFAULT, COUNTER_BASED };
+ private:
+ friend class ExecutionContext;
+ ze_event_pool_handle_t _eventPool{nullptr};
+ std::vector<ze_event_handle_t> _events;
+ uint32_t _currentMaxEventCount = 0;
+ ze_device_handle_t _device{nullptr};
+ ze_context_handle_t _context{nullptr};
+ EventType _eventType = EventType::DEFAULT;
+ ExecutionMode _executionMode = ExecutionMode::TILE_BOUND;
+ uint32_t _eventGroupSize = 1;
+ // Specifies whether the number of events is dynamic,
+ // which will be used for determining whether to create a large number of events
+ bool _dynamicEventCount = false;
+
+ // Stores the current index of the event to be used for synchronization.
+ uint32_t _curEventIndex = 0;
+
+ // Stores signal events for synchronization
+ std::vector<std::vector<ze_event_handle_t>> _signalEvents;
+ uint32_t _signalEventsArrayIndex = 1;
+
+ ov::ZeroApi* _ddiTable{nullptr};
+
+ bool _hostSyncWithEventRequired = false;
+
+ bool _eventResetRequired = true;
+
+ public:
+ EventPool() = default;
+ ~EventPool() {
+ destroy();
+ }
+ EventPool(const EventPool&) = delete;
+ EventPool& operator=(const EventPool&) = delete;
+ EventPool(EventPool&&) = delete;
+ EventPool& operator=(EventPool&&) = delete;
+
+ result_t initialize(ze_device_handle_t deviceHandle, ze_context_handle_t context, uint32_t cmdListCount,
+ ExecutionMode executionMode, bool isCounterBasedEventSupported,
+ bool hostSyncWithEventRequired, npu_vm_batch_mode batchMode,
+ uint32_t concurrentJobCount, ov::ZeroApi* ddiTable);
+
+ // Returns the next event handle for synchronization.
+ ze_event_handle_t getSignalEvent();
+
+ // Returns the next event handle for synchronization, and increments the event index if a signal event has been
+ // used.
+ std::vector<ze_event_handle_t>& getWaitEvents();
+
+ result_t resetEvents() {
+ _curEventIndex = (_hostSyncWithEventRequired) ? 1 : 0;
+ _signalEventsArrayIndex = 1;
+ _signalEvents.clear();
+ return ZE_RESULT_SUCCESS;
+ }
+
+ bool destroy();
+
+ // Increases the signal events array index, which is used for tracking
+ // the current signal event to be used for synchronization.
+ void increaseSignalEventsArrayIndex() {
+ _signalEventsArrayIndex++;
+
+ if (_eventType == EventType::COUNTER_BASED) {
+ // Increases the current event index for counter-based events
+ // as signal event is used per subgraph for counter-based events
+ _curEventIndex++;
+ }
+
+ if (_signalEventsArrayIndex >= _signalEvents.size()) {
+ _signalEvents.push_back(std::vector<ze_event_handle_t>());
+ }
+ }
+
+ // Returns the number of events to be reset on device
+ uint32_t getEventCountForReset() {
+ // Note: when _internalHostSyncObjectType == EVENT, _events[0] is reserved for host sync.
+ // resetEventCount is selected below to reset only the events that may remain signaled on host.
+ uint32_t resetEventCount = 0;
+ if (_eventResetRequired) {
+ if (_executionMode != ExecutionMode::TILE_BOUND) {
+ // Currently, concurrent executions require resetting events.
+ if (_eventType == EventType::COUNTER_BASED) {
+ // For counter-based event, _curEventIndex will increase by 1
+ // when all of inference executions of a subgraph is submitted
+ // So, resetEventCount should be _curEventIndex - 1 to reset all of the events
+ resetEventCount = (_curEventIndex > 0) ? _curEventIndex - 1 : 0;
+ } else {
+ resetEventCount = _curEventIndex;
+ }
+ } else if (_hostSyncWithEventRequired) {
+ // For TILE_BOUND execution mode, event reset cmd is stored in the command list,
+ // so we need to reset the event on host only for the first event.
+ resetEventCount = 1;
+ }
+ }
+ return resetEventCount;
+ }
+
+ // Resets L0 events on host only without changing the event index,
+ // used for resetting the synchronization state of the execution context.
+ result_t resetL0Events() {
+ // Note: when _internalHostSyncObjectType == EVENT, _events[0] is reserved for host sync.
+ // resetEventCount is selected below to reset only the events that may remain signaled on host.
+ auto resetEventCount = getEventCountForReset();
+
+ if (_ddiTable) {
+ auto pfnEventHostReset = _ddiTable->zeEventHostReset;
+ for (uint32_t i = 0; i < resetEventCount; ++i) {
+ auto& event = _events.at(i);
+ if (event != nullptr) {
+ auto result = pfnEventHostReset(event);
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ }
+ }
+ }
+
+ return ZE_RESULT_SUCCESS;
+ }
+
+ bool getHostSyncEvent(ze_event_handle_t& handle) {
+ if (_hostSyncWithEventRequired) {
+ handle = _events[HOST_SYNC_EVENT_INDEX];
+ return true;
+ }
+ return false;
+ }
+
+ EventType getEventType() {
+ return _eventType;
+ }
+ };
+
+ class CmdListPool {
+ friend class ExecutionContext;
+
+ std::vector<ze_command_list_handle_t> _cmdLists;
+ bool _dynamicCmdListCount = false;
+ ze_context_handle_t _context{nullptr};
+ ze_device_handle_t _device{nullptr};
+ ExecutionMode _executionMode = ExecutionMode::TILE_BOUND;
+ uint32_t _groupOrdinal = 0;
+ ov::ZeroApi* _ddiTable{nullptr};
+ // specifies how many command lists should be created at once
+ // when they need to be created
+ uint32_t _cmdListGroupSize = 1;
+
+ // Stores the current cmd ids
+ std::vector<uint32_t> _inferenceCmdIds;
+
+ // VM runtime V2
+ // Stores the recorded command lists for the execution context,
+ // which will be used when no tensor shape changes are detected
+ // and the recorded command lists can be reused for execution.
+ std::vector<ze_command_list_handle_t> _recordedCommandLists;
+ public:
+ CmdListPool() = default;
+ ~CmdListPool() {
+ destroy();
+ }
+
+ CmdListPool(const CmdListPool&) = delete;
+ CmdListPool& operator=(const CmdListPool&) = delete;
+ CmdListPool(CmdListPool&& other) = delete;
+ CmdListPool& operator=(CmdListPool&& other) = delete;
+
+ ze_command_list_handle_t getCmdList(uint32_t index) {
+ if (index >= _cmdLists.size() && _dynamicCmdListCount) {
+ if (index >= MAX_CMDLIST_POOL_SIZE) {
+ return nullptr;
+ }
+
+ // create CMDLIST_GROUP_SIZE command lists at a time to avoid frequent allocation
+ uint32_t startIndex = static_cast<uint32_t>(_cmdLists.size());
+ _cmdLists.resize(
+ std::min(static_cast<uint32_t>(_cmdLists.size()) + _cmdListGroupSize, MAX_CMDLIST_POOL_SIZE));
+
+ if (_executionMode == ExecutionMode::TILE_BOUND || _executionMode == ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST) {
+ _inferenceCmdIds.resize(_cmdLists.size());
+ std::fill(_inferenceCmdIds.begin() + startIndex, _inferenceCmdIds.end(), DEFAULT_INFERENCE_ID);
+ }
+
+ for (uint32_t i = startIndex; i < _cmdLists.size(); ++i) {
+ auto result = createCmdList(_context, _device, _groupOrdinal, _cmdLists.at(i));
+ if (result != ZE_RESULT_SUCCESS) {
+ return nullptr;
+ }
+ }
+ }
+
+ if (index < _cmdLists.size()) {
+ return _cmdLists.at(index);
+ }
+ return nullptr;
+ }
+
+ size_t size() const {
+ return _cmdLists.size();
+ }
+
+ result_t initialize(ze_context_handle_t context, ze_device_handle_t device, uint32_t cmdListCount,
+ uint32_t groupOrdinal, uint32_t concurrentJobCount, bool dynamicCmdListCount,
+ ExecutionMode executionMode, ov::ZeroApi* ddiTable);
+
+ ze_command_list_handle_t* getCmdListArrayPtr(uint32_t cmdListIndex) {
+ return _cmdLists.data() + cmdListIndex;
+ }
+
+ bool destroy();
+
+ std::vector<uint32_t>& getInferenceCmdIds() {
+ return _inferenceCmdIds;
+ }
+
+ // Increases the inference command id for the given command list index,
+ // which is used for tracking the command id for each command list in the execution context.
+ void increaseInferenceCmdId(uint32_t cmdListIndex) {
+ if (cmdListIndex < _inferenceCmdIds.size()) {
+ _inferenceCmdIds.at(cmdListIndex)++;
+ }
+ }
+
+ void reset() {
+ std::fill(_inferenceCmdIds.begin(), _inferenceCmdIds.end(), DEFAULT_INFERENCE_ID);
+ _recordedCommandLists.clear();
+ }
+
+ // Returns the concurrent job count
+ bool appendRecordedCmdLists(ze_command_list_handle_t* handleArray, uint32_t count) {
+ for (size_t i = 0; i < count; ++i) {
+ if (handleArray[i] == nullptr) {
+ return false;
+ }
+ _recordedCommandLists.push_back(handleArray[i]);
+ }
+ return true;
+ }
+
+ std::vector<ze_command_list_handle_t>& getRecordedCmdLists() {
+ return _recordedCommandLists;
+ }
+ protected:
+ result_t createCmdList(ze_context_handle_t context, ze_device_handle_t device, uint32_t groupOrdinal,
+ ze_command_list_handle_t& handle);
+ };
+
+protected:
+ // CmdList index to get the next command list from an array of command lists,
+ // used for tracking the current command list
+ // Stores index to get the next command list from an array of command lists
+ uint32_t _nextCmdListIndex = 0;
+
+ // Stores index to get the next command list from an array of command lists
+ uint32_t _currentCmdListIndex = 0;
+
+ // Stores the round index of the command list, which is used for tracking
+ // the current round of command list execution. Range [0 .. _concurrentJobCount - 1]
+ uint32_t _cmdListRoundIndex = 0;
+
+ // Stores whether all command lists of a group of command lists for round robin execution
+ bool _allCmdListsUsedInGroup = false;
+
+ // Stores the total number of command lists
+ uint32_t _cmdListCount = 0;
+
+ // Stores the number of concurrent command list executions,
+ // which is used for determining the number of events to be created for synchronization
+ uint32_t _concurrentJobCount = 1;
+
+ // Manages events for synchronization.
+ EventPool _eventPool;
+
+ // Specifies execution context type
+ ExecutionContextType _executionContextType = ExecutionContextType::V1;
+
+ // Specifies execution mode, which can be TILE_BOUND or TILE_AGNOSTIC.
+ ExecutionMode _executionMode = ExecutionMode::TILE_BOUND;
+
+ // Specifies the type of host synchronization object to be used for synchronization,
+ // which can be a fence, an event, or a counter-based event.
+ HostSyncOjbectType _internalHostSyncObjectType = HostSyncOjbectType::NONE;
+
+ // Stores fence for host sync
+ ze_fence_handle_t _hostSyncFence{nullptr};
+
+ // Stores event for host sync
+ ze_event_handle_t _hostSyncEvent{nullptr};
+
+ npu_vm_runtime_execute_params_t* _executeParamsV1{nullptr};
+ npu_vm_runtime_execute_params2_t* _executeParamsV2{nullptr};
+
+ CmdListPool _cmdListPool;
+ ze_command_list_handle_t _immediateCmdList{nullptr};
+
+ // L0 handles and DDI tables for context, device, command queue, and graph,
+ // used for executing the graph and setting arguments
+ ze_context_handle_t _context{nullptr};
+ ze_device_handle_t _device{nullptr};
+ ze_command_queue_handle_t _commandQueue{nullptr};
+ ze_graph_dditable_ext_t* _graphDdiTable{nullptr};
+ ze_command_queue_npu_dditable_ext_t* _commandQueueDdiTableExt{nullptr};
+ std::shared_ptr<ov::ZeroApi> _ddiTable{nullptr};
+ ov::ZeroApi* _levelZeroDdiTable{nullptr};
+ npu_vm_batch_mode _batchMode = npu_vm_batch_mode_none;
+ uint64_t _batchSize = 1;
+
+ // Stores whether the execution context has been initialized,
+ // used for determining whether to initialize the event pool and events
+ bool _executionObjectsInitialized = false;
+
+ // Stores whether optimized dynamic strides is supported, which will be queried from the driver
+ // and used for determining whether to use optimized dynamic strides when setting graph arguments
+ bool _optimizedDynamicStridesSupported = false;
+
+ // Stores whether counter-based event is supported, which is used to configure synchronization objects.
+ bool _isCounterBasedEventSupported = false;
+
+ // Specify whether the recorded command list can be reused, which will be queried from the driver
+ bool _recordedCmdListReusable = false;
+
+public:
+ // note: numNetworkArgs will be used in support for mutable command list in the future
+ // but currently it is not used.
+ ExecutionContext() = default;
+ ExecutionContext(const ExecutionContext&) = delete;
+ ExecutionContext& operator=(const ExecutionContext&) = delete;
+ ExecutionContext(ExecutionContext&&) noexcept = delete;
+ ExecutionContext& operator=(ExecutionContext&&) noexcept = delete;
+ ~ExecutionContext();
+
+ // Returns whether the execution context has been initialized,
+ // used for determining whether to initialize the event pool and events
+ bool executionObjectsInitialized() const {
+ return _executionObjectsInitialized;
+ }
+
+ // Resets the execution context to its initial state, including resetting the command list index and events.
+ result_t reset() {
+ _nextCmdListIndex = 0;
+ _currentCmdListIndex = 0;
+ _cmdListRoundIndex = 0;
+ _allCmdListsUsedInGroup = false;
+
+ _cmdListPool.reset();
+
+ return resetEvents();
+ }
+
+ // Returns the next command list handle from the array of command lists in the execution parameters,
+ // and increments the command list index.
+ result_t createCmdList(ze_command_list_handle_t& cmdListHandle);
+
+ // Closes a command list after recording graph execution commands
+ result_t closeCmdList(ze_command_list_handle_t) {
+ // Currently, close will be done in submitCmdList, so this function is a NO OP,
+ // but it is defined here for completeness and future extension if needed.
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Resets L0 events on host only without changing the event index,
+ // used for resetting the synchronization state of the execution context.
+ result_t resetL0SyncObjects() {
+ auto result = _eventPool.resetL0Events();
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ if (_internalHostSyncObjectType == HostSyncOjbectType::FENCE && _hostSyncFence != nullptr) {
+ auto pfnFenceReset = _levelZeroDdiTable->zeFenceReset;
+ result = pfnFenceReset(_hostSyncFence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Resets the event index and signal event count to their initial state,
+ // used for resetting the synchronization state of the execution context.
+ result_t resetEvents() {
+ auto result = resetL0SyncObjects();
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+
+ return _eventPool.resetEvents();
+ }
+
+ result_t initializeExecutionObjects(ze_context_handle_t context, ze_device_handle_t device,
+ ze_command_queue_handle_t commandQueue, ze_graph_dditable_ext_t* ddiTable,
+ ze_command_queue_npu_dditable_ext_t* cmdQueueDdiTable,
+ bool useInternalCmdQueue);
+
+ // Returns the current command list index,
+ // which is the index of the command list that was most recently returned by createCommandList.
+ uint32_t getCurrentCmdListIndex() const {
+ return _currentCmdListIndex;
+ }
+
+ // Returns the current round command list index,
+ uint32_t getCmdListRoundIndex() const {
+ return _cmdListRoundIndex;
+ }
+
+ // Returns the inference command ids, which is used for tracking the command id for each command list in the
+ // execution context.
+ std::vector<uint32_t>& getInferenceCmdIds() {
+ return _cmdListPool.getInferenceCmdIds();
+ }
+
+ // Increases the inference command id for the given command list index,
+ // which is used for tracking the command id for each command list in the execution context.
+ void increaseInferenceCmdId(uint32_t cmdListIndex) {
+ _cmdListPool.increaseInferenceCmdId(cmdListIndex);
+ }
+
+ // Returns whether optimized dynamic strides is supported,
+ // which is used for determining whether to use optimized dynamic strides when setting graph arguments.
+ bool isOptimizedDynamicStridesSupported() const {
+ return _optimizedDynamicStridesSupported;
+ }
+
+ // Returns a command list handle from the array of command lists in the execution parameters
+ // based on the given command list index.
+ ze_command_list_handle_t getCmdList(const npu_vm_runtime_execute_params_t& params, uint32_t cmdListIndex) {
+ if (cmdListIndex < params.numCommandLists && params.commandLists != nullptr) {
+ return *std::next(params.commandLists, static_cast<std::ptrdiff_t>(cmdListIndex));
+ }
+ return nullptr;
+ }
+
+ // Returns a command list handle from the array of command lists in the execution parameters
+ // based on the given command list index.
+ // In the case of concurrent execution, it will return the command list handle based on the round index.
+ ze_command_list_handle_t getCmdList(const npu_vm_runtime_execute_params2_t&, uint32_t cmdListIndex) {
+ if (_concurrentJobCount == 1) {
+ return _cmdListPool.getCmdList(cmdListIndex);
+ }
+
+ switch (_executionMode) {
+ case ExecutionMode::TILE_AGNOSTIC_IMMEDIATE_CMD_LIST:
+ return _immediateCmdList;
+ case ExecutionMode::TILE_AGNOSTIC_CMDLIST_POOL:
+ // no need to increase _nextCmdListIndex as it is not used
+ return _cmdListPool.getCmdList(_currentCmdListIndex++);
+ case ExecutionMode::TILE_BOUND:
+ case ExecutionMode::TILE_AGNOSTIC_ROUND_ROBIN_CMDLIST: {
+ // Each call will return one of the command lists in a round-robin manner based on the round index.
+ auto handle = _cmdListPool.getCmdList(cmdListIndex + _cmdListRoundIndex++);
+ if (handle != nullptr) {
+ if (_cmdListRoundIndex >= _concurrentJobCount) {
+ // Reset the round index to 0 when it reaches the concurrent job count,
+ // so that the next call will return the first command list in the next round.
+ _cmdListRoundIndex = 0;
+
+ if (!_allCmdListsUsedInGroup) {
+ _allCmdListsUsedInGroup = true;
+ }
+ }
+ return handle;
+ }
+ return nullptr;
+ }
+ }
+ return nullptr;
+ }
+
+ ze_command_list_handle_t getCmdList(uint32_t cmdListIndex) {
+ if (_executeParamsV2 != nullptr) {
+ return getCmdList(*_executeParamsV2, cmdListIndex);
+ } else if (_executeParamsV1 != nullptr) {
+ return getCmdList(*_executeParamsV1, cmdListIndex);
+ }
+ return nullptr;
+ }
+
+ // Returns a pointer to the array of command list handles in the execution parameters
+ ze_command_list_handle_t* getCmdListArrayPtr() {
+ if (_executeParamsV2 != nullptr) {
+ if ((_currentCmdListIndex + _concurrentJobCount) <= _cmdListPool.size()) {
+ return _cmdListPool.getCmdListArrayPtr(_currentCmdListIndex);
+ }
+ } else if (_executeParamsV1 != nullptr && _executeParamsV1->commandLists) {
+ if ((_currentCmdListIndex + _concurrentJobCount) <= _cmdListCount) {
+ return _executeParamsV1->commandLists + _currentCmdListIndex;
+ }
+ }
+ return nullptr;
+ }
+
+ // Sets the execution parameters for the executor, which will be used for executing the graph.
+ result_t setParams(npu_vm_runtime_execute_params_t* params) {
+ if (params != nullptr) {
+ if (_executionObjectsInitialized == false) {
+ // one time setting is required for level zero handles and DDI tables,
+ // which will be used for executing the graph
+ _context = params->ctx;
+ _device = params->device;
+ _graphDdiTable = params->graphDdiTableExt;
+ }
+
+ // all the parameters are set by the plugin
+ _commandQueue = params->commandQueue;
+ _hostSyncEvent = params->event;
+ _hostSyncFence = params->inferenceFence;
+ }
+ _executeParamsV1 = params;
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Creates a host synchronization object (fence or event) based on the specified type
+ // and associates it with the given command queue.
+ result_t createHostSyncObject(ze_command_queue_handle_t commandQueue) {
+ if (_internalHostSyncObjectType == HostSyncOjbectType::FENCE) {
+ if (_hostSyncFence != nullptr) {
+ auto pfnFenceDestroy = _levelZeroDdiTable->zeFenceDestroy;
+ auto result = pfnFenceDestroy(_hostSyncFence);
+ _hostSyncFence = nullptr;
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ }
+
+ if (commandQueue != nullptr) {
+ auto pfnFenceCreate = _levelZeroDdiTable->zeFenceCreate;
+ ze_fence_desc_t fence_desc = {ZE_STRUCTURE_TYPE_FENCE_DESC, nullptr, 0};
+ auto result = pfnFenceCreate(commandQueue, &fence_desc, &_hostSyncFence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ }
+ } else if (_internalHostSyncObjectType == HostSyncOjbectType::EVENT) {
+ if (!_eventPool.getHostSyncEvent(_hostSyncEvent)) {
+ return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
+ }
+ }
+
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Sets the execution parameters for the executor, which will be used for executing the graph.
+ result_t setParams(npu_vm_runtime_execute_params2_t* params) {
+ if (params != nullptr && params->commandQueue != nullptr) {
+ if (_commandQueue != params->commandQueue) {
+ _commandQueue = params->commandQueue;
+ if (auto result = createHostSyncObject(params->commandQueue)) {
+ return result;
+ }
+ }
+ }
+
+ _executeParamsV2 = params;
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Returns L0 context handle
+ ze_context_handle_t getContext() {
+ return _context;
+ }
+
+ // Returns L0 device handle
+ ze_device_handle_t getDevice() {
+ return _device;
+ }
+
+ // Returns L0 command queue handle
+ ze_command_queue_handle_t getCommandQueue() {
+ return _commandQueue;
+ }
+
+ // Returns L0 graph DDI table handle
+ ze_graph_dditable_ext_t* getGraphDdiTable() {
+ return _graphDdiTable;
+ }
+
+ // Returns L0 command queue DDI table handle
+ ze_command_queue_npu_dditable_ext_t* getCmdQueueDdiTable() {
+ return _commandQueueDdiTableExt;
+ }
+
+ // Returns the host synchronization event handle,
+ // which will be used for synchronizing the host with the command queue.
+ ze_event_handle_t getHostSyncEvent() {
+ return _hostSyncEvent;
+ }
+
+ // Returns the host synchronization fence handle,
+ // which will be used for synchronizing the host with the command queue.
+ ze_fence_handle_t getHostSyncFence() {
+ return _hostSyncFence;
+ }
+
+ // Returns the execution context type, which indicates
+ // whether the execution context is using V1 or V2 execution parameters.
+ ExecutionContextType getExecutionContextType() const {
+ return _executionContextType;
+ }
+
+ // Returns the execution mode, which indicates the execution mode of
+ // the command lists in the execution context.
+ ExecutionMode getExecutionMode() const {
+ return _executionMode;
+ }
+
+ // Returns the concurrent job count
+ uint64_t getConcurrentJobCount() const {
+ return _concurrentJobCount;
+ }
+
+ // Returns the concurrent job count
+ bool appendRecordedCmdLists(ze_command_list_handle_t* handleArray, uint32_t count) {
+ return _cmdListPool.appendRecordedCmdLists(handleArray, count);
+ }
+
+ // return a ddi table pointer to the level zero ddi table, which will be used for executing the graph.
+ ov::ZeroApi* getDdiTable() {
+ return _levelZeroDdiTable;
+ }
+
+ // Prepares submission by adding signal events for sync between command lists and host
+ result_t prepareSubmission(ze_command_list_handle_t cmdListHandle, bool needHostSync,
+ uint32_t& cmdListCountToBeSubmitted);
+
+ // Synchronizes the host with the command queue using the host synchronization object (fence or event)
+ result_t hostSync();
+
+ // Submits recorded command lists for execution
+ result_t submitRecordedCmdLists() {
+ // Reset Level Zero events referenced by recorded command lists before resubmission
+ auto result = resetL0SyncObjects();
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+
+ if (_commandQueue) {
+ auto pfnCommandQueueExecuteCommandLists = _levelZeroDdiTable->zeCommandQueueExecuteCommandLists;
+ auto& recordedCommandLists = _cmdListPool.getRecordedCmdLists();
+ auto result = pfnCommandQueueExecuteCommandLists(_commandQueue,
+ static_cast<uint32_t>(recordedCommandLists.size()),
+ recordedCommandLists.data(), _hostSyncFence);
+ if (result != ZE_RESULT_SUCCESS) {
+ return result;
+ }
+ }
+ return ZE_RESULT_SUCCESS;
+ }
+
+ // Returns whether the recorded command list can be reused for execution
+ bool isRecordedCmdListReusable() const {
+ return _recordedCmdListReusable;
+ }
+
+ // Destroys the synchronization objects (events and fences)
+ // associated with the execution context.
+ bool destroySyncObjects();
+
+ // Initializes the execution context with the specified type, number of command lists, and concurrent job count
+ bool initialize(ExecutionContextType type, uint32_t numCmdLists, uint32_t /*numNetworkArgs*/,
+ uint32_t concurrentJobCount, bool isCounterBasedEventSupported, npu_vm_batch_mode batchMode,
+ uint64_t batchSize);
+
+ // returns the event pool for the execution context, which will be used for managing events for synchronization.
+ EventPool& getEventPool() {
+ return _eventPool;
+ }
+
+private:
+ ExecutionMode getDefaultExecutionMode() const;
+ void applyExecutionModeOverride(bool useInternalCmdQueue);
+ void updateExecutionModePolicy();
+ result_t createEventPool(ze_device_handle_t deviceHandle, ze_context_handle_t context);
+};
+
+result_t createKernel(ExecutionContext& executionContext, uint8_t* blob, size_t blobSize, const std::string& kernelName,
+ ze_graph_handle_t& graphHandle, KernelInfo& graphInfo);
+
+// Sets the graph arguments for the given kernel handle based on the input and output buffer descriptions,
+// which will be used for executing the graph.
+result_t setBindings(ExecutionContext& executionContext, ze_graph_handle_t graphHandle,
+ const std::vector<BufferMapperItem>& inputs, const std::vector<BufferMapperItem>& outputs,
+ KernelInfo& graphInfo);
+
+// Executes the graph for the given kernel handle and command list handle
+result_t executeGraph(ExecutionContext& executionContext, ze_command_list_handle_t commandListHandle,
+ ze_graph_handle_t graphHandle, void* kernelName);
+
+// Submit a command list
+result_t submitCmdList(ExecutionContext& executionContext, ze_command_list_handle_t commandListHandle,
+ bool needHostSync);
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.cpp
new file mode 100644
index 00000000000..1e593954d97
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.cpp
@@ -0,0 +1,47 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "level_zero_allocator.hpp"
+#include "allocator_core.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
+#include "composable_allocators.hpp"
+
+#include <cstddef>
+#include <cstdint>
+
+intel_npu::vm::LevelZeroAllocator::LevelZeroAllocator(ze_context_handle_t context): _context(context) {
+}
+
+intel_npu::vm::Block intel_npu::vm::LevelZeroAllocator::allocate(size_t bytes) {
+ if (_context == nullptr || bytes == 0) {
+ return Block{};
+ }
+
+ ze_host_mem_alloc_desc_t desc{ZE_STRUCTURE_TYPE_HOST_MEM_ALLOC_DESC, nullptr, 0};
+ void* data = nullptr;
+ // Page-aligned so device buffers satisfy the NPU's host-memory alignment expectation.
+ try {
+ if (::intel_npu::zeMemAllocHost(_context, &desc, bytes, ALIGNMENT, &data) != ZE_RESULT_SUCCESS) {
+ return Block{};
+ }
+ }
+ catch (...) {
+ return Block{};
+ }
+
+ return Block{static_cast<uint8_t*>(data), bytes};
+}
+
+void intel_npu::vm::LevelZeroAllocator::deallocate(Block block) noexcept {
+ if (_context != nullptr && block.ptr != nullptr) {
+ ::intel_npu::zeMemFree(_context, block.ptr);
+ }
+}
+
+intel_npu::vm::AnyAllocator intel_npu::vm::makeLevelZeroAllocator(ze_context_handle_t context) {
+ // GrowingArena of BumpRegions over Level Zero memory, page-aligned so buffers are device-visible.
+ return AnyAllocator{
+ GrowingArena<LevelZeroAllocator, BumpRegion<LevelZeroAllocator::ALIGNMENT>,
+ DEFAULT_ARENA_INITIAL_SLAB_BYTES, DEFAULT_ARENA_MAX_SLAB_BYTES>(LevelZeroAllocator(context))};
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.hpp
new file mode 100644
index 00000000000..fa48850ecad
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/level_zero_allocator.hpp
@@ -0,0 +1,46 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "allocator_core.hpp"
+#include "vm_export.hpp"
+
+#include <intel_npu/utils/utils.hpp>
+
+#include <ze_api.h>
+
+#include <cstddef>
+#include <cstdint>
+
+namespace intel_npu::vm {
+
+// Tuning for the default GrowingArena: first slab size and the geometric per-slab growth cap. It grows on
+// demand (doubling each slab toward the cap) and reuses slabs, so the initial size need not match the working
+// set. Kept small so a first allocation of a few small buffers (e.g. output-shape prediction / metadata) does
+// not eagerly reserve tens of MiB of device memory; a larger first request still gets a chunk sized to it.
+inline constexpr uint64_t DEFAULT_ARENA_INITIAL_SLAB_BYTES = uint64_t{1} << 20; // 1 MiB
+inline constexpr uint64_t DEFAULT_ARENA_MAX_SLAB_BYTES = uint64_t{64} << 20; // 64 MiB
+
+// Leaf over Level Zero host-visible memory (zeMemAllocHost/zeMemFree) so the NPU can read the buffers
+// directly. Bound to one context. recycle()/release() are no-ops: it retains nothing and frees per-block.
+class NPU_VM_EXPORT LevelZeroAllocator {
+ ze_context_handle_t _context;
+
+public:
+ // Chunk-base alignment this backing guarantees: zeMemAllocHost is asked for page-aligned memory.
+ static constexpr size_t ALIGNMENT = intel_npu::utils::STANDARD_PAGE_SIZE;
+
+ explicit LevelZeroAllocator(ze_context_handle_t context);
+
+ // Returns a null Block on failure (never throws).
+ Block allocate(size_t bytes);
+ void deallocate(Block block) noexcept;
+};
+
+// Level Zero device allocator: a GrowingArena of BumpRegions over a Level Zero backing, page-aligned so
+// buffers are device-visible. Slabs are reserved lazily, so the context is touched only on first allocation.
+NPU_VM_EXPORT AnyAllocator makeLevelZeroAllocator(ze_context_handle_t context);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.cpp
new file mode 100644
index 00000000000..2c165710b32
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.cpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "math.hpp"
+
+#include <cstdint>
+#include <limits>
+
+bool intel_npu::vm::checkedMultiply(uint64_t lhs, uint64_t rhs, uint64_t& result) {
+ if (rhs != 0 && lhs > std::numeric_limits<uint64_t>::max() / rhs) {
+ return false;
+ }
+ result = lhs * rhs;
+ return true;
+}
+
+bool intel_npu::vm::checkedAddProduct(uint64_t lhs, uint64_t rhs, uint64_t& accumulator) {
+ uint64_t product = 0;
+ if (!checkedMultiply(lhs, rhs, product)) {
+ return false;
+ }
+ if (accumulator > std::numeric_limits<uint64_t>::max() - product) {
+ return false;
+ }
+ accumulator += product;
+ return true;
+}
+
+bool intel_npu::vm::checkedMultiplyNonNegative(int64_t lhs, int64_t rhs, int64_t& result) {
+ if (lhs < 0 || rhs < 0) {
+ return false;
+ }
+ uint64_t product = 0;
+ if (!checkedMultiply(static_cast<uint64_t>(lhs), static_cast<uint64_t>(rhs), product) ||
+ product > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
+ return false;
+ }
+ result = static_cast<int64_t>(product);
+ return true;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.hpp
new file mode 100644
index 00000000000..2c1eea6007d
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/math.hpp
@@ -0,0 +1,17 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "vm_export.hpp"
+
+#include <cstdint>
+
+namespace intel_npu::vm {
+
+bool NPU_VM_EXPORT checkedMultiply(uint64_t lhs, uint64_t rhs, uint64_t& result);
+bool NPU_VM_EXPORT checkedAddProduct(uint64_t lhs, uint64_t rhs, uint64_t& accumulator);
+bool NPU_VM_EXPORT checkedMultiplyNonNegative(int64_t lhs, int64_t rhs, int64_t& result);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/network_metadata.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/network_metadata.hpp
new file mode 100644
index 00000000000..98609e5b230
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/network_metadata.hpp
@@ -0,0 +1,16 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/network_description.hpp"
+#include "vm_runtime/virtual_machine.h"
+
+#include <optional>
+
+namespace intel_npu::vm {
+
+std::optional<NetworkMetadata> getNetworkMetadata(npu_vm_module* module);
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.cpp
new file mode 100644
index 00000000000..3f8b9ecd76b
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.cpp
@@ -0,0 +1,82 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "parameters.hpp"
+#include "buffer.hpp"
+#include "buffer_metadata.hpp"
+#include "function.hpp"
+#include "math.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#include <climits>
+#include <cstdint>
+#include <cstring>
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+using namespace intel_npu::vm;
+
+std::optional<BufferHandle> intel_npu::vm::extractMemRef(
+ npu_vm_runtime_mem_ref_handle_t handle, BufferManager& bufferManager,
+ std::unordered_map<BufferHandle, BufferMetadata>& bufferMetadata, Permission permission,
+ const FuncParamResType& type, const std::vector<uint16_t>& typeByteSizes) {
+ if (!std::holds_alternative<BufferType>(type.type.data)) {
+ NPU_VM_LOG_ERROR("Unsupported parameter type for memref argument: expected BufferType, got type index {}",
+ type.typeSectionIndex);
+ return std::nullopt;
+ }
+ auto bufferType = std::get<BufferType>(type.type.data);
+ if (bufferType.dataTypeIndex >= static_cast<uint64_t>(typeByteSizes.size())) {
+ NPU_VM_LOG_ERROR("Data type index {} out of bounds for type byte sizes table of size {}",
+ bufferType.dataTypeIndex, typeByteSizes.size());
+ return std::nullopt;
+ }
+ const auto elemByteSize = typeByteSizes.at(bufferType.dataTypeIndex);
+
+ if (handle == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer provided for memref argument");
+ return std::nullopt;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto& memRef = *reinterpret_cast<npu_vm_runtime_mem_ref*>(handle);
+ if (memRef.basePtr == nullptr || memRef.data == nullptr) {
+ NPU_VM_LOG_ERROR("Invalid memref argument: basePtr ({}) and data ({}) must not be null", memRef.basePtr,
+ memRef.data);
+ return std::nullopt;
+ }
+ if (memRef.dimsCount == 0 || bufferType.rank != memRef.dimsCount) {
+ NPU_VM_LOG_ERROR(
+ "Invalid memref argument: dimsCount is 0 or does not match bufferType rank (dimsCount: {}, rank: {})",
+ memRef.dimsCount, bufferType.rank);
+ return std::nullopt;
+ }
+ if (memRef.dimsCount > static_cast<int64_t>(memRef.sizes.size()) ||
+ memRef.dimsCount > static_cast<int64_t>(memRef.strides.size())) {
+ NPU_VM_LOG_ERROR("Invalid memref argument: dimsCount ({}) exceeds sizes/strides vector capacity (sizes: {}, "
+ "strides: {})",
+ memRef.dimsCount, memRef.sizes.size(), memRef.strides.size());
+ return std::nullopt;
+ }
+ int64_t bufferByteSize = 0;
+ if (!checkedMultiplyNonNegative(memRef.sizes.at(0), memRef.strides.at(0), bufferByteSize) ||
+ !checkedMultiplyNonNegative(bufferByteSize, elemByteSize, bufferByteSize)) {
+ NPU_VM_LOG_ERROR(
+ "Buffer byte size calculation overflow for memref argument with sizes {}, strides {}, elemByteSize {}",
+ formatVector(memRef.sizes), formatVector(memRef.strides), elemByteSize);
+ return std::nullopt;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
+ auto* address = static_cast<uint8_t*>(const_cast<void*>(memRef.data));
+ auto bufferHandle = bufferManager.createFromMemory(address, static_cast<size_t>(bufferByteSize), permission);
+
+ BufferMetadata metadata{static_cast<int64_t>(bufferType.dataTypeIndex), memRef.sizes, memRef.strides, elemByteSize};
+ bufferMetadata.emplace(bufferHandle, metadata);
+
+ return bufferHandle;
+}
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.hpp
new file mode 100644
index 00000000000..0d9739f7ad4
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/parameters.hpp
@@ -0,0 +1,52 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "buffer.hpp"
+#include "buffer_metadata.hpp"
+#include "function.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#include <cstdint>
+#include <optional>
+#include <unordered_map>
+#include <vector>
+
+namespace intel_npu::vm {
+
+struct MemRef {
+ enum class DirtyFlag : uint32_t {
+ NONE = 0,
+ BUFFER_PTR = 0x01,
+ OFFSET = 0x02,
+ SIZES = 0x04,
+ STRIDES = 0x08,
+ ALL = 0xFF
+ };
+
+ const void* basePtr = nullptr;
+ const void* data = nullptr;
+ int64_t offset = 0;
+ int64_t dimsCount = 0;
+ std::vector<int64_t> sizes;
+ std::vector<int64_t> strides;
+ uint32_t dirtyFlags = static_cast<uint32_t>(DirtyFlag::NONE);
+
+ explicit MemRef(int64_t dims): dimsCount(dims), sizes(dims, 0), strides(dims, 0) {
+ }
+
+ void resetDirtyBits() {
+ dirtyFlags = static_cast<uint32_t>(DirtyFlag::NONE);
+ }
+};
+
+std::optional<BufferHandle> extractMemRef(npu_vm_runtime_mem_ref_handle_t handle, BufferManager& bufferManager,
+ std::unordered_map<BufferHandle, BufferMetadata>& metadata,
+ Permission permission, const FuncParamResType& type,
+ const std::vector<uint16_t>& typeByteSizes);
+
+} // namespace intel_npu::vm
+
+using npu_vm_runtime_mem_ref = intel_npu::vm::MemRef;
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/vm_export.hpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/vm_export.hpp
new file mode 100644
index 00000000000..72e25dc6dbb
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils/vm_export.hpp
@@ -0,0 +1,13 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#ifndef NPU_VM_EXPORT
+#if defined(_WIN32)
+#define NPU_VM_EXPORT __declspec(dllexport)
+#else
+#define NPU_VM_EXPORT __attribute__((visibility("default")))
+#endif // defined(_WIN32)
+#endif // NPU_VM_EXPORT
diff --git a/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/virtual_machine.cpp b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/virtual_machine.cpp
new file mode 100644
index 00000000000..a66824f11c9
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/virtual_machine.cpp
@@ -0,0 +1,3545 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "vm_runtime/virtual_machine.h"
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/logger.hpp"
+#include "npu_bytecode_utils/managed_vector.hpp"
+#include "npu_bytecode_utils/network_description.hpp"
+#include "npu_bytecode_utils/print_utils.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "utils/allocator_core.hpp"
+#include "utils/buffer.hpp"
+#include "utils/buffer_metadata.hpp"
+#include "utils/call_frame.hpp"
+#include "utils/function.hpp"
+#include "utils/host_allocator.hpp"
+#include "utils/kernel_execution.hpp"
+#include "utils/level_zero_allocator.hpp"
+#include "utils/math.hpp"
+#include "utils/network_metadata.hpp"
+#include "utils/parameters.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#include <ze_api.h>
+#include <ze_graph_ext.h>
+
+#include <algorithm>
+#include <array>
+#include <cfenv>
+#include <climits>
+#include <cmath>
+#include <cstdarg>
+#include <cstddef>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <exception>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <new>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <type_traits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+using namespace intel_npu;
+using namespace intel_npu::vm;
+
+namespace {
+
+// Represents the execution lifecycle of the VMEngine.
+// Transitions: Initialized -> Running -> Finalized (normal) or Halted (error).
+enum class ExecState : uint8_t { Initialized, Running, Halted, Finalized };
+
+template <typename T>
+std::optional<int64_t> evaluateCmp(T lhs, T rhs, uint8_t cmpType) {
+ switch (static_cast<intel_npu::vm::CmpPredicate>(cmpType)) {
+ case intel_npu::vm::CmpPredicate::EQ:
+ return static_cast<int64_t>(lhs == rhs);
+ case intel_npu::vm::CmpPredicate::NE:
+ return static_cast<int64_t>(lhs != rhs);
+ case intel_npu::vm::CmpPredicate::GT:
+ return static_cast<int64_t>(lhs > rhs);
+ case intel_npu::vm::CmpPredicate::GTE:
+ return static_cast<int64_t>(lhs >= rhs);
+ case intel_npu::vm::CmpPredicate::LT:
+ return static_cast<int64_t>(lhs < rhs);
+ case intel_npu::vm::CmpPredicate::LTE:
+ return static_cast<int64_t>(lhs <= rhs);
+ default:
+ NPU_VM_LOG_ERROR("Unknown CMP predicate: {}", static_cast<unsigned>(cmpType));
+ return std::nullopt;
+ }
+}
+
+template <typename SignedT>
+inline SignedT convertUnsignedToSignedPreserveBits(std::make_unsigned_t<SignedT> value) {
+ using UnsignedT = std::make_unsigned_t<SignedT>;
+ // For logical shifts:
+ // - We intentionally compute in unsigned type to get logical bit behavior
+ // - That leaves us with an unsigned result that may have the top bit set
+ // - Storing that directly to a 64-bit signed register would zero-extend
+ // - The helper converts to signed 32-bit first, so later widening to 64-bit sign-extends correctly
+ constexpr auto signBit = UnsignedT{1} << ((sizeof(SignedT) * 8) - 1);
+ if (value <= static_cast<UnsignedT>(std::numeric_limits<SignedT>::max())) {
+ return static_cast<SignedT>(value);
+ }
+ return static_cast<SignedT>(value - signBit) + std::numeric_limits<SignedT>::min();
+}
+
+template <typename SignedT>
+inline SignedT arithmeticShiftRightDefined(SignedT value, int64_t rawShiftAmount) {
+ using UnsignedT = std::make_unsigned_t<SignedT>;
+ constexpr auto bitWidth = sizeof(SignedT) * 8;
+ constexpr auto shiftMask = bitWidth - 1;
+
+ // Arithmetic right shift of a negative signed value is implementation-defined in C++.
+ // The bytecode opcode contract is stricter: SRA must preserve the sign bit regardless of
+ // compiler or target. Implement the operation in unsigned space, then explicitly fill the
+ // high bits when the source is negative. Finally, convert the resulting bit pattern back to
+ // the signed type through convertUnsignedToSignedPreserveBits().
+ const auto shiftAmount = static_cast<uint64_t>(rawShiftAmount) & shiftMask;
+ auto shifted = static_cast<UnsignedT>(static_cast<UnsignedT>(value) >> shiftAmount);
+ if (value < 0 && shiftAmount != 0) {
+ shifted |= static_cast<UnsignedT>(~UnsignedT{0} << (bitWidth - shiftAmount));
+ }
+ return convertUnsignedToSignedPreserveBits<SignedT>(shifted);
+}
+
+template <typename To, typename From>
+inline To vmBitCast(From from) {
+ static_assert(sizeof(To) == sizeof(From), "vmBitCast requires same-size types");
+ To result;
+ std::memcpy(&result, &from, sizeof(To));
+ return result;
+}
+
+// Extract the low N bits of a register value and sign-extend to int64_t.
+// This avoids relying on implementation-defined narrowing casts from wider integer types.
+inline int64_t signExtend8(int64_t regValue) {
+ constexpr uint64_t signBit = 0x80u;
+ constexpr int64_t twosComplementOffset = 0x100;
+ const auto raw = static_cast<uint64_t>(regValue) & 0xFFu;
+ return raw >= signBit ? static_cast<int64_t>(raw) - twosComplementOffset : static_cast<int64_t>(raw);
+}
+
+inline int64_t signExtend16(int64_t regValue) {
+ constexpr uint64_t signBit = 0x8000u;
+ constexpr int64_t twosComplementOffset = 0x10000;
+ const auto raw = static_cast<uint64_t>(regValue) & 0xFFFFu;
+ return raw >= signBit ? static_cast<int64_t>(raw) - twosComplementOffset : static_cast<int64_t>(raw);
+}
+
+inline int64_t signExtend32(int64_t regValue) {
+ constexpr uint64_t signBit = 0x80000000u;
+ constexpr int64_t twosComplementOffset = 0x100000000LL;
+ const auto raw = static_cast<uint64_t>(regValue) & 0xFFFFFFFFu;
+ return raw >= signBit ? static_cast<int64_t>(raw) - twosComplementOffset : static_cast<int64_t>(raw);
+}
+
+// Converts a floating-point value to a signed integer type with saturating semantics:
+// - NaN → 0
+// - +infinity or src > INT_MAX → INT_MAX
+// - -infinity or src < INT_MIN → INT_MIN
+// - finite, in-range → truncate toward zero (standard C++ cast)
+// This avoids the C++ undefined behaviour that occurs when a finite float is outside
+// the representable range of the destination integer type.
+template <typename IntT, typename FloatT>
+inline int64_t saturatingFloatToInt(FloatT src) noexcept {
+ static_assert(std::is_floating_point_v<FloatT>);
+ static_assert(std::is_signed_v<IntT> && std::is_integral_v<IntT>);
+ if (std::isnan(src)) {
+ return 0;
+ }
+ // The float representation of the integer limits may not be exact (e.g. INT64_MAX rounds
+ // up to 2^63 in float/double). Using the float-converted limit for comparison is still
+ // correct: any src that survives the lower-bound check and is < maxF is a finite value
+ // whose truncation is representable in IntT.
+ constexpr auto minF = static_cast<FloatT>(std::numeric_limits<IntT>::min());
+ constexpr auto maxF = static_cast<FloatT>(std::numeric_limits<IntT>::max());
+ if (src <= minF) {
+ return static_cast<int64_t>(std::numeric_limits<IntT>::min());
+ }
+ if (src >= maxF) {
+ return static_cast<int64_t>(std::numeric_limits<IntT>::max());
+ }
+ return static_cast<int64_t>(static_cast<IntT>(src));
+}
+
+bool decodeInstruction(const uint8_t* pc, size_t bytesAvailable, intel_npu::vm::OpCode& opcode,
+ size_t& instructionSize) {
+ if (bytesAvailable < intel_npu::vm::OPCODE_SIZE) {
+ NPU_VM_LOG_ERROR("Reached end of function body while decoding opcode. This likely means the function body "
+ "is malformed.");
+ return false;
+ }
+ opcode = intel_npu::vm::getOpcode(pc);
+ const auto sizeOpt = intel_npu::vm::getInstructionSize(opcode, pc, bytesAvailable);
+ if (!sizeOpt.has_value()) {
+ NPU_VM_LOG_ERROR("Failed to decode instruction size for opcode {}: unknown opcode or malformed instruction.",
+ static_cast<uint16_t>(opcode));
+ return false;
+ }
+ instructionSize = sizeOpt.value();
+ if (bytesAvailable < instructionSize) {
+ NPU_VM_LOG_ERROR("Reached end of function body while decoding an instruction. "
+ "This likely means the function body is malformed.");
+ return false;
+ }
+ return true;
+}
+
+class BytecodeModule {
+ std::vector<Function> _functions; // All functions from the bytecode function section(s)
+ std::vector<ManagedVector<uint8_t>> _constants; // All constant entries from the bytecode constant section(s)
+ std::vector<ManagedVector<uint8_t>> _kernelBinaries; // All kernel binaries from the bytecode kernel section(s)
+ std::vector<ManagedVector<uint8_t>> _rawStrings; // All raw strings from the bytecode string section(s)
+ std::vector<uint16_t> _typeByteSizes; // Element byte size for each type entry
+ std::optional<NetworkMetadata> _networkMetadata; // Metadata about the network, if present in the bytecode
+
+ /// Parses the bytecode and populates the module's internal data structures.
+ /// @param bytecode The serialized bytecode to parse.
+ /// @param copyBytecode If true, the module will make a copy of the bytecode and own the memory. If false, the
+ /// module will reference the provided bytecode directly, meaning the caller must ensure the bytecode remains valid
+ /// for the lifetime of the module
+ /// @return true on success, false on failure
+ bool parse(const intel_npu::vm::Span<uint8_t>& bytecode, bool copyBytecode = false) {
+ intel_npu::vm::BytecodeReader reader(bytecode);
+ if (!reader.parseFile()) {
+ NPU_VM_LOG_ERROR("Failed to parse bytecode file.");
+ return false;
+ }
+
+ auto& sectionHeaderTable = reader.getSectionHeaderTable();
+ auto& sectionHeaders = sectionHeaderTable.getSectionHeaders();
+ auto& sections = reader.getSections();
+
+ const auto typeByteSizes = intel_npu::vm::extractTypeByteSizes(sectionHeaderTable, sections);
+ if (!typeByteSizes.has_value()) {
+ return false;
+ }
+ _typeByteSizes = typeByteSizes.value();
+
+ // Iterate over section headers to find function sections and extract individual function bodies
+ for (size_t headerIdx = 0; headerIdx < sectionHeaders.size(); ++headerIdx) {
+ const auto& header = sectionHeaders.at(headerIdx);
+ if (header.type != intel_npu::vm::SectionType::ConstantSection) {
+ continue;
+ }
+
+ auto constantSectionInfo = dynamic_cast<intel_npu::vm::details::DataSectionInfo*>(header.info.get());
+ if (constantSectionInfo == nullptr || headerIdx >= sections.size()) {
+ NPU_VM_LOG_ERROR("Constant section header is malformed");
+ return false;
+ }
+ const auto& section = sections.at(headerIdx);
+ for (const auto& dataInfo : constantSectionInfo->dataInfos) {
+ if (dataInfo.offset > section.size() || dataInfo.size > section.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("Constant data exceeds section bounds: offset={}, size={}, sectionSize={}",
+ dataInfo.offset, dataInfo.size, section.size());
+ return false;
+ }
+ _constants.emplace_back(section.subspan(dataInfo.offset, dataInfo.size), /*copyData=*/copyBytecode);
+ }
+ }
+
+ for (size_t headerIdx = 0; headerIdx < sectionHeaders.size(); ++headerIdx) {
+ const auto& header = sectionHeaders.at(headerIdx);
+ if (header.type != intel_npu::vm::SectionType::FuncSection) {
+ continue;
+ }
+ auto funcSectionInfo = dynamic_cast<intel_npu::vm::details::FunctionSectionInfo*>(header.info.get());
+ if (funcSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Function section header does not contain function section info");
+ return false;
+ }
+ for (size_t i = 0; i < funcSectionInfo->functionInfos.size(); ++i) {
+ if (headerIdx >= sections.size()) {
+ NPU_VM_LOG_ERROR("Could not find associated section with section header {}", headerIdx);
+ return false;
+ }
+
+ const auto& funcInfo = funcSectionInfo->functionInfos.at(i);
+ const auto functionNameOpt = reader.getString(funcInfo.nameIndex);
+ if (!functionNameOpt.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to retrieve function name string for function at index {} in function section "
+ "header {}",
+ i, headerIdx);
+ return false;
+ }
+ auto functionName = functionNameOpt.value();
+ // Remove null-terminator from string
+ functionName.erase(std::find(functionName.begin(), functionName.end(), '\0'), functionName.end());
+
+ const auto functionTypeOpt = reader.getFunctionType(funcInfo.functionTypeIndex);
+ if (!functionTypeOpt.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to retrieve function type for function at index {} in function section header {}",
+ i, headerIdx);
+ return false;
+ }
+ const auto& functionType = functionTypeOpt.value();
+ std::vector<intel_npu::vm::FuncParamResType> paramTypes;
+ for (auto paramTypeIndex : functionType.paramTypeIndices) {
+ auto paramType = intel_npu::vm::extractFuncParamResType(reader, paramTypeIndex);
+ if (!paramType.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to extract parameter type for param type index {} in function at index {} "
+ "in function section header {}",
+ paramTypeIndex, i, headerIdx);
+ return false;
+ }
+ paramTypes.push_back(std::move(paramType.value()));
+ }
+ std::vector<intel_npu::vm::FuncParamResType> resultTypes;
+ for (auto resultTypeIndex : functionType.resultTypeIndices) {
+ auto resultType = intel_npu::vm::extractFuncParamResType(reader, resultTypeIndex);
+ if (!resultType.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "Failed to extract result type for result type index {} in function at index {} "
+ "in function section header {}",
+ resultTypeIndex, i, headerIdx);
+ return false;
+ }
+ resultTypes.push_back(std::move(resultType.value()));
+ }
+
+ const auto numGeneralRegisters = funcInfo.numGeneralRegisters;
+ if (numGeneralRegisters < paramTypes.size()) {
+ NPU_VM_LOG_ERROR("Function '{}' does not have enough general registers to hold all parameters. "
+ "Required: {}, "
+ "available: {}.",
+ functionName, paramTypes.size(), numGeneralRegisters);
+ return false;
+ }
+ if (numGeneralRegisters > std::numeric_limits<int16_t>::max()) {
+ NPU_VM_LOG_ERROR("Function '{}' has too many general registers: {}. Maximum supported is {}.",
+ functionName, numGeneralRegisters, std::numeric_limits<int16_t>::max());
+ return false;
+ }
+
+ const auto isEntrypoint = funcSectionInfo->entrypointFunctionIndex == i;
+ const auto& section = sections.at(headerIdx);
+ if (funcInfo.bodyOffset > section.size() || funcInfo.bodySize > section.size() - funcInfo.bodyOffset) {
+ NPU_VM_LOG_ERROR("Function body exceeds section bounds for function {}", functionName);
+ return false;
+ }
+ const auto functionBody = section.subspan(funcInfo.bodyOffset, funcInfo.bodySize);
+ _functions.emplace_back(functionName, numGeneralRegisters, isEntrypoint, std::move(paramTypes),
+ std::move(resultTypes), functionBody, /*copyBody=*/copyBytecode);
+
+ if (!_functions.back().parseInstructionOffsets()) {
+ NPU_VM_LOG_ERROR("Failed to pre-decode instruction offsets for function '{}'",
+ _functions.back().getName());
+ return false;
+ }
+ }
+ }
+
+ for (size_t headerIdx = 0; headerIdx < sectionHeaders.size(); ++headerIdx) {
+ const auto& header = sectionHeaders.at(headerIdx);
+ if (header.type != intel_npu::vm::SectionType::KernelSection) {
+ continue;
+ }
+
+ auto kernelSectionInfo = dynamic_cast<intel_npu::vm::details::DataSectionInfo*>(header.info.get());
+ if (kernelSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("Kernel section header does not contain data section info");
+ return false;
+ }
+ if (headerIdx >= sections.size()) {
+ NPU_VM_LOG_ERROR("Could not find associated section with section header {}", headerIdx);
+ return false;
+ }
+ const auto& section = sections.at(headerIdx);
+
+ for (auto& dataInfo : kernelSectionInfo->dataInfos) {
+ if (dataInfo.offset > section.size() || dataInfo.size > section.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("Kernel binary exceeds section bounds: offset={}, size={}, sectionSize={}",
+ dataInfo.offset, dataInfo.size, section.size());
+ return false;
+ }
+ const auto kernelBinary = section.subspan(dataInfo.offset, dataInfo.size);
+ _kernelBinaries.emplace_back(kernelBinary, /*copyData=*/copyBytecode);
+ }
+ }
+
+ for (size_t headerIdx = 0; headerIdx < sectionHeaders.size(); ++headerIdx) {
+ const auto& header = sectionHeaders.at(headerIdx);
+ if (header.type != intel_npu::vm::SectionType::StringSection) {
+ continue;
+ }
+
+ auto stringSectionInfo = dynamic_cast<intel_npu::vm::details::DataSectionInfo*>(header.info.get());
+ if (stringSectionInfo == nullptr) {
+ NPU_VM_LOG_ERROR("String section header does not contain data section info");
+ return false;
+ }
+ if (headerIdx >= sections.size()) {
+ NPU_VM_LOG_ERROR("Could not find associated section with section header {}", headerIdx);
+ return false;
+ }
+ const auto& section = sections.at(headerIdx);
+
+ for (auto& dataInfo : stringSectionInfo->dataInfos) {
+ if (dataInfo.offset > section.size() || dataInfo.size > section.size() - dataInfo.offset) {
+ NPU_VM_LOG_ERROR("String data exceeds section bounds: offset={}, size={}, sectionSize={}",
+ dataInfo.offset, dataInfo.size, section.size());
+ return false;
+ }
+ const auto rawString = section.subspan(dataInfo.offset, dataInfo.size);
+ _rawStrings.emplace_back(rawString, /*copyData=*/copyBytecode);
+ }
+ }
+
+ _networkMetadata = parseNetworkMetadata(reader);
+
+ return true;
+ }
+
+public:
+ /// Creates a BytecodeModule from the given bytecode buffer
+ /// @param bytecode The buffer containing the bytecode to parse and create the module from
+ /// @param copyBytecode If true, the module will make a copy of the bytecode and own the memory. If false, the
+ /// module will reference the provided bytecode directly, meaning the caller must ensure the bytecode remains valid
+ /// for the lifetime of the module
+ /// @return A unique pointer to the created BytecodeModule if parsing succeeded, or nullptr if parsing failed
+ static std::unique_ptr<BytecodeModule> createFrom(const intel_npu::vm::Span<uint8_t>& bytecode,
+ bool copyBytecode = false) {
+ auto bytecodeModule = std::make_unique<BytecodeModule>();
+ if (!bytecodeModule->parse(bytecode, copyBytecode)) {
+ return nullptr;
+ }
+ return bytecodeModule;
+ }
+
+ /// Returns the list of all functions loaded from the bytecode
+ const std::vector<Function>& getFunctions() const {
+ return _functions;
+ }
+
+ const std::vector<ManagedVector<uint8_t>>& getConstants() const {
+ return _constants;
+ }
+
+ /// Returns a function by name among the loaded functions
+ /// @param name The name of the function to find
+ /// @return A pointer to the Function if found, or nullptr
+ Function* getFunction(std::string_view name) {
+ for (auto& function : _functions) {
+ if (function.getName() == name) {
+ return &function;
+ }
+ }
+ return nullptr;
+ }
+
+ /// Returns the list of all kernel binaries loaded from the bytecode
+ std::vector<ManagedVector<uint8_t>>& getKernelBinaries() {
+ return _kernelBinaries;
+ }
+
+ const std::vector<ManagedVector<uint8_t>>& getRawStrings() const {
+ return _rawStrings;
+ }
+
+ /// Returns the vector containing the byte size of each type entry, indexed by the type's index in the bytecode type
+ /// section
+ std::vector<uint16_t>& getTypeByteSizes() {
+ return _typeByteSizes;
+ }
+
+ void setNetworkMetadata(const NetworkMetadata& metadata) {
+ _networkMetadata = metadata;
+ }
+
+ const std::optional<NetworkMetadata>& getNetworkMetadata() const {
+ return _networkMetadata;
+ }
+};
+
+// Groups the buffer state a single inference needs: the active BufferManager, its bytecode-level metadata, and
+// the Level Zero context plus bookkeeping that decide when the manager must be (re)installed. Kept together so
+// the install/recycle policy lives in one place rather than scattered across EngineState members (see ensure()).
+class ContextBuffers {
+ // Host-arena-backed until ensure() installs a context-appropriate manager before inference.
+ BufferManager _manager{DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeHostAllocator()};
+ std::unordered_map<BufferHandle, BufferMetadata> _metadata; // Bytecode-level metadata per handle
+ ze_context_handle_t _allocatorContext = nullptr; // nullptr for a host-backed manager
+ bool _managerInstalled = false;
+
+public:
+ BufferManager& manager() {
+ return _manager;
+ }
+
+ std::unordered_map<BufferHandle, BufferMetadata>& metadata() {
+ return _metadata;
+ }
+
+ // Install a context-appropriate BufferManager before an inference. With a Level Zero context,
+ // (re)install a device-backed manager whenever the context changes so owned buffers are NPU-visible.
+ // Without a context, install a host-backed manager only if none exists yet, so an intervening predict
+ // call does not clobber a device manager from a prior execute.
+ void ensure(ze_context_handle_t ctx) {
+ const bool contextChanged = (ctx != nullptr && ctx != _allocatorContext);
+ if (_managerInstalled && !contextChanged) {
+ // Same context: keep the grown arena and recycle its memory so this inference reuses the
+ // previous one's. No external reset required.
+ _manager.recycle();
+ _metadata.clear();
+ return;
+ }
+ // Reached only when no manager is installed yet, or the device context changed. Build one to match
+ // the incoming context: a GrowingArena over Level Zero (NPU-visible) for a device context, or a
+ // host-memory arena when there is none (first-time predict / offline execute). A null context with a
+ // manager already installed returned above, so it never clobbers an existing (possibly device) manager.
+ AnyAllocator allocator = ctx != nullptr ? makeLevelZeroAllocator(ctx) : makeHostAllocator();
+ _manager = BufferManager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, std::move(allocator));
+ _allocatorContext = ctx;
+ _managerInstalled = true;
+ _metadata.clear();
+ }
+
+ // Per-inference cleanup invoked from EngineState::reset(): drop the previous inference's buffers and
+ // metadata but keep the grown arena, so the next inference on the same context reuses its memory instead
+ // of re-growing it. Genuine release of the underlying memory happens on a context change (the rebuild in
+ // ensure()) and on destruction; see recycle() vs reset() in buffer.hpp.
+ void recycle() noexcept {
+ _manager.recycle();
+ _metadata.clear();
+ }
+};
+
+class ConstantPool {
+ // Bytecode parsing only gives us constant payloads as views into the parsed module. That storage is not the right
+ // runtime owner for zero-copy buffers because BUFFER_FROM_CONST needs the bytes to stay alive after the VM turns
+ // them into buffer handles, and createFromMemory() only borrows memory instead of extending its lifetime.
+ //
+ // ConstantPool is the missing owner: it copies each constant once into allocator-backed shared memory, keeps that
+ // storage alive for the whole module lifetime, and stores the resulting memory as spans. BUFFER_FROM_CONST can
+ // then create read-only handles directly on top of those spans without a second copy, while the pool still
+ // controls when the backing memory is released (module reload, context change, or engine destruction)
+ AnyAllocator _allocator{makeHostAllocator()};
+ std::vector<Block> _ownedBlocks;
+ std::vector<Span<const uint8_t>> _constants;
+ ze_context_handle_t _allocatorContext = nullptr;
+ std::shared_ptr<const BytecodeModule> _materializedModule;
+ bool _materialized = false;
+
+public:
+ ConstantPool() = default;
+ ConstantPool(const ConstantPool&) = delete;
+ ConstantPool& operator=(const ConstantPool&) = delete;
+ ConstantPool(ConstantPool&&) = default;
+ ConstantPool& operator=(ConstantPool&&) = default;
+ ~ConstantPool() {
+ deallocateAll();
+ }
+
+ void ensure(std::shared_ptr<const BytecodeModule> module, ze_context_handle_t ctx) {
+ // If we already materialized constants for this context, keep the existing
+ // storage and do nothing. Rebuilding is only needed when the Level Zero
+ // context changes or the module changes
+ const bool contextChanged = (ctx != _allocatorContext);
+ if (_materialized && !contextChanged && _materializedModule == module) {
+ return;
+ }
+
+ // Build a fresh pool for the new context so all constant bytes live in a
+ // stable allocator-owned block that survives VM buffer creation
+ ConstantPool nextPool;
+ nextPool._allocator = ctx != nullptr ? makeLevelZeroAllocator(ctx) : makeHostAllocator();
+ nextPool._allocatorContext = ctx;
+
+ // Copy every extracted constant once into allocator-backed storage.
+ // The VM will later create read-only buffer handles directly from these
+ // spans, so the pool owns the lifetime
+ const auto& sourceConstants = module->getConstants();
+ nextPool._ownedBlocks.reserve(sourceConstants.size());
+ nextPool._constants.reserve(sourceConstants.size());
+
+ for (const auto& constant : sourceConstants) {
+ const auto constantData = constant.get();
+ if (constantData.empty()) {
+ nextPool._constants.emplace_back();
+ continue;
+ }
+
+ auto block = nextPool._allocator.allocate(constantData.size());
+ if (!block) {
+ throw std::bad_alloc();
+ }
+
+ std::memcpy(block.ptr, constantData.data(), constantData.size());
+ nextPool._ownedBlocks.push_back(block);
+ nextPool._constants.emplace_back(Span<const uint8_t>(block.ptr, block.size));
+ }
+
+ deallocateAll();
+ *this = std::move(nextPool);
+ _materializedModule = std::move(module);
+ _materialized = true;
+ }
+
+ const std::vector<Span<const uint8_t>>& getConstants() const {
+ return _constants;
+ }
+
+ void deallocateAll() noexcept {
+ // Release the backing blocks first, then clear the span views and reset
+ // the allocator state so the next ensure() starts from a clean pool
+ for (auto& block : _ownedBlocks) {
+ _allocator.deallocate(block);
+ }
+ _ownedBlocks.clear();
+ _constants.clear();
+ _allocator.release();
+ _allocatorContext = nullptr;
+ _materializedModule.reset();
+ _materialized = false;
+ }
+};
+
+class EngineState {
+ ExecState _execState{ExecState::Initialized}; // Current execution state of the VM
+ const uint8_t* _pc{nullptr}; // Program counter
+
+ ContextBuffers _buffers; // BufferManager + metadata + the context bookkeeping that drives ensure()
+
+ using kernel_binary_handle_t = void*;
+ std::unordered_map<kernel_binary_handle_t, KernelInfo>
+ _kernelInfos; // Metadata for created kernels, keyed by their handles
+
+ ExecutionContext _executionContext;
+ ze_graph_dditable_ext_t* _graphDdiTableHandle =
+ nullptr; // Ddi table handle provided at execution time, used for kernel execution
+
+public:
+ EngineState() = default;
+ EngineState(const EngineState&) = delete;
+ EngineState& operator=(const EngineState&) = delete;
+ EngineState(EngineState&&) = delete;
+ EngineState& operator=(EngineState&&) = delete;
+ ~EngineState() {
+ destroyGraphHandles();
+ }
+
+ /// Resets the engine state to prepare for a new inference execution
+ /// Note: The _kernelInfos map is not cleared here, as the graph handles can be reused across inferences, to avoid
+ /// recreating them every time
+ bool reset(bool resetExecutionContext) {
+ _execState = ExecState::Initialized;
+ _pc = nullptr;
+ _buffers.recycle();
+ if (resetExecutionContext) {
+ if (_executionContext.reset()) {
+ NPU_VM_LOG_ERROR("Failed to reset execution context");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// Destroys all graph handles associated with the kernels in the current engine state
+ void destroyGraphHandles() {
+ if (_graphDdiTableHandle) {
+ for (auto& [_, kernelInfo] : _kernelInfos) {
+ auto graphHandle = kernelInfo.getGraphHandle();
+ if (graphHandle) {
+ _graphDdiTableHandle->pfnDestroy(graphHandle);
+ }
+ }
+ }
+ _kernelInfos.clear();
+ }
+
+ ExecState getExecState() const {
+ return _execState;
+ }
+
+ void setExecState(ExecState newState) {
+ _execState = newState;
+ }
+
+ const uint8_t* getPC() const {
+ return _pc;
+ }
+
+ void setPC(const uint8_t* newPC) {
+ _pc = newPC;
+ }
+
+ BufferManager& getBufferManager() {
+ return _buffers.manager();
+ }
+
+ std::unordered_map<BufferHandle, BufferMetadata>& getBufferMetadata() {
+ return _buffers.metadata();
+ }
+
+ // (Re)installs a context-appropriate BufferManager before an inference; see ContextBuffers::ensure.
+ void ensureBufferManager(ze_context_handle_t ctx) {
+ _buffers.ensure(ctx);
+ }
+
+ std::unordered_map<kernel_binary_handle_t, KernelInfo>& getKernelInfos() {
+ return _kernelInfos;
+ }
+
+ ExecutionContext& getExecutionContext() {
+ return _executionContext;
+ }
+
+ ze_graph_dditable_ext_t* getDDITableHandle() {
+ return _graphDdiTableHandle;
+ }
+
+ void setDDITableHandle(ze_graph_dditable_ext_t* ddiTableHandle) {
+ _graphDdiTableHandle = ddiTableHandle;
+ }
+};
+
+bool applyJump(EngineState& engineState, int64_t jumpOffset, const uint8_t* functionBodyStart,
+ const uint8_t* functionBodyEnd, const Function& function) {
+ if (jumpOffset == 0) {
+ return false;
+ }
+ const auto pc = engineState.getPC();
+ const auto bodySize = static_cast<int64_t>(functionBodyEnd - functionBodyStart);
+ const auto currentIndex = static_cast<int64_t>(pc - functionBodyStart);
+ if (jumpOffset > 0) {
+ if (jumpOffset >= bodySize - currentIndex) {
+ return false;
+ }
+ } else {
+ if (jumpOffset < -currentIndex) {
+ return false;
+ }
+ }
+ const auto targetIndex = currentIndex + jumpOffset;
+ // Reject jumps that would land in the middle of an instruction. Only body-relative offsets that
+ // correspond to a previously decoded instruction start are permitted.
+ if (!function.isValidInstructionOffset(static_cast<size_t>(targetIndex))) {
+ NPU_VM_LOG_ERROR("Jump target offset {} in function '{}' does not land on an instruction boundary "
+ "(jumpOffset={}, currentIndex={})",
+ targetIndex, function.getName(), jumpOffset, currentIndex);
+ return false;
+ }
+ engineState.setPC(std::next(pc, static_cast<std::ptrdiff_t>(jumpOffset)));
+ return true;
+}
+
+class VMEngine {
+ std::shared_ptr<BytecodeModule> _bytecodeModule;
+ ConstantPool _constantPool;
+ EngineState _state{};
+
+ // Advances the program counter by the given bytes
+ // No-op if the VM is not in the Running state
+ void incrementPC(size_t bytes);
+
+ // Interprets the instruction stream of the given function until a RET instruction is encountered or an unknown
+ // opcode halts execution
+ bool inferImpl(std::string_view functionName, Span<npu_vm_runtime_mem_ref_handle_t> inputMemRefs,
+ Span<npu_vm_runtime_mem_ref_handle_t> outputMemRefs);
+
+ // Interprets the instruction stream of the given function until a RET instruction is encountered or an unknown
+ // opcode halts execution. Results are written as raw register values to the provided sinks
+ void execute(intel_npu::vm::CallFrame entryFrame);
+
+public:
+ /// Loads a bytecode module into the engine, replacing any previously loaded module. The loaded module can then be
+ /// executed by calling its functions through the engine. The state of the engine is reset when a new module is
+ /// loaded
+ /// @param bytecodeModule The module to load into the engine
+ /// @param loadParams parameters to load a module
+ /// @return true if the module was successfully loaded, or false otherwise
+ bool loadModule(std::shared_ptr<BytecodeModule> bytecodeModule, npu_vm_module_load_params* loadParams);
+
+ /// Returns the currently loaded bytecode module, or nullptr if no module is loaded
+ const std::shared_ptr<BytecodeModule>& getModule() const;
+
+ /// Resets the internal state of the engine, to prepare for a new inference execution. This includes clearing any
+ /// cached data or resources from previous executions, but does not unload the currently loaded module
+ /// @param resetExecutionContext Whether to reset the execution context
+ /// @return true if the state was successfully reset, or false otherwise
+ bool resetState(bool resetExecutionContext);
+
+ /// Calls the given function with the specified arguments and storage for return values. The number and types of
+ /// the arguments / result values must match the function's parameter & result types.
+ /// @param name The name of the function to call
+ /// @param arguments The argument values to pass to the function
+ /// @param results The result values to store the function's output
+ /// @return true if the function executed and finalized successfully, or false otherwise
+ bool call(std::string_view name, Span<const npu_vm_value> arguments, Span<npu_vm_value> results);
+
+ /// Calls the main inference function with the specified execution parameters
+ /// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+ /// @return true if the function executed and finalized successfully, or false otherwise
+ /// @details The main inference function is expected to have the name 'main' and to have the same number and types
+ /// of parameters as specified in the execution parameters (i.e. buffers for all inputs and outputs)
+ bool infer(npu_vm_runtime_execute_params_t* params);
+
+ /// Calls the main inference function with the specified execution parameters
+ /// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+ /// @return true if the function executed and finalized successfully, or false otherwise
+ /// @details The main inference function is expected to have the name 'main' and to have the same number and types
+ /// of parameters as specified in the execution parameters (i.e. buffers for all inputs and outputs)
+ bool infer(npu_vm_runtime_execute_params2_t* params);
+
+ /// Calls the output shape prediction function with the specified execution parameters
+ /// @param params The execution parameters from the VM Runtime API, specifying the model's buffer information needed
+ /// for output shape prediction, and the result buffers where to store the predicted output shapes
+ /// @return true if the function executed and finalized successfully, or false otherwise
+ /// @details The output shape prediction function is expected to have the name 'output_shape' and to have
+ /// the same number and types of parameters as specified in the output shape prediction execution parameters (i.e.
+ /// buffers)
+ bool predictOutputShape(npu_vm_runtime_predict_output_shape_params_t2* params);
+
+ /// Host synchronizes the engine, blocking until all previously submitted commands have completed execution.
+ bool hostSync();
+
+ /// Submit recorded command lists
+ bool submitRecordedCmdLists(npu_vm_runtime_execute_params2_t* params);
+
+ /// Returns true if host code execution is required for the given execution parameters
+ /// @param params The execution parameters from the VM Runtime API, including input and output buffer information
+ bool hostCodeExecutionRequired(npu_vm_runtime_execute_params2_t* params);
+
+ /// Sets Level Zero objects for the engine, including the context and the DDI table
+ void setLevelZeroObjects(ze_context_handle_t ctx, ze_graph_dditable_ext_t* graphDdiTableExt);
+
+ void ensureConstantPool(ze_context_handle_t ctx) {
+ if (_bytecodeModule != nullptr) {
+ _constantPool.ensure(_bytecodeModule, ctx);
+ }
+ }
+};
+
+bool VMEngine::loadModule(std::shared_ptr<BytecodeModule> bytecodeModule, npu_vm_module_load_params* loadParams) {
+ if (bytecodeModule == nullptr) {
+ NPU_VM_LOG_ERROR("Cannot load a null bytecode module");
+ return false;
+ }
+ _bytecodeModule = std::move(bytecodeModule);
+ _state.reset(/*resetExecutionContext=*/true);
+ _state.destroyGraphHandles(); // Ensure any graph handles from a previous module are released
+ auto metadata = _bytecodeModule->getNetworkMetadata();
+
+ uint32_t concurrentJobCount = 1;
+ npu_vm_runtime_create_execution_context_params_t* params = nullptr;
+ if (loadParams != nullptr) {
+ if (loadParams->create_execution_context_params) {
+ params = loadParams->create_execution_context_params;
+ setLevelZeroObjects(params->ctx, params->graphDdiTableExt);
+ }
+ concurrentJobCount = loadParams->concurrentJobCount;
+ }
+ ensureConstantPool(params ? params->ctx : nullptr);
+
+ auto contextType = params ? ExecutionContext::ExecutionContextType::V2 : ExecutionContext::ExecutionContextType::V1;
+ if (metadata.has_value()) {
+ // V2 execution context is used when create_execution_context_params is provided,
+ // otherwise V1 execution context is used
+ auto& executionContext = _state.getExecutionContext();
+
+ // initialize the execution context with the number of command lists,
+ // number of network arguments, and concurrent job count
+ bool counterBasedEventSupported = (loadParams && loadParams->counterBasedEventSupported) ? true : false;
+ auto batchMode = (loadParams) ? loadParams->batchMode : npu_vm_batch_mode_none;
+ auto batchSize = (loadParams) ? loadParams->batchSize : 1;
+ bool result =
+ executionContext.initialize(contextType, static_cast<uint32_t>(metadata->numCmdLists),
+ static_cast<uint32_t>(metadata->inputs.size() + metadata->outputs.size()),
+ concurrentJobCount, counterBasedEventSupported, batchMode, batchSize);
+ if (result == false) {
+ NPU_VM_LOG_ERROR("Failed to initialize execution context");
+ return false;
+ }
+
+ if (params) {
+ auto initResult = executionContext.initializeExecutionObjects(
+ params->ctx, params->device, params->commandQueue, params->graphDdiTableExt,
+ params->commandQueueDdiTableExt, loadParams->internalCommandQueue);
+ if (initResult != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to initialize execution context");
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+const std::shared_ptr<BytecodeModule>& VMEngine::getModule() const {
+ return _bytecodeModule;
+}
+
+bool VMEngine::resetState(bool resetExecutionContext) {
+ return _state.reset(resetExecutionContext);
+}
+
+bool VMEngine::hostSync() {
+ auto& executionContext = _state.getExecutionContext();
+ if (executionContext.hostSync() != ZE_RESULT_SUCCESS) {
+ NPU_VM_LOG_ERROR("Failed to host sync execution context");
+ return false;
+ }
+ return true;
+}
+
+bool VMEngine::submitRecordedCmdLists(npu_vm_runtime_execute_params2_t* params) {
+ auto& executionContext = _state.getExecutionContext();
+ executionContext.setParams(params);
+ return executionContext.submitRecordedCmdLists() == ZE_RESULT_SUCCESS;
+}
+
+bool VMEngine::hostCodeExecutionRequired(npu_vm_runtime_execute_params2_t* params) {
+ auto& executionContext = _state.getExecutionContext();
+
+ if (!executionContext.isRecordedCmdListReusable()) {
+ return true;
+ }
+
+ constexpr uint32_t dirtyFlagNone = static_cast<uint32_t>(MemRef::DirtyFlag::NONE);
+ uint32_t tensorDirtyBits = dirtyFlagNone;
+ if (params->pInputs) {
+ for (uint32_t i = 0; i < params->numOfInputs; ++i) {
+ auto inputMemRefHandle = params->pInputs[i];
+ auto inputMemRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(inputMemRefHandle);
+ if (inputMemRef != nullptr && inputMemRef->dirtyFlags != dirtyFlagNone) {
+ tensorDirtyBits |= inputMemRef->dirtyFlags;
+ }
+ }
+ }
+
+ if (params->pOutputs) {
+ for (uint32_t i = 0; i < params->numOfOutputs; ++i) {
+ auto outputMemRefHandle = params->pOutputs[i];
+ auto outputMemRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(outputMemRefHandle);
+ if (outputMemRef != nullptr && outputMemRef->dirtyFlags != dirtyFlagNone) {
+ tensorDirtyBits |= outputMemRef->dirtyFlags;
+ }
+ }
+ }
+
+ return tensorDirtyBits != dirtyFlagNone;
+}
+
+void VMEngine::setLevelZeroObjects(ze_context_handle_t ctx, ze_graph_dditable_ext_t* graphDdiTableExt) {
+ // Install/refresh the BufferManager for this context before allocating buffers (see ensureBufferManager).
+ _state.ensureBufferManager(ctx);
+ // Materialize constants into the same memory space so BUFFER_FROM_CONST can
+ // borrow them through createFromMemory without a second copy
+ ensureConstantPool(ctx);
+ // Keep the DDI table to release graph handle later, as graph handles are created with the DDI table
+ _state.setDDITableHandle(graphDdiTableExt);
+}
+
+bool VMEngine::call(std::string_view name, Span<const npu_vm_value> arguments, Span<npu_vm_value> results) {
+ if (_bytecodeModule == nullptr) {
+ NPU_VM_LOG_ERROR("No bytecode module loaded in the engine");
+ return false;
+ }
+ auto function = _bytecodeModule->getFunction(name);
+ if (function == nullptr) {
+ NPU_VM_LOG_ERROR("Function '{}' not found among loaded functions", name);
+ return false;
+ }
+ const auto& paramTypes = function->getParamTypes();
+ if (arguments.size() != paramTypes.size()) {
+ NPU_VM_LOG_ERROR("Number of arguments passed ({}) does not match the function's parameter count ({})",
+ arguments.size(), paramTypes.size());
+ return false;
+ }
+
+ const auto& resultTypes = function->getResultTypes();
+ if (results.size() != resultTypes.size()) {
+ NPU_VM_LOG_ERROR("Number of result slots provided ({}) does not match the function's result count ({}).",
+ results.size(), resultTypes.size());
+ return false;
+ }
+
+ std::vector<int64_t> rawResults(resultTypes.size(), int64_t{0});
+ std::vector<int64_t*> resultTargets;
+ resultTargets.reserve(rawResults.size());
+ for (auto& value : rawResults) {
+ resultTargets.push_back(&value);
+ }
+
+ CallFrame frame(*function, EXIT_RETURN_ADDR, std::move(resultTargets));
+
+ // NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) - npu_vm_value is an union type from the C API
+
+ // Set the arguments into the parameter registers from the call frame
+ const auto firstParamRegIndex = function->getNumGeneralRegisters() - paramTypes.size();
+ for (size_t i = 0; i < paramTypes.size(); ++i) {
+ const auto paramType = paramTypes.at(i);
+ const auto& argument = arguments.at(i);
+ const auto typeCode = getTypeCode(paramType.type);
+ switch (typeCode) {
+ case TypeCode::INTEGER: {
+ const auto isSigned = isTypeSigned(paramType.type);
+ const auto bitWidth = getBitWidth(paramType.type);
+ if (bitWidth == sizeof(int8_t) * CHAR_BIT) {
+ auto value = isSigned ? static_cast<int64_t>(argument.i8) : static_cast<int64_t>(argument.u8);
+ frame.setReg(static_cast<int16_t>(firstParamRegIndex + i), value);
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type {}) to value: {}", i, isSigned ? "i8" : "u8", value);
+ } else if (bitWidth == sizeof(int16_t) * CHAR_BIT) {
+ auto value = isSigned ? static_cast<int64_t>(argument.i16) : static_cast<int64_t>(argument.u16);
+ frame.setReg(static_cast<int16_t>(firstParamRegIndex + i), value);
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type {}) to value: {}", i, isSigned ? "i16" : "u16", value);
+ } else if (bitWidth == sizeof(int32_t) * CHAR_BIT) {
+ auto value = isSigned ? static_cast<int64_t>(argument.i32) : static_cast<int64_t>(argument.u32);
+ frame.setReg(static_cast<int16_t>(firstParamRegIndex + i), value);
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type {}) to value: {}", i, isSigned ? "i32" : "u32", value);
+ } else if (bitWidth == sizeof(int64_t) * CHAR_BIT) {
+ auto value = isSigned ? argument.i64 : vmBitCast<int64_t>(argument.u64);
+ frame.setReg(static_cast<int16_t>(firstParamRegIndex + i), value);
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type {}) to value: {}", i, isSigned ? "i64" : "u64", value);
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported integer bit width for argument {}: {} bits", i,
+ static_cast<int>(bitWidth));
+ return false;
+ }
+ break;
+ }
+ case TypeCode::FLOAT: {
+ const auto bitWidth = getBitWidth(paramType.type);
+ if (bitWidth == sizeof(float) * CHAR_BIT) {
+ std::memcpy(&frame.getReg(static_cast<int16_t>(firstParamRegIndex + i)), &argument.f32, sizeof(float));
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type f32) to value: {}", i, argument.f32);
+ } else if (bitWidth == sizeof(double) * CHAR_BIT) {
+ std::memcpy(&frame.getReg(static_cast<int16_t>(firstParamRegIndex + i)), &argument.f64, sizeof(double));
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type f64) to value: {}", i, argument.f64);
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported float bit width for argument {}: {} bits", i, static_cast<int>(bitWidth));
+ return false;
+ }
+ break;
+ }
+ case TypeCode::BUFFER: {
+ auto* data = static_cast<uint8_t*>(argument.buffer.data);
+ const auto size = argument.buffer.size;
+ if (data == nullptr) {
+ NPU_VM_LOG_ERROR("Null buffer pointer for argument {}", i);
+ return false;
+ }
+ if (size == 0) {
+ NPU_VM_LOG_ERROR("Zero-sized buffer for argument {}", i);
+ return false;
+ }
+ BufferHandle handle = 0;
+ try {
+ // npu_vm_call* arguments can alias host memory; create an unowned read-only VM handle over the buffer
+ handle = _state.getBufferManager().createFromMemory(data, size, Permission::Read);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Failed to bind buffer argument {}: {}", i, e.what());
+ return false;
+ }
+
+ frame.setReg(static_cast<int16_t>(firstParamRegIndex + i), static_cast<int64_t>(handle));
+ NPU_VM_LOG_DEBUG(" Setting parameter {} (type buffer) to handle={} size={}", i, handle, size);
+ break;
+ }
+ default: {
+ NPU_VM_LOG_ERROR("Unsupported parameter type for argument {}", i);
+ return false;
+ }
+ }
+ }
+
+ _state.setExecState(ExecState::Running);
+ execute(std::move(frame));
+ if (_state.getExecState() != ExecState::Finalized) {
+ return false;
+ }
+
+ // Internal CALL/RETV propagation now moves raw register payloads through int64_t sinks.
+ // This conversion keeps the public call() API contract by decoding those payloads into
+ // the caller-provided ValueType variants at the API boundary
+ for (size_t i = 0; i < resultTypes.size(); ++i) {
+ const auto resultType = resultTypes.at(i);
+ auto& result = results.at(i);
+ const auto rawResult = rawResults.at(i);
+ const auto typeCode = getTypeCode(resultType.type);
+ if (typeCode == TypeCode::INTEGER) {
+ const auto isSigned = isTypeSigned(resultType.type);
+ const auto bitWidth = getBitWidth(resultType.type);
+ if (bitWidth == sizeof(int8_t) * CHAR_BIT) {
+ if (isSigned) {
+ result.i8 = static_cast<int8_t>(rawResult);
+ } else {
+ result.u8 = static_cast<uint8_t>(rawResult);
+ }
+ } else if (bitWidth == sizeof(int16_t) * CHAR_BIT) {
+ if (isSigned) {
+ result.i16 = static_cast<int16_t>(rawResult);
+ } else {
+ result.u16 = static_cast<uint16_t>(rawResult);
+ }
+ } else if (bitWidth == sizeof(int32_t) * CHAR_BIT) {
+ if (isSigned) {
+ result.i32 = static_cast<int32_t>(rawResult);
+ } else {
+ result.u32 = static_cast<uint32_t>(rawResult);
+ }
+ } else if (bitWidth == sizeof(int64_t) * CHAR_BIT) {
+ if (isSigned) {
+ result.i64 = rawResult;
+ } else {
+ result.u64 = vmBitCast<uint64_t>(rawResult);
+ }
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported integer bit width for result {}: {} bits", i, static_cast<int>(bitWidth));
+ return false;
+ }
+ } else if (typeCode == TypeCode::FLOAT) {
+ const auto bitWidth = getBitWidth(resultType.type);
+ if (bitWidth == sizeof(float) * CHAR_BIT) {
+ std::memcpy(&result.f32, &rawResult, sizeof(float));
+ } else if (bitWidth == sizeof(double) * CHAR_BIT) {
+ std::memcpy(&result.f64, &rawResult, sizeof(double));
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported float bit width for result {}: {} bits", i, static_cast<int>(bitWidth));
+ return false;
+ }
+ } else if (typeCode == TypeCode::BUFFER) {
+ const auto handle = static_cast<BufferHandle>(rawResult);
+
+ if (!_state.getBufferManager().exists(handle)) {
+ NPU_VM_LOG_ERROR("Unknown buffer handle in result {}: {}", i, handle);
+ return false;
+ }
+ auto& buffer = _state.getBufferManager().getBuffer(handle);
+ auto& resultBuffer = result.buffer;
+
+ // The user provided an empty buffer slot for the result, so allocate memory for the result buffer and set
+ // the data pointer and size in the result buffer
+ if (resultBuffer.data == nullptr) {
+ if (resultBuffer.size != 0) {
+ NPU_VM_LOG_ERROR("Result {} has null data pointer but non-zero size in the provided results array.",
+ i);
+ return false;
+ }
+ // NOLINTNEXTLINE - malloc is used here to allow the caller to free the buffer memory with free()
+ resultBuffer.data = reinterpret_cast<uint8_t*>(malloc(buffer.getSize()));
+ if (resultBuffer.data == nullptr) {
+ NPU_VM_LOG_ERROR("Failed to allocate memory for buffer result {}", i);
+ return false;
+ }
+ resultBuffer.size = static_cast<uint32_t>(buffer.getSize());
+ } else {
+ // The user provided a buffer for the result, so write the result to the provided buffer. The caller is
+ // responsible for ensuring that the provided buffer has sufficient size to hold the result.
+ if (resultBuffer.size < buffer.getSize()) {
+ NPU_VM_LOG_ERROR("Provided buffer for result {} is too small. Required size: {}, provided size: {}",
+ i, buffer.getSize(), resultBuffer.size);
+ return false;
+ }
+ }
+ std::memcpy(resultBuffer.data, buffer.getData(), buffer.getSize());
+ } else {
+ NPU_VM_LOG_ERROR("Unsupported result type for result {}", i);
+ return false;
+ }
+ }
+ // NOLINTEND(cppcoreguidelines-pro-type-union-access)
+
+ return _state.getExecState() == ExecState::Finalized;
+}
+
+bool VMEngine::inferImpl(std::string_view functionName, Span<npu_vm_runtime_mem_ref_handle_t> inputMemRefs,
+ Span<npu_vm_runtime_mem_ref_handle_t> outputMemRefs) {
+ if (_bytecodeModule == nullptr) {
+ NPU_VM_LOG_ERROR("No bytecode module loaded in the engine");
+ return false;
+ }
+ auto function = _bytecodeModule->getFunction(functionName);
+ if (function == nullptr) {
+ NPU_VM_LOG_ERROR("Could not find entrypoint function with name '{}'", functionName);
+ return false;
+ }
+
+ const auto funcNumParams = function->getParamTypes().size();
+ if (funcNumParams != (inputMemRefs.size() + outputMemRefs.size())) {
+ NPU_VM_LOG_ERROR("Number of inputs and outputs passed ({}) does not match the function's parameter count ({})",
+ inputMemRefs.size() + outputMemRefs.size(), funcNumParams);
+ return false;
+ }
+
+ CallFrame frame(*function, EXIT_RETURN_ADDR, std::vector<int64_t*>{});
+
+ const auto firstInputParamRegIndex = function->getNumGeneralRegisters() - funcNumParams;
+ const auto firstOutputParamRegIndex = firstInputParamRegIndex + inputMemRefs.size();
+
+ for (uint32_t i = 0; i < inputMemRefs.size(); ++i) {
+ auto handle =
+ extractMemRef(inputMemRefs.at(i), _state.getBufferManager(), _state.getBufferMetadata(),
+ Permission::Read, function->getParamTypes().at(i), _bytecodeModule->getTypeByteSizes());
+ if (!handle.has_value()) {
+ NPU_VM_LOG_ERROR("Failed to extract memref for input {}", i);
+ return false;
+ }
+ frame.setReg(static_cast<int16_t>(firstInputParamRegIndex + i), static_cast<int64_t>(handle.value()));
+ NPU_VM_LOG_DEBUG(" Set input {} buffer handle {}", i, handle.value());
+ }
+ for (uint32_t i = 0; i < outputMemRefs.size(); ++i) {
+ const auto outputMemRef = outputMemRefs.at(i);
+ auto handle = extractMemRef(outputMemRef, _state.getBufferManager(), _state.getBufferMetadata(),
+ Permission::ReadWrite, function->getParamTypes().at(i + inputMemRefs.size()),
+ _bytecodeModule->getTypeByteSizes());
+ if (!handle.has_value()) {
+ NPU_VM_LOG_ERROR("Failed to extract memref for output {}", i);
+ return false;
+ }
+ frame.setReg(static_cast<int16_t>(firstOutputParamRegIndex + i), static_cast<int64_t>(handle.value()));
+ NPU_VM_LOG_DEBUG(" Set output {} buffer handle {}", i, handle.value());
+ }
+
+ // The infer method does not return values directly, but instead stores the inference results into output
+ // buffers whose handles are passed as parameters
+ _state.setExecState(ExecState::Running);
+ execute(std::move(frame));
+
+ return _state.getExecState() == ExecState::Finalized;
+}
+
+bool VMEngine::infer(npu_vm_runtime_execute_params_t* params) {
+ if (_state.getDDITableHandle() == nullptr) {
+ setLevelZeroObjects(params->ctx, params->graphDdiTableExt);
+ }
+
+ auto& executionContext = _state.getExecutionContext();
+ executionContext.setParams(params);
+
+ return inferImpl(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ Span<npu_vm_runtime_mem_ref_handle_t>(params->pInputs, params->numOfInputs),
+ Span<npu_vm_runtime_mem_ref_handle_t>(params->pOutputs, params->numOfOutputs));
+}
+
+bool VMEngine::infer(npu_vm_runtime_execute_params2_t* params) {
+ auto& executionContext = _state.getExecutionContext();
+ executionContext.setParams(params);
+
+ auto result = inferImpl(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ Span<npu_vm_runtime_mem_ref_handle_t>(params->pInputs, params->numOfInputs),
+ Span<npu_vm_runtime_mem_ref_handle_t>(params->pOutputs, params->numOfOutputs));
+
+ // Update tensor dirty flag to NONE after successful inference,
+ // so that the next inference can skip host code execution if the tensor is not modified
+ if (result) {
+ constexpr uint32_t dirtyFlagNone = static_cast<uint32_t>(MemRef::DirtyFlag::NONE);
+ if (params->pInputs) {
+ for (uint32_t i = 0; i < params->numOfInputs; ++i) {
+ auto inputMemRefHandle = params->pInputs[i];
+ auto inputMemRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(inputMemRefHandle);
+ inputMemRef->dirtyFlags = dirtyFlagNone;
+ }
+ }
+
+ if (params->pOutputs) {
+ for (uint32_t i = 0; i < params->numOfOutputs; ++i) {
+ auto outputMemRefHandle = params->pOutputs[i];
+ auto outputMemRef = reinterpret_cast<npu_vm_runtime_mem_ref*>(outputMemRefHandle);
+ outputMemRef->dirtyFlags = dirtyFlagNone;
+ }
+ }
+ }
+
+ return result;
+}
+
+bool VMEngine::predictOutputShape(npu_vm_runtime_predict_output_shape_params_t2* params) {
+ // No Level Zero context here: keep any device manager from a prior execute, else install a host one.
+ _state.ensureBufferManager(/*ctx=*/nullptr);
+ if (params->numOfOutputs == 0 || params->pOutputs == nullptr) {
+ NPU_VM_LOG_ERROR("Number of outputs is zero or output pointer is null. At least one output is required for "
+ "output shape prediction.");
+ return false;
+ }
+
+ const auto numOutputs = params->numOfOutputs;
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto* const outputs = reinterpret_cast<npu_vm_runtime_mem_ref**>(params->pOutputs);
+
+ // Backing storage for the predicted shapes: one 1D vector per output, each sized to that output's rank
+ std::vector<std::vector<int64_t>> predictedOutputShapes(numOutputs);
+ // 1D MemRefs describing predictedOutputShapes, passed to the prediction function as output arguments
+ std::vector<npu_vm_runtime_mem_ref> predictedOutputShapeMemrefs(numOutputs, npu_vm_runtime_mem_ref(1));
+ std::vector<npu_vm_runtime_mem_ref*> predictedOutputShapeMemrefPtrs(numOutputs);
+
+ for (uint32_t i = 0; i < numOutputs; ++i) {
+ const auto* output = *std::next(outputs, static_cast<std::ptrdiff_t>(i));
+ if (output == nullptr || output->dimsCount <= 0) {
+ NPU_VM_LOG_ERROR("Invalid output tensor");
+ return false;
+ }
+
+ auto& predictedShape = predictedOutputShapes.at(i);
+ predictedShape.assign(static_cast<size_t>(output->dimsCount), 0);
+
+ // Describe the predicted shape as a packed 1D tensor of length dimsCount
+ auto& memref = predictedOutputShapeMemrefs.at(i);
+ memref.basePtr = memref.data = predictedShape.data();
+ memref.sizes.at(0) = output->dimsCount;
+ memref.strides.at(0) = 1;
+
+ predictedOutputShapeMemrefPtrs.at(i) = &memref;
+ }
+
+ const auto outputStoragePtr =
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ reinterpret_cast<npu_vm_runtime_mem_ref_handle_t*>(predictedOutputShapeMemrefPtrs.data());
+ // Inputs and outputs are passed as function arguments to the output shape prediction function
+ if (!inferImpl(NPU_VM_OUTPUT_SHAPE_PREDICTION_FUNCTION_NAME,
+ Span<npu_vm_runtime_mem_ref_handle_t>(params->pInputs, params->numOfInputs),
+ Span<npu_vm_runtime_mem_ref_handle_t>(outputStoragePtr, numOutputs))) {
+ NPU_VM_LOG_ERROR("Output shape prediction function execution failed.");
+ return false;
+ }
+
+ // Write the predicted shapes and matching packed strides back into the caller-provided memrefs
+ for (uint32_t i = 0; i < numOutputs; ++i) {
+ auto* output = *std::next(outputs, static_cast<std::ptrdiff_t>(i));
+ const auto& predictedShape = predictedOutputShapes.at(i);
+
+ output->sizes = predictedShape;
+
+ // Packed (row-major) strides: the innermost dimension has stride 1 and each outer
+ // dimension's stride is the product of the sizes to its right
+ std::vector<int64_t> strides(predictedShape.size());
+ int64_t stride = 1;
+ for (size_t dim = predictedShape.size(); dim-- > 0;) {
+ strides.at(dim) = stride;
+ stride *= predictedShape.at(dim);
+ }
+ output->strides = std::move(strides);
+ }
+
+ return true;
+}
+
+void VMEngine::incrementPC(size_t bytes) {
+ if (_state.getExecState() != ExecState::Running) {
+ return;
+ }
+ const auto pc = _state.getPC();
+ _state.setPC(std::next(pc, static_cast<std::ptrdiff_t>(bytes)));
+ NPU_VM_LOG_DEBUG(" pc: {}", static_cast<const void*>(_state.getPC()));
+}
+
+void VMEngine::execute(CallFrame entryFrame) {
+ // maxCallDepth bounds the number of nested calls. Reserving the worst-case capacity up front guarantees the
+ // call stack never reallocates, so the caller register buffers that callee result sinks point into stay at
+ // stable addresses for the whole call chain. Each frame carries the function it executes and the result sinks
+ // that RETV writes into, so arbitrarily deep bytecode call chains run on this heap-allocated stack instead of
+ // the native C++ call stack.
+ constexpr size_t maxCallDepth = 1000;
+ std::vector<CallFrame> callStack;
+ callStack.reserve(maxCallDepth + 1);
+ callStack.push_back(std::move(entryFrame));
+
+ const Function& entryFunction = callStack.back().getFunction();
+ _state.setPC(entryFunction.getBody().begin());
+
+ NPU_VM_LOG_DEBUG("Executing function '{}' with {} parameter(s) and {} result(s)", entryFunction.getName(),
+ entryFunction.getParamTypes().size(), entryFunction.getResultTypes().size());
+ NPU_VM_LOG_DEBUG(" call depth: {}", callStack.size() - 1);
+ NPU_VM_LOG_DEBUG(" pc: {}", static_cast<const void*>(_state.getPC()));
+
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+
+ // Main dispatch loop: decode the opcode at the current program counter, execute the corresponding operation, then
+ // advance the PC by the instruction size. CALL/RET/RETV mutate the call stack rather than recursing. The
+ // loop exits when the call stack drains or the state transitions away from Running.
+ while (_state.getExecState() == ExecState::Running && !callStack.empty()) {
+ CallFrame& frame = callStack.back();
+ const Function& function = frame.getFunction();
+ std::vector<int64_t*>& results = frame.getResults();
+
+ const auto functionBodyStart = function.getBody().begin();
+ const auto endOfFunction = function.getBody().end();
+
+ const auto pc = _state.getPC();
+ if (pc >= endOfFunction) {
+ // The function body ran out before an explicit RET/RETV. Well-formed bytecode always returns, so treat a
+ // run past the end as a malformed-body error rather than silently unwinding.
+ NPU_VM_LOG_ERROR("Reached end of function body '{}' without a return instruction. This likely means the "
+ "function body is malformed.",
+ function.getName());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto bytesAvailable = static_cast<size_t>(endOfFunction - pc);
+ OpCode opcode{};
+ size_t instructionSize{};
+ if (!decodeInstruction(pc, bytesAvailable, opcode, instructionSize)) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ switch (opcode) {
+ case OpCode::ADD_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Cast to uint64_t first to avoid UB from signed overflow, then cast back to int64_t after the addition
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, static_cast<int64_t>(lhs + rhs));
+ NPU_VM_LOG_DEBUG(" add.i64 {}, {}, {} ({} + {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::SET: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ frame.setReg(dstRegNum, frame.getReg(srcRegNum));
+ NPU_VM_LOG_DEBUG(" set {}, {} (reg[{}] = {})", dstRegNum, srcRegNum, dstRegNum, frame.getReg(srcRegNum));
+ break;
+ }
+ case OpCode::SET_IMM: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto immValue = get64BitImm(pc, 1);
+ frame.setReg(dstRegNum, immValue);
+ NPU_VM_LOG_DEBUG(" set.imm {}, {} (reg[{}] = {})", dstRegNum, immValue, dstRegNum, immValue);
+ break;
+ }
+ case OpCode::ASSERT: {
+ const auto conditionRegNum = getOperand(pc, 0);
+ const auto msgSymIndex = getOperand(pc, 1);
+ NPU_VM_LOG_DEBUG(" assert {}, {}", conditionRegNum, msgSymIndex);
+ if (frame.getReg(conditionRegNum) == 0) {
+ const auto& rawStrings = _bytecodeModule->getRawStrings();
+ if (msgSymIndex >= 0 && static_cast<size_t>(msgSymIndex) < rawStrings.size()) {
+ const auto rawString = rawStrings.at(msgSymIndex).get();
+ std::string message(rawString.begin(), rawString.end());
+ NPU_VM_LOG_ERROR("Assertion failed: {}", message);
+ } else {
+ NPU_VM_LOG_ERROR("Assertion failed: ? (message not found; index {})", msgSymIndex);
+ }
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::MUL_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Cast to uint64_t first to avoid UB from signed overflow, then cast back to int64_t after the
+ // multiplication
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, static_cast<int64_t>(lhs * rhs));
+ NPU_VM_LOG_DEBUG(" mul.i64 {}, {}, {} ({} * {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::MIN_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ frame.setReg(dstRegNum, std::min(frame.getReg(srcReg1Num), frame.getReg(srcReg2Num)));
+ NPU_VM_LOG_DEBUG(" min.i64 {}, {}, {} (min({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::MAX_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ frame.setReg(dstRegNum, std::max(frame.getReg(srcReg1Num), frame.getReg(srcReg2Num)));
+ NPU_VM_LOG_DEBUG(" max.i64 {}, {}, {} (max({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::CMP_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto flag = static_cast<uint16_t>(getOperand(pc, 3));
+ const auto cmpType = static_cast<uint8_t>(flag & 0xFF);
+ const bool isSigned = (flag >> 8) & 0x1;
+ const auto result = isSigned ? evaluateCmp(frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), cmpType)
+ : evaluateCmp(static_cast<uint64_t>(frame.getReg(srcReg1Num)),
+ static_cast<uint64_t>(frame.getReg(srcReg2Num)), cmpType);
+ if (!result.has_value()) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ frame.setReg(dstRegNum, *result);
+ NPU_VM_LOG_DEBUG(" cmp.i64 {}, {}, {}, {} (cmp({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num, flag,
+ isSigned ? frame.getReg(srcReg1Num) : static_cast<uint64_t>(frame.getReg(srcReg1Num)),
+ isSigned ? frame.getReg(srcReg2Num) : static_cast<uint64_t>(frame.getReg(srcReg2Num)),
+ *result);
+ break;
+ }
+ case OpCode::CMP_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto flag = static_cast<uint16_t>(getOperand(pc, 3));
+ const auto cmpType = static_cast<uint8_t>(flag & 0xFF);
+ double lhs = 0.0, rhs = 0.0;
+ std::memcpy(&lhs, &frame.getReg(srcReg1Num), sizeof(double));
+ std::memcpy(&rhs, &frame.getReg(srcReg2Num), sizeof(double));
+ const auto result = evaluateCmp(lhs, rhs, cmpType);
+ if (!result.has_value()) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ frame.setReg(dstRegNum, *result);
+ NPU_VM_LOG_DEBUG(" cmp.f64 {}, {}, {}, {} (cmp({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num, flag,
+ lhs, rhs, *result);
+ break;
+ }
+ case OpCode::SUB_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Cast to uint64_t first to avoid UB from signed overflow, then cast back to int64_t after the subtraction
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, static_cast<int64_t>(lhs - rhs));
+ NPU_VM_LOG_DEBUG(" sub.i64 {}, {}, {} ({} - {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::DIV_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto rhs = frame.getReg(srcReg2Num);
+ if (rhs == 0) {
+ NPU_VM_LOG_ERROR("Division by zero error in DIV_I64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto lhs = frame.getReg(srcReg1Num);
+ if (lhs == std::numeric_limits<int64_t>::min() && rhs == -1) {
+ // Handle overflow case where result cannot be represented as int64_t. In this case, the result of the
+ // division operation is defined to be INT64_MIN (INT64_MAX + 1)
+ frame.setReg(dstRegNum, std::numeric_limits<int64_t>::min());
+
+ } else {
+ frame.setReg(dstRegNum, lhs / rhs);
+ }
+ NPU_VM_LOG_DEBUG(" div.i64 {}, {}, {} ({} / {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::DIV_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ if (rhs == 0) {
+ NPU_VM_LOG_ERROR("Division by zero error in DIV_U64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs / rhs));
+ NPU_VM_LOG_DEBUG(" div.u64 {}, {}, {} ({} / {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ static_cast<uint64_t>(frame.getReg(srcReg1Num)),
+ static_cast<uint64_t>(frame.getReg(srcReg2Num)),
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MIN_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::min(lhs, rhs)));
+ NPU_VM_LOG_DEBUG(" min.u64 {}, {}, {} (min({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num, lhs, rhs,
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::ADD_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs + rhs));
+ NPU_VM_LOG_DEBUG(" add.u64 {}, {}, {} ({} + {} = {})", dstRegNum, srcReg1Num, srcReg2Num, lhs, rhs,
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MAX_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::max(lhs, rhs)));
+ NPU_VM_LOG_DEBUG(" max.u64 {}, {}, {} (max({}, {}) = {})", dstRegNum, srcReg1Num, srcReg2Num, lhs, rhs,
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MUL_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs * rhs));
+ NPU_VM_LOG_DEBUG(" mul.u64 {}, {}, {} ({} * {} = {})", dstRegNum, srcReg1Num, srcReg2Num, lhs, rhs,
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::REM_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ if (rhs == 0) {
+ NPU_VM_LOG_ERROR("Division by zero error in REM_U64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs % rhs));
+ NPU_VM_LOG_DEBUG(" rem.u64 {}, {}, {} ({} %% {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ static_cast<uint64_t>(frame.getReg(srcReg1Num)),
+ static_cast<uint64_t>(frame.getReg(srcReg2Num)),
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::SUB_U64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto lhs = static_cast<uint64_t>(frame.getReg(srcReg1Num));
+ const auto rhs = static_cast<uint64_t>(frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs - rhs));
+ NPU_VM_LOG_DEBUG(" sub.u64 {}, {}, {} ({} - {} = {})", dstRegNum, srcReg1Num, srcReg2Num, lhs, rhs,
+ static_cast<uint64_t>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::REM_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ const auto rhs = frame.getReg(srcReg2Num);
+ if (rhs == 0) {
+ NPU_VM_LOG_ERROR("Division by zero error in REM_I64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto lhs = frame.getReg(srcReg1Num);
+ if (lhs == std::numeric_limits<int64_t>::min() && rhs == -1) {
+ // Handle overflow case where result cannot be represented as int64_t. In this case, the
+ // result of the remainder operation is defined to be 0
+ frame.setReg(dstRegNum, 0);
+ } else {
+ frame.setReg(dstRegNum, lhs % rhs);
+ }
+ NPU_VM_LOG_DEBUG(" rem.i64 {}, {}, {} ({} % {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::ABS_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto value = frame.getReg(srcRegNum);
+ if (value == std::numeric_limits<int64_t>::min()) {
+ // Handle overflow case where abs(INT64_MIN) cannot be represented in an int64_t. In this case, the
+ // result of the absolute value operation is defined to be INT64_MIN.
+ frame.setReg(dstRegNum, std::numeric_limits<int64_t>::min());
+ } else {
+ frame.setReg(dstRegNum, std::abs(value));
+ }
+ NPU_VM_LOG_DEBUG(" abs.i64 {}, {} (abs({}) = {})", dstRegNum, srcRegNum, frame.getReg(srcRegNum),
+ frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::AND_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ frame.setReg(dstRegNum, frame.getReg(srcReg1Num) & frame.getReg(srcReg2Num));
+ NPU_VM_LOG_DEBUG(" and.64 {}, {}, {} ({} & {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::NOT_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ frame.setReg(dstRegNum, ~frame.getReg(srcRegNum));
+ NPU_VM_LOG_DEBUG(" not.64 {}, {} (~{} = {})", dstRegNum, srcRegNum, frame.getReg(srcRegNum),
+ frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::OR_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ frame.setReg(dstRegNum, frame.getReg(srcReg1Num) | frame.getReg(srcReg2Num));
+ NPU_VM_LOG_DEBUG(" or.64 {}, {}, {} ({} | {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::XOR_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ frame.setReg(dstRegNum, frame.getReg(srcReg1Num) ^ frame.getReg(srcReg2Num));
+ NPU_VM_LOG_DEBUG(" xor.64 {}, {}, {} ({} ^ {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), frame.getReg(srcReg2Num), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::SLL_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Force the shift amount into the valid 0-63 range
+ const auto shiftAmount = frame.getReg(srcReg2Num) & 63;
+ const auto unsignedResult = static_cast<uint64_t>(frame.getReg(srcReg1Num)) << shiftAmount;
+ const auto signedResult = convertUnsignedToSignedPreserveBits<int64_t>(unsignedResult);
+ frame.setReg(dstRegNum, signedResult);
+ NPU_VM_LOG_DEBUG(" sll.64 {}, {}, {} ({} << {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), shiftAmount, signedResult);
+ break;
+ }
+ case OpCode::SRL_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Force the shift amount into the valid 0-63 range
+ const auto shiftAmount = frame.getReg(srcReg2Num) & 63;
+ const auto unsignedResult = static_cast<uint64_t>(frame.getReg(srcReg1Num)) >> shiftAmount;
+ const auto signedResult = convertUnsignedToSignedPreserveBits<int64_t>(unsignedResult);
+ frame.setReg(dstRegNum, signedResult);
+ NPU_VM_LOG_DEBUG(" srl.64 {}, {}, {} ({} >> {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), shiftAmount, signedResult);
+ break;
+ }
+ case OpCode::SRA_64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcReg1Num = getOperand(pc, 1);
+ const auto srcReg2Num = getOperand(pc, 2);
+ // Arithmetic right shift with defined behavior for negative operands.
+ // Returns int64_t directly; no sign extension needed.
+ const auto shiftedValue =
+ arithmeticShiftRightDefined<int64_t>(frame.getReg(srcReg1Num), frame.getReg(srcReg2Num));
+ frame.setReg(dstRegNum, shiftedValue);
+ NPU_VM_LOG_DEBUG(" sra.64 {}, {}, {} ({} >> {} = {})", dstRegNum, srcReg1Num, srcReg2Num,
+ frame.getReg(srcReg1Num), (frame.getReg(srcReg2Num) & 63), frame.getReg(dstRegNum));
+ break;
+ }
+ case OpCode::SELECT: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto condRegNum = getOperand(pc, 1);
+ const auto trueRegNum = getOperand(pc, 2);
+ const auto falseRegNum = getOperand(pc, 3);
+ const auto result = frame.getReg(condRegNum) != 0 ? frame.getReg(trueRegNum) : frame.getReg(falseRegNum);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" select {}, {}, {}, {} (if {} then {} else {} = {})", dstRegNum, condRegNum, trueRegNum,
+ falseRegNum, frame.getReg(condRegNum), frame.getReg(trueRegNum), frame.getReg(falseRegNum),
+ result);
+ break;
+ }
+ case OpCode::ADD_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs + rhs));
+ NPU_VM_LOG_DEBUG(" add.f64 {}, {}, {} ({} + {} = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::SUB_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs - rhs));
+ NPU_VM_LOG_DEBUG(" sub.f64 {}, {}, {} ({} - {} = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MUL_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs * rhs));
+ NPU_VM_LOG_DEBUG(" mul.f64 {}, {}, {} ({} * {} = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::DIV_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(lhs / rhs));
+ NPU_VM_LOG_DEBUG(" div.f64 {}, {}, {} ({} / {} = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::REM_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::fmod(lhs, rhs)));
+ NPU_VM_LOG_DEBUG(" rem.f64 {}, {}, {} ({} % {} = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MAX_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::fmax(lhs, rhs)));
+ NPU_VM_LOG_DEBUG(" max.f64 {}, {}, {} (max({}, {}) = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::MIN_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto lhsRegNum = getOperand(pc, 1);
+ const auto rhsRegNum = getOperand(pc, 2);
+ const auto lhs = vmBitCast<double>(frame.getReg(lhsRegNum));
+ const auto rhs = vmBitCast<double>(frame.getReg(rhsRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::fmin(lhs, rhs)));
+ NPU_VM_LOG_DEBUG(" min.f64 {}, {}, {} (min({}, {}) = {})", dstRegNum, lhsRegNum, rhsRegNum, lhs, rhs,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::ABS_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::fabs(src)));
+ NPU_VM_LOG_DEBUG(" abs.f64 {}, {} (abs({}) = {})", dstRegNum, srcRegNum, src,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::NEG_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(-src));
+ NPU_VM_LOG_DEBUG(" neg.f64 {}, {} (-{} = {})", dstRegNum, srcRegNum, src,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::CEIL_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::ceil(src)));
+ NPU_VM_LOG_DEBUG(" ceil.f64 {}, {} (ceil({}) = {})", dstRegNum, srcRegNum, src,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::FLOOR_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(std::floor(src)));
+ NPU_VM_LOG_DEBUG(" floor.f64 {}, {} (floor({}) = {})", dstRegNum, srcRegNum, src,
+ vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::ROUND_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto mode = static_cast<RoundingMode>(getOperand(pc, 2));
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ double result{};
+ switch (mode) {
+ case RoundingMode::RNE: {
+ // Change the rounding mode to FE_TONEAREST for the call to std::nearbyint, then restore the original
+ // rounding mode. The change of the rounding mode in the environment is thread local
+ const auto origRoundMode = std::fegetround();
+ if (std::fesetround(FE_TONEAREST) != 0) {
+ NPU_VM_LOG_ERROR("Failed to set rounding mode to FE_TONEAREST for round.f64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ result = std::nearbyint(src);
+ if (std::fesetround(origRoundMode) != 0) {
+ NPU_VM_LOG_ERROR("Failed to restore original rounding mode after round.f64 instruction");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ break;
+ }
+ case RoundingMode::RNA: {
+ result = std::round(src);
+ break;
+ }
+ case RoundingMode::RDN:
+ result = std::floor(src);
+ break;
+ case RoundingMode::RUP:
+ result = std::ceil(src);
+ break;
+ case RoundingMode::RTZ:
+ result = std::trunc(src);
+ break;
+ default:
+ NPU_VM_LOG_ERROR("Unknown rounding mode {} in round.f64 instruction", static_cast<int16_t>(mode));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ if (_state.getExecState() == ExecState::Halted) {
+ break;
+ }
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" round.f64 {}, {}, {} (round({}) = {})", dstRegNum, srcRegNum,
+ static_cast<int16_t>(mode), src, vmBitCast<double>(frame.getReg(dstRegNum)));
+ break;
+ }
+ case OpCode::BUFFER_CREATE: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto elemTypeIdx = static_cast<int64_t>(getOperand(pc, 1));
+ const auto rank = static_cast<int64_t>(getOperand(pc, 2));
+ if (rank < 0) {
+ NPU_VM_LOG_ERROR("buffer.create requires non-negative rank, got {}", rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto elemByteSize =
+ intel_npu::vm::lookupTypeByteSize(_bytecodeModule->getTypeByteSizes(), elemTypeIdx);
+ if (elemByteSize == 0) {
+ NPU_VM_LOG_ERROR("buffer.create references unknown or non-primitive type index {}, type table size={}",
+ elemTypeIdx, _bytecodeModule->getTypeByteSizes().size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ BufferMetadata meta;
+ meta.elemTypeIndex = elemTypeIdx;
+ meta.elemByteSize = elemByteSize;
+ meta.shape.reserve(rank);
+ meta.strides.reserve(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ meta.shape.push_back(frame.getReg(getOperand(pc, 3 + i)));
+ }
+ for (int64_t i = 0; i < rank; ++i) {
+ meta.strides.push_back(frame.getReg(getOperand(pc, 3 + rank + i)));
+ }
+ if (!intel_npu::vm::validateShapeAndStrides("buffer.create", meta)) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto byteSize = intel_npu::vm::computeLogicalByteSize(meta);
+ if (!byteSize.has_value()) {
+ NPU_VM_LOG_ERROR("buffer.create size overflows the addressable range, shape={}, strides={}, element "
+ "byte size={}",
+ intel_npu::vm::formatVector(meta.shape), intel_npu::vm::formatVector(meta.strides),
+ meta.elemByteSize);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ try {
+ const auto handle = _state.getBufferManager().create(static_cast<size_t>(*byteSize),
+ Permission::ReadWrite, /*zeroInitialized*/ true);
+ _state.getBufferMetadata().emplace(handle, std::move(meta));
+ frame.setReg(dstReg, static_cast<int64_t>(handle));
+ NPU_VM_LOG_DEBUG(" buffer.create -> handle {}, ({} bytes)", handle, *byteSize);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.create failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_FROM_CONST: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto constantIndex = getOperand(pc, 1);
+ const auto elemTypeIdx = static_cast<int64_t>(getOperand(pc, 2));
+ const auto rank = static_cast<int64_t>(getOperand(pc, 3));
+ if (constantIndex < 0 || rank < 0 || rank > intel_npu::vm::BufferType::MAX_RANK) {
+ NPU_VM_LOG_ERROR(
+ "buffer.from_const requires non-negative constant index and rank in [0, {}], got {} and {}",
+ intel_npu::vm::BufferType::MAX_RANK, constantIndex, rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto elemByteSize =
+ intel_npu::vm::lookupTypeByteSize(_bytecodeModule->getTypeByteSizes(), elemTypeIdx);
+ const auto& constants = _constantPool.getConstants();
+ if (elemByteSize == 0 || static_cast<size_t>(constantIndex) >= constants.size()) {
+ NPU_VM_LOG_ERROR("buffer.from_const references unknown type {} or constant {}", elemTypeIdx,
+ constantIndex);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ BufferMetadata meta;
+ meta.elemTypeIndex = elemTypeIdx;
+ meta.elemByteSize = elemByteSize;
+ meta.shape.reserve(rank);
+ meta.strides.reserve(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ meta.shape.push_back(frame.getReg(getOperand(pc, 4 + i)));
+ meta.strides.push_back(frame.getReg(getOperand(pc, 4 + rank + i)));
+ }
+ if (!intel_npu::vm::validateShapeAndStrides("buffer.from_const", meta)) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto byteSize = intel_npu::vm::computeLogicalByteSize(meta);
+ const auto constantData = constants.at(static_cast<size_t>(constantIndex));
+ if (!byteSize.has_value() || *byteSize != constantData.size()) {
+ NPU_VM_LOG_ERROR("buffer.from_const descriptor size {} does not match constant {} size {}",
+ byteSize.has_value() ? std::to_string(*byteSize) : "<overflow>", constantIndex,
+ constantData.size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ try {
+ const auto handle = _state.getBufferManager().createFromMemory(
+ const_cast<uint8_t*>(constantData.data()), constantData.size(), Permission::Read);
+ _state.getBufferMetadata().emplace(handle, std::move(meta));
+ frame.setReg(dstReg, static_cast<int64_t>(handle));
+ NPU_VM_LOG_DEBUG(" buffer.from_const -> handle {}, constant {}", handle, constantIndex);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.from_const failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_GET_DIM: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto bufReg = getOperand(pc, 1);
+ const auto dimReg = getOperand(pc, 2);
+ const auto handle = static_cast<BufferHandle>(frame.getReg(bufReg));
+ const auto dim = frame.getReg(dimReg);
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ const auto it = bufferMetadata.find(handle);
+ if (it == bufferMetadata.end() || !bufferManager.exists(handle)) {
+ NPU_VM_LOG_ERROR("buffer.get_dim on unknown buffer handle {}", handle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto& shape = it->second.shape;
+ if (dim < 0 || static_cast<size_t>(dim) >= shape.size()) {
+ NPU_VM_LOG_ERROR("buffer.get_dim dimension index {} is out of range for buffer {} with rank {}", dim,
+ handle, shape.size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ frame.setReg(dstReg, shape.at(static_cast<size_t>(dim)));
+ NPU_VM_LOG_DEBUG(" buffer.get_dim {}, {}, {} (source handle {}, dim {}, value {})", dstReg, bufReg, dimReg,
+ handle, dim, frame.getReg(dstReg));
+ break;
+ }
+ case OpCode::BUFFER_SUBVIEW: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto srcReg = getOperand(pc, 1);
+ const auto rank = static_cast<int64_t>(getOperand(pc, 2));
+ if (rank < 0) {
+ NPU_VM_LOG_ERROR("buffer.subview requires non-negative rank, got {}", rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto srcHandle = static_cast<BufferHandle>(frame.getReg(srcReg));
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ auto srcIt = bufferMetadata.find(srcHandle);
+ if (srcIt == bufferMetadata.end() || !bufferManager.exists(srcHandle) ||
+ static_cast<int64_t>(srcIt->second.shape.size()) != rank ||
+ static_cast<int64_t>(srcIt->second.strides.size()) != rank) {
+ NPU_VM_LOG_ERROR("buffer.subview invalid handle or rank mismatch: handle={}, encoded rank={}, buffer "
+ "rank={}, stride rank={}",
+ srcHandle, rank, srcIt != bufferMetadata.end() ? srcIt->second.shape.size() : 0,
+ srcIt != bufferMetadata.end() ? srcIt->second.strides.size() : 0);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ std::vector<int64_t> offsets(rank), sizes(rank), strides(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ offsets.at(i) = frame.getReg(getOperand(pc, 3 + i));
+ }
+ for (int64_t i = 0; i < rank; ++i) {
+ sizes.at(i) = frame.getReg(getOperand(pc, 3 + rank + i));
+ }
+ for (int64_t i = 0; i < rank; ++i) {
+ strides.at(i) = frame.getReg(getOperand(pc, 3 + 2 * rank + i));
+ }
+ const auto startElem = computeSubviewStartElement(srcIt->second, offsets, sizes, strides);
+ if (!startElem.has_value()) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ BufferMetadata newMeta;
+ newMeta.elemTypeIndex = srcIt->second.elemTypeIndex;
+ newMeta.elemByteSize = srcIt->second.elemByteSize;
+ newMeta.shape = std::move(sizes);
+ newMeta.strides.reserve(rank);
+ for (int64_t i = 0; i < rank; ++i) {
+ const auto dimIdx = static_cast<size_t>(i);
+ int64_t composedStride = 0;
+ if (!checkedMultiplyNonNegative(strides.at(dimIdx), srcIt->second.strides.at(dimIdx), composedStride)) {
+ NPU_VM_LOG_ERROR("buffer.subview stride overflows at dim {}: subview stride={}, source stride={}",
+ i, strides.at(dimIdx), srcIt->second.strides.at(dimIdx));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ newMeta.strides.push_back(composedStride);
+ }
+ if (_state.getExecState() == ExecState::Halted) {
+ break;
+ }
+
+ try {
+ uint64_t byteOffset = 0;
+ const auto byteSize = computeLogicalByteSize(newMeta);
+ const auto elemByteSize = static_cast<uint64_t>(srcIt->second.elemByteSize);
+ if (!byteSize.has_value() || !checkedMultiply(*startElem, elemByteSize, byteOffset)) {
+ NPU_VM_LOG_ERROR("buffer.subview byte range overflows for source handle {}: start element={}, "
+ "element byte size={}, byte offset={}, byte size={}",
+ srcHandle, *startElem, elemByteSize, byteOffset,
+ byteSize.has_value() ? std::to_string(*byteSize) : "<overflow>");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto newHandle = bufferManager.createFromBuffer(srcHandle, byteOffset, *byteSize);
+ bufferMetadata.emplace(newHandle, std::move(newMeta));
+ frame.setReg(dstReg, static_cast<int64_t>(newHandle));
+ NPU_VM_LOG_DEBUG(" buffer.subview -> handle {}, (source handle {}, byteOffset {}, byteSize {})",
+ newHandle, srcHandle, byteOffset, *byteSize);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.subview failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_VIEW: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto srcReg = getOperand(pc, 1);
+ const auto byteOffsetReg = getOperand(pc, 2);
+ const auto elemTypeIdx = static_cast<int64_t>(getOperand(pc, 3));
+ const auto rank = static_cast<int64_t>(getOperand(pc, 4));
+ if (rank < 0) {
+ NPU_VM_LOG_ERROR("buffer.view requires non-negative rank, got {}", rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto srcHandle = static_cast<BufferHandle>(frame.getReg(srcReg));
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ const auto srcIt = bufferMetadata.find(srcHandle);
+ if (srcIt == bufferMetadata.end() || !bufferManager.exists(srcHandle)) {
+ NPU_VM_LOG_ERROR("buffer.view on unknown buffer handle {}", srcHandle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto byteOffset = static_cast<uint64_t>(frame.getReg(byteOffsetReg));
+ const auto elemByteSize =
+ intel_npu::vm::lookupTypeByteSize(_bytecodeModule->getTypeByteSizes(), elemTypeIdx);
+ if (elemByteSize == 0) {
+ NPU_VM_LOG_ERROR("buffer.view references unknown or non-primitive type index {}, type table size={}",
+ elemTypeIdx, _bytecodeModule->getTypeByteSizes().size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ BufferMetadata newMeta;
+ newMeta.elemTypeIndex = elemTypeIdx;
+ newMeta.elemByteSize = elemByteSize;
+ newMeta.shape.reserve(rank);
+ newMeta.strides.reserve(rank);
+ constexpr auto shapeStartIndex = 5;
+ for (int64_t i = 0; i < rank; ++i) {
+ newMeta.shape.push_back(frame.getReg(getOperand(pc, shapeStartIndex + i)));
+ }
+ for (int64_t i = 0; i < rank; ++i) {
+ newMeta.strides.push_back(frame.getReg(getOperand(pc, shapeStartIndex + rank + i)));
+ }
+ if (!intel_npu::vm::validateShapeAndStrides("buffer.view", newMeta)) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto byteSize = intel_npu::vm::computeLogicalByteSize(newMeta);
+ if (!byteSize.has_value()) {
+ NPU_VM_LOG_ERROR(
+ "buffer.view size overflows the addressable range, shape={}, strides={}, element byte size={}",
+ intel_npu::vm::formatVector(newMeta.shape), intel_npu::vm::formatVector(newMeta.strides),
+ newMeta.elemByteSize);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto& srcBuf = bufferManager.getBuffer(srcHandle);
+ if (byteOffset > srcBuf.getSize() || *byteSize > srcBuf.getSize() - byteOffset) {
+ NPU_VM_LOG_ERROR("buffer.view byte offset {} + view size {} exceeds source buffer size {}", byteOffset,
+ *byteSize, srcBuf.getSize());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ try {
+ const auto newHandle = bufferManager.createFromBuffer(srcHandle, byteOffset, *byteSize);
+ bufferMetadata.emplace(newHandle, std::move(newMeta));
+ frame.setReg(dstReg, static_cast<int64_t>(newHandle));
+ NPU_VM_LOG_DEBUG(" buffer.view -> handle {} ({} bytes)", newHandle, *byteSize);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.view failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_STORE: {
+ const auto bufReg = getOperand(pc, 0);
+ const auto valReg = getOperand(pc, 1);
+ const auto rank = static_cast<int64_t>(getOperand(pc, 2));
+ if (rank < 0) {
+ NPU_VM_LOG_ERROR("buffer.store requires non-negative rank, got {}", rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto handle = static_cast<BufferHandle>(frame.getReg(bufReg));
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ const auto it = bufferMetadata.find(handle);
+ if (it == bufferMetadata.end() || !bufferManager.exists(handle) ||
+ static_cast<int64_t>(it->second.shape.size()) != rank ||
+ static_cast<int64_t>(it->second.strides.size()) != rank) {
+ NPU_VM_LOG_ERROR("buffer.store invalid handle or rank mismatch: handle={}, encoded rank={}, buffer "
+ "rank={}, stride rank={}",
+ handle, rank, it != bufferMetadata.end() ? it->second.shape.size() : 0,
+ it != bufferMetadata.end() ? it->second.strides.size() : 0);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto& meta = it->second;
+ uint64_t elemOffset = 0;
+ bool indexFailure = false;
+ for (int64_t i = 0; i < rank; ++i) {
+ const auto idx = frame.getReg(getOperand(pc, 3 + i));
+ const auto dimIdx = static_cast<size_t>(i);
+ if (idx < 0 || idx >= meta.shape.at(dimIdx) || meta.strides.at(dimIdx) < 0) {
+ NPU_VM_LOG_ERROR(
+ "buffer.store index {} at dim {} is out of range for buffer {} (shape={}, strides={})", idx,
+ i, handle, intel_npu::vm::formatVector(meta.shape),
+ intel_npu::vm::formatVector(meta.strides));
+ indexFailure = true;
+ break;
+ }
+ if (!checkedAddProduct(static_cast<uint64_t>(idx), static_cast<uint64_t>(meta.strides.at(dimIdx)),
+ elemOffset)) {
+ NPU_VM_LOG_ERROR("buffer.store linear offset overflows at dim {}: index={}, stride={}", i, idx,
+ meta.strides.at(dimIdx));
+ indexFailure = true;
+ break;
+ }
+ }
+ if (indexFailure) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ uint64_t byteOffset = 0;
+ const auto elemByteSize = static_cast<uint64_t>(meta.elemByteSize);
+ if (!checkedMultiply(elemOffset, elemByteSize, byteOffset)) {
+ NPU_VM_LOG_ERROR(
+ "buffer.store byte offset overflows for handle {}: element offset={}, element byte size={}",
+ handle, elemOffset, elemByteSize);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ try {
+ auto& buf = bufferManager.getBuffer(handle);
+ if (buf.getPermission() != Permission::ReadWrite) {
+ NPU_VM_LOG_ERROR("buffer.store on read-only buffer handle {}", handle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ if ((byteOffset > buf.getSize()) || (elemByteSize > (buf.getSize() - byteOffset))) {
+ NPU_VM_LOG_ERROR("buffer.store out-of-bounds: byteOffset={}, elemByteSize={}, buffer size={}",
+ byteOffset, elemByteSize, buf.getSize());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const int64_t valueWord = frame.getReg(valReg);
+ if (elemByteSize > sizeof(valueWord)) {
+ NPU_VM_LOG_ERROR("buffer.store element size {} exceeds register-backed value width {}",
+ elemByteSize, sizeof(valueWord));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ std::array<uint8_t, sizeof(valueWord)> valueBytes{};
+ std::memcpy(valueBytes.data(), &valueWord, sizeof(valueWord));
+ buf.writeData(byteOffset, valueBytes.data(), static_cast<size_t>(elemByteSize));
+ NPU_VM_LOG_DEBUG(" buffer.store handle={}, byteOffset={}, elemByteSize={}, value={}", handle,
+ byteOffset, elemByteSize, valueWord);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.store failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_LOAD: {
+ const auto dstReg = getOperand(pc, 0);
+ const auto bufReg = getOperand(pc, 1);
+ const auto rank = static_cast<int64_t>(getOperand(pc, 2));
+ if (rank < 0) {
+ NPU_VM_LOG_ERROR("buffer.load requires non-negative rank, got {}", rank);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto handle = static_cast<BufferHandle>(frame.getReg(bufReg));
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ // Load shares the same shape/rank contract as buffer.store: the encoded rank must match the
+ // buffer metadata so the variadic index operands are interpreted against the right tensor rank
+ const auto it = bufferMetadata.find(handle);
+ if (it == bufferMetadata.end() || !bufferManager.exists(handle) ||
+ static_cast<int64_t>(it->second.shape.size()) != rank ||
+ static_cast<int64_t>(it->second.strides.size()) != rank) {
+ NPU_VM_LOG_ERROR("buffer.load invalid handle or rank mismatch: handle={}, encoded rank={}, buffer "
+ "rank={}, stride rank={}",
+ handle, rank, it != bufferMetadata.end() ? it->second.shape.size() : 0,
+ it != bufferMetadata.end() ? it->second.strides.size() : 0);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ const auto& meta = it->second;
+ uint64_t elemOffset = 0;
+ bool indexFailure = false;
+ for (int64_t i = 0; i < rank; ++i) {
+ const auto idx = frame.getReg(getOperand(pc, 3 + i));
+ const auto dimIdx = static_cast<size_t>(i);
+ // Reject negative, out-of-bounds, and negatively-strided accesses before computing the flattened
+ // element offset. The VM only supports forward linearization for direct buffer loads
+ if (idx < 0 || idx >= meta.shape.at(dimIdx) || meta.strides.at(dimIdx) < 0) {
+ NPU_VM_LOG_ERROR(
+ "buffer.load index {} at dim {} is out of range for buffer {} (shape={}, strides={})", idx,
+ i, handle, intel_npu::vm::formatVector(meta.shape),
+ intel_npu::vm::formatVector(meta.strides));
+ indexFailure = true;
+ break;
+ }
+ // Accumulate the logical element offset using the precomputed stride for each dimension
+ if (!checkedAddProduct(static_cast<uint64_t>(idx), static_cast<uint64_t>(meta.strides.at(dimIdx)),
+ elemOffset)) {
+ NPU_VM_LOG_ERROR("buffer.load linear offset overflows at dim {}: index={}, stride={}", i, idx,
+ meta.strides.at(dimIdx));
+ indexFailure = true;
+ break;
+ }
+ }
+ if (indexFailure) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ uint64_t byteOffset = 0;
+ const auto elemByteSize = static_cast<uint64_t>(meta.elemByteSize);
+ // Convert element offset to bytes only after the full linear index is known, so overflow handling stays
+ // centralized in the checked multiply helper
+ if (!checkedMultiply(elemOffset, elemByteSize, byteOffset)) {
+ NPU_VM_LOG_ERROR(
+ "buffer.load byte offset overflows for handle {}: element offset={}, element byte size={}",
+ handle, elemOffset, elemByteSize);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ if (elemByteSize > sizeof(int64_t)) {
+ NPU_VM_LOG_ERROR("buffer.load element size {} exceeds register-backed value width {}", elemByteSize,
+ sizeof(int64_t));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ try {
+ auto& buf = bufferManager.getBuffer(handle);
+ // Write directly into the destination register storage. Zero the whole register first so narrower
+ // element types still have a deterministic widened representation in the 64-bit register file
+ auto& valueWord = frame.getReg(dstReg);
+ valueWord = 0;
+ buf.readData(byteOffset, reinterpret_cast<uint8_t*>(&valueWord), static_cast<size_t>(elemByteSize));
+ NPU_VM_LOG_DEBUG(" buffer.load handle={}, byteOffset={}, elemByteSize={}, value={}", handle,
+ byteOffset, elemByteSize, valueWord);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.load failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::BUFFER_COPY: {
+ const auto dstHandle = static_cast<BufferHandle>(frame.getReg(getOperand(pc, 0)));
+ const auto srcHandle = static_cast<BufferHandle>(frame.getReg(getOperand(pc, 1)));
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+ const auto dstIt = bufferMetadata.find(dstHandle);
+ const auto srcIt = bufferMetadata.find(srcHandle);
+ if (dstIt == bufferMetadata.end() || srcIt == bufferMetadata.end() || !bufferManager.exists(dstHandle) ||
+ !bufferManager.exists(srcHandle)) {
+ NPU_VM_LOG_ERROR("buffer.copy uses an unknown buffer handle: dst={}, src={}", dstHandle, srcHandle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto& dstMeta = dstIt->second;
+ const auto& srcMeta = srcIt->second;
+ if (dstMeta.elemTypeIndex != srcMeta.elemTypeIndex || dstMeta.shape != srcMeta.shape ||
+ dstMeta.strides != srcMeta.strides) {
+ NPU_VM_LOG_ERROR("buffer.copy requires matching buffer descriptors: dst={} elemType={} shape={} "
+ "strides={}, src={} elemType={} shape={} strides={}",
+ dstHandle, dstMeta.elemTypeIndex, intel_npu::vm::formatVector(dstMeta.shape),
+ intel_npu::vm::formatVector(dstMeta.strides), srcHandle, srcMeta.elemTypeIndex,
+ intel_npu::vm::formatVector(srcMeta.shape),
+ intel_npu::vm::formatVector(srcMeta.strides));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto byteSize = intel_npu::vm::computeLogicalByteSize(dstMeta);
+ if (!byteSize.has_value()) {
+ NPU_VM_LOG_ERROR("buffer.copy descriptor size overflows");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ try {
+ auto& dstBuffer = bufferManager.getBuffer(dstHandle);
+ const auto& srcBuffer = static_cast<const BufferManager&>(bufferManager).getBuffer(srcHandle);
+ if (dstBuffer.getSize() != *byteSize || srcBuffer.getSize() != *byteSize) {
+ NPU_VM_LOG_ERROR("buffer.copy descriptor size does not match source or destination buffer size");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ dstBuffer.copyDataFrom(srcBuffer);
+ NPU_VM_LOG_DEBUG(" buffer.copy dst={}, src={}, size={}", dstHandle, srcHandle, *byteSize);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("buffer.copy failed: {}", e.what());
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::CMD_LIST_CREATE: {
+ ze_command_list_handle_t handle = nullptr;
+ if (_state.getExecutionContext().createCmdList(handle) != ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ const auto dstRegNum = getOperand(pc, 0);
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ frame.setReg(dstRegNum, static_cast<int64_t>(reinterpret_cast<uint64_t>(handle)));
+ break;
+ }
+ case OpCode::CMD_LIST_CLOSE: {
+ const auto srcRegNum = getOperand(pc, 0);
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto cmdListHandle = reinterpret_cast<ze_command_list_handle_t>(frame.getReg(srcRegNum));
+ if (_state.getExecutionContext().closeCmdList(cmdListHandle) != ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::CMD_LIST_EXEC: {
+ const auto srcRegNum = getOperand(pc, 0);
+ const auto hostSyncFlag = getOperand(pc, 1);
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto cmdListHandle = reinterpret_cast<ze_command_list_handle_t>(frame.getReg(srcRegNum));
+ if (submitCmdList(_state.getExecutionContext(), cmdListHandle, hostSyncFlag != 0) != ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::CMD_LIST_ADD_KERNEL: {
+ size_t index = 0;
+ const auto cmdListHandleRegNum = getOperand(pc, index++);
+ const auto kernelHandleRegNum = getOperand(pc, index++);
+ const auto numSignalEvents = getOperand(pc, index++);
+ if (numSignalEvents != 0) {
+ NPU_VM_LOG_ERROR("cmd_list.add_kernel with non-zero signal events is not yet supported");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ const auto numWaitEvents = getOperand(pc, index++);
+ if (numSignalEvents != 0 || numWaitEvents != 0) {
+ NPU_VM_LOG_ERROR("cmd_list.add_kernel with non-zero wait events is not yet supported");
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
+ auto cmdListHandle = reinterpret_cast<ze_command_list_handle_t>(frame.getReg(cmdListHandleRegNum));
+ auto graphHandle = reinterpret_cast<ze_graph_handle_t>(frame.getReg(kernelHandleRegNum));
+ // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
+ if (executeGraph(_state.getExecutionContext(), cmdListHandle, graphHandle, nullptr) != ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ }
+ break;
+ }
+ case OpCode::KERNEL_CREATE: {
+ std::vector<BufferMapperItem> inputs;
+ std::vector<BufferMapperItem> outputs;
+ size_t operandIndex = 0;
+ const auto dstRegNum = getOperand(pc, operandIndex++);
+ const auto kernelIndex = getOperand(pc, operandIndex++);
+ const auto kernelNameIndex = getOperand(pc, operandIndex++);
+
+ auto& kernelBinaries = _bytecodeModule->getKernelBinaries();
+ if (static_cast<size_t>(kernelIndex) >= kernelBinaries.size()) {
+ NPU_VM_LOG_ERROR("kernel_create with explicit kernel index is not supported in this stub. index: {}, "
+ "kernelBinaries.size(): {}",
+ kernelIndex, kernelBinaries.size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ auto kernelBinary = kernelBinaries.at(kernelIndex).get();
+ auto* kernelBlob = kernelBinary.begin();
+ auto& kernelInfos = _state.getKernelInfos();
+ auto iter = kernelInfos.find(kernelBlob);
+ ze_graph_handle_t graphHandle = nullptr;
+ KernelInfo* kernelInfoPtr = nullptr;
+ if (iter == kernelInfos.end()) {
+ KernelInfo kernelInfo;
+ auto& rawStrings = _bytecodeModule->getRawStrings();
+ const auto kernelName = (static_cast<size_t>(kernelNameIndex) >= rawStrings.size())
+ ? "Unknown"
+ : std::string(rawStrings.at(kernelNameIndex).get().begin(),
+ rawStrings.at(kernelNameIndex).get().end());
+ if (createKernel(_state.getExecutionContext(), kernelBlob, kernelBinary.size(), kernelName, graphHandle,
+ kernelInfo) != ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ auto insertResult = kernelInfos.emplace(kernelBlob, std::move(kernelInfo));
+ kernelInfoPtr = &(insertResult.first->second);
+ } else {
+ graphHandle = iter->second.getGraphHandle();
+ kernelInfoPtr = &(iter->second);
+ }
+
+ auto& bufferManager = _state.getBufferManager();
+ auto& bufferMetadata = _state.getBufferMetadata();
+
+ const auto inputCount = getOperand(pc, operandIndex++);
+ for (int16_t i = 0; i < inputCount; ++i) {
+ auto bufReg = getOperand(pc, operandIndex++); // input register numbers (not used in this stub)
+ const auto handle = static_cast<BufferHandle>(frame.getReg(bufReg));
+ const auto bufferMetadataIt = bufferMetadata.find(handle);
+ if (bufferMetadataIt == bufferMetadata.end() || !bufferManager.exists(handle)) {
+ NPU_VM_LOG_ERROR("buffer.get_dim on unknown buffer handle {}", handle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ auto& buffer = bufferManager.getBuffer(handle);
+ inputs.emplace_back(&buffer, &bufferMetadataIt->second);
+ }
+
+ const auto outputCount = getOperand(pc, operandIndex++);
+ for (int16_t i = 0; i < outputCount; ++i) {
+ auto bufReg = getOperand(pc, operandIndex++); // input register numbers (not used in this stub)
+ const auto handle = static_cast<BufferHandle>(frame.getReg(bufReg));
+ const auto bufferMetadataIt = bufferMetadata.find(handle);
+ if (bufferMetadataIt == bufferMetadata.end() || !bufferManager.exists(handle)) {
+ NPU_VM_LOG_ERROR("buffer.get_dim on unknown buffer handle {}", handle);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ auto& buffer = bufferManager.getBuffer(handle);
+ outputs.emplace_back(&buffer, &bufferMetadataIt->second);
+ }
+
+ if (setBindings(_state.getExecutionContext(), graphHandle, inputs, outputs, *kernelInfoPtr) !=
+ ZE_RESULT_SUCCESS) {
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
+ frame.setReg(dstRegNum, static_cast<int64_t>(reinterpret_cast<uint64_t>(graphHandle)));
+ break;
+ }
+ case OpCode::RET: {
+ // Capture the return address before unwinding: pop_back invalidates `frame`.
+ const auto returnAddr = frame.getReturnAddress();
+ callStack.pop_back();
+ if (returnAddr == EXIT_RETURN_ADDR) {
+ // Returning from the entrypoint function: signal end of execution
+ NPU_VM_LOG_DEBUG(" ret (return address={}) (finishing execution)",
+ static_cast<const void*>(returnAddr));
+ _state.setExecState(ExecState::Finalized);
+ } else {
+ // Resume the caller frame at the instruction following its CALL
+ _state.setPC(returnAddr);
+ NPU_VM_LOG_DEBUG(" ret (return address={})", static_cast<const void*>(returnAddr));
+ }
+ // Skip incrementPC: the PC is already positioned at the caller's resume address (or execution is done)
+ continue;
+ }
+ case OpCode::CALL: {
+ // CALL transfers control to a callee function using the bytecode calling convention.
+ // See bytecode_format.md 6.3 for calling convention specification
+ //
+ // Bytecode encoding: `call rs, N, rN..., M, rM...`
+ // rs: register containing function index (index into _functions)
+ // N: immediate value; number of destination registers (for return values)
+ // rN...: N destination register operands (caller's storage for return values)
+ // M: immediate value; number of argument registers
+ // rM...: M source register operands (caller's argument values)
+
+ // 1. Decode operands from CALL instruction
+ const auto funcIdxReg = getOperand(pc, 0);
+ const auto n = static_cast<uint16_t>(getOperand(pc, 1));
+
+ // Collect caller's destination registers (rN...) for return-value storage.
+ // Per bytecode spec, destination registers are zero-indexed; when callee
+ // executes RETV, these are the targets for storing return values
+ std::vector<int16_t> destRegs(n);
+ for (uint16_t i = 0; i < n; ++i) {
+ destRegs.at(i) = getOperand(pc, 2 + i);
+ }
+
+ const auto m = static_cast<uint16_t>(getOperand(pc, 2 + n));
+
+ // Collect argument values from caller's frame. These will be copied into
+ // the callee's parameter registers after the callee frame is created
+ std::vector<int64_t> argValues(m);
+ for (uint16_t i = 0; i < m; ++i) {
+ argValues.at(i) = frame.getReg(getOperand(pc, 3 + n + i));
+ }
+
+ // 2. Resolve and validate callee function reference
+ // funcIndex is read from the caller's register
+ const auto funcIndex = static_cast<size_t>(frame.getReg(funcIdxReg));
+ const auto& functions = _bytecodeModule->getFunctions();
+ if (funcIndex >= functions.size()) {
+ NPU_VM_LOG_ERROR("CALL refers to invalid function index {}", funcIndex);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // Enforce recursion depth limit to prevent stack overflow
+ if (callStack.size() > maxCallDepth) {
+ NPU_VM_LOG_ERROR("Maximum call depth ({}) exceeded.", maxCallDepth);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ const auto& callee = functions.at(funcIndex);
+
+ // Validate: argument count must not exceed callee's total register capacity.
+ // Per bytecode spec: callee frame has G general registers + P parameter registers,
+ // where P = M (argument count). So M <= num_general_registers must hold
+ if (m > callee.getNumGeneralRegisters()) {
+ NPU_VM_LOG_ERROR("CALL passes {} argument registers, but callee frame has only {} registers.", m,
+ callee.getNumGeneralRegisters());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // Validate: argument count must exactly match the callee parameter count.
+ // CALL frame setup uses M to define the parameter register window
+ if (m != static_cast<uint16_t>(callee.getParamTypes().size())) {
+ NPU_VM_LOG_ERROR("CALL passes {} arguments, but callee function {} expects {} parameters.", m,
+ callee.getName(), callee.getParamTypes().size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // Validate: destination register count must match callee's return type count.
+ // This ensures caller provides exactly the right number of result storage slots
+ if (n != static_cast<uint16_t>(callee.getResultTypes().size())) {
+ NPU_VM_LOG_ERROR("CALL specifies {} destination registers, but callee function {} returns {} values.",
+ n, callee.getName(), callee.getResultTypes().size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // 3. Save the address of the instruction following CALL; the callee returns here.
+ // The outer decodeInstruction() has already computed the size of this CALL, so reuse it.
+ const auto returnAddr = std::next(pc, static_cast<std::ptrdiff_t>(instructionSize));
+
+ // 4. Create and initialize callee's call frame
+ // Per bytecode spec 6.3, callee frame layout is:
+ // registers [0, 1, ..., G - 1]: general (scratch) registers
+ // registers [G, G + 1, ..., G + P - 1]: parameter registers
+ // where G = num_general_registers - P and P = M (argument count)
+ //
+ // Route callee RETV values directly into the caller's destination registers. These pointers stay valid for
+ // the whole call because callStack is reserved up front and therefore never reallocates its frames. They
+ // read the caller frame, so they must be collected before the callee frame is pushed
+ std::vector<int64_t*> calleeResultTargets;
+ calleeResultTargets.reserve(n);
+ for (uint16_t i = 0; i < n; ++i) {
+ calleeResultTargets.push_back(&frame.getReg(destRegs.at(i)));
+ }
+
+ CallFrame calleeFrame(callee, returnAddr, std::move(calleeResultTargets));
+ const auto g = callee.getNumGeneralRegisters() - m;
+
+ // Populate callee's parameter registers with caller's argument values.
+ // Register G + i receives the i-th argument value
+ for (uint16_t i = 0; i < m; ++i) {
+ calleeFrame.setReg(static_cast<int16_t>(g + i), argValues.at(i));
+ }
+
+ NPU_VM_LOG_DEBUG(" call '{}' (index {}), arguments={}, destRegs={}", callee.getName(), funcIndex,
+ intel_npu::vm::formatVector(argValues), intel_npu::vm::formatVector(destRegs));
+
+ // 5. Transfer control to the callee by pushing its frame and jumping to its body
+ callStack.push_back(std::move(calleeFrame));
+ _state.setPC(callee.getBody().begin());
+
+ // Skip incrementPC: the PC is now positioned at the callee body start
+ continue;
+ }
+ case OpCode::RETV: {
+ // The first operand is an immediate value specifying the number of results to return. The same number of
+ // operands follow, each specifying a register containing a result value
+ //
+ // RETV returns from current function, transferring values to caller's destination registers.
+ // See bytecode_format.md 6.3 for calling convention specification.
+ //
+ // Bytecode encoding: `retv N, rN...`
+ // N: immediate value; number of values to return (must match callee function signature)
+ // rN...: N source register operands containing return values
+ //
+ // When RETV executes, return values are copied from specified registers into caller-provided sinks.
+
+ const auto numResults = getOperand(pc, 0);
+
+ // Validate return value count matches function signature
+ if (static_cast<size_t>(numResults) != results.size()) {
+ NPU_VM_LOG_ERROR("RETV instruction specifies {} results, but function signature expects {}", numResults,
+ results.size());
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+
+ // Collect return values from specified registers into the provided result sinks.
+ // Per bytecode spec 6.3, RETV operand order corresponds to destination register
+ // order in the calling CALL instruction
+ constexpr auto variadicOperandOffset = 1;
+ for (int64_t i = 0; i < numResults; ++i) {
+ auto reg = getOperand(pc, variadicOperandOffset + i);
+ if (results.at(i) == nullptr) {
+ NPU_VM_LOG_ERROR("RETV sink pointer is null for result {}", i);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ *results.at(i) = frame.getReg(reg);
+ }
+ if (_state.getExecState() == ExecState::Halted) {
+ break;
+ }
+
+ // Determine return target: entrypoint finalization or nested call return. All reads of `frame`/`results`
+ // must happen before pop_back, which invalidates the current frame references
+ const auto returnAddr = frame.getReturnAddress();
+ if (returnAddr == EXIT_RETURN_ADDR) {
+ // Returning from entrypoint function: signal end of execution
+ NPU_VM_LOG_DEBUG(" retv {} (values={}, return address={}) (finishing execution)", numResults,
+ formatPtrVectorContent(results), static_cast<const void*>(returnAddr));
+ _state.setExecState(ExecState::Finalized);
+ } else {
+ // Nested call: resume the caller frame. Result sinks have already been written above
+ NPU_VM_LOG_DEBUG(" retv {} (values={}, return address={})", numResults,
+ formatPtrVectorContent(results), static_cast<const void*>(returnAddr));
+ _state.setPC(returnAddr);
+ }
+ callStack.pop_back();
+ // Skip incrementPC: the PC is already positioned at the caller's resume address (or execution is done)
+ continue;
+ }
+ case OpCode::JMP: {
+ const auto offset = get64BitImm(pc, 0);
+ if (!applyJump(_state, offset, functionBodyStart, endOfFunction, function)) {
+ const auto pcOffset = static_cast<int64_t>(_state.getPC() - functionBodyStart);
+ NPU_VM_LOG_ERROR("jmp invalid target: pc+{} offset={} target={}", pcOffset, offset,
+ (pcOffset + offset));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ NPU_VM_LOG_DEBUG(" jmp {} (new pc={})", offset, static_cast<const void*>(_state.getPC()));
+ continue;
+ }
+ case OpCode::JE: {
+ const auto lhsReg = getAsOperand<int16_t>(pc, OPCODE_SIZE + sizeof(int64_t));
+ const auto rhsReg = getAsOperand<int16_t>(pc, OPCODE_SIZE + sizeof(int64_t) + sizeof(int16_t));
+ const auto lhs = frame.getReg(lhsReg);
+ const auto rhs = frame.getReg(rhsReg);
+ if (lhs == rhs) {
+ const auto offset = get64BitImm(pc, 0);
+ if (!applyJump(_state, offset, functionBodyStart, endOfFunction, function)) {
+ const auto pcOffset = static_cast<int64_t>(_state.getPC() - functionBodyStart);
+ NPU_VM_LOG_ERROR("je invalid target: pc+{} offset={} target={} (lhs={} rhs={})", pcOffset, offset,
+ (pcOffset + offset), lhs, rhs);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ NPU_VM_LOG_DEBUG(" je {}, {}, {} ({} == {} -> taken)", offset, lhsReg, rhsReg, lhs, rhs);
+ continue;
+ }
+ NPU_VM_LOG_DEBUG(" je {}, {}, {} ({} == {} -> not taken)", get64BitImm(_state.getPC(), 0), lhsReg, rhsReg,
+ lhs, rhs);
+ break;
+ }
+ case OpCode::JNE: {
+ const auto lhsReg = getAsOperand<int16_t>(pc, OPCODE_SIZE + sizeof(int64_t));
+ const auto rhsReg = getAsOperand<int16_t>(pc, OPCODE_SIZE + sizeof(int64_t) + sizeof(int16_t));
+ const auto lhs = frame.getReg(lhsReg);
+ const auto rhs = frame.getReg(rhsReg);
+ if (lhs != rhs) {
+ const auto offset = get64BitImm(pc, 0);
+ if (!applyJump(_state, offset, functionBodyStart, endOfFunction, function)) {
+ const auto pcOffset = static_cast<int64_t>(_state.getPC() - functionBodyStart);
+ NPU_VM_LOG_ERROR("jne invalid target: pc+{} offset={} target={} (lhs={} rhs={})", pcOffset, offset,
+ (pcOffset + offset), lhs, rhs);
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ NPU_VM_LOG_DEBUG(" jne {}, {}, {} ({} != {} -> taken)", offset, lhsReg, rhsReg, lhs, rhs);
+ continue;
+ }
+ NPU_VM_LOG_DEBUG(" jne {}, {}, {} ({} != {} -> not taken)", get64BitImm(_state.getPC(), 0), lhsReg, rhsReg,
+ lhs, rhs);
+ break;
+ }
+ case OpCode::CONVERT_I8_TO_F32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto floatResult = static_cast<float>(signExtend8(frame.getReg(srcRegNum)));
+ int64_t regVal = 0;
+ std::memcpy(&regVal, &floatResult, sizeof(float));
+ frame.setReg(dstRegNum, regVal);
+ NPU_VM_LOG_DEBUG(" convert.i8tof32 {}, {} = {}", dstRegNum, srcRegNum, floatResult);
+ break;
+ }
+ case OpCode::CONVERT_I8_TO_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = static_cast<double>(signExtend8(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" convert.i8tof64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_I8: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend8(signExtend16(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i16toi8 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_F32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto floatResult = static_cast<float>(signExtend16(frame.getReg(srcRegNum)));
+ int64_t regVal = 0;
+ std::memcpy(&regVal, &floatResult, sizeof(float));
+ frame.setReg(dstRegNum, regVal);
+ NPU_VM_LOG_DEBUG(" convert.i16tof32 {}, {} = {}", dstRegNum, srcRegNum, floatResult);
+ break;
+ }
+ case OpCode::CONVERT_I16_TO_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = static_cast<double>(signExtend16(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" convert.i16tof64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_I8: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend8(signExtend32(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i32toi8 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_I16: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend16(signExtend32(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i32toi16 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_F32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto floatResult = static_cast<float>(signExtend32(frame.getReg(srcRegNum)));
+ int64_t regVal = 0;
+ std::memcpy(&regVal, &floatResult, sizeof(float));
+ frame.setReg(dstRegNum, regVal);
+ NPU_VM_LOG_DEBUG(" convert.i32tof32 {}, {} = {}", dstRegNum, srcRegNum, floatResult);
+ break;
+ }
+ case OpCode::CONVERT_I32_TO_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = static_cast<double>(signExtend32(frame.getReg(srcRegNum)));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" convert.i32tof64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I8: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend8(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i64toi8 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I16: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend16(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i64toi16 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_I32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = signExtend32(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.i64toi32 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_F32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto floatResult = static_cast<float>(frame.getReg(srcRegNum));
+ int64_t regVal = 0;
+ std::memcpy(&regVal, &floatResult, sizeof(float));
+ frame.setReg(dstRegNum, regVal);
+ NPU_VM_LOG_DEBUG(" convert.i64tof32 {}, {} = {}", dstRegNum, srcRegNum, floatResult);
+ break;
+ }
+ case OpCode::CONVERT_I64_TO_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto result = static_cast<double>(frame.getReg(srcRegNum));
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" convert.i64tof64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I8: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ float src = 0.0f;
+ std::memcpy(&src, &frame.getReg(srcRegNum), sizeof(float));
+ const auto result = saturatingFloatToInt<int8_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f32toi8 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I16: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ float src = 0.0f;
+ std::memcpy(&src, &frame.getReg(srcRegNum), sizeof(float));
+ const auto result = saturatingFloatToInt<int16_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f32toi16 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ float src = 0.0f;
+ std::memcpy(&src, &frame.getReg(srcRegNum), sizeof(float));
+ const auto result = saturatingFloatToInt<int32_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f32toi32 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ float src = 0.0f;
+ std::memcpy(&src, &frame.getReg(srcRegNum), sizeof(float));
+ const auto result = saturatingFloatToInt<int64_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f32toi64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F32_TO_F64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ float src = 0.0f;
+ std::memcpy(&src, &frame.getReg(srcRegNum), sizeof(float));
+ const auto result = static_cast<double>(src);
+ frame.setReg(dstRegNum, vmBitCast<int64_t>(result));
+ NPU_VM_LOG_DEBUG(" convert.f32tof64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I8: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ const auto result = saturatingFloatToInt<int8_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f64toi8 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I16: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ const auto result = saturatingFloatToInt<int16_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f64toi16 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ const auto result = saturatingFloatToInt<int32_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f64toi32 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_I64: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ const auto result = saturatingFloatToInt<int64_t>(src);
+ frame.setReg(dstRegNum, result);
+ NPU_VM_LOG_DEBUG(" convert.f64toi64 {}, {} = {}", dstRegNum, srcRegNum, result);
+ break;
+ }
+ case OpCode::CONVERT_F64_TO_F32: {
+ const auto dstRegNum = getOperand(pc, 0);
+ const auto srcRegNum = getOperand(pc, 1);
+ const auto src = vmBitCast<double>(frame.getReg(srcRegNum));
+ const auto floatResult = static_cast<float>(src);
+ int64_t regVal = 0;
+ std::memcpy(&regVal, &floatResult, sizeof(float));
+ frame.setReg(dstRegNum, regVal);
+ NPU_VM_LOG_DEBUG(" convert.f64tof32 {}, {} = {}", dstRegNum, srcRegNum, floatResult);
+ break;
+ }
+ default:
+ NPU_VM_LOG_ERROR("Unknown opcode {}", static_cast<uint16_t>(opcode));
+ _state.setExecState(ExecState::Halted);
+ break;
+ }
+ incrementPC(instructionSize);
+ }
+}
+
+} // namespace
+
+struct _npu_vm_engine {
+ std::unique_ptr<VMEngine> impl;
+};
+
+struct _npu_vm_module {
+ std::shared_ptr<BytecodeModule> impl;
+};
+
+std::optional<intel_npu::vm::NetworkMetadata> intel_npu::vm::getNetworkMetadata(npu_vm_module* bytecodeModule) {
+ if (bytecodeModule == nullptr || bytecodeModule->impl == nullptr) {
+ return std::nullopt;
+ }
+ return bytecodeModule->impl->getNetworkMetadata();
+}
+
+namespace {
+
+std::optional<npu_vm_type> convertToVmType(const FuncParamResType& value) {
+ switch (getTypeCode(value.type)) {
+ case TypeCode::INTEGER: {
+ const auto isSigned = isTypeSigned(value.type);
+ auto bitWidth = getBitWidth(value.type);
+ if (bitWidth == sizeof(int8_t) * CHAR_BIT) {
+ return isSigned ? npu_vm_type_int8 : npu_vm_type_uint8;
+ } else if (bitWidth == sizeof(int16_t) * CHAR_BIT) {
+ return isSigned ? npu_vm_type_int16 : npu_vm_type_uint16;
+ } else if (bitWidth == sizeof(int32_t) * CHAR_BIT) {
+ return isSigned ? npu_vm_type_int32 : npu_vm_type_uint32;
+ } else if (bitWidth == sizeof(int64_t) * CHAR_BIT) {
+ return isSigned ? npu_vm_type_int64 : npu_vm_type_uint64;
+ } else {
+ return std::nullopt;
+ }
+ break;
+ }
+ case TypeCode::FLOAT: {
+ auto bitWidth = getBitWidth(value.type);
+ if (bitWidth == sizeof(float) * CHAR_BIT) {
+ return npu_vm_type_float32;
+ } else if (bitWidth == sizeof(double) * CHAR_BIT) {
+ return npu_vm_type_float64;
+ } else {
+ return std::nullopt;
+ }
+ break;
+ }
+ case TypeCode::BUFFER: {
+ return npu_vm_type_buffer;
+ break;
+ }
+ default:
+ return std::nullopt;
+ }
+}
+
+template <typename T>
+bool isValid(T* ptr) {
+ if (ptr == nullptr) {
+ return false;
+ }
+ if (ptr->impl == nullptr) {
+ return false;
+ }
+ return true;
+}
+
+npu_vm_result vmCallImpl(npu_vm_engine* engine, const char* name, uint32_t numArguments, const npu_vm_value* arguments,
+ uint32_t numResults, npu_vm_value* results, const char* callerFunction) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (name == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for function name");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ const auto bytecodeModule = engine->impl->getModule();
+ if (bytecodeModule == nullptr) {
+ NPU_VM_LOG_ERROR("Bytecode module is not loaded");
+ return NPU_VM_ERROR_MODULE_NOT_FOUND;
+ }
+ const auto function = bytecodeModule->getFunction(name);
+ if (function == nullptr) {
+ NPU_VM_LOG_ERROR("Function not found: {}", name);
+ return NPU_VM_ERROR_FUNCTION_NOT_FOUND;
+ }
+ if (numArguments > 0 && arguments == nullptr) {
+ NPU_VM_LOG_ERROR("Argument array is null while argument count is {}", numArguments);
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (numResults > 0 && results == nullptr) {
+ NPU_VM_LOG_ERROR("Result array is null while result count is {}", numResults);
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ Span<const npu_vm_value> argSpan(arguments, numArguments);
+ Span<npu_vm_value> resultSpan(results, numResults);
+ if (!engine->impl->call(name, argSpan, resultSpan)) {
+ NPU_VM_LOG_ERROR("Error during function call: {}", name);
+ return NPU_VM_ERROR_FUNCTION_CALL_FAILED;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during {}: {}", callerFunction, e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+} // namespace
+
+// NOLINTBEGIN(readability-identifier-naming) - C API identifiers must follow C naming conventions
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_print(const uint8_t* bytecode, uint32_t bytecode_size, int print_full,
+ uint32_t indent_level) {
+ if (bytecode == nullptr || bytecode_size == 0) {
+ NPU_VM_LOG_ERROR("Null pointer or empty bytecode passed");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - function receives a pointer to const data
+ const auto bytecodeView = Span<uint8_t>(const_cast<uint8_t*>(bytecode), bytecode_size);
+ BytecodeReader reader(bytecodeView);
+ if (!reader.parseFile()) {
+ NPU_VM_LOG_ERROR("Failed to parse bytecode file.");
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ reader.printFile(static_cast<bool>(print_full), indent_level);
+ return NPU_VM_SUCCESS;
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_print: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_parse_module(const uint8_t* bytecode, uint32_t bytecode_size,
+ npu_vm_module** module_out) {
+ if (module_out == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for module_out");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (bytecode == nullptr || bytecode_size == 0) {
+ NPU_VM_LOG_ERROR("Null pointer or empty bytecode passed");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ // The provided bytecode is expected to live beyond the lifetime of the module, so the created module does not
+ // take ownership
+ const auto copyBytecode = false;
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - function receives a pointer to const data
+ const auto bytecodeView = Span<uint8_t>(const_cast<uint8_t*>(bytecode), bytecode_size);
+ auto moduleImpl = BytecodeModule::createFrom(bytecodeView, copyBytecode);
+ if (moduleImpl == nullptr) {
+ NPU_VM_LOG_ERROR("Bytecode parsing failed");
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - using raw pointer for C API struct
+ *module_out = new (std::nothrow) npu_vm_module;
+ if (*module_out == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for bytecode module");
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ (*module_out)->impl = std::move(moduleImpl);
+ return NPU_VM_SUCCESS;
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_parse_module: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_module(npu_vm_module* module) {
+ if (module == nullptr) {
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ module->impl.reset();
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - using raw pointer for C API struct
+ delete module;
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_get_function_info(npu_vm_module* module, const char* name,
+ npu_vm_function_info** info_out) {
+ if (!isValid(module)) {
+ NPU_VM_LOG_ERROR("Null pointer to module instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (name == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for function name");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (info_out == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for info_out");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+
+ const auto function = module->impl->getFunction(name);
+ if (function == nullptr) {
+ NPU_VM_LOG_ERROR("Function not found: {}", name);
+ return NPU_VM_ERROR_FUNCTION_NOT_FOUND;
+ }
+
+ // NOLINTBEGIN(cppcoreguidelines-owning-memory) - using C API struct with raw pointers
+ auto info = new (std::nothrow) npu_vm_function_info;
+ if (info == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for npu_vm_function_info");
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ const auto& funcName = function->getName();
+ info->name = new (std::nothrow) char[funcName.size() + 1];
+ if (info->name == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for function name");
+ delete info;
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ std::memcpy(info->name, funcName.c_str(), funcName.size() + 1);
+
+ info->num_params = static_cast<uint32_t>(function->getParamTypes().size());
+ info->num_results = static_cast<uint32_t>(function->getResultTypes().size());
+ // Allocate arrays for param_types and result_types (caller must free)
+ if (info->num_params > 0) {
+ info->param_types = new (std::nothrow) npu_vm_type[info->num_params];
+ if (info->param_types == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for param_types");
+ delete[] info->name;
+ delete info;
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ Span<npu_vm_type> paramTypesSpan(info->param_types, info->num_params);
+ for (uint32_t i = 0; i < info->num_params; ++i) {
+ const auto type = convertToVmType(function->getParamTypes().at(i));
+ if (!type.has_value()) {
+ NPU_VM_LOG_ERROR("Unsupported parameter type for parameter {} in function {}", i, name);
+ delete[] info->param_types;
+ delete[] info->name;
+ delete info;
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ paramTypesSpan.at(i) = type.value();
+ }
+ } else {
+ info->param_types = nullptr;
+ }
+ if (info->num_results > 0) {
+ info->result_types = new (std::nothrow) npu_vm_type[info->num_results];
+ if (info->result_types == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for result_types");
+ delete[] info->param_types;
+ delete[] info->name;
+ delete info;
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ Span<npu_vm_type> resultTypesSpan(info->result_types, info->num_results);
+ for (uint32_t i = 0; i < info->num_results; ++i) {
+ const auto type = convertToVmType(function->getResultTypes().at(i));
+ if (!type.has_value()) {
+ NPU_VM_LOG_ERROR("Unsupported result type for result {} in function {}", i, name);
+ delete[] info->result_types;
+ delete[] info->param_types;
+ delete[] info->name;
+ delete info;
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ resultTypesSpan.at(i) = type.value();
+ }
+ } else {
+ info->result_types = nullptr;
+ }
+ // NOLINTEND(cppcoreguidelines-owning-memory)
+
+ *info_out = info;
+
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_function_info(npu_vm_function_info* info) {
+ if (info == nullptr) {
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ // NOLINTBEGIN(cppcoreguidelines-owning-memory) - using C API struct with raw pointers
+ delete[] info->name;
+ delete[] info->param_types;
+ delete[] info->result_types;
+ delete info;
+ // NOLINTEND(cppcoreguidelines-owning-memory)
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_new_engine(npu_vm_engine** engine_out) {
+ if (engine_out == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for engine_out");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - using raw pointer for C API struct
+ *engine_out = new (std::nothrow) npu_vm_engine;
+ if (*engine_out == nullptr) {
+ NPU_VM_LOG_ERROR("Memory allocation failed for npu_vm_engine");
+ return NPU_VM_ERROR_MEMORY_ALLOCATION_FAILED;
+ }
+ (*engine_out)->impl = std::make_unique<VMEngine>();
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_new_engine: {}", e.what());
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - cannot use smart pointer for the C API
+ delete *engine_out;
+ *engine_out = nullptr;
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_destroy_engine(npu_vm_engine* engine) {
+ if (engine == nullptr) {
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ engine->impl.reset();
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - using raw pointer for C API struct
+ delete engine;
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_load_module(npu_vm_engine* engine, npu_vm_module_load_params* params,
+ npu_vm_module* module) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (!isValid(module)) {
+ NPU_VM_LOG_ERROR("Null pointer to module instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ if (!engine->impl->loadModule(module->impl, params)) {
+ NPU_VM_LOG_ERROR("Failed to load module into engine");
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_load_module: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_reset_state(npu_vm_engine* engine, int resetExecutionContext) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ if (!engine->impl->resetState(static_cast<bool>(resetExecutionContext))) {
+ NPU_VM_LOG_ERROR("Failed to reset engine state");
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_reset_state: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_call(npu_vm_engine* engine, const char* name, uint32_t num_arguments,
+ const npu_vm_value* arguments) {
+ return vmCallImpl(engine, name, num_arguments, arguments, /*numResults=*/0, /*results=*/nullptr, "npu_vm_call");
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_call_with_results(npu_vm_engine* engine, const char* name,
+ uint32_t num_arguments,
+ const npu_vm_value* arguments, uint32_t num_results,
+ npu_vm_value* results) {
+ return vmCallImpl(engine, name, num_arguments, arguments, num_results, results, "npu_vm_call_with_results");
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_infer(npu_vm_engine* engine,
+ npu_vm_runtime_execute_params_t* params) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (params == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for params");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ if (!engine->impl->infer(params)) {
+ NPU_VM_LOG_ERROR("Inference failed for the given parameters");
+ return NPU_VM_ERROR_INFERENCE_FAILED;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_infer: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL
+npu_vm_predict_output_shape(npu_vm_engine* engine, npu_vm_runtime_predict_output_shape_params_t2* params) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (params == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for params");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ if (!engine->impl->predictOutputShape(params)) {
+ NPU_VM_LOG_ERROR("Output shape prediction failed for the given parameters");
+ return NPU_VM_ERROR_OUTPUT_SHAPE_PREDICTION_FAILED;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_predict_output_shape: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_infer2(npu_vm_engine* engine,
+ npu_vm_runtime_execute_params2_t* params) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (params == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for params");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ try {
+ if (!engine->impl->infer(params)) {
+ NPU_VM_LOG_ERROR("Inference failed for the given parameters");
+ return NPU_VM_ERROR_INFERENCE_FAILED;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_infer: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT bool NPU_VM_APICALL npu_vm_host_code_execution_required(npu_vm_engine* engine,
+ npu_vm_runtime_execute_params2_t* params) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return true;
+ }
+
+ if (params == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for params");
+ return true;
+ }
+
+ try {
+ return engine->impl->hostCodeExecutionRequired(params);
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_host_code_execution_required: {}", e.what());
+ return true;
+ }
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL
+npu_vm_submit_recorded_command_lists(npu_vm_engine* engine, npu_vm_runtime_execute_params2_t* params) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+ if (params == nullptr) {
+ NPU_VM_LOG_ERROR("Null pointer passed for params");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ if (!engine->impl->submitRecordedCmdLists(params)) {
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_host_code_execution_required: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+NPU_VM_EXPORT npu_vm_result NPU_VM_APICALL npu_vm_host_sync(npu_vm_engine* engine) {
+ if (!isValid(engine)) {
+ NPU_VM_LOG_ERROR("Null pointer to engine instance");
+ return NPU_VM_ERROR_INVALID_NULL_POINTER;
+ }
+
+ try {
+ if (!engine->impl->hostSync()) {
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ } catch (const std::exception& e) {
+ NPU_VM_LOG_ERROR("Error during npu_vm_host_code_execution_required: {}", e.what());
+ return NPU_VM_ERROR_UNKNOWN;
+ }
+ return NPU_VM_SUCCESS;
+}
+
+// NOLINTEND(readability-identifier-naming)
diff --git a/src/plugins/intel_npu/tests/functional/CMakeLists.txt b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
index ae1bdc202e9..2365c588075 100644
--- a/src/plugins/intel_npu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
@@ -20,6 +20,7 @@ set(SKIP_CONFIG_PATH ${CMAKE_CURRENT_SOURCE_DIR}/shared_tests_instances/${SKIP_C
list(APPEND OPTIONAL_FUNC_TESTS_INCLUDES
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/compiler_adapter/include"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/include"
+ "${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils"
)
list(APPEND OPTIONAL_FUNC_TESTS_LIBS openvino_npu_common openvino_npu_compiler_adapter
@@ -56,7 +57,8 @@ ov_add_test_target(
openvino::format_reader
openvino::reference
openvino::runtime
- openvino::npu_al)
+ openvino::npu_al
+ openvino::intel_npu_vm_runtime)
if(ENABLE_INTEL_CPU)
add_dependencies(${TARGET_NAME} openvino_intel_cpu_plugin)
diff --git a/src/plugins/intel_npu/tests/functional/behavior/vm/data/bytecode.blob b/src/plugins/intel_npu/tests/functional/behavior/vm/data/bytecode.blob
new file mode 100644
index 00000000000..b73b58b2d54
Binary files /dev/null and b/src/plugins/intel_npu/tests/functional/behavior/vm/data/bytecode.blob differ
diff --git a/src/plugins/intel_npu/tests/functional/behavior/vm/level_zero_allocator.cpp b/src/plugins/intel_npu/tests/functional/behavior/vm/level_zero_allocator.cpp
new file mode 100644
index 00000000000..36622153858
--- /dev/null
+++ b/src/plugins/intel_npu/tests/functional/behavior/vm/level_zero_allocator.cpp
@@ -0,0 +1,138 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+// Device-backed tests for the bytecode VM's Level Zero allocator. Unlike the composable-allocator unit
+// tests (which run over host memory), these exercise the real zeMemAllocHost/zeMemFree leaf against a live
+// Level Zero context, so they only run where an NPU is present and GTEST_SKIP otherwise.
+
+#include "level_zero_allocator.hpp"
+#include "allocator_core.hpp"
+#include "common/npu_test_env_cfg.hpp"
+
+#include <common_test_utils/test_common.hpp>
+#include <functional_test_utils/skip_tests_config.hpp>
+#include <intel_npu/utils/utils.hpp>
+#include <intel_npu/utils/zero/zero_init.hpp>
+
+#include <ze_api.h>
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <memory>
+#include <sstream>
+#include <string>
+
+using intel_npu::vm::AnyAllocator;
+using intel_npu::vm::Block;
+using intel_npu::vm::LevelZeroAllocator;
+using intel_npu::vm::makeLevelZeroAllocator;
+
+using LevelZeroAllocatorDeviceTestParams = std::string;
+
+namespace {
+
+constexpr size_t kPage = intel_npu::utils::STANDARD_PAGE_SIZE;
+
+bool isPageAligned(const uint8_t* ptr) {
+ return reinterpret_cast<uintptr_t>(ptr) % kPage == 0;
+}
+
+} // namespace
+
+class LevelZeroAllocatorDeviceTest :
+ public testing::WithParamInterface<LevelZeroAllocatorDeviceTestParams>,
+ public ov::test::TestsCommon {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<LevelZeroAllocatorDeviceTestParams>& obj) {
+ std::string targetDevice = obj.param;
+
+ std::ostringstream result;
+ result << "target_platform=" << ov::test::utils::getTestsPlatformFromEnvironmentOr(targetDevice) << "_";
+ result << "target_device=" << targetDevice << "_";
+ return result.str();
+ }
+
+protected:
+ void SetUp() override {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ _targetDevice = GetParam();
+ try {
+ _initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ } catch (const std::exception& e) {
+ GTEST_SKIP() << "No Level Zero / NPU device available: " << e.what();
+ }
+ _context = _initStruct->getContext();
+ ASSERT_NE(_context, nullptr);
+ }
+
+ std::string _targetDevice;
+ std::shared_ptr<intel_npu::ZeroInitStructsHolder> _initStruct;
+ ze_context_handle_t _context = nullptr;
+};
+
+// The bare leaf: zeMemAllocHost-backed, page-aligned, host-visible, reusable across allocate/deallocate.
+TEST_P(LevelZeroAllocatorDeviceTest, LeafAllocatesPageAlignedHostVisibleMemory) {
+ LevelZeroAllocator allocator(_context);
+
+ const Block block = allocator.allocate(4 * kPage);
+ ASSERT_TRUE(block);
+ EXPECT_TRUE(isPageAligned(block.ptr));
+ EXPECT_EQ(block.size, 4u * kPage);
+
+ // Host-visible: the CPU can write and read the device buffer back.
+ for (size_t i = 0; i < block.size; ++i) {
+ block.ptr[i] = static_cast<uint8_t>(i);
+ }
+ for (size_t i = 0; i < block.size; ++i) {
+ ASSERT_EQ(block.ptr[i], static_cast<uint8_t>(i));
+ }
+
+ allocator.deallocate(block);
+
+ // A fresh allocation after a free still succeeds.
+ const Block again = allocator.allocate(kPage);
+ ASSERT_TRUE(again);
+ EXPECT_TRUE(isPageAligned(again.ptr));
+ allocator.deallocate(again);
+}
+
+// The Level Zero device allocator (GrowingArena<LevelZeroAllocator, BumpRegion<page>, ...>): page-aligned, distinct,
+// host-visible sub-buffers; recycle() reuses the same memory; release() frees and the arena re-grows.
+TEST_P(LevelZeroAllocatorDeviceTest, DefaultAllocatorHandsOutAlignedDistinctReusableBuffers) {
+ AnyAllocator allocator = makeLevelZeroAllocator(_context);
+ ASSERT_TRUE(allocator);
+
+ const Block a = allocator.allocate(1024);
+ const Block b = allocator.allocate(2048);
+ const Block c = allocator.allocate(4096);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ ASSERT_TRUE(c);
+
+ for (const Block& block : {a, b, c}) {
+ EXPECT_TRUE(isPageAligned(block.ptr));
+ }
+ EXPECT_NE(a.ptr, b.ptr);
+ EXPECT_NE(a.ptr, c.ptr);
+ EXPECT_NE(b.ptr, c.ptr);
+
+ // Host-visible: writing through the returned pointers must not fault.
+ a.ptr[0] = 0xAB;
+ c.ptr[c.size - 1] = 0xCD;
+
+ // recycle() rewinds the arena: replaying the same requests reuses the same addresses (no growth).
+ allocator.recycle();
+ const Block a2 = allocator.allocate(1024);
+ EXPECT_EQ(a2.ptr, a.ptr);
+
+ // release() frees the slabs back to the device; the allocator stays usable and re-grows on demand.
+ allocator.release();
+ const Block afterRelease = allocator.allocate(1024);
+ ASSERT_TRUE(afterRelease);
+ EXPECT_TRUE(isPageAligned(afterRelease.ptr));
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest_level_zero_allocator, LevelZeroAllocatorDeviceTest,
+ ::testing::Values(ov::test::utils::DEVICE_NPU), LevelZeroAllocatorDeviceTest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/functional/behavior/vm/vm_runtime.cpp b/src/plugins/intel_npu/tests/functional/behavior/vm/vm_runtime.cpp
new file mode 100644
index 00000000000..d9d59756a07
--- /dev/null
+++ b/src/plugins/intel_npu/tests/functional/behavior/vm/vm_runtime.cpp
@@ -0,0 +1,1208 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+#include <array>
+#include <common_test_utils/test_common.hpp>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <numeric>
+#include "common/npu_test_env_cfg.hpp"
+#include "intel_npu/utils/zero/zero_api.hpp"
+#include "intel_npu/utils/zero/zero_mem.hpp"
+#include "intel_npu/utils/zero/zero_result.hpp"
+#include "intel_npu/utils/zero/zero_utils.hpp"
+#include "intel_npu/utils/zero/zero_wrappers.hpp"
+#include "vm_runtime/npu_vm_runtime.hpp"
+
+#include <openvino/openvino.hpp>
+#include <openvino/opsets/opset6.hpp>
+#include <openvino/util/common_util.hpp>
+#include <openvino/util/shared_object.hpp>
+#include <sstream>
+#include <tuple>
+
+struct npu_vm_runtime_fntbl {
+ using npu_vm_runtime_get_api_version_t = npu_vm_runtime_result_t(npu_vm_runtime_version_t* pVersion);
+ using npu_vm_runtime_create_t = npu_vm_runtime_result_t(const npu_vm_runtime_blob_desc_t* desc,
+ npu_vm_runtime_handle_t* phRuntime,
+ npu_vm_runtime_properties_t* pProperties);
+ using npu_vm_runtime_destroy_t = npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime);
+ using npu_vm_runtime_get_metadata_t =
+ npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime, uint32_t argIndex,
+ ze_graph_argument_properties_3_t* pGraphArgumentProperties,
+ ze_graph_argument_metadata_t* pGraphArgumentMetadata, int64_t* upperBound);
+ using npu_vm_runtime_execute_t = npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime,
+ npu_vm_runtime_execute_params_t* pParams);
+ using npu_vm_runtime_create_execution_context_t = npu_vm_runtime_result_t(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execution_context_handle_t* phExecutionHandle);
+ using npu_vm_runtime_destroy_execution_context_t =
+ npu_vm_runtime_result_t(npu_vm_runtime_execution_context_handle_t phExecutionHandle);
+ using npu_vm_runtime_update_mutable_commandlist_t =
+ npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_execute_params_t* pParams,
+ uint64_t* argIndexArray, uint64_t argIndexArraySize);
+ using npu_vm_runtime_predict_output_shape_t = npu_vm_runtime_result_t(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_predict_output_shape_params_t* pParams);
+
+ using npu_vm_runtime_create_mem_ref_t = npu_vm_runtime_result_t(int64_t dimsCount,
+ npu_vm_runtime_mem_ref_handle_t* phMemRef);
+
+ using npu_vm_runtime_destroy_mem_ref_t = npu_vm_runtime_result_t(npu_vm_runtime_mem_ref_handle_t hMemRef);
+
+ using npu_vm_runtime_set_mem_ref_t = npu_vm_runtime_result_t(npu_vm_runtime_mem_ref_handle_t hMemRef,
+ const void* basePtr, const void* data, int64_t offset,
+ int64_t* pSizes, int64_t* pStrides, int64_t dimsCount);
+
+ using npu_vm_runtime_parse_mem_ref_t = npu_vm_runtime_result_t(npu_vm_runtime_mem_ref_handle_t hMemRef,
+ const void** pBasePtr, const void** pData,
+ int64_t* pOffset, int64_t* pSizes, int64_t* pStrides,
+ int64_t* pDimsCount);
+
+ using npu_vm_runtime_predict_output_shape2_t = npu_vm_runtime_result_t(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_predict_output_shape_params_t2* pParams);
+
+ using npu_vm_runtime_create2_t = npu_vm_runtime_result_t(const npu_vm_runtime_blob_desc_t* desc,
+ const npu_vm_runtime_config_desc_t* pConfig,
+ npu_vm_runtime_handle_t* phRuntime,
+ npu_vm_runtime_properties_t* pProperties);
+ using npu_vm_runtime_create_execution_context2_t = npu_vm_runtime_result_t(
+ npu_vm_runtime_handle_t hRuntime, npu_vm_runtime_create_execution_context_params_t* pParams,
+ npu_vm_runtime_execution_context_handle_t* phExecutionHandle);
+ using npu_vm_runtime_execute2_t = npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime,
+ npu_vm_runtime_execute_params2_t* pParams);
+ using npu_vm_runtime_host_sync_t = npu_vm_runtime_result_t(npu_vm_runtime_handle_t hRuntime,
+ npu_vm_runtime_execute_params2_t* pParams);
+
+ std::function<npu_vm_runtime_get_api_version_t> npuVMRuntimeGetAPIVersion = nullptr;
+ std::function<npu_vm_runtime_create_t> npuVMRuntimeCreate = nullptr;
+ std::function<npu_vm_runtime_destroy_t> npuVMRuntimeDestroy = nullptr;
+ std::function<npu_vm_runtime_get_metadata_t> npuVMRuntimeGetMetadata = nullptr;
+ std::function<npu_vm_runtime_execute_t> npuVMRuntimeExecute = nullptr;
+ std::function<npu_vm_runtime_create_execution_context_t> npuVMRuntimeCreateExecutionContext = nullptr;
+ std::function<npu_vm_runtime_destroy_execution_context_t> npuVMRuntimeDestroyExecutionContext = nullptr;
+ std::function<npu_vm_runtime_update_mutable_commandlist_t> npuVMRuntimeUpdateMutableCommandList = nullptr;
+ std::function<npu_vm_runtime_predict_output_shape_t> npuVMRuntimePredictOutputShape = nullptr;
+ std::function<npu_vm_runtime_create_mem_ref_t> npuVMRuntimeCreateMemRef = nullptr;
+ std::function<npu_vm_runtime_destroy_mem_ref_t> npuVMRuntimeDestroyMemRef = nullptr;
+ std::function<npu_vm_runtime_set_mem_ref_t> npuVMRuntimeSetMemRef = nullptr;
+ std::function<npu_vm_runtime_parse_mem_ref_t> npuVMRuntimeParseMemRef = nullptr;
+ std::function<npu_vm_runtime_predict_output_shape2_t> npuVMRuntimePredictOutputShape2 = nullptr;
+ std::function<npu_vm_runtime_create2_t> npuVMRuntimeCreate2 = nullptr;
+ std::function<npu_vm_runtime_create_execution_context2_t> npuVMRuntimeCreateExecutionContext2 = nullptr;
+ std::function<npu_vm_runtime_execute2_t> npuVMRuntimeExecute2 = nullptr;
+ std::function<npu_vm_runtime_host_sync_t> npuVMRuntimeHostSync = nullptr;
+
+ void init(std::shared_ptr<void> lib, const std::string&) {
+ npuVMRuntimeGetAPIVersion = reinterpret_cast<npu_vm_runtime_get_api_version_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeGetAPIVersion"));
+ npuVMRuntimeCreate =
+ reinterpret_cast<npu_vm_runtime_create_t*>(ov::util::get_symbol(lib, "npuVMRuntimeCreate"));
+ npuVMRuntimeDestroy =
+ reinterpret_cast<npu_vm_runtime_destroy_t*>(ov::util::get_symbol(lib, "npuVMRuntimeDestroy"));
+ npuVMRuntimeGetMetadata =
+ reinterpret_cast<npu_vm_runtime_get_metadata_t*>(ov::util::get_symbol(lib, "npuVMRuntimeGetMetadata"));
+ npuVMRuntimeExecute =
+ reinterpret_cast<npu_vm_runtime_execute_t*>(ov::util::get_symbol(lib, "npuVMRuntimeExecute"));
+
+ npuVMRuntimeCreateExecutionContext = reinterpret_cast<npu_vm_runtime_create_execution_context_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeCreateExecutionContext"));
+ npuVMRuntimeDestroyExecutionContext = reinterpret_cast<npu_vm_runtime_destroy_execution_context_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeDestroyExecutionContext"));
+ npuVMRuntimeUpdateMutableCommandList = reinterpret_cast<npu_vm_runtime_update_mutable_commandlist_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeUpdateMutableCommandList"));
+
+ npuVMRuntimePredictOutputShape = reinterpret_cast<npu_vm_runtime_predict_output_shape_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimePredictOutputShape"));
+ npuVMRuntimeCreateMemRef = reinterpret_cast<npu_vm_runtime_create_mem_ref_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeCreateMemRef"));
+ npuVMRuntimeDestroyMemRef = reinterpret_cast<npu_vm_runtime_destroy_mem_ref_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeDestroyMemRef"));
+ npuVMRuntimeSetMemRef =
+ reinterpret_cast<npu_vm_runtime_set_mem_ref_t*>(ov::util::get_symbol(lib, "npuVMRuntimeSetMemRef"));
+ npuVMRuntimeParseMemRef =
+ reinterpret_cast<npu_vm_runtime_parse_mem_ref_t*>(ov::util::get_symbol(lib, "npuVMRuntimeParseMemRef"));
+ npuVMRuntimePredictOutputShape2 = reinterpret_cast<npu_vm_runtime_predict_output_shape2_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimePredictOutputShape2"));
+
+ npuVMRuntimeCreate2 =
+ reinterpret_cast<npu_vm_runtime_create2_t*>(ov::util::get_symbol(lib, "npuVMRuntimeCreate2"));
+ npuVMRuntimeCreateExecutionContext2 = reinterpret_cast<npu_vm_runtime_create_execution_context2_t*>(
+ ov::util::get_symbol(lib, "npuVMRuntimeCreateExecutionContext2"));
+ npuVMRuntimeExecute2 =
+ reinterpret_cast<npu_vm_runtime_execute2_t*>(ov::util::get_symbol(lib, "npuVMRuntimeExecute2"));
+ npuVMRuntimeHostSync =
+ reinterpret_cast<npu_vm_runtime_execute2_t*>(ov::util::get_symbol(lib, "npuVMRuntimeHostSync"));
+ }
+};
+
+namespace {
+
+std::string formatCheckedPaths(const std::vector<std::filesystem::path>& paths) {
+ std::ostringstream oss;
+ for (size_t i = 0; i < paths.size(); ++i) {
+ if (i != 0) {
+ oss << "; ";
+ }
+ oss << paths[i].string();
+ }
+ return oss.str();
+}
+
+std::vector<std::filesystem::path> getBlobSearchPaths(const std::filesystem::path& blobPath) {
+ if (blobPath.is_absolute()) {
+ return {blobPath};
+ }
+
+ std::vector<std::filesystem::path> candidates;
+ candidates.push_back(blobPath);
+ candidates.push_back(ov::test::utils::NpuTestEnvConfig::getInstance().OV_NPU_TESTS_BLOBS_PATH + blobPath.string());
+ return candidates;
+}
+
+std::filesystem::path resolveExistingPathOrThrow(const std::filesystem::path& inputPath,
+ const std::string& resourceDescription) {
+ const auto candidatePaths = getBlobSearchPaths(inputPath);
+
+ for (const auto& candidate : candidatePaths) {
+ if (std::filesystem::exists(candidate)) {
+ return candidate;
+ }
+ }
+
+ throw std::runtime_error("Cannot open " + resourceDescription + ": " + inputPath.string() +
+ ". Checked paths: " + formatCheckedPaths(candidatePaths));
+}
+
+std::shared_ptr<ov::Model> createMaxPoolModel() {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16,
+ ov::PartialShape{1, 16, 720, ov::Dimension(10, 1280)});
+ input->set_friendly_name("input1");
+
+ auto maxpool = std::make_shared<ov::op::v1::MaxPool>(input, ov::Strides{1, 1}, ov::Shape{0, 0}, ov::Shape{0, 0},
+ ov::Shape{1, 1}, ov::op::RoundingType::FLOOR,
+ ov::op::PadType::EXPLICIT);
+ maxpool->set_friendly_name("MaxPool_2");
+
+ auto result = std::make_shared<ov::op::v0::Result>(maxpool);
+ result->set_friendly_name("output");
+
+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input}, "MaxPool");
+}
+
+} // namespace
+
+using NPUVMRuntimeCAPITestParams = std::tuple<std::string, // Device name
+ std::string, // Model path or name
+ std::string, // Library name
+ ov::AnyMap // Config
+ >;
+
+class NPUVMRuntimeCAPITest :
+ public testing::WithParamInterface<NPUVMRuntimeCAPITestParams>,
+ public ov::test::TestsCommon {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<NPUVMRuntimeCAPITestParams>& obj) {
+ std::string targetDevice;
+ std::string modelPath;
+ std::string libName;
+ ov::AnyMap configuration;
+
+ std::tie(targetDevice, modelPath, libName, configuration) = obj.param;
+ std::replace(targetDevice.begin(), targetDevice.end(), ':', '.');
+
+ std::ostringstream result;
+ result << "target_platform=" << ov::test::utils::getTestsPlatformFromEnvironmentOr(targetDevice) << "_";
+ result << "model=" << modelPath << "_";
+ result << "target_device=" << targetDevice << "_";
+ result << "library_name=" << libName << "_";
+
+ if (!configuration.empty()) {
+ using namespace ov::test::utils;
+ for (auto& configItem : configuration) {
+ result << "configItem=" << configItem.first << "_";
+ configItem.second.print(result);
+ }
+ }
+
+ return result.str();
+ }
+
+protected:
+ void checkStatus(const std::string& step, const ze_result_t result) {
+ if (ZE_RESULT_SUCCESS != result) {
+ throw std::runtime_error("L0 " + step + " failed: " + intel_npu::ze_result_to_string(result) + ", code 0x" +
+ std::to_string(result) + " - " + intel_npu::ze_result_to_description(result));
+ }
+ }
+
+ void SetUp() override {
+ // Skip test according to plugin specific disabled_test_patterns() (if any)
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+
+ try {
+ std::string targetDevice;
+ std::string modelPath;
+ std::string libName;
+ ov::AnyMap configuration;
+
+ std::tie(targetDevice, modelPath, libName, configuration) = this->GetParam();
+
+ auto libpath = ov::util::make_plugin_library_name({}, libName);
+#if defined(OPENVINO_ENABLE_UNICODE_PATH_SUPPORT) && defined(_WIN32)
+ lib = ov::util::load_shared_object(ov::util::string_to_wstring(libpath).c_str());
+#else
+ lib = ov::util::load_shared_object(libpath.c_str());
+#endif
+ fntbl.init(lib, libName);
+
+ ov::Core core;
+ const auto deviceNames =
+ core.get_property("NPU", ov::available_devices.name()).as<std::vector<std::string>>();
+ const bool deviceAvailable =
+ std::any_of(deviceNames.begin(), deviceNames.end(), [&](const std::string& name) {
+ return targetDevice.find(name) != std::string::npos;
+ });
+ if (!deviceAvailable) {
+ std::cerr << "Warning: Target device " << targetDevice
+ << " not found in available devices: " << ov::util::join(deviceNames) << std::endl;
+ GTEST_SKIP() << "Skip test for current device";
+ }
+
+ const auto ext = std::filesystem::path(modelPath).extension().string();
+ if (ext == ".xml") {
+ compileBlobFromOvIR(core, modelPath, targetDevice, configuration);
+ } else if (ext == ".blob") {
+ loadBlobFromFile(modelPath);
+ } else {
+ compileBlobFromCustomModel(core, modelPath, targetDevice, configuration);
+ }
+
+ if (blob.str().empty()) {
+ std::cerr << "[SetUp] Cannot export blob" << std::endl;
+ GTEST_FAIL() << "Cannot export blob";
+ }
+ } catch (const std::runtime_error& error) {
+ std::cerr << "[SetUp] std::runtime_error: " << error.what() << std::endl;
+ GTEST_FAIL() << error.what();
+ }
+ }
+
+ void compileBlobFromOvIR(ov::Core& core, const std::string& modelPath, const std::string& targetDevice,
+ const ov::AnyMap& config) {
+ const auto resolvedPath = resolveExistingPathOrThrow(std::filesystem::path(modelPath), "IR model");
+ auto model = core.read_model(resolvedPath.string());
+ auto preprocessor = ov::preprocess::PrePostProcessor(model);
+ for (size_t i = 0; i < model->inputs().size(); i++) {
+ preprocessor.input(i).tensor().set_element_type(ov::element::f16);
+ }
+ for (size_t i = 0; i < model->outputs().size(); i++) {
+ preprocessor.output(i).tensor().set_element_type(ov::element::f16);
+ }
+ auto compiledModel = core.compile_model(preprocessor.build(), targetDevice, config);
+ compiledModel.export_model(blob);
+ }
+
+ // Reads a pre-compiled blob file directly into the blob stream, bypassing compilation.
+ void loadBlobFromFile(const std::string& blobPath) {
+ const auto resolvedPath = resolveExistingPathOrThrow(std::filesystem::path(blobPath), "blob file");
+
+ std::ifstream file(resolvedPath, std::ios::binary);
+ if (!file) {
+ throw std::runtime_error("Failed to read blob file: " + resolvedPath.string());
+ }
+ blob << file.rdbuf();
+ }
+
+ // Builds a named model via the OpenVINO C++ API, compiles, and exports to blob.
+ void compileBlobFromCustomModel(ov::Core& core, const std::string& modelName, const std::string& targetDevice,
+ const ov::AnyMap& config) {
+ static const std::unordered_map<std::string, std::function<std::shared_ptr<ov::Model>()>> kBuilders = {
+ {"MaxPool", createMaxPoolModel},
+ };
+ auto it = kBuilders.find(modelName);
+ if (it == kBuilders.end()) {
+ throw std::runtime_error("Unknown custom model name: " + modelName);
+ }
+ auto compiledModel = core.compile_model(it->second(), targetDevice, config);
+ compiledModel.export_model(blob);
+ }
+
+ using ZeroMemRef = std::pair<std::shared_ptr<intel_npu::ZeroMem>, npu_vm_runtime_mem_ref_handle_t>;
+
+ // Creates a runtime handle from the compiled blob. Uses ASSERT to abort on failure so callers
+ // receive a valid, non-null handle.
+ void createRuntimeHandle(npu_vm_runtime_handle_t& handle, npu_vm_runtime_properties_t& props) {
+ const std::string content = blob.str();
+ npu_vm_runtime_blob_desc_t blobDesc;
+ blobDesc.pInput = reinterpret_cast<const uint8_t*>(content.data());
+ blobDesc.inputSize = content.size();
+ ASSERT_EQ(fntbl.npuVMRuntimeCreate(&blobDesc, &handle, &props), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(handle, nullptr);
+ }
+
+ // Allocates ZeroMem-backed memref handles for all graph arguments.
+ void prepareZeroMemRefs(npu_vm_runtime_handle_t handle, const npu_vm_runtime_properties_t& props,
+ const std::shared_ptr<intel_npu::ZeroInitStructsHolder>& initStruct,
+ std::vector<ZeroMemRef>& inputs, std::vector<ZeroMemRef>& outputs) {
+ constexpr std::size_t kPageSize = 4096;
+ ze_graph_argument_properties_3_t arg;
+ ze_graph_argument_metadata_t meta;
+ int64_t upperBound[5];
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &arg, &meta, upperBound), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ ov::Shape shapeFromCompiler;
+ for (uint32_t d = 0; d < arg.dims_count; d++) {
+ shapeFromCompiler.push_back(arg.dims[d]);
+ }
+
+ ov::element::Type_t precision = intel_npu::zeroUtils::toOVElementType(arg.devicePrecision);
+ ov::element::Type elementType(precision);
+ size_t totalSize = std::accumulate(shapeFromCompiler.begin(), shapeFromCompiler.end(), elementType.size(),
+ [](size_t a, size_t b) {
+ return a * b;
+ });
+
+ std::shared_ptr<intel_npu::ZeroMem> memPtr = intel_npu::zero_mem::allocate_memory(
+ initStruct, totalSize, kPageSize, arg.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT);
+
+ void* pData = memPtr->data();
+ std::vector<int64_t> tensorSize(shapeFromCompiler.begin(), shapeFromCompiler.end());
+ std::vector<int64_t> tensorStride(tensorSize.size());
+ int64_t stride = 1;
+ for (int64_t j = static_cast<int64_t>(tensorSize.size()) - 1; j >= 0; j--) {
+ tensorStride[j] = stride;
+ stride *= tensorSize[j];
+ }
+
+ npu_vm_runtime_mem_ref_handle_t hMemRef;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateMemRef(static_cast<int64_t>(tensorSize.size()), &hMemRef),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(fntbl.npuVMRuntimeSetMemRef(hMemRef, pData, pData, 0, tensorSize.data(), tensorStride.data(),
+ static_cast<int64_t>(tensorSize.size())),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ inputs.emplace_back(memPtr, hMemRef);
+ } else if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_OUTPUT) {
+ outputs.emplace_back(memPtr, hMemRef);
+ }
+ }
+ }
+
+ // Extracts raw handles from ZeroMemRef pairs into a flat vector.
+ static void extractHandles(const std::vector<ZeroMemRef>& memRefs,
+ std::vector<npu_vm_runtime_mem_ref_handle_t>& handles) {
+ handles.reserve(memRefs.size());
+ for (const auto& [mem, handle] : memRefs) {
+ handles.push_back(handle);
+ }
+ }
+
+ // Initialises a command queue, graph extension table, command lists, and a fence.
+ void setupZEInfrastructure(const std::shared_ptr<intel_npu::ZeroInitStructsHolder>& initStruct,
+ const npu_vm_runtime_properties_t& props,
+ std::shared_ptr<intel_npu::CommandQueue>& commandQueue,
+ ze_graph_dditable_ext_t*& graphDdiTableExt,
+ ze_command_queue_npu_dditable_ext_t*& commandQueueDdiTableExt,
+ std::vector<std::shared_ptr<intel_npu::CommandList>>& commandLists,
+ std::vector<ze_command_list_handle_t>& commandListHandles,
+ std::shared_ptr<intel_npu::Fence>& fence) {
+ const intel_npu::CommandQueueDesc commandQueueDesc{
+ ZE_COMMAND_QUEUE_PRIORITY_NORMAL, // priority
+ std::nullopt, // workload
+ 0, // options
+ nullptr, // owner_tag
+ true, // shared_common_queue
+ };
+
+ commandQueue = std::make_shared<intel_npu::CommandQueue>(initStruct, commandQueueDesc);
+
+ graphDdiTableExt = nullptr;
+ checkStatus("zeDriverGetExtensionFunctionAddress",
+ intel_npu::zeDriverGetExtensionFunctionAddress(initStruct->getDriver(), ZE_GRAPH_EXT_NAME,
+ reinterpret_cast<void**>(&graphDdiTableExt)));
+
+ commandQueueDdiTableExt = nullptr;
+ checkStatus(
+ "zeDriverGetExtensionFunctionAddress",
+ intel_npu::zeDriverGetExtensionFunctionAddress(initStruct->getDriver(), ZE_COMMAND_QUEUE_NPU_EXT_NAME,
+ reinterpret_cast<void**>(&commandQueueDdiTableExt)));
+
+ commandLists.reserve(props.numOfSubGraphs);
+ for (size_t i = 0; i < props.numOfSubGraphs; ++i) {
+ commandLists.emplace_back(std::make_shared<intel_npu::CommandList>(initStruct));
+ }
+
+ commandListHandles.reserve(commandLists.size());
+ for (const auto& cl : commandLists) {
+ commandListHandles.push_back(cl->handle());
+ }
+
+ fence = std::make_shared<intel_npu::Fence>(commandQueue);
+ }
+
+ // Builds execution parameters from the provided ZE handles and memref arg arrays.
+ static npu_vm_runtime_execute_params_t buildExecParams(
+ const std::shared_ptr<intel_npu::ZeroInitStructsHolder>& initStruct,
+ std::vector<npu_vm_runtime_mem_ref_handle_t>& inputArgs,
+ std::vector<npu_vm_runtime_mem_ref_handle_t>& outputArgs,
+ std::vector<ze_command_list_handle_t>& commandListHandles,
+ const std::shared_ptr<intel_npu::CommandQueue>& commandQueue,
+ const std::shared_ptr<intel_npu::Fence>& fence, ze_graph_dditable_ext_t* graphDdiTableExt,
+ npu_vm_runtime_execution_context_handle_t executionContext = nullptr) {
+ npu_vm_runtime_execute_params_t execParams;
+ execParams.numOfInputs = static_cast<uint32_t>(inputArgs.size());
+ execParams.pInputs = inputArgs.data();
+ execParams.numOfOutputs = static_cast<uint32_t>(outputArgs.size());
+ execParams.pOutputs = outputArgs.data();
+ execParams.ctx = initStruct->getContext();
+ execParams.device = initStruct->getDevice();
+ execParams.graphDdiTableExt = graphDdiTableExt;
+ execParams.commandLists = commandListHandles.data();
+ execParams.numCommandLists = static_cast<uint64_t>(commandListHandles.size());
+ execParams.commandQueue = commandQueue->handle();
+ execParams.inferenceFence = fence->handle();
+ execParams.event = nullptr;
+ execParams.executionContext = executionContext;
+ return execParams;
+ }
+
+ void destroyMemRefs(const std::vector<npu_vm_runtime_mem_ref_handle_t>& handles) {
+ for (const auto h : handles) {
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroyMemRef(h), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ }
+ }
+
+ // Creates a runtime handle from the compiled blob. Uses ASSERT to abort on failure so callers
+ // receive a valid, non-null handle.
+ void createRuntimeHandle_v2(npu_vm_runtime_handle_t& handle, npu_vm_runtime_properties_t& props) {
+ const std::string content = blob.str();
+ npu_vm_runtime_blob_desc_t blobDesc;
+ blobDesc.pInput = reinterpret_cast<const uint8_t*>(content.data());
+ blobDesc.inputSize = content.size();
+ ASSERT_EQ(fntbl.npuVMRuntimeCreate2(&blobDesc, nullptr, &handle, &props), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(handle, nullptr);
+ }
+
+ // Builds execution parameters from the provided ZE handles and memref arg arrays.
+ static npu_vm_runtime_execute_params2_t buildExecParams_v2(
+ std::vector<npu_vm_runtime_mem_ref_handle_t>& inputArgs,
+ std::vector<npu_vm_runtime_mem_ref_handle_t>& outputArgs,
+ const std::shared_ptr<intel_npu::CommandQueue>& commandQueue, npu_vm_runtime_config_desc_t* pConfig,
+ npu_vm_runtime_execution_context_handle_t executionContext) {
+ npu_vm_runtime_execute_params2_t execParams;
+ execParams.numOfInputs = static_cast<uint32_t>(inputArgs.size());
+ execParams.pInputs = inputArgs.data();
+ execParams.numOfOutputs = static_cast<uint32_t>(outputArgs.size());
+ execParams.pOutputs = outputArgs.data();
+ execParams.commandQueue = commandQueue->handle();
+ execParams.pConfig = pConfig;
+ execParams.executionContext = executionContext;
+ return execParams;
+ }
+
+ std::stringstream blob;
+ std::shared_ptr<void> lib;
+ npu_vm_runtime_fntbl fntbl;
+};
+
+TEST_P(NPUVMRuntimeCAPITest, GetAPIVersion_Success) {
+ npu_vm_runtime_version_t version;
+ auto result = fntbl.npuVMRuntimeGetAPIVersion(&version);
+ EXPECT_EQ(result, NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ std::string libName;
+ std::tie(std::ignore, std::ignore, libName, std::ignore) = this->GetParam();
+ EXPECT_EQ(version, NPU_VM_RUNTIME_VERSION_CURRENT);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, GetMetadata_ReturnsValidArgProperties) {
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ ASSERT_GT(props.numOfGraphArgs, 0u);
+
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ze_graph_argument_properties_3_t argProps{};
+ ze_graph_argument_metadata_t argMeta{};
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE]{};
+
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &argProps, &argMeta, upperBound),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ // Type must be either input or output
+ EXPECT_TRUE(argProps.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT || argProps.type == ZE_GRAPH_ARGUMENT_TYPE_OUTPUT);
+
+ // Precision must be resolved — UNKNOWN indicates unhandled element type
+ EXPECT_NE(argProps.networkPrecision, ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN);
+ EXPECT_NE(argProps.devicePrecision, ZE_GRAPH_ARGUMENT_PRECISION_UNKNOWN);
+
+ // Name must be non-empty
+ EXPECT_GT(strnlen(argProps.name, ZE_MAX_GRAPH_ARGUMENT_NAME), 0u);
+
+ // Rank must be positive
+ EXPECT_GT(argProps.dims_count, 0u);
+
+ // Metadata argument type must match properties
+ EXPECT_EQ(argMeta.type, argProps.type);
+ }
+
+ // Out-of-range index must return an error
+ {
+ ze_graph_argument_properties_3_t argProps{};
+ ze_graph_argument_metadata_t argMeta{};
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE]{};
+ EXPECT_NE(fntbl.npuVMRuntimeGetMetadata(handle, props.numOfGraphArgs, &argProps, &argMeta, upperBound),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ }
+
+ // Null handle must return an error
+ {
+ ze_graph_argument_properties_3_t argProps{};
+ ze_graph_argument_metadata_t argMeta{};
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE]{};
+ EXPECT_NE(fntbl.npuVMRuntimeGetMetadata(nullptr, 0, &argProps, &argMeta, upperBound),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ }
+
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+}
+
+// Verifies that the metadata extracted from bytecode.blob matches the exact values defined in
+// tests/lit/NPU/dialect/bytecode/serialization.mlir:
+// - 1 input ("Another example") and 1 output ("arithmetic")
+// - Shape [42, 100, 50], precision FP32
+//
+// The blob was generated with:
+// ./vpux-translate --split-input-file --platform=NPU5010 --export-bytecode
+// <compiler_repo>/tests/lit/NPU/dialect/bytecode/serialization.mlir -o bytecode.blob
+TEST_P(NPUVMRuntimeCAPITest, GetMetadata_ExactValuesForBytecodeBlob) {
+ std::string modelPath;
+ std::tie(std::ignore, modelPath, std::ignore, std::ignore) = this->GetParam();
+ if (modelPath != "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ // serialization.mlir metadata section defines 1 input + 1 output = 2 graph args
+ ASSERT_EQ(props.numOfGraphArgs, 2u);
+
+ struct ExpectedArg {
+ const char* name;
+ ze_graph_argument_type_t type;
+ uint32_t dimsCount;
+ uint32_t dims[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE];
+ };
+
+ const ExpectedArg expected[] = {
+ {"Another example", ZE_GRAPH_ARGUMENT_TYPE_INPUT, 3, {42, 100, 50}},
+ {"arithmetic", ZE_GRAPH_ARGUMENT_TYPE_OUTPUT, 3, {42, 100, 50}},
+ };
+
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ze_graph_argument_properties_3_t argProps{};
+ ze_graph_argument_metadata_t argMeta{};
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE]{};
+
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &argProps, &argMeta, upperBound),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ EXPECT_STREQ(argProps.name, expected[i].name) << "Arg " << i << " name mismatch";
+ EXPECT_EQ(argProps.type, expected[i].type) << "Arg " << i << " type mismatch";
+ EXPECT_EQ(argProps.networkPrecision, ZE_GRAPH_ARGUMENT_PRECISION_FP32)
+ << "Arg " << i << " networkPrecision mismatch";
+ EXPECT_EQ(argProps.devicePrecision, ZE_GRAPH_ARGUMENT_PRECISION_FP32)
+ << "Arg " << i << " devicePrecision mismatch";
+ EXPECT_EQ(argProps.dims_count, expected[i].dimsCount) << "Arg " << i << " dims_count mismatch";
+ for (uint32_t d = 0; d < expected[i].dimsCount; d++) {
+ EXPECT_EQ(argProps.dims[d], expected[i].dims[d]) << "Arg " << i << " dim[" << d << "] mismatch";
+ }
+
+ EXPECT_EQ(argMeta.type, expected[i].type) << "Arg " << i << " metadata type mismatch";
+ EXPECT_STREQ(argMeta.friendly_name, expected[i].name) << "Arg " << i << " friendly_name mismatch";
+ }
+
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, ExecuteCompiledModel) {
+ std::string libName;
+ std::string modelPath;
+ std::tie(std::ignore, modelPath, libName, std::ignore) = this->GetParam();
+
+ if (modelPath == "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ auto initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ std::vector<ZeroMemRef> inputs, outputs;
+ ASSERT_NO_FATAL_FAILURE(prepareZeroMemRefs(handle, props, initStruct, inputs, outputs));
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs, outputArgs;
+ extractHandles(inputs, inputArgs);
+ extractHandles(outputs, outputArgs);
+
+ std::shared_ptr<intel_npu::CommandQueue> commandQueue;
+ ze_graph_dditable_ext_t* graphDdiTableExt = nullptr;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt = nullptr;
+ std::vector<std::shared_ptr<intel_npu::CommandList>> commandLists;
+ std::vector<ze_command_list_handle_t> commandListHandles;
+ std::shared_ptr<intel_npu::Fence> fence;
+ setupZEInfrastructure(initStruct, props, commandQueue, graphDdiTableExt, commandQueueDdiTableExt, commandLists,
+ commandListHandles, fence);
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext(handle, &executionContextHandle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ auto execParams = buildExecParams(initStruct, inputArgs, outputArgs, commandListHandles, commandQueue, fence,
+ graphDdiTableExt, executionContextHandle);
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ fence->hostSynchronize();
+
+ // TODO: dump output to check accuracy once more models are supported
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, UpdateMutableCommandList) {
+ std::string libName;
+ std::tie(std::ignore, std::ignore, libName, std::ignore) = this->GetParam();
+ // E#211625: Skip update mutable command list support for interpreter runtime is not implemented
+ if (libName == "openvino_intel_npu_vm_runtime") {
+ GTEST_SKIP() << "UpdateMutableCommandList is temporarily disabled for interpreter runtime";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext(handle, &executionContextHandle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ auto initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ std::vector<ZeroMemRef> inputs, outputs;
+ ASSERT_NO_FATAL_FAILURE(prepareZeroMemRefs(handle, props, initStruct, inputs, outputs));
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs, outputArgs;
+ extractHandles(inputs, inputArgs);
+ extractHandles(outputs, outputArgs);
+
+ std::shared_ptr<intel_npu::CommandQueue> commandQueue;
+ ze_graph_dditable_ext_t* graphDdiTableExt = nullptr;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt = nullptr;
+ std::vector<std::shared_ptr<intel_npu::CommandList>> commandLists;
+ std::vector<ze_command_list_handle_t> commandListHandles;
+ std::shared_ptr<intel_npu::Fence> fence;
+ setupZEInfrastructure(initStruct, props, commandQueue, graphDdiTableExt, commandQueueDdiTableExt, commandLists,
+ commandListHandles, fence);
+
+ auto execParams = buildExecParams(initStruct, inputArgs, outputArgs, commandListHandles, commandQueue, fence,
+ graphDdiTableExt, executionContextHandle);
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ fence->hostSynchronize();
+
+ std::vector<uint64_t> argIndexArray(props.numOfGraphArgs);
+ std::iota(argIndexArray.begin(), argIndexArray.end(), 0u);
+ EXPECT_EQ(
+ fntbl.npuVMRuntimeUpdateMutableCommandList(handle, &execParams, argIndexArray.data(), argIndexArray.size()),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ intel_npu::zeCommandQueueExecuteCommandLists(commandQueue->handle(), static_cast<uint32_t>(commandLists.size()), commandListHandles.data(),
+ fence->handle());
+ fence->hostSynchronize();
+
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroyExecutionContext(executionContextHandle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ // TODO: dump output to check accuracy once more models are supported
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+// E#227224: PredictOutputShape is temporarily disabled.
+TEST_P(NPUVMRuntimeCAPITest, DISABLED_PredictShape) {
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ struct LocalMemRef {
+ const void* basePtr;
+ const void* data;
+ int64_t offset;
+ std::vector<int64_t> sizes;
+ std::vector<int64_t> strides;
+ int64_t dimsCount;
+ std::vector<int64_t> dynamicRanks;
+ };
+
+ std::vector<LocalMemRef> inputs;
+ std::vector<LocalMemRef> outputs;
+
+ ze_graph_argument_properties_3_t arg;
+ ze_graph_argument_metadata_t meta;
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE];
+ const uint64_t dynamicRankValue = std::numeric_limits<uint64_t>::max();
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &arg, &meta, upperBound), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ LocalMemRef localMemRef;
+ localMemRef.basePtr = nullptr;
+ localMemRef.data = nullptr;
+ localMemRef.offset = 0;
+ localMemRef.dimsCount = arg.dims_count;
+ // Upper bound shape — actual size may be smaller
+ for (uint32_t d = 0; d < arg.dims_count; d++) {
+ localMemRef.sizes.push_back(arg.dims[d]);
+ }
+ // Dimensions where shape[d] == max uint64 are dynamic
+ for (uint32_t d = 0; d < meta.shape_size; d++) {
+ if (meta.shape[d] == dynamicRankValue) {
+ localMemRef.dynamicRanks.push_back(d);
+ }
+ }
+ // Compute row-major (NCHW) strides
+ uint64_t stride = 1;
+ localMemRef.strides.resize(localMemRef.dimsCount);
+ for (auto d = static_cast<int64_t>(localMemRef.dimsCount - 1); d >= 0; d--) {
+ localMemRef.strides[d] = stride;
+ stride *= localMemRef.sizes[d];
+ }
+ if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ inputs.push_back(localMemRef);
+ } else if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_OUTPUT) {
+ outputs.push_back(localMemRef);
+ }
+ }
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs;
+ std::vector<npu_vm_runtime_mem_ref_handle_t> outputArgs;
+ for (auto& input : inputs) {
+ npu_vm_runtime_mem_ref_handle_t hMemRef;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateMemRef(input.dimsCount, &hMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(fntbl.npuVMRuntimeSetMemRef(hMemRef, input.basePtr, input.data, input.offset, input.sizes.data(),
+ input.strides.data(), input.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ inputArgs.push_back(hMemRef);
+ }
+ for (auto& output : outputs) {
+ npu_vm_runtime_mem_ref_handle_t hMemRef;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateMemRef(output.dimsCount, &hMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(fntbl.npuVMRuntimeSetMemRef(hMemRef, output.basePtr, output.data, output.offset, output.sizes.data(),
+ output.strides.data(), output.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ outputArgs.push_back(hMemRef);
+ }
+ npu_vm_runtime_predict_output_shape_params_t predictParam;
+ predictParam.pInputs = inputArgs.data();
+ predictParam.numOfInputs = static_cast<uint32_t>(inputArgs.size());
+ predictParam.pOutputs = outputArgs.data();
+ predictParam.numOfOutputs = static_cast<uint32_t>(outputArgs.size());
+ EXPECT_EQ(fntbl.npuVMRuntimePredictOutputShape(handle, &predictParam), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ // Verify the output shape
+ for (size_t i = 0; i < outputs.size(); i++) {
+ LocalMemRef parsedMemRef;
+ parsedMemRef.sizes.resize(outputs[i].dimsCount);
+ parsedMemRef.strides.resize(outputs[i].dimsCount);
+ EXPECT_EQ(fntbl.npuVMRuntimeParseMemRef(outputArgs[i], &parsedMemRef.basePtr, &parsedMemRef.data,
+ &parsedMemRef.offset, parsedMemRef.sizes.data(),
+ parsedMemRef.strides.data(), &parsedMemRef.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(outputs[i].dimsCount, parsedMemRef.dimsCount);
+
+ for (int64_t d = 0; d < outputs[i].dimsCount; d++) {
+ EXPECT_TRUE(outputs[i].sizes[d] >= parsedMemRef.sizes[d]);
+ EXPECT_TRUE(outputs[i].strides[d] >= parsedMemRef.strides[d]);
+ }
+ }
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+// E#227224: PredictOutputShape is temporarily disabled.
+TEST_P(NPUVMRuntimeCAPITest, DISABLED_PredictShape2) {
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle(handle, props));
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext(handle, &executionContextHandle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ struct LocalMemRef {
+ const void* basePtr;
+ const void* data;
+ int64_t offset;
+ std::vector<int64_t> sizes;
+ std::vector<int64_t> strides;
+ int64_t dimsCount;
+ std::vector<int64_t> dynamicRanks;
+ };
+
+ std::vector<LocalMemRef> inputs;
+ std::vector<LocalMemRef> outputs;
+
+ ze_graph_argument_properties_3_t arg;
+ ze_graph_argument_metadata_t meta;
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE];
+ const uint64_t dynamicRankValue = std::numeric_limits<uint64_t>::max();
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &arg, &meta, upperBound), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ LocalMemRef localMemRef;
+ localMemRef.basePtr = nullptr;
+ localMemRef.data = nullptr;
+ localMemRef.offset = 0;
+ localMemRef.dimsCount = arg.dims_count;
+ // Upper bound shape — actual size may be smaller
+ for (uint32_t d = 0; d < arg.dims_count; d++) {
+ localMemRef.sizes.push_back(arg.dims[d]);
+ }
+ // Dimensions where shape[d] == max uint64 are dynamic
+ for (uint32_t d = 0; d < meta.shape_size; d++) {
+ if (meta.shape[d] == dynamicRankValue) {
+ localMemRef.dynamicRanks.push_back(d);
+ }
+ }
+ // Compute row-major (NCHW) strides
+ uint64_t stride = 1;
+ localMemRef.strides.resize(localMemRef.dimsCount);
+ for (int64_t d = localMemRef.dimsCount - 1; d >= 0; d--) {
+ localMemRef.strides[d] = stride;
+ stride *= localMemRef.sizes[d];
+ }
+ if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
+ inputs.push_back(localMemRef);
+ } else if (arg.type == ZE_GRAPH_ARGUMENT_TYPE_OUTPUT) {
+ outputs.push_back(localMemRef);
+ }
+ }
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs;
+ std::vector<npu_vm_runtime_mem_ref_handle_t> outputArgs;
+ for (auto& input : inputs) {
+ npu_vm_runtime_mem_ref_handle_t hMemRef;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateMemRef(input.dimsCount, &hMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(fntbl.npuVMRuntimeSetMemRef(hMemRef, input.basePtr, input.data, input.offset, input.sizes.data(),
+ input.strides.data(), input.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ inputArgs.push_back(hMemRef);
+ }
+ for (auto& output : outputs) {
+ npu_vm_runtime_mem_ref_handle_t hMemRef;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateMemRef(output.dimsCount, &hMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(fntbl.npuVMRuntimeSetMemRef(hMemRef, output.basePtr, output.data, output.offset, output.sizes.data(),
+ output.strides.data(), output.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ outputArgs.push_back(hMemRef);
+ }
+ npu_vm_runtime_predict_output_shape_params_t2 predictParam;
+ predictParam.pInputs = inputArgs.data();
+ predictParam.numOfInputs = static_cast<uint32_t>(inputArgs.size());
+ predictParam.pOutputs = outputArgs.data();
+ predictParam.numOfOutputs = static_cast<uint32_t>(outputArgs.size());
+ predictParam.executionContext = executionContextHandle;
+ EXPECT_EQ(fntbl.npuVMRuntimePredictOutputShape2(handle, &predictParam), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ // Verify the output shape
+ for (size_t i = 0; i < outputs.size(); i++) {
+ LocalMemRef parsedMemRef;
+ parsedMemRef.sizes.resize(outputs[i].dimsCount);
+ parsedMemRef.strides.resize(outputs[i].dimsCount);
+ EXPECT_EQ(fntbl.npuVMRuntimeParseMemRef(outputArgs[i], &parsedMemRef.basePtr, &parsedMemRef.data,
+ &parsedMemRef.offset, parsedMemRef.sizes.data(),
+ parsedMemRef.strides.data(), &parsedMemRef.dimsCount),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(outputs[i].dimsCount, parsedMemRef.dimsCount);
+
+ for (int64_t d = 0; d < outputs[i].dimsCount; d++) {
+ EXPECT_TRUE(outputs[i].sizes[d] >= parsedMemRef.sizes[d]);
+ EXPECT_TRUE(outputs[i].strides[d] >= parsedMemRef.strides[d]);
+ }
+ }
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroyExecutionContext(executionContextHandle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, GetMetadata_ExactValuesForBytecodeBlob_v2) {
+ std::string modelPath;
+ std::string libName;
+ std::tie(std::ignore, modelPath, libName, std::ignore) = this->GetParam();
+ if (modelPath != "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+
+ npu_vm_runtime_version_t version;
+ auto result = fntbl.npuVMRuntimeGetAPIVersion(&version);
+ EXPECT_EQ(result, NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ if (NPU_VM_RUNTIME_MAJOR_VERSION(version) < 2) {
+ GTEST_SKIP() << "GetMetadata_ExactValuesForBytecodeBlob_v2 requires NPU VM Runtime v2.0 or later";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle_v2(handle, props));
+
+ // serialization.mlir metadata section defines 1 input + 1 output = 2 graph args
+ ASSERT_EQ(props.numOfGraphArgs, 2u);
+
+ struct ExpectedArg {
+ const char* name;
+ ze_graph_argument_type_t type;
+ uint32_t dimsCount;
+ uint32_t dims[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE];
+ };
+
+ const ExpectedArg expected[] = {
+ {"Another example", ZE_GRAPH_ARGUMENT_TYPE_INPUT, 3, {42, 100, 50}},
+ {"arithmetic", ZE_GRAPH_ARGUMENT_TYPE_OUTPUT, 3, {42, 100, 50}},
+ };
+
+ for (uint32_t i = 0; i < props.numOfGraphArgs; i++) {
+ ze_graph_argument_properties_3_t argProps{};
+ ze_graph_argument_metadata_t argMeta{};
+ int64_t upperBound[ZE_MAX_GRAPH_ARGUMENT_DIMENSIONS_SIZE]{};
+
+ ASSERT_EQ(fntbl.npuVMRuntimeGetMetadata(handle, i, &argProps, &argMeta, upperBound),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ EXPECT_STREQ(argProps.name, expected[i].name) << "Arg " << i << " name mismatch";
+ EXPECT_EQ(argProps.type, expected[i].type) << "Arg " << i << " type mismatch";
+ EXPECT_EQ(argProps.networkPrecision, ZE_GRAPH_ARGUMENT_PRECISION_FP32)
+ << "Arg " << i << " networkPrecision mismatch";
+ EXPECT_EQ(argProps.devicePrecision, ZE_GRAPH_ARGUMENT_PRECISION_FP32)
+ << "Arg " << i << " devicePrecision mismatch";
+ EXPECT_EQ(argProps.dims_count, expected[i].dimsCount) << "Arg " << i << " dims_count mismatch";
+ for (uint32_t d = 0; d < expected[i].dimsCount; d++) {
+ EXPECT_EQ(argProps.dims[d], expected[i].dims[d]) << "Arg " << i << " dim[" << d << "] mismatch";
+ }
+
+ EXPECT_EQ(argMeta.type, expected[i].type) << "Arg " << i << " metadata type mismatch";
+ EXPECT_STREQ(argMeta.friendly_name, expected[i].name) << "Arg " << i << " friendly_name mismatch";
+ }
+
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, ExecuteCompiledModel_v2) {
+ std::string libName;
+ std::string modelPath;
+ std::tie(std::ignore, modelPath, libName, std::ignore) = this->GetParam();
+
+ if (modelPath == "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+ npu_vm_runtime_version_t version;
+ auto result = fntbl.npuVMRuntimeGetAPIVersion(&version);
+ EXPECT_EQ(result, NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ if (NPU_VM_RUNTIME_MAJOR_VERSION(version) < 2) {
+ GTEST_SKIP() << "ExecuteCompiledModel_v2 requires NPU VM Runtime v2.0 or later";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle_v2(handle, props));
+
+ auto initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ std::vector<ZeroMemRef> inputs, outputs;
+ ASSERT_NO_FATAL_FAILURE(prepareZeroMemRefs(handle, props, initStruct, inputs, outputs));
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs, outputArgs;
+ extractHandles(inputs, inputArgs);
+ extractHandles(outputs, outputArgs);
+
+ std::shared_ptr<intel_npu::CommandQueue> commandQueue;
+ ze_graph_dditable_ext_t* graphDdiTableExt = nullptr;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt = nullptr;
+ std::vector<std::shared_ptr<intel_npu::CommandList>> commandLists;
+ std::vector<ze_command_list_handle_t> commandListHandles;
+ std::shared_ptr<intel_npu::Fence> fence;
+ setupZEInfrastructure(initStruct, props, commandQueue, graphDdiTableExt, commandQueueDdiTableExt, commandLists,
+ commandListHandles, fence);
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ npu_vm_runtime_create_execution_context_params_t createContextParams;
+ createContextParams.commandQueue = nullptr;
+ createContextParams.ctx = initStruct->getContext();
+ createContextParams.device = initStruct->getDevice();
+ createContextParams.graphDdiTableExt = graphDdiTableExt;
+ createContextParams.commandQueueDdiTableExt = commandQueueDdiTableExt;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext2(handle, &createContextParams, &executionContextHandle),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ auto execParams =
+ buildExecParams_v2(inputArgs, outputArgs, commandQueue, /*pConfig*/ nullptr, executionContextHandle);
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute2(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(fntbl.npuVMRuntimeHostSync(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ // TODO: dump output to check accuracy once more models are supported
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, ExecuteCompiledModelWithSharedCmdQueue_v2) {
+ std::string libName;
+ std::string modelPath;
+ std::tie(std::ignore, modelPath, libName, std::ignore) = this->GetParam();
+
+ if (modelPath == "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+ npu_vm_runtime_version_t version;
+ auto result = fntbl.npuVMRuntimeGetAPIVersion(&version);
+ EXPECT_EQ(result, NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ if (NPU_VM_RUNTIME_MAJOR_VERSION(version) < 2) {
+ GTEST_SKIP() << "ExecuteCompiledModel_v2 requires NPU VM Runtime v2.0 or later";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle_v2(handle, props));
+
+ auto initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ std::vector<ZeroMemRef> inputs, outputs;
+ ASSERT_NO_FATAL_FAILURE(prepareZeroMemRefs(handle, props, initStruct, inputs, outputs));
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs, outputArgs;
+ extractHandles(inputs, inputArgs);
+ extractHandles(outputs, outputArgs);
+
+ std::shared_ptr<intel_npu::CommandQueue> commandQueue;
+ ze_graph_dditable_ext_t* graphDdiTableExt = nullptr;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt = nullptr;
+ std::vector<std::shared_ptr<intel_npu::CommandList>> commandLists;
+ std::vector<ze_command_list_handle_t> commandListHandles;
+ std::shared_ptr<intel_npu::Fence> fence;
+ setupZEInfrastructure(initStruct, props, commandQueue, graphDdiTableExt, commandQueueDdiTableExt, commandLists,
+ commandListHandles, fence);
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ npu_vm_runtime_create_execution_context_params_t createContextParams;
+ createContextParams.commandQueue = commandQueue->handle();
+
+ createContextParams.ctx = initStruct->getContext();
+ createContextParams.device = initStruct->getDevice();
+ createContextParams.graphDdiTableExt = graphDdiTableExt;
+ createContextParams.commandQueueDdiTableExt = commandQueueDdiTableExt;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext2(handle, &createContextParams, &executionContextHandle),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ auto execParams =
+ buildExecParams_v2(inputArgs, outputArgs, commandQueue, /*pConfig*/ nullptr, executionContextHandle);
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute2(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(fntbl.npuVMRuntimeHostSync(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ // TODO: dump output to check accuracy once more models are supported
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+TEST_P(NPUVMRuntimeCAPITest, ExecuteCompiledModelWithCmdQueueConfig_v2) {
+ std::string libName;
+ std::string modelPath;
+ std::tie(std::ignore, modelPath, libName, std::ignore) = this->GetParam();
+
+ if (modelPath == "bytecode.blob") {
+ GTEST_SKIP() << "Test applies only to bytecode.blob";
+ }
+ npu_vm_runtime_version_t version;
+ auto result = fntbl.npuVMRuntimeGetAPIVersion(&version);
+ EXPECT_EQ(result, NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ if (NPU_VM_RUNTIME_MAJOR_VERSION(version) < 2) {
+ GTEST_SKIP() << "ExecuteCompiledModel_v2 requires NPU VM Runtime v2.0 or later";
+ }
+
+ npu_vm_runtime_handle_t handle = nullptr;
+ npu_vm_runtime_properties_t props;
+ ASSERT_NO_FATAL_FAILURE(createRuntimeHandle_v2(handle, props));
+
+ auto initStruct = std::make_shared<intel_npu::ZeroInitStructsHolder>();
+ std::vector<ZeroMemRef> inputs, outputs;
+ ASSERT_NO_FATAL_FAILURE(prepareZeroMemRefs(handle, props, initStruct, inputs, outputs));
+
+ std::vector<npu_vm_runtime_mem_ref_handle_t> inputArgs, outputArgs;
+ extractHandles(inputs, inputArgs);
+ extractHandles(outputs, outputArgs);
+
+ std::shared_ptr<intel_npu::CommandQueue> commandQueue;
+ ze_graph_dditable_ext_t* graphDdiTableExt = nullptr;
+ ze_command_queue_npu_dditable_ext_t* commandQueueDdiTableExt = nullptr;
+ std::vector<std::shared_ptr<intel_npu::CommandList>> commandLists;
+ std::vector<ze_command_list_handle_t> commandListHandles;
+ std::shared_ptr<intel_npu::Fence> fence;
+ setupZEInfrastructure(initStruct, props, commandQueue, graphDdiTableExt, commandQueueDdiTableExt, commandLists,
+ commandListHandles, fence);
+
+ npu_vm_runtime_execution_context_handle_t executionContextHandle = nullptr;
+ npu_vm_runtime_create_execution_context_params_t createContextParams;
+ createContextParams.commandQueue = nullptr;
+ createContextParams.ctx = initStruct->getContext();
+ createContextParams.device = initStruct->getDevice();
+ createContextParams.graphDdiTableExt = graphDdiTableExt;
+ createContextParams.commandQueueDdiTableExt = commandQueueDdiTableExt;
+
+ npu_vm_runtime_config_desc_t configDesc[2];
+ configDesc[0].type = NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY;
+ configDesc[0].value = ZE_COMMAND_QUEUE_PRIORITY_PRIORITY_LOW;
+ configDesc[0].pNext = &configDesc[1];
+ configDesc[1].type = NPU_VM_RUNTIME_CONFIG_TYPE_WORKLOAD_TYPE;
+ configDesc[1].type = ZE_WORKLOAD_TYPE_BACKGROUND;
+ configDesc[1].pNext = nullptr;
+ ASSERT_EQ(fntbl.npuVMRuntimeCreateExecutionContext2(handle, &createContextParams, &executionContextHandle),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_NE(executionContextHandle, nullptr);
+
+ auto execParams = buildExecParams_v2(inputArgs, outputArgs, commandQueue, &configDesc[0], executionContextHandle);
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute2(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(fntbl.npuVMRuntimeHostSync(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ npu_vm_runtime_config_desc_t configDesc2{};
+ configDesc2.type = NPU_VM_RUNTIME_CONFIG_TYPE_QUEUE_PRIORITY;
+ configDesc2.value = ZE_COMMAND_QUEUE_PRIORITY_NORMAL;
+ execParams.pConfig = &configDesc2;
+ EXPECT_EQ(fntbl.npuVMRuntimeExecute2(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ EXPECT_EQ(fntbl.npuVMRuntimeHostSync(handle, &execParams), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ // TODO: dump output to check accuracy once more models are supported
+ EXPECT_EQ(fntbl.npuVMRuntimeDestroy(handle), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ destroyMemRefs(inputArgs);
+ destroyMemRefs(outputArgs);
+}
+
+const std::vector<std::string> devices = {"NPU.4000", "NPU.5010", "NPU.6010"};
+
+const std::vector<std::string> interpreterModels = {
+ // E#214461: Temporarily disabled because IR is unavailable in CI environment.
+ // "CustomNet_canonical_strides_1x1_no_fork.xml",
+ "bytecode.blob", "MaxPool"};
+
+const std::vector<std::string> interpreterLibNames = {"openvino_intel_npu_vm_runtime"};
+
+const std::vector<ov::AnyMap> configsHostCompile = {
+ {{"NPU_COMPILER_TYPE", "PLUGIN"}, {"NPU_COMPILATION_MODE", "HostCompile_Interpreter"}}};
+INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTest_interpreter_runtime, NPUVMRuntimeCAPITest,
+ ::testing::Combine(::testing::ValuesIn(devices), ::testing::ValuesIn(interpreterModels),
+ ::testing::ValuesIn(interpreterLibNames),
+ ::testing::ValuesIn(configsHostCompile)),
+ NPUVMRuntimeCAPITest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 16eeddb1b26..ab379b1f22b 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -17,6 +17,9 @@ set(MANDATORY_UNIT_TESTS_LIBS
"openvino::npu_ops"
"openvino_npu_vm_utils"
"openvino_npu_compiler_adapter"
+ "openvino::intel_npu_bytecode_utils"
+ "openvino::intel_npu_vm_runtime"
+
)
ov_add_test_target(
@@ -30,6 +33,7 @@ ov_add_test_target(
INCLUDES
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/npuw
+ ${CMAKE_CURRENT_SOURCE_DIR}/vm
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pipelines
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/utils/include
@@ -40,6 +44,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/backend/include/
${OpenVINO_SOURCE_DIR}/thirdparty/level_zero/level-zero
${OpenVINO_SOURCE_DIR}/thirdparty/level_zero/level-zero/include
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/utils/src/vm_runtime/vm_runtime/src/utils
OBJECT_FILES
# plugin/src
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/executor.cpp
@@ -178,6 +183,12 @@ install(TARGETS ${TARGET_NAME}
EXCLUDE_FROM_ALL
)
+if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT ENABLE_DEVELOPER_BUILD)
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=4)
+else()
+ target_compile_options(${TARGET_NAME} PRIVATE -DBUILD_LOG_LEVEL=6)
+endif()
+
target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npu/executor_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npu/should_use_host_compile_interpreter_test.cpp
@@ -248,4 +259,5 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/make_tensor_slice_bounds_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_topology_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/untangle_weight_converts_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/vm/buffer.cpp
)
diff --git a/src/plugins/intel_npu/tests/unit/vm/buffer.cpp b/src/plugins/intel_npu/tests/unit/vm/buffer.cpp
new file mode 100644
index 00000000000..034bba6e981
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/buffer.cpp
@@ -0,0 +1,627 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "buffer.hpp"
+#include "buffer_metadata.hpp"
+#include "composable_allocators.hpp"
+#include "counting_leaf.hpp"
+#include "host_allocator.hpp"
+
+#include <intel_npu/utils/utils.hpp>
+
+#include <gtest/gtest.h>
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <new>
+#include <numeric>
+#include <stdexcept>
+#include <utility>
+#include <vector>
+
+using namespace intel_npu::vm;
+using intel_npu::vm::test::AllocCounters;
+using intel_npu::vm::test::CountingLeaf;
+
+// ============================================================
+// Buffer Tests
+// ============================================================
+
+class VirtualMachineBufferTest : public ::testing::Test {};
+
+TEST_F(VirtualMachineBufferTest, ConstructNewAllocation) {
+ BufferManager mgr(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeHostAllocator());
+ {
+ // 64 bytes + Read-Write
+ const auto h = mgr.create(/*size=*/64, Permission::ReadWrite);
+ auto& buf = mgr.getBuffer(h);
+ EXPECT_NE(buf.getData(), nullptr);
+ EXPECT_EQ(buf.getSize(), 64u);
+ EXPECT_EQ(buf.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Owned);
+ }
+ {
+ // 128 bytes + Read-Only
+ const auto h = mgr.create(/*size=*/128, Permission::Read);
+ auto& buf = mgr.getBuffer(h);
+ EXPECT_NE(buf.getData(), nullptr);
+ EXPECT_EQ(buf.getSize(), 128u);
+ EXPECT_EQ(buf.getPermission(), Permission::Read);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Owned);
+ }
+}
+
+TEST_F(VirtualMachineBufferTest, ConstructFromExternalMemory) {
+ std::array<uint8_t, 8> externalData = {1, 2, 3, 4, 5, 6, 7, 8};
+ Buffer buf(externalData.data(), externalData.size(), Permission::Read);
+ EXPECT_EQ(buf.getData(), externalData.data());
+ EXPECT_EQ(buf.getSize(), externalData.size());
+ EXPECT_EQ(buf.getPermission(), Permission::Read);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Unowned);
+}
+
+TEST_F(VirtualMachineBufferTest, DataWrite) {
+ std::array<uint8_t, 4> data = {0xDE, 0xAD, 0xBE, 0xEF};
+ BufferManager mgr(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeHostAllocator());
+ {
+ // Read-Write buffer
+ const auto h = mgr.create(4, Permission::ReadWrite);
+ auto& buf = mgr.getBuffer(h);
+ buf.writeData(/*offset=*/0, data.data(), data.size());
+ EXPECT_EQ(buf.getData()[0], 0xDE);
+ EXPECT_EQ(buf.getData()[1], 0xAD);
+ EXPECT_EQ(buf.getData()[2], 0xBE);
+ EXPECT_EQ(buf.getData()[3], 0xEF);
+ }
+ {
+ // Read-only buffer
+ const auto h = mgr.create(4, Permission::Read);
+ auto& buf = mgr.getBuffer(h);
+ EXPECT_THROW(buf.writeData(/*offset=*/0, data.data(), data.size()), std::runtime_error);
+ }
+ {
+ // Out-of-bounds write
+ const auto h = mgr.create(4, Permission::ReadWrite);
+ auto& buf = mgr.getBuffer(h);
+ EXPECT_THROW(buf.writeData(/*offset=*/2, data.data(), data.size()), std::out_of_range);
+ }
+}
+
+TEST_F(VirtualMachineBufferTest, MoveLeavesSourceAsEmptyView) {
+ std::array<uint8_t, 4> payload = {1, 2, 3, 4};
+ Buffer source(payload.data(), payload.size(), Permission::ReadWrite, Ownership::Unowned);
+
+ Buffer moved(std::move(source));
+ EXPECT_EQ(moved.getData(), payload.data());
+ EXPECT_EQ(moved.getSize(), payload.size());
+ EXPECT_EQ(moved.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(moved.getOwnership(), Ownership::Unowned);
+
+ EXPECT_EQ(source.getData(), nullptr);
+ EXPECT_EQ(source.getSize(), 0u);
+
+ std::array<uint8_t, 2> otherPayload = {9, 9};
+ Buffer target(otherPayload.data(), otherPayload.size(), Permission::Read, Ownership::Unowned);
+ target = std::move(moved);
+
+ EXPECT_EQ(target.getData(), payload.data());
+ EXPECT_EQ(target.getSize(), payload.size());
+ EXPECT_EQ(target.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(target.getOwnership(), Ownership::Unowned);
+
+ EXPECT_EQ(moved.getData(), nullptr);
+ EXPECT_EQ(moved.getSize(), 0u);
+}
+
+// ============================================================
+// BufferManager Tests
+// ============================================================
+
+class VirtualMachineBufferManagerTest : public ::testing::Test {
+protected:
+ static constexpr size_t DEFAULT_MAX_MEMORY = 1024;
+ BufferManager manager{DEFAULT_MAX_MEMORY, makeHostAllocator()};
+};
+
+TEST_F(VirtualMachineBufferManagerTest, Create) {
+ auto handle = manager.create(/*size=*/64);
+ ASSERT_TRUE(manager.exists(handle));
+ ASSERT_NO_THROW(manager.getBuffer(handle));
+ auto& buf = manager.getBuffer(handle);
+ EXPECT_NE(buf.getData(), nullptr);
+ EXPECT_EQ(buf.getSize(), 64u);
+ EXPECT_EQ(buf.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Owned);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateMultipleBuffers) {
+ auto handle1 = manager.create(/*size=*/64);
+ auto handle2 = manager.create(/*size=*/128);
+ ASSERT_TRUE(manager.exists(handle1));
+ ASSERT_TRUE(manager.exists(handle2));
+ EXPECT_NE(handle1, handle2);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateZeroSizeThrows) {
+ EXPECT_THROW(manager.create(0), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateExactlyMaximumSizeSucceeds) {
+ EXPECT_NO_THROW(manager.create(DEFAULT_MAX_MEMORY));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateExceedingMaximumSizeThrows) {
+ EXPECT_THROW(manager.create(DEFAULT_MAX_MEMORY + 1), std::bad_alloc);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateCumulativeExceedingMaximumSizeThrows) {
+ manager.create(DEFAULT_MAX_MEMORY / 2);
+ EXPECT_THROW(manager.create(DEFAULT_MAX_MEMORY / 2 + 1), std::bad_alloc);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateAfterDeleteFitsWithinMaximumSize) {
+ auto handle = manager.create(DEFAULT_MAX_MEMORY);
+ manager.deleteBuffer(handle);
+ EXPECT_NO_THROW(manager.create(DEFAULT_MAX_MEMORY));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromMemory) {
+ std::array<uint8_t, 4> data = {0xDE, 0xAD, 0xBE, 0xEF};
+ const auto handle = manager.createFromMemory(data.data(), data.size(), Permission::Read);
+ EXPECT_TRUE(manager.exists(handle));
+ ASSERT_NO_THROW(manager.getBuffer(handle));
+ const auto& buf = manager.getBuffer(handle);
+ EXPECT_EQ(buf.getData(), data.data());
+ EXPECT_EQ(buf.getSize(), data.size());
+ EXPECT_EQ(buf.getPermission(), Permission::Read);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Unowned);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromMemoryNullDataThrows) {
+ EXPECT_THROW(manager.createFromMemory(nullptr, /*size=*/4, Permission::Read), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromMemoryZeroSizeThrows) {
+ std::array<uint8_t, 4> data = {};
+ EXPECT_THROW(manager.createFromMemory(data.data(), 0, Permission::Read), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromMemoryDoesNotContributeToMemoryBudget) {
+ // Fill budget with external memory, then still create an owned buffer
+ std::array<uint8_t, DEFAULT_MAX_MEMORY * 2> externalData = {};
+ manager.createFromMemory(externalData.data(), externalData.size(), Permission::Read);
+ EXPECT_NO_THROW(manager.create(DEFAULT_MAX_MEMORY));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromBuffer) {
+ auto handle = manager.create(/*size=*/64, Permission::ReadWrite);
+ ASSERT_TRUE(manager.exists(handle));
+ const auto& buf = manager.getBuffer(handle);
+ EXPECT_NE(buf.getData(), nullptr);
+ EXPECT_EQ(buf.getSize(), 64u);
+ EXPECT_EQ(buf.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(buf.getOwnership(), Ownership::Owned);
+
+ auto newHandle = manager.createFromBuffer(handle, /*offset=*/32, /*size=*/32);
+ ASSERT_TRUE(manager.exists(newHandle));
+ const auto& newBuf = manager.getBuffer(newHandle);
+ EXPECT_EQ(newBuf.getData(), buf.getData() + 32);
+ EXPECT_EQ(newBuf.getSize(), 32u);
+ EXPECT_EQ(newBuf.getPermission(), Permission::ReadWrite);
+ EXPECT_EQ(newBuf.getOwnership(), Ownership::Unowned);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromBufferEncodesTwoDimensionalSubviewOffsetsInBasePointer) {
+ // Mirrors a 2D buffer.subview over a row-major [5, 5] i32 source with source strides [5, 1].
+ // offsets [2, 2], sizes [2, 2], and subview strides [1, 1] select:
+ // [12, 13]
+ // [17, 18]
+ std::array<int32_t, 25> sourceData = {};
+ std::iota(sourceData.begin(), sourceData.end(), 0);
+
+ const auto sourceSizeBytes = sourceData.size() * sizeof(sourceData.front());
+ const auto sourceHandle =
+ manager.createFromMemory(reinterpret_cast<uint8_t*>(sourceData.data()), sourceSizeBytes, Permission::Read);
+
+ constexpr size_t sourceRowStride = 5;
+ constexpr size_t sourceColStride = 1;
+ constexpr size_t rowOffset = 2;
+ constexpr size_t colOffset = 2;
+ constexpr size_t subviewRowStride = 1;
+ constexpr size_t subviewColStride = 1;
+
+ const auto startElement = rowOffset * sourceRowStride + colOffset * sourceColStride;
+ const auto byteOffset = startElement * sizeof(sourceData.front());
+
+ const auto derivedRowStride = subviewRowStride * sourceRowStride;
+ const auto derivedColStride = subviewColStride * sourceColStride;
+ const auto maxDerivedElementOffset = derivedRowStride + derivedColStride;
+ const auto derivedSizeBytes = (maxDerivedElementOffset + 1) * sizeof(sourceData.front());
+
+ const auto derivedHandle = manager.createFromBuffer(sourceHandle, byteOffset, derivedSizeBytes);
+ const auto& derivedBuffer = manager.getBuffer(derivedHandle);
+ const auto* derivedData = reinterpret_cast<const int32_t*>(derivedBuffer.getData());
+
+ EXPECT_EQ(derivedData[0 * derivedRowStride + 0 * derivedColStride], 12);
+ EXPECT_EQ(derivedData[0 * derivedRowStride + 1 * derivedColStride], 13);
+ EXPECT_EQ(derivedData[1 * derivedRowStride + 0 * derivedColStride], 17);
+ EXPECT_EQ(derivedData[1 * derivedRowStride + 1 * derivedColStride], 18);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, ComputeSubviewStartElementRejectsMismatchedSubviewRanks) {
+ BufferMetadata sourceMeta;
+ sourceMeta.shape = {5, 5};
+ sourceMeta.strides = {5, 1};
+
+ EXPECT_FALSE(computeSubviewStartElement(sourceMeta, /*offsets=*/{0, 0}, /*sizes=*/{1},
+ /*strides=*/{1, 1})
+ .has_value());
+ EXPECT_FALSE(computeSubviewStartElement(sourceMeta, /*offsets=*/{0, 0}, /*sizes=*/{1, 1},
+ /*strides=*/{1})
+ .has_value());
+ EXPECT_FALSE(computeSubviewStartElement(sourceMeta, /*offsets=*/{0}, /*sizes=*/{1, 1},
+ /*strides=*/{1, 1})
+ .has_value());
+}
+
+TEST_F(VirtualMachineBufferManagerTest, ComputeSubviewStartElementRejectsMismatchedSourceMetadataRank) {
+ BufferMetadata sourceMeta;
+ sourceMeta.shape = {5};
+ sourceMeta.strides = {5, 1};
+
+ EXPECT_FALSE(computeSubviewStartElement(sourceMeta, /*offsets=*/{0, 0}, /*sizes=*/{1, 1},
+ /*strides=*/{1, 1})
+ .has_value());
+
+ sourceMeta.shape = {5, 5};
+ sourceMeta.strides = {5};
+ EXPECT_FALSE(computeSubviewStartElement(sourceMeta, /*offsets=*/{0, 0}, /*sizes=*/{1, 1},
+ /*strides=*/{1, 1})
+ .has_value());
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromBufferInvalidHandleThrows) {
+ EXPECT_THROW(manager.createFromBuffer(9999, /*offset=*/0, /*size=*/1), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, CreateFromBufferOutOfBoundsThrows) {
+ auto handle = manager.create(/*size=*/64);
+ ASSERT_TRUE(manager.exists(handle));
+
+ EXPECT_THROW(manager.createFromBuffer(handle, /*offset=*/32, /*size=*/33), std::out_of_range);
+ EXPECT_THROW(manager.createFromBuffer(handle, /*offset=*/64, /*size=*/1), std::out_of_range);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, MultipleExternalBuffersHaveUniqueHandles) {
+ std::array<uint8_t, 4> data = {};
+ const auto h1 = manager.createFromMemory(data.data(), data.size(), Permission::Read);
+ const auto h2 = manager.createFromMemory(data.data() + 2, data.size(), Permission::Read);
+ EXPECT_NE(h1, h2);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteBuffer) {
+ std::array<uint8_t, 4> data = {};
+ const auto handle = manager.createFromMemory(data.data(), data.size(), Permission::Read);
+ manager.deleteBuffer(handle);
+ EXPECT_FALSE(manager.exists(handle));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteBufferInvalidHandleThrows) {
+ EXPECT_THROW(manager.deleteBuffer(9999), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteSameHandleTwiceThrows) {
+ const auto handle = manager.create(/*size=*/4);
+ manager.deleteBuffer(handle);
+ EXPECT_THROW(manager.deleteBuffer(handle), std::invalid_argument);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteBufferDeletesDerivedBuffer) {
+ const auto parentHandle = manager.create(/*size=*/64);
+ const auto derivedHandle = manager.createFromBuffer(parentHandle, /*offset=*/0, /*size=*/32);
+ ASSERT_TRUE(manager.exists(derivedHandle));
+
+ manager.deleteBuffer(parentHandle);
+
+ EXPECT_FALSE(manager.exists(parentHandle));
+ EXPECT_FALSE(manager.exists(derivedHandle));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteDerivedBufferDoesNotDeleteParent) {
+ const auto parentHandle = manager.create(/*size=*/64);
+ const auto derivedHandle = manager.createFromBuffer(parentHandle, /*offset=*/0, /*size=*/32);
+
+ manager.deleteBuffer(derivedHandle);
+
+ EXPECT_FALSE(manager.exists(derivedHandle));
+ EXPECT_TRUE(manager.exists(parentHandle));
+ EXPECT_NO_THROW(manager.deleteBuffer(parentHandle));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteBufferCascadesAcrossChain) {
+ const auto handleA = manager.create(/*size=*/64);
+ const auto handleB = manager.createFromBuffer(handleA, /*offset=*/0, /*size=*/64);
+ const auto handleC = manager.createFromBuffer(handleB, /*offset=*/0, /*size=*/32);
+
+ manager.deleteBuffer(handleA);
+
+ EXPECT_FALSE(manager.exists(handleA));
+ EXPECT_FALSE(manager.exists(handleB));
+ EXPECT_FALSE(manager.exists(handleC));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, DeleteDerivedBufferThenDeleteParentDoesNotThrow) {
+ const auto parentHandle = manager.create(/*size=*/64);
+ const auto derivedHandle = manager.createFromBuffer(parentHandle, /*offset=*/0, /*size=*/32);
+
+ manager.deleteBuffer(derivedHandle);
+ EXPECT_NO_THROW(manager.deleteBuffer(parentHandle));
+
+ EXPECT_FALSE(manager.exists(parentHandle));
+ EXPECT_FALSE(manager.exists(derivedHandle));
+}
+
+TEST_F(VirtualMachineBufferManagerTest, RecycleReleasesOwnedBuffersAndClearsBudget) {
+ const auto owned = manager.create(/*size=*/256);
+ std::array<uint8_t, 4> external = {};
+ const auto unowned = manager.createFromMemory(external.data(), external.size(), Permission::Read);
+ ASSERT_GT(manager.getCurrentMemorySize(), 0u);
+
+ manager.recycle();
+
+ EXPECT_EQ(manager.getCurrentMemorySize(), 0u);
+ EXPECT_FALSE(manager.exists(owned));
+ EXPECT_FALSE(manager.exists(unowned));
+ // Handles stay monotonic across recycles: a fresh create never reuses a released handle.
+ const auto reborn = manager.create(/*size=*/256);
+ EXPECT_NE(reborn, owned);
+}
+
+TEST_F(VirtualMachineBufferManagerTest, RecycleLetsBudgetBeReusedAcrossManyRounds) {
+ // recycle() rewinds the budget each round, so the same full-budget allocation keeps succeeding.
+ for (int round = 0; round < 100; ++round) {
+ ASSERT_NO_THROW(manager.create(DEFAULT_MAX_MEMORY));
+ manager.recycle();
+ ASSERT_EQ(manager.getCurrentMemorySize(), 0u);
+ }
+}
+
+// ============================================================
+// BufferManager over an arena allocator
+//
+// The device path wraps a GrowingArena. These tests stand in a CountingLeaf-backed arena and assert the
+// BufferManager<->allocator contract: recycle() reuses memory across inferences and
+// owned buffers are handed out zeroed.
+// ============================================================
+
+namespace {
+
+constexpr size_t kPage = intel_npu::utils::STANDARD_PAGE_SIZE;
+
+// A GrowingArena over a CountingLeaf, erased into AnyAllocator, so a test can observe backing allocations.
+AnyAllocator makeCountingArena(AllocCounters& counters) {
+ return AnyAllocator{GrowingArena<CountingLeaf, BumpRegion<CountingLeaf::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/0>(CountingLeaf{&counters})};
+}
+
+} // namespace
+
+TEST(VirtualMachineBufferManagerArenaTest, RecycleReusesDeviceMemoryAcrossRounds) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeCountingArena(counters));
+
+ auto runRound = [&]() {
+ manager.create(kPage);
+ manager.create(kPage);
+ manager.create(kPage);
+ };
+
+ runRound(); // first inference grows the arena from the parent
+ const int slabsAfterFirst = counters.allocCalls;
+ EXPECT_GT(slabsAfterFirst, 0);
+
+ for (int round = 0; round < 5; ++round) {
+ manager.recycle();
+ EXPECT_EQ(manager.getCurrentMemorySize(), 0u); // budget freed for reuse
+ runRound();
+ }
+ // No new parent allocations after the first round, and slabs are retained (not freed).
+ EXPECT_EQ(counters.allocCalls, slabsAfterFirst);
+ EXPECT_EQ(counters.live, slabsAfterFirst);
+}
+
+TEST(VirtualMachineBufferManagerArenaTest, RecycleRetainsUnderlyingSlabsForReuse) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeCountingArena(counters));
+
+ manager.create(kPage);
+ manager.create(kPage);
+ const int slabsBefore = counters.live;
+ ASSERT_GT(slabsBefore, 0);
+
+ manager.recycle();
+ EXPECT_EQ(counters.live, slabsBefore); // slabs are kept for reuse, not freed
+ EXPECT_EQ(manager.getCurrentMemorySize(), 0u); // budget cleared
+
+ // The manager stays usable: a fresh create reuses existing slabs (no new parent allocation).
+ ASSERT_NO_THROW(manager.create(kPage));
+ EXPECT_EQ(counters.live, slabsBefore); // no new slab needed
+}
+
+TEST(VirtualMachineBufferManagerArenaTest, HandsOutZeroedBuffersAfterRecycle) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeCountingArena(counters));
+
+ const std::array<uint8_t, 8> pattern = {1, 2, 3, 4, 5, 6, 7, 8};
+ const auto first = manager.create(pattern.size());
+ manager.getBuffer(first).writeData(0, pattern.data(), pattern.size());
+
+ manager.recycle(); // rewinds the arena; the same memory will be handed out again
+
+ const auto reborn = manager.create(pattern.size());
+ const auto& buffer = manager.getBuffer(reborn);
+ for (size_t i = 0; i < pattern.size(); ++i) {
+ EXPECT_EQ(buffer.getData()[i], 0u); // BufferManager zeroed the reused bytes
+ }
+}
+
+TEST(VirtualMachineBufferManagerArenaTest, CreateZeroesMemoryReusedFromADeletedBuffer) {
+ // BufferManager -- not the allocator -- zero-initializes owned buffers in create(). Deleting the
+ // top-of-stack buffer lets the arena hand its (dirtied) slot straight back, so the next create() must
+ // clear the previous buffer's bytes even without a recycle().
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, makeCountingArena(counters));
+
+ const std::array<uint8_t, 8> pattern = {1, 2, 3, 4, 5, 6, 7, 8};
+ const auto first = manager.create(pattern.size());
+ auto& firstBuffer = manager.getBuffer(first);
+ firstBuffer.writeData(0, pattern.data(), pattern.size());
+ const auto* firstData = firstBuffer.getData();
+ manager.deleteBuffer(first); // LIFO pop: the arena will reuse this exact slot
+
+ const auto reborn = manager.create(pattern.size());
+ const auto& buffer = manager.getBuffer(reborn);
+ ASSERT_EQ(buffer.getData(), firstData); // same slot handed back
+ for (size_t i = 0; i < pattern.size(); ++i) {
+ EXPECT_EQ(buffer.getData()[i], 0u); // create() cleared the slot the deleted buffer dirtied
+ }
+}
+
+// ============================================================
+// BufferManager over a bare leaf allocator
+//
+// BufferManager must not depend on wrapping an arena: it frees its own Owned buffers in recycle(),
+// move assignment and destruction. These tests erase a bare CountingLeaf and assert every teardown path
+// balances allocate()/deallocate(), so leaf-owned memory is reclaimed and never double-freed.
+// ============================================================
+
+TEST(VirtualMachineBufferManagerLeafTest, RecycleDeallocatesOwnedBuffersWithLeafAllocator) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&counters}});
+
+ manager.create(/*size=*/64);
+ manager.create(/*size=*/128);
+ manager.create(/*size=*/256);
+ ASSERT_EQ(counters.live, 3);
+
+ manager.recycle();
+ EXPECT_EQ(counters.live, 0); // every owned block freed back to the leaf
+ EXPECT_EQ(manager.getCurrentMemorySize(), 0u);
+
+ // The manager stays usable across rounds and never leaks.
+ for (int round = 0; round < 5; ++round) {
+ manager.create(/*size=*/64);
+ manager.create(/*size=*/64);
+ manager.recycle();
+ EXPECT_EQ(counters.live, 0);
+ }
+}
+
+TEST(VirtualMachineBufferManagerLeafTest, RecycleDeallocatesOwnedBuffersWithLeafAllocator2) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&counters}});
+
+ manager.create(/*size=*/64);
+ manager.create(/*size=*/128);
+ ASSERT_EQ(counters.live, 2);
+
+ manager.recycle();
+ EXPECT_EQ(counters.live, 0);
+ EXPECT_EQ(manager.getCurrentMemorySize(), 0u);
+}
+
+TEST(VirtualMachineBufferManagerLeafTest, DestructorDeallocatesOwnedBuffersWithLeafAllocator) {
+ AllocCounters counters;
+ {
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&counters}});
+ manager.create(/*size=*/64);
+ manager.create(/*size=*/128);
+ ASSERT_EQ(counters.live, 2);
+ }
+ EXPECT_EQ(counters.live, 0); // destruction frees the leaf-owned blocks
+}
+
+TEST(VirtualMachineBufferManagerLeafTest, MoveAssignDeallocatesReplacedOwnedBuffersWithLeafAllocator) {
+ AllocCounters victimCounters;
+ AllocCounters freshCounters;
+
+ BufferManager victim(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&victimCounters}});
+ victim.create(/*size=*/64);
+ victim.create(/*size=*/128);
+ ASSERT_EQ(victimCounters.live, 2);
+
+ // Replacing the populated manager must free the blocks it still owns (mirrors ensureBufferManager's
+ // _bufferManager = BufferManager(...) on context change).
+ victim = BufferManager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&freshCounters}});
+ EXPECT_EQ(victimCounters.live, 0); // the replaced manager's owned blocks were freed
+
+ // The moved-in manager remains usable and leak-free.
+ victim.create(/*size=*/32);
+ EXPECT_EQ(freshCounters.live, 1);
+ victim.recycle();
+ EXPECT_EQ(freshCounters.live, 0);
+}
+
+TEST(VirtualMachineBufferManagerLeafTest, UnownedBuffersAreNotDeallocatedByRecycle) {
+ AllocCounters counters;
+ BufferManager manager(DEFAULT_BUFFER_MEMORY_LIMIT_BYTES, AnyAllocator{CountingLeaf{&counters}});
+
+ std::array<uint8_t, 16> external = {};
+ const auto owned = manager.create(/*size=*/64);
+ manager.createFromMemory(external.data(), external.size(), Permission::Read); // unowned: external memory
+ manager.createFromBuffer(owned, /*offset=*/0, /*size=*/32); // unowned: derived view
+ ASSERT_EQ(counters.live, 1); // only the single owned buffer hit the leaf
+
+ manager.recycle();
+ EXPECT_EQ(counters.live, 0); // exactly one deallocate matching the one allocate, no double free
+}
+
+// ============================================================
+// Stress Tests
+// ============================================================
+
+TEST(VirtualMachineBufferManagerStressTest, CreateAndDeleteManyBuffers) {
+ constexpr size_t count = 10'000;
+ constexpr size_t bufferSize = 1;
+ BufferManager manager(count * bufferSize, makeHostAllocator());
+
+ for (size_t i = 0; i < count; ++i) {
+ const auto handle = manager.create(bufferSize);
+ ASSERT_TRUE(manager.exists(handle));
+ manager.deleteBuffer(handle);
+ ASSERT_FALSE(manager.exists(handle));
+ }
+}
+
+TEST(VirtualMachineBufferManagerStressTest, CreateAndDeleteManyExternalBuffers) {
+ constexpr size_t iterations = 10'000;
+ BufferManager manager(0, makeHostAllocator()); // No owned memory limit needed
+ std::array<uint8_t, 1> dummy = {};
+
+ for (size_t i = 0; i < iterations; ++i) {
+ const auto handle = manager.createFromMemory(dummy.data(), dummy.size(), Permission::Read);
+ ASSERT_TRUE(manager.exists(handle));
+ manager.deleteBuffer(handle);
+ ASSERT_FALSE(manager.exists(handle));
+ }
+}
+
+TEST(VirtualMachineBufferManagerStressTest, CreateManyExternalBuffersThenDeleteAll) {
+ constexpr size_t count = 10'000;
+ BufferManager manager(0, makeHostAllocator());
+ std::array<uint8_t, 1> dummy = {};
+
+ std::vector<BufferHandle> handles;
+ handles.reserve(count);
+
+ for (size_t i = 0; i < count; ++i) {
+ handles.push_back(manager.createFromMemory(dummy.data(), dummy.size(), Permission::Read));
+ }
+ for (const auto& handle : handles) {
+ ASSERT_TRUE(manager.exists(handle));
+ manager.deleteBuffer(handle);
+ ASSERT_FALSE(manager.exists(handle));
+ }
+}
diff --git a/src/plugins/intel_npu/tests/unit/vm/bytecode_builder.hpp b/src/plugins/intel_npu/tests/unit/vm/bytecode_builder.hpp
new file mode 100644
index 00000000000..575eae8a409
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/bytecode_builder.hpp
@@ -0,0 +1,376 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "function.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "npu_bytecode_utils/version.hpp"
+
+#include <array>
+#include <cstdint>
+#include <cstring>
+#include <deque>
+#include <initializer_list>
+#include <memory>
+#include <optional>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+namespace utils {
+
+// Encodes bytecode instructions and manages bytecode file generation
+class BytecodeBuilder {
+private:
+ // Context for a function with its definition and name / type indices into the string and type sections
+ struct FunctionContext {
+ intel_npu::vm::Function definition;
+ uint64_t nameIndex{}; // Pre-interned index into the string section
+ uint64_t functionTypeIndex{}; // Pre-interned index into the type section
+ };
+
+ // Function list order defines function indices referenced by CALL instructions
+ std::deque<FunctionContext> _functions;
+
+ // Bytecode version serialized into the output binary
+ intel_npu::vm::Version _version{1, 0, 0};
+
+ // Incrementally built string section state
+ std::vector<uint8_t> _stringSectionPayload;
+ intel_npu::vm::details::DataSectionInfo _stringSectionInfo;
+
+ // Incrementally built type section state
+ std::vector<uint8_t> _typeSectionPayload;
+ intel_npu::vm::details::DataSectionInfo _typeSectionInfo;
+
+ // Interns a string into the string section, returning its index
+ uint64_t internString(std::string_view str) {
+ // String section entries are null-terminated
+ const auto makeNullTerminatedString = [](std::string_view str) -> std::vector<uint8_t> {
+ std::vector<uint8_t> result(str.begin(), str.end());
+ result.push_back('\0');
+ return result;
+ };
+
+ const auto index = static_cast<uint64_t>(_stringSectionInfo.dataInfos.size());
+ const auto bytes = makeNullTerminatedString(str);
+ intel_npu::vm::details::DataSectionInfo::DataInfo dataInfo{};
+ dataInfo.offset = _stringSectionPayload.size();
+ dataInfo.size = bytes.size();
+ _stringSectionPayload.insert(_stringSectionPayload.end(), bytes.begin(), bytes.end());
+ _stringSectionInfo.dataInfos.push_back(dataInfo);
+ _stringSectionInfo.numData = _stringSectionInfo.dataInfos.size();
+ return index;
+ }
+
+ // Interns a serialized type blob into the type section, returning its index
+ uint64_t internTypeBytes(const std::vector<uint8_t>& serialized) {
+ const auto index = static_cast<uint64_t>(_typeSectionInfo.dataInfos.size());
+ intel_npu::vm::details::DataSectionInfo::DataInfo dataInfo{};
+ dataInfo.offset = _typeSectionPayload.size();
+ dataInfo.size = serialized.size();
+ _typeSectionPayload.insert(_typeSectionPayload.end(), serialized.begin(), serialized.end());
+ _typeSectionInfo.dataInfos.push_back(dataInfo);
+ _typeSectionInfo.numData = _typeSectionInfo.dataInfos.size();
+ return index;
+ }
+
+ // Interns a primitive (integer, float, opaque, buffer) type, returning its type section index
+ uint64_t internNonFunctionType(const intel_npu::vm::Type& type) {
+ std::vector<uint8_t> entry;
+ switch (intel_npu::vm::getTypeCode(type)) {
+ case intel_npu::vm::TypeCode::INTEGER:
+ std::get<intel_npu::vm::IntegerType>(type.data).appendTo(entry);
+ break;
+ case intel_npu::vm::TypeCode::FLOAT:
+ std::get<intel_npu::vm::FloatType>(type.data).appendTo(entry);
+ break;
+ case intel_npu::vm::TypeCode::OPAQUE:
+ std::get<intel_npu::vm::OpaqueType>(type.data).appendTo(entry);
+ break;
+ case intel_npu::vm::TypeCode::BUFFER:
+ std::get<intel_npu::vm::BufferType>(type.data).appendTo(entry);
+ break;
+ default:
+ throw std::runtime_error("Unsupported primitive type code: " +
+ std::to_string(static_cast<uint64_t>(intel_npu::vm::getTypeCode(type))));
+ }
+ return internTypeBytes(entry);
+ }
+
+ // Interns a function type signature, returning its type section index
+ uint64_t internFunctionType(const intel_npu::vm::FunctionType& funcType) {
+ std::vector<uint8_t> entry;
+ funcType.appendTo(entry);
+ return internTypeBytes(entry);
+ }
+
+public:
+ // Builds and encodes a single function's instruction body
+ class FunctionBuilder {
+ private:
+ std::string _name;
+ int64_t _numGeneralRegisters;
+ std::vector<intel_npu::vm::Type> _paramTypes;
+ std::vector<intel_npu::vm::Type> _resultTypes;
+ bool _isEntrypoint;
+ std::vector<uint8_t> _body;
+
+ friend BytecodeBuilder;
+
+ // Appends a value to the function body
+ template <typename T>
+ void append(T value) {
+ std::array<uint8_t, sizeof(T)> buf{};
+ std::memcpy(buf.data(), &value, sizeof(T));
+ _body.insert(_body.end(), buf.begin(), buf.end());
+ }
+
+ std::string getName() const {
+ return _name;
+ }
+
+ int64_t getNumGeneralRegisters() const {
+ return _numGeneralRegisters;
+ }
+
+ const std::vector<intel_npu::vm::Type>& getParamTypes() const {
+ return _paramTypes;
+ }
+
+ const std::vector<intel_npu::vm::Type>& getResultTypes() const {
+ return _resultTypes;
+ }
+
+ bool isEntrypoint() const {
+ return _isEntrypoint;
+ }
+
+ const std::vector<uint8_t>& getBody() const {
+ return _body;
+ }
+
+ public:
+ FunctionBuilder(std::string name, int64_t numGeneralRegisters, std::vector<intel_npu::vm::Type> paramTypes = {},
+ std::vector<intel_npu::vm::Type> resultTypes = {}, bool isEntrypoint = false)
+ : _name(std::move(name)),
+ _numGeneralRegisters(numGeneralRegisters),
+ _paramTypes(std::move(paramTypes)),
+ _resultTypes(std::move(resultTypes)),
+ _isEntrypoint(isEntrypoint) {
+ }
+
+ // Appends an instruction with the given opcode and 16-bit operands
+ FunctionBuilder& instruction(intel_npu::vm::OpCode op, const std::vector<int16_t>& operands) {
+ append(static_cast<uint16_t>(op));
+ for (auto operand : operands) {
+ append(operand);
+ }
+ return *this;
+ }
+
+ // Encode SET_IMM: reg[dst] = imm (64-bit immediate)
+ FunctionBuilder& setImm(int16_t dst, int64_t imm) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::SET_IMM));
+ append(dst);
+ append(imm);
+ return *this;
+ }
+
+ // Encode RETV: return values held in the listed registers
+ FunctionBuilder& retv(std::initializer_list<int16_t> resultRegs) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::RETV));
+ append(static_cast<int16_t>(resultRegs.size()));
+ for (auto reg : resultRegs) {
+ append(reg);
+ }
+ return *this;
+ }
+
+ // Encode JMP: unconditional jump by the given int64 PC-relative byte offset
+ FunctionBuilder& jmp(int64_t offset) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::JMP));
+ append(offset);
+ return *this;
+ }
+
+ // Encode JE: jump by the given int64 PC-relative byte offset if lhsReg == rhsReg
+ FunctionBuilder& je(int64_t offset, int16_t lhsReg, int16_t rhsReg) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::JE));
+ append(offset);
+ append(lhsReg);
+ append(rhsReg);
+ return *this;
+ }
+
+ // Encode JNE: jump by the given int64 PC-relative byte offset if lhsReg != rhsReg
+ FunctionBuilder& jne(int64_t offset, int16_t lhsReg, int16_t rhsReg) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::JNE));
+ append(offset);
+ append(lhsReg);
+ append(rhsReg);
+ return *this;
+ }
+
+ // Encode RET: return with no values
+ FunctionBuilder& ret() {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::RET));
+ return *this;
+ }
+
+ // Encode CALL: call rs, N, rN..., M, rM...
+ FunctionBuilder& call(int16_t functionIndexReg, std::initializer_list<int16_t> dstRegs,
+ std::initializer_list<int16_t> argRegs) {
+ append(static_cast<uint16_t>(intel_npu::vm::OpCode::CALL));
+ append(functionIndexReg);
+ append(static_cast<int16_t>(dstRegs.size()));
+ for (auto reg : dstRegs) {
+ append(reg);
+ }
+ append(static_cast<int16_t>(argRegs.size()));
+ for (auto reg : argRegs) {
+ append(reg);
+ }
+ return *this;
+ }
+ };
+
+ // Adds a function to the module using the provided FunctionBuilder, which encodes the function body and metadata
+ BytecodeBuilder& addFunction(const FunctionBuilder& functionBuilder) {
+ const auto nameIdx = internString(functionBuilder.getName());
+
+ intel_npu::vm::FunctionType functionType;
+ functionType.paramTypeIndices.reserve(functionBuilder.getParamTypes().size());
+ functionType.resultTypeIndices.reserve(functionBuilder.getResultTypes().size());
+
+ std::vector<intel_npu::vm::FuncParamResType> fnParamTypes;
+ fnParamTypes.reserve(functionBuilder.getParamTypes().size());
+ for (const auto& paramType : functionBuilder.getParamTypes()) {
+ const auto typeIdx = internNonFunctionType(paramType);
+ functionType.paramTypeIndices.push_back(typeIdx);
+ fnParamTypes.push_back({paramType, static_cast<int64_t>(typeIdx)});
+ }
+
+ std::vector<intel_npu::vm::FuncParamResType> fnResultTypes;
+ fnResultTypes.reserve(functionBuilder.getResultTypes().size());
+ for (const auto& resultType : functionBuilder.getResultTypes()) {
+ const auto typeIdx = internNonFunctionType(resultType);
+ functionType.resultTypeIndices.push_back(typeIdx);
+ fnResultTypes.push_back({resultType, static_cast<int64_t>(typeIdx)});
+ }
+
+ const auto funcTypeIdx = internFunctionType(functionType);
+
+ auto body = intel_npu::vm::Span<uint8_t>(const_cast<uint8_t*>(functionBuilder.getBody().data()),
+ functionBuilder.getBody().size());
+ _functions.push_back(FunctionContext{
+ intel_npu::vm::Function(functionBuilder.getName(), functionBuilder.getNumGeneralRegisters(),
+ functionBuilder.isEntrypoint(), std::move(fnParamTypes),
+ std::move(fnResultTypes), body, /*copyBody=*/true),
+ nameIdx, funcTypeIdx});
+ return *this;
+ }
+
+ std::optional<uint64_t> getFunctionIndex(std::string_view name) const {
+ for (size_t i = 0; i < _functions.size(); ++i) {
+ if (_functions[i].definition.getName() == name) {
+ return i;
+ }
+ }
+ return std::nullopt;
+ }
+
+ // Sets the bytecode version serialized into the output binary
+ BytecodeBuilder& setVersion(intel_npu::vm::Version version) {
+ _version = version;
+ return *this;
+ }
+
+ // Builds the complete bytecode module with all added functions.
+ // String and type sections are already populated incrementally; only the function section is assembled here.
+ std::vector<uint8_t> build() const {
+ if (_functions.empty()) {
+ return {};
+ }
+
+ // Assemble the function section payload from each function's pre-built body
+ std::vector<uint8_t> funcSectionPayload;
+ intel_npu::vm::details::FunctionSectionInfo funcInfo;
+ funcInfo.numFunctions = _functions.size();
+ funcInfo.entrypointFunctionIndex = 0;
+
+ // First entrypoint-marked function becomes module entrypoint
+ for (size_t idx = 0; idx < _functions.size(); ++idx) {
+ if (_functions[idx].definition.isEntrypoint()) {
+ funcInfo.entrypointFunctionIndex = idx;
+ break;
+ }
+ }
+
+ for (const auto& ctx : _functions) {
+ const auto& body = ctx.definition.getBody();
+
+ intel_npu::vm::details::FunctionSectionInfo::FunctionInfo functionInfo{};
+ functionInfo.nameIndex = ctx.nameIndex;
+ functionInfo.functionTypeIndex = ctx.functionTypeIndex;
+ functionInfo.numGeneralRegisters = ctx.definition.getNumGeneralRegisters();
+ functionInfo.bodyOffset = funcSectionPayload.size();
+ functionInfo.bodySize = body.size();
+
+ funcSectionPayload.insert(funcSectionPayload.end(), body.begin(), body.end());
+ funcInfo.functionInfos.push_back(functionInfo);
+ }
+
+ // Build section header table for function, string, and type sections
+ intel_npu::vm::SectionHeaderTable sectionHeaderTable;
+
+ intel_npu::vm::SectionHeader funcHeader{};
+ funcHeader.type = intel_npu::vm::SectionType::FuncSection;
+ funcHeader.nameIndex = 0;
+ funcHeader.offset = 0; // Computed later by `computeOffsets` call
+ funcHeader.size = funcSectionPayload.size();
+ funcHeader.info = std::make_unique<intel_npu::vm::details::FunctionSectionInfo>(std::move(funcInfo));
+ sectionHeaderTable.addSectionHeader(std::move(funcHeader));
+
+ intel_npu::vm::SectionHeader stringHeader{};
+ stringHeader.type = intel_npu::vm::SectionType::StringSection;
+ stringHeader.nameIndex = 0;
+ stringHeader.offset = 0; // Computed later by `computeOffsets` call
+ stringHeader.size = _stringSectionPayload.size();
+ stringHeader.info = std::make_unique<intel_npu::vm::details::DataSectionInfo>(_stringSectionInfo);
+ sectionHeaderTable.addSectionHeader(std::move(stringHeader));
+
+ intel_npu::vm::SectionHeader typeHeader{};
+ typeHeader.type = intel_npu::vm::SectionType::TypeSection;
+ typeHeader.nameIndex = 0;
+ typeHeader.offset = 0; // Computed later by `computeOffsets` call
+ typeHeader.size = _typeSectionPayload.size();
+ typeHeader.info = std::make_unique<intel_npu::vm::details::DataSectionInfo>(_typeSectionInfo);
+ sectionHeaderTable.addSectionHeader(std::move(typeHeader));
+
+ // Compute payload offsets using canonical section ordering
+ sectionHeaderTable.computeOffsets();
+
+ std::vector<uint8_t> bytecodeBuffer;
+ // File layout: magic number, version, section header table, then section payloads
+ intel_npu::vm::MagicNumber(intel_npu::vm::MAGIC_NUMBER).appendTo(bytecodeBuffer);
+ _version.appendTo(bytecodeBuffer);
+ sectionHeaderTable.appendTo(bytecodeBuffer);
+
+ bytecodeBuffer.insert(bytecodeBuffer.end(), funcSectionPayload.begin(), funcSectionPayload.end());
+ bytecodeBuffer.insert(bytecodeBuffer.end(), _stringSectionPayload.begin(), _stringSectionPayload.end());
+ bytecodeBuffer.insert(bytecodeBuffer.end(), _typeSectionPayload.begin(), _typeSectionPayload.end());
+
+ return bytecodeBuffer;
+ }
+};
+
+} // namespace utils
diff --git a/src/plugins/intel_npu/tests/unit/vm/composable_allocators.cpp b/src/plugins/intel_npu/tests/unit/vm/composable_allocators.cpp
new file mode 100644
index 00000000000..eb91eeeb37f
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/composable_allocators.cpp
@@ -0,0 +1,357 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "composable_allocators.hpp"
+
+#include "counting_leaf.hpp"
+#include "host_allocator.hpp"
+
+#include <intel_npu/utils/utils.hpp>
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <vector>
+
+using namespace intel_npu::vm;
+using intel_npu::vm::test::AllocCounters;
+using intel_npu::vm::test::CountingLeaf;
+
+namespace {
+
+constexpr size_t kPage = intel_npu::utils::STANDARD_PAGE_SIZE;
+
+// Owns a heap chunk for a BumpRegion under test; the region borrows the chunk and never frees it (the
+// GrowingArena owns chunk lifetime in production).
+class OwnedChunk {
+ std::vector<uint8_t> _storage;
+
+public:
+ explicit OwnedChunk(size_t bytes): _storage(bytes) {
+ }
+ Block block() noexcept {
+ return Block{_storage.data(), _storage.size()};
+ }
+};
+
+} // namespace
+
+// ============================================================
+// BumpRegion
+// ============================================================
+
+TEST(BumpRegionTest, HandsOutAlignedOffsets) {
+ OwnedChunk chunk(8 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block first = region.allocate(100);
+ const Block second = region.allocate(100);
+ ASSERT_TRUE(first);
+ ASSERT_TRUE(second);
+ EXPECT_EQ(first.size, 100u); // Block.size mirrors the request; alignment padding is private
+ // Sub-blocks are spaced by the alignment, so each is aligned relative to the chunk base.
+ EXPECT_EQ(static_cast<size_t>(second.ptr - first.ptr), kPage);
+}
+
+TEST(BumpRegionTest, RejectsRequestsThatDoNotFit) {
+ OwnedChunk chunk(2 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ EXPECT_FALSE(region.allocate(3 * kPage)); // larger than the whole chunk (a region cannot grow it)
+ EXPECT_TRUE(region.allocate(kPage));
+ EXPECT_TRUE(region.allocate(kPage));
+ EXPECT_FALSE(region.allocate(1)); // chunk now exhausted
+}
+
+TEST(BumpRegionTest, DeallocateRewindsMostRecentBlock) {
+ OwnedChunk chunk(4 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(64);
+ const Block b = region.allocate(64);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+
+ region.deallocate(b); // b is on top of the stack, so its slot is reclaimed (LIFO bump-back)
+ const Block reborn = region.allocate(64);
+ EXPECT_EQ(reborn.ptr, b.ptr); // the just-freed slot is handed out again
+}
+
+TEST(BumpRegionTest, DeallocateOfAnOlderBlockIsIgnored) {
+ OwnedChunk chunk(4 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(64);
+ const Block b = region.allocate(64);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+
+ region.deallocate(a); // a is NOT on top (b is): a bump region cannot punch a hole, so this no-ops
+ const Block c = region.allocate(64);
+ EXPECT_NE(c.ptr, a.ptr); // a's slot is not reused
+ EXPECT_EQ(c.ptr, b.ptr + kPage); // c is handed out past b, not into a's hole
+}
+
+TEST(BumpRegionTest, DeallocateIsMultiLevelLifo) {
+ OwnedChunk chunk(4 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(64);
+ const Block b = region.allocate(64);
+ const Block c = region.allocate(64);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ ASSERT_TRUE(c);
+
+ region.deallocate(c); // popping c restores the cursor so b becomes the new top...
+ region.deallocate(b); // ...and can be popped too
+ const Block reborn = region.allocate(64);
+ EXPECT_EQ(reborn.ptr, b.ptr); // b's slot (the new top) is reused
+}
+
+TEST(BumpRegionTest, OwnsReportsChunkMembership) {
+ OwnedChunk chunk(4 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(64);
+ ASSERT_TRUE(a);
+ EXPECT_TRUE(region.owns(a)); // handed out of this chunk
+
+ OwnedChunk other(kPage);
+ EXPECT_FALSE(region.owns(other.block())); // a block from a different chunk
+ EXPECT_FALSE(region.owns(Block{})); // the null block
+}
+
+TEST(BumpRegionTest, RecycleRewindsAndReusesSameMemory) {
+ OwnedChunk chunk(4 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(64);
+ region.allocate(64);
+ ASSERT_TRUE(a);
+
+ region.recycle();
+
+ const Block reborn = region.allocate(64);
+ EXPECT_EQ(reborn.ptr, a.ptr); // same chunk, cursor rewound
+}
+
+TEST(BumpRegionTest, AlignmentControlsSpacing) {
+ // A smaller alignment packs sub-blocks tighter.
+ OwnedChunk chunk(kPage);
+ BumpRegion<64> region(chunk.block());
+
+ const Block a = region.allocate(100);
+ const Block b = region.allocate(100);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ EXPECT_EQ(static_cast<size_t>(b.ptr - a.ptr), 128u); // 100 rounded up to a multiple of 64
+}
+
+TEST(BumpRegionTest, RefusesWhenAlignedFootprintExceedsChunkEvenIfRawSizeFits) {
+ // The raw 100 bytes fit the 100-byte chunk, but the aligned footprint (alignUp(100, 64) == 128) does
+ // not, so the region refuses rather than clamping the cursor to the chunk end.
+ OwnedChunk chunk(100);
+ BumpRegion<64> region(chunk.block());
+
+ EXPECT_FALSE(region.allocate(100));
+ EXPECT_TRUE(region.allocate(64)); // a request whose aligned footprint fits still succeeds
+}
+
+TEST(BumpRegionTest, DeallocateReclaimsBlockThatFillsChunkToTheEnd) {
+ // A block whose footprint reaches exactly the chunk end is still the top of stack, so deallocate() pops
+ // it cleanly -- the last-in-chunk case a clamping cursor would miss.
+ OwnedChunk chunk(2 * kPage);
+ BumpRegion<kPage> region(chunk.block());
+
+ const Block a = region.allocate(kPage);
+ const Block b = region.allocate(kPage); // fills the chunk to the end
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ EXPECT_FALSE(region.allocate(1)); // chunk is full
+
+ region.deallocate(b);
+ const Block reborn = region.allocate(kPage);
+ EXPECT_EQ(reborn.ptr, b.ptr); // b's slot reclaimed and handed out again
+}
+
+// ============================================================
+// GrowingArena
+// ============================================================
+
+TEST(GrowingArenaTest, GrowsAcrossSlabsToFitWorkingSet) {
+ // Initial slab holds one page; a second allocation forces a new slab.
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/4 * kPage>
+ arena(HostAllocator{});
+
+ const Block a = arena.allocate(kPage);
+ const Block b = arena.allocate(kPage);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ EXPECT_NE(b.ptr, a.ptr + kPage); // distinct slabs, not contiguous
+}
+
+TEST(GrowingArenaTest, FirstFitReusesAnEarlierSlabTail) {
+ // A 3-page request leaves 1 page in slab 0; a 2-page request grows slab 1; a later 1-page request
+ // must first-fit back into slab 0's tail rather than strand it.
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/4 * kPage,
+ /*maxSlabBytes=*/8 * kPage>
+ arena(HostAllocator{});
+
+ const Block big = arena.allocate(3 * kPage);
+ ASSERT_TRUE(big);
+ const Block grown = arena.allocate(2 * kPage);
+ ASSERT_TRUE(grown);
+ const Block small = arena.allocate(kPage);
+ ASSERT_TRUE(small);
+
+ EXPECT_EQ(small.ptr, big.ptr + 3 * kPage); // packed right after `big` in slab 0
+}
+
+TEST(GrowingArenaTest, OversizeRequestGetsASlabLargeEnough) {
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/2 * kPage>
+ arena(HostAllocator{});
+
+ const Block big = arena.allocate(5 * kPage); // larger than initial and max slab size
+ ASSERT_TRUE(big);
+ EXPECT_EQ(big.size, 5u * kPage);
+}
+
+TEST(GrowingArenaTest, OversizeRequestWithUnalignedSizeStillSucceeds) {
+ // An oversize request whose size is not alignment-aligned must still get a chunk big enough for its
+ // aligned footprint: the arena rounds the chunk size up so the strict-fit sub-allocator accepts it.
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/2 * kPage>
+ arena(HostAllocator{});
+
+ const Block big = arena.allocate(5 * kPage + 1); // oversize and not page-aligned
+ ASSERT_TRUE(big);
+ EXPECT_EQ(big.size, 5u * kPage + 1);
+}
+
+TEST(GrowingArenaTest, RecycleRewindsAllSlabsAndKeepsThem) {
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/4 * kPage>
+ arena(HostAllocator{});
+
+ const Block a = arena.allocate(kPage);
+ const Block b = arena.allocate(kPage);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+
+ arena.recycle(); // grow & keep: rewind cursors, retain slabs
+
+ const Block a2 = arena.allocate(kPage);
+ const Block b2 = arena.allocate(kPage);
+ EXPECT_EQ(a2.ptr, a.ptr);
+ EXPECT_EQ(b2.ptr, b.ptr);
+}
+
+TEST(GrowingArenaTest, AdaptsToPeakThenStopsAllocatingFromParent) {
+ // Once the working set is reached, replaying it allocates nothing new from the parent.
+ AllocCounters counters;
+ GrowingArena<CountingLeaf, BumpRegion<CountingLeaf::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/4 * kPage>
+ arena(CountingLeaf{&counters});
+
+ auto runWorkingSet = [&]() {
+ ASSERT_TRUE(arena.allocate(kPage));
+ ASSERT_TRUE(arena.allocate(kPage));
+ ASSERT_TRUE(arena.allocate(kPage));
+ };
+
+ runWorkingSet(); // infer 1: grows slabs from the parent
+ const int slabsAfterFirst = counters.allocCalls;
+ EXPECT_GT(slabsAfterFirst, 0);
+
+ for (int infer = 0; infer < 5; ++infer) {
+ arena.recycle();
+ runWorkingSet();
+ }
+ // No new parent allocations after the first working set.
+ EXPECT_EQ(counters.allocCalls, slabsAfterFirst);
+ EXPECT_EQ(counters.live, slabsAfterFirst); // all slabs retained
+}
+
+TEST(GrowingArenaTest, ReleaseFreesAllSlabsThenReallocatesFromParent) {
+ AllocCounters counters;
+ GrowingArena<CountingLeaf, BumpRegion<CountingLeaf::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/4 * kPage>
+ arena(CountingLeaf{&counters});
+
+ ASSERT_TRUE(arena.allocate(kPage));
+ ASSERT_TRUE(arena.allocate(kPage)); // forces a second slab
+ const int slabsBefore = counters.live;
+ EXPECT_GT(slabsBefore, 0);
+
+ arena.release();
+ EXPECT_EQ(counters.live, 0); // every slab freed back to the parent
+
+ // After release the arena re-mints from the parent again (growth rewound to the initial size).
+ ASSERT_TRUE(arena.allocate(kPage));
+ EXPECT_GT(counters.live, 0);
+ EXPECT_GT(counters.allocCalls, slabsBefore);
+}
+
+TEST(GrowingArenaTest, HandsOutBlocksAlignedToBackingAlignment) {
+ // Absolute alignment, not just relative spacing: the handed-out address is aligned only because the
+ // backing aligns the chunk base. Odd request sizes would expose a regression in either layer.
+ constexpr size_t kAlign = HostAllocator::ALIGNMENT;
+ GrowingArena<HostAllocator, BumpRegion<kAlign>, /*initialSlabBytes=*/kPage, /*maxSlabBytes=*/4 * kPage> arena(
+ HostAllocator{});
+
+ for (const size_t bytes : {size_t{1}, size_t{7}, size_t{100}, size_t{kPage + 3}}) {
+ const Block block = arena.allocate(bytes);
+ ASSERT_TRUE(block);
+ EXPECT_EQ(reinterpret_cast<uintptr_t>(block.ptr) % kAlign, 0u); // aligned base, not merely spaced
+ }
+}
+
+TEST(GrowingArenaTest, OwnsReportsMembershipAcrossSlabs) {
+ // Single-page slabs force two of them, so owns() must span every slab rather than just the latest.
+ GrowingArena<HostAllocator, BumpRegion<HostAllocator::ALIGNMENT>, /*initialSlabBytes=*/kPage,
+ /*maxSlabBytes=*/kPage>
+ arena(HostAllocator{});
+
+ const Block a = arena.allocate(kPage); // slab 0
+ const Block b = arena.allocate(kPage); // forces slab 1
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ EXPECT_TRUE(arena.owns(a)); // carved from slab 0
+ EXPECT_TRUE(arena.owns(b)); // carved from slab 1
+
+ OwnedChunk foreign(kPage);
+ EXPECT_FALSE(arena.owns(foreign.block())); // memory the arena never handed out
+ EXPECT_FALSE(arena.owns(Block{})); // the null block
+
+ arena.release();
+ EXPECT_FALSE(arena.owns(a)); // no slabs remain to own anything
+}
+
+// ============================================================
+// AnyAllocator (type erasure)
+// ============================================================
+
+TEST(AnyAllocatorTest, OwnsDelegatesToTheErasedAllocator) {
+ AllocCounters counters;
+ AnyAllocator allocator{CountingLeaf{&counters}};
+
+ const Block block = allocator.allocate(kPage);
+ ASSERT_TRUE(block);
+ EXPECT_TRUE(allocator.owns(block)); // a leaf claims any non-null block it could free
+ EXPECT_FALSE(allocator.owns(Block{})); // ...but never the null block
+
+ allocator.deallocate(block);
+}
+
+TEST(AnyAllocatorTest, EmptyHandleOwnsNothing) {
+ uint8_t byte = 0;
+ AnyAllocator allocator; // default-constructed: no erased allocator behind it
+ ASSERT_FALSE(allocator);
+ EXPECT_FALSE(allocator.owns(Block{&byte, 1})); // an empty handle owns nothing, even a non-null block
+}
diff --git a/src/plugins/intel_npu/tests/unit/vm/counting_leaf.hpp b/src/plugins/intel_npu/tests/unit/vm/counting_leaf.hpp
new file mode 100644
index 00000000000..e9feb778062
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/counting_leaf.hpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "allocator_core.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <new>
+
+namespace intel_npu::vm::test {
+
+// Test-owned counters; CountingLeaf holds a pointer to them so they survive the leaf being moved
+// into a composition or erased into a BufferManager.
+struct AllocCounters {
+ int live = 0; // outstanding successful allocations (successes minus frees)
+ int allocCalls = 0; // total allocate() invocations, whether they succeed or fail
+};
+
+// Host new[]/delete[] allocator leaf that records live allocations and allocate() calls.
+class CountingLeaf {
+ AllocCounters* _counters;
+
+public:
+ // Chunk-base alignment this backing guarantees: new[] returns max_align_t-aligned storage.
+ static constexpr size_t ALIGNMENT = alignof(std::max_align_t);
+
+ explicit CountingLeaf(AllocCounters* counters): _counters(counters) {
+ }
+ Block allocate(size_t bytes) {
+ ++_counters->allocCalls; // every call, success or failure
+ // Mirror HostAllocator/BumpRegion: a zero-byte request is not a successful allocation. new uint8_t[0]
+ // may return a unique non-null pointer, which would bump `live` and yield a truthy Block, diverging
+ // from the production leaf. Reject it up front so the test leaf encodes the same zero-allocation behavior.
+ if (bytes == 0) {
+ return Block{};
+ }
+ auto* ptr = new (std::nothrow) uint8_t[bytes];
+ if (ptr == nullptr) {
+ return Block{};
+ }
+ ++_counters->live;
+ return Block{ptr, bytes};
+ }
+ void deallocate(Block block) noexcept {
+ if (block.ptr != nullptr) {
+ --_counters->live;
+ delete[] block.ptr;
+ }
+ }
+ // A heap leaf tracks no bounds; it claims any non-null block, mirroring delete[] in deallocate().
+ bool owns(Block block) const noexcept {
+ return block.ptr != nullptr;
+ }
+ void recycle() noexcept {
+ }
+ void release() noexcept {
+ }
+};
+
+} // namespace intel_npu::vm::test
diff --git a/src/plugins/intel_npu/tests/unit/vm/except.cpp b/src/plugins/intel_npu/tests/unit/vm/except.cpp
new file mode 100644
index 00000000000..8cf5bfe4b0f
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/except.cpp
@@ -0,0 +1,73 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/except.hpp"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <stdexcept>
+#include <string>
+
+namespace {
+
+TEST(VirtualMachineExceptTest, ThrowAlwaysThrowsRuntimeError) {
+ EXPECT_THROW(NPU_VM_THROW("error happened"), std::runtime_error);
+}
+
+TEST(VirtualMachineExceptTest, ThrowFormatsMessageWithPlaceholders) {
+ try {
+ NPU_VM_THROW("parse failed at {}:{}", "file.vm", 42);
+ FAIL() << "Expected std::runtime_error";
+ } catch (const std::runtime_error& ex) {
+ EXPECT_THAT(ex.what(), testing::HasSubstr("parse failed at file.vm:42"));
+ }
+}
+
+TEST(VirtualMachineExceptTest, ThrowAppendsExtraArgumentsWithoutPlaceholders) {
+ try {
+ NPU_VM_THROW("bad input", 7, "token");
+ FAIL() << "Expected std::runtime_error";
+ } catch (const std::runtime_error& ex) {
+ EXPECT_THAT(ex.what(), testing::HasSubstr("bad input 7 token"));
+ }
+}
+
+TEST(VirtualMachineExceptTest, ThrowKeepsUnmatchedPlaceholders) {
+ try {
+ NPU_VM_THROW("missing {} {}", "arg");
+ FAIL() << "Expected std::runtime_error";
+ } catch (const std::runtime_error& ex) {
+ EXPECT_THAT(ex.what(), testing::HasSubstr("missing arg {}"));
+ }
+}
+
+TEST(VirtualMachineExceptTest, ThrowConvertsNullCStringToEmptyText) {
+ const char* text = nullptr;
+
+ try {
+ NPU_VM_THROW("null='{}'", text);
+ FAIL() << "Expected std::runtime_error";
+ } catch (const std::runtime_error& ex) {
+ EXPECT_THAT(ex.what(), testing::HasSubstr("null=''"));
+ }
+}
+
+TEST(VirtualMachineExceptTest, ThrowWhenThrowsWhenConditionIsTrue) {
+ EXPECT_THROW(NPU_VM_THROW_WHEN(true, "condition met: {}", 3), std::runtime_error);
+}
+
+TEST(VirtualMachineExceptTest, ThrowWhenDoesNotThrowWhenConditionIsFalse) {
+ EXPECT_NO_THROW(NPU_VM_THROW_WHEN(false, "should not throw"));
+}
+
+TEST(VirtualMachineExceptTest, ThrowUnlessThrowsWhenConditionIsFalse) {
+ EXPECT_THROW(NPU_VM_THROW_UNLESS(false, "condition failed: {}", "x"), std::runtime_error);
+}
+
+TEST(VirtualMachineExceptTest, ThrowUnlessDoesNotThrowWhenConditionIsTrue) {
+ EXPECT_NO_THROW(NPU_VM_THROW_UNLESS(true, "should not throw"));
+}
+
+} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/vm/instruction_sizes.cpp b/src/plugins/intel_npu/tests/unit/vm/instruction_sizes.cpp
new file mode 100644
index 00000000000..c7033fc1814
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instruction_sizes.cpp
@@ -0,0 +1,149 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/instructions.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <cstring>
+#include <vector>
+
+using namespace intel_npu::vm;
+namespace {
+
+std::vector<uint8_t> encodeInstruction(OpCode opcode, const std::vector<int16_t>& operands) {
+ std::vector<uint8_t> bytes(OPCODE_SIZE + operands.size() * OPERAND_SIZE);
+ const auto opcodeValue = static_cast<uint16_t>(opcode);
+ std::memcpy(bytes.data(), &opcodeValue, sizeof(opcodeValue));
+ std::memcpy(bytes.data() + OPCODE_SIZE, operands.data(), operands.size() * OPERAND_SIZE);
+ return bytes;
+}
+
+} // namespace
+
+TEST(VirtualMachineInstructionSizesTest, BufferCreateVariadicSize) {
+ // operands: rd, elemType, rank=2, shape0, shape1, stride0, stride1
+ const auto rank = static_cast<int16_t>(2);
+ const auto bytes = encodeInstruction(OpCode::BUFFER_CREATE, {/*dst=*/1, /*elem_type=*/2, rank, 10, 20, 30, 40});
+ EXPECT_EQ(getInstructionSize(OpCode::BUFFER_CREATE, bytes.data(), bytes.size()),
+ OPCODE_SIZE + (3 + 2 * rank) * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, BufferSubviewVariadicSize) {
+ // operands: rd, src, rank=2, offsets[2], sizes[2], strides[2]
+ const auto rank = static_cast<int16_t>(2);
+ const auto bytes = encodeInstruction(OpCode::BUFFER_SUBVIEW, {1, 2, rank, 10, 20, 30, 40, 50, 60});
+ EXPECT_EQ(getInstructionSize(OpCode::BUFFER_SUBVIEW, bytes.data(), bytes.size()),
+ OPCODE_SIZE + (3 + 3 * rank) * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, BufferViewVariadicSize) {
+ // operands: dst, src, byte_offset, elem_type, rank=2, shape[2], strides[2]
+ const auto rank = static_cast<int16_t>(2);
+ const auto bytes = encodeInstruction(
+ OpCode::BUFFER_VIEW, {/*dst=*/1, /*src=*/2, /*byte_offset=*/0, /*elem_type=*/3, rank, 10, 20, 30, 40});
+ EXPECT_EQ(getInstructionSize(OpCode::BUFFER_VIEW, bytes.data(), bytes.size()),
+ OPCODE_SIZE + (5 + 2 * rank) * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, BufferLoadVariadicSize) {
+ // operands: dst, src, rank=2, index0, index1
+ const auto rank = static_cast<int16_t>(2);
+ const auto bytes = encodeInstruction(OpCode::BUFFER_LOAD, {/*dst=*/1, /*src=*/2, rank, 10, 20});
+ EXPECT_EQ(getInstructionSize(OpCode::BUFFER_LOAD, bytes.data(), bytes.size()),
+ OPCODE_SIZE + (3 + rank) * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, GetInstructionSizeFallsBackToStaticInstructions) {
+ const auto bufferGetDimBytes = encodeInstruction(OpCode::BUFFER_GET_DIM, {1, 2, 3});
+ EXPECT_EQ(getStaticInstructionSize(OpCode::ADD_I64), OPCODE_SIZE + 3 * OPERAND_SIZE);
+ EXPECT_EQ(getInstructionSize(OpCode::BUFFER_GET_DIM, bufferGetDimBytes.data(), bufferGetDimBytes.size()),
+ OPCODE_SIZE + 3 * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, VariadicInstructionSizeRejectsMalformedOps) {
+ const auto negativeBufferRankBytes =
+ encodeInstruction(OpCode::BUFFER_CREATE, {/*dst=*/1, /*elem_type=*/2, /*rank=*/-1});
+ EXPECT_FALSE(
+ getInstructionSize(OpCode::BUFFER_CREATE, negativeBufferRankBytes.data(), negativeBufferRankBytes.size())
+ .has_value());
+
+ const auto negativeRankBytes = encodeInstruction(OpCode::BUFFER_SUBVIEW, {/*dst=*/1, /*src=*/2, /*rank=*/-1});
+ EXPECT_FALSE(
+ getInstructionSize(OpCode::BUFFER_SUBVIEW, negativeRankBytes.data(), negativeRankBytes.size()).has_value());
+
+ const auto negativeViewRankBytes = encodeInstruction(
+ OpCode::BUFFER_VIEW, {/*dst=*/1, /*src=*/2, /*byte_offset=*/0, /*elem_type=*/3, /*rank=*/-1});
+ EXPECT_FALSE(getInstructionSize(OpCode::BUFFER_VIEW, negativeViewRankBytes.data(), negativeViewRankBytes.size())
+ .has_value());
+
+ const auto unknownOpcode = static_cast<OpCode>(0xFFFF);
+ EXPECT_FALSE(getInstructionSize(unknownOpcode, negativeRankBytes.data(), negativeRankBytes.size()).has_value());
+}
+
+TEST(VirtualMachineInstructionSizesTest, RetvVariadicSize) {
+ const auto resultCount = static_cast<int16_t>(2);
+ const auto bytes = encodeInstruction(OpCode::RETV, {resultCount, 4, 5});
+ EXPECT_EQ(getInstructionSize(OpCode::RETV, bytes.data(), bytes.size()),
+ OPCODE_SIZE + (1 + resultCount) * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, CmdListAddKernelVariadicSize) {
+ // operands: cmd_list, kernel, N=1, signal0, M=2, wait0, wait1
+ const auto bytes = encodeInstruction(OpCode::CMD_LIST_ADD_KERNEL, {1, 2, 1, 10, 2, 11, 12});
+ EXPECT_EQ(getInstructionSize(OpCode::CMD_LIST_ADD_KERNEL, bytes.data(), bytes.size()),
+ OPCODE_SIZE + 7 * OPERAND_SIZE);
+}
+
+TEST(VirtualMachineInstructionSizesTest, CallVariadicSize) {
+ const auto bytes = encodeInstruction(OpCode::CALL, {/*rs=*/1, /*N=*/2, /*dst0=*/4, /*dst1=*/5, /*M=*/3,
+ /*arg0=*/6, /*arg1=*/7, /*arg2=*/8});
+ EXPECT_EQ(getInstructionSize(OpCode::CALL, bytes.data(), bytes.size()), OPCODE_SIZE + 8 * OPERAND_SIZE);
+}
+
+TEST(InstructionSizesTest, KernelCreateVariadicSize) {
+ const auto n = static_cast<int16_t>(2);
+ const auto m = static_cast<int16_t>(1);
+ const auto bytes = encodeInstruction(
+ OpCode::KERNEL_CREATE, {/*dst=*/0, /*kidx=*/1, /*kNameIdx=*/1, n, /*in0=*/2, /*in1=*/3, m, /*out0=*/4});
+ const auto expected = (6 + n + m) * OPERAND_SIZE;
+ EXPECT_EQ(getInstructionSize(OpCode::KERNEL_CREATE, bytes.data(), bytes.size()), expected);
+}
+
+TEST(InstructionSizesTest, KernelCreateZeroInputsOutputs) {
+ const auto bytes =
+ encodeInstruction(OpCode::KERNEL_CREATE, {/*dst=*/0, /*kidx=*/1, /*kNameIdx=*/1, /*N=*/0, /*M=*/0});
+ const auto expected = 6 * OPERAND_SIZE; // opcode + dst + kidx + kNameIdx + N + M
+ EXPECT_EQ(getInstructionSize(OpCode::KERNEL_CREATE, bytes.data(), bytes.size()), expected);
+}
+
+TEST(InstructionSizesTest, KernelCreateRejectsNegativeInputCount) {
+ const auto bytes = encodeInstruction(OpCode::KERNEL_CREATE, {/*dst=*/0, /*kidx=*/1, /*kNameIdx=*/1, /*N=*/-1});
+ EXPECT_FALSE(getInstructionSize(OpCode::KERNEL_CREATE, bytes.data(), bytes.size()).has_value());
+}
+
+TEST(InstructionSizesTest, KernelCreateRejectsNegativeOutputCount) {
+ const auto bytes =
+ encodeInstruction(OpCode::KERNEL_CREATE, {/*dst=*/0, /*kidx=*/1, /*kNameIdx=*/1, /*N=*/0, /*M=*/-1});
+ EXPECT_FALSE(getInstructionSize(OpCode::KERNEL_CREATE, bytes.data(), bytes.size()).has_value());
+}
+
+TEST(InstructionSizesTest, KernelCreateRejectsTruncatedBufferBeforeOutputCount) {
+ const auto bytes = encodeInstruction(OpCode::KERNEL_CREATE, {/*dst=*/0, /*kidx=*/1, /*kNameIdx=*/1, /*N=*/2});
+ EXPECT_FALSE(getInstructionSize(OpCode::KERNEL_CREATE, bytes.data(), bytes.size()).has_value());
+}
+
+TEST(VirtualMachineInstructionSizesTest, VariadicInstructionSizeGatesDecodeHeaderInternally) {
+ const auto shortBytes = std::vector<uint8_t>(OPCODE_SIZE, 0u);
+
+ EXPECT_FALSE(getInstructionSize(OpCode::RETV, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::BUFFER_CREATE, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::BUFFER_LOAD, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::BUFFER_SUBVIEW, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::BUFFER_VIEW, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::KERNEL_CREATE, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::CMD_LIST_ADD_KERNEL, shortBytes.data(), shortBytes.size()).has_value());
+ EXPECT_FALSE(getInstructionSize(OpCode::CALL, shortBytes.data(), shortBytes.size()).has_value());
+}
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_float.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_float.cpp
new file mode 100644
index 00000000000..faf14dd7112
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_float.cpp
@@ -0,0 +1,420 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <initializer_list>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+namespace {
+
+struct RoundF64Params {
+ int64_t src;
+ RoundingMode flag;
+ double expected;
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const RoundF64Params& params) {
+ os << "{ src=" << params.src << ", flag=" << static_cast<int16_t>(params.flag)
+ << ", expected=" << params.expected << " }";
+ return os;
+ }
+};
+
+class VirtualMachineRoundF64Test :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<RoundF64Params> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<RoundF64Params>& obj) {
+ std::ostringstream result;
+ result << "flag=" << static_cast<int16_t>(obj.param.flag) << "_src=" << obj.param.src
+ << "_expected=" << obj.param.expected;
+ return result.str();
+ }
+};
+
+} // namespace
+
+TEST_P(VirtualMachineRoundF64Test, Execute) {
+ const auto& params = GetParam();
+
+ const auto funcName = "test";
+ auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/2,
+ {getF64Type()}, {getF64Type()},
+ /*isEntrypoint=*/true)
+ .instruction(OpCode::ROUND_F64,
+ {/*dst=*/0, /*src=*/1, static_cast<int16_t>(params.flag)})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ double srcDouble{};
+ std::memcpy(&srcDouble, &params.src, sizeof(srcDouble));
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeF64(srcDouble)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeF64(0.0)};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+
+ expectF64Eq(results.at(0).f64, params.expected);
+}
+
+// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers)
+
+INSTANTIATE_TEST_SUITE_P(
+ AddF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(0.0), f64Bits(0.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-0.0), f64Bits(-0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-0.0), f64Bits(0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(1.0), f64Bits(0.0), double{1.0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(1.0), f64Bits(2.0), double{3.0}},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(1.5), f64Bits(2.5), double{4.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-1.0), f64Bits(2.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-1.0), f64Bits(1.0), double{0.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-3.0), f64Bits(-4.0), double{-7.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(INF_F64), f64Bits(1.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-INF_F64), f64Bits(1.0), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(INF_F64), f64Bits(INF_F64), INF_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(INF_F64), f64Bits(-INF_F64), NAN_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(NAN_F64), f64Bits(1.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(1.0), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(-INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(NAN_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::ADD_F64, f64Bits(NAN_F64), f64Bits(-INF_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ SubF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(0.0), f64Bits(0.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-0.0), f64Bits(-0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-0.0), f64Bits(0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(1.0), f64Bits(0.0), double{1.0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(5.0), f64Bits(3.0), double{2.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(1.0), f64Bits(1.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(1.0), f64Bits(3.0), double{-2.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-1.0), f64Bits(2.0), double{-3.0}},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(1.0), f64Bits(-2.0), double{3.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-2.0), f64Bits(-5.0), double{3.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(INF_F64), f64Bits(1.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-INF_F64), f64Bits(1.0), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(INF_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(INF_F64), f64Bits(-INF_F64), INF_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-INF_F64), f64Bits(INF_F64), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), NAN_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(NAN_F64), f64Bits(1.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(1.0), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(-INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(NAN_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::SUB_F64, f64Bits(NAN_F64), f64Bits(-INF_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MulF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(0.0), f64Bits(0.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(0.0), f64Bits(-0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-0.0), f64Bits(0.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-0.0), f64Bits(-0.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(0.0), f64Bits(5.0), double{0.0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(1.0), f64Bits(1.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(2.0), f64Bits(3.0), double{6.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-2.0), f64Bits(3.0), double{-6.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-2.0), f64Bits(-3.0), double{6.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(INF_F64), f64Bits(1.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-INF_F64), f64Bits(1.0), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(INF_F64), f64Bits(INF_F64), INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(INF_F64), f64Bits(-INF_F64), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-INF_F64), f64Bits(INF_F64), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), INF_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(INF_F64), f64Bits(0.0), NAN_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(NAN_F64), f64Bits(1.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(1.0), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(-INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(NAN_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::MUL_F64, f64Bits(NAN_F64), f64Bits(-INF_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ DivF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(0.0), f64Bits(1.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(0.0), f64Bits(-1.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-0.0), f64Bits(1.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-0.0), f64Bits(-1.0), double{0.0}},
+ // Division by zero (not a trap in floating point)
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(0.0), f64Bits(0.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(1.0), f64Bits(0.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-1.0), f64Bits(0.0), -INF_F64},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(6.0), f64Bits(2.0), double{3.0}},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(1.0), f64Bits(4.0), double{0.25}},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(7.0), f64Bits(7.0), double{1.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-6.0), f64Bits(2.0), double{-3.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-6.0), f64Bits(-2.0), double{3.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(2.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(-2.0), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(-INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-INF_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(0.0), INF_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(NAN_F64), f64Bits(1.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(1.0), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(-INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(NAN_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::DIV_F64, f64Bits(NAN_F64), f64Bits(-INF_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ RemF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(0.0), f64Bits(1.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(0.0), f64Bits(-1.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-0.0), f64Bits(1.0), double{-0.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-0.0), f64Bits(-1.0), double{0.0}},
+ // Division by zero (not a trap in floating point)
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(0.0), f64Bits(0.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(1.0), f64Bits(0.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-1.0), f64Bits(0.0), NAN_F64},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(6.0), f64Bits(2.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(1.0), f64Bits(4.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(7.0), f64Bits(7.0), double{0.0}},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(2.5), f64Bits(1.0), double{0.5}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-7.0), f64Bits(3.0), double{-1.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-7.0), f64Bits(-3.0), double{-1.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(2.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(-2.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(-INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-INF_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(0.0), NAN_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(NAN_F64), f64Bits(1.0), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(1.0), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(-INF_F64), f64Bits(NAN_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(NAN_F64), f64Bits(INF_F64), NAN_F64},
+ ThreeOperandInstructionParams{OpCode::REM_F64, f64Bits(NAN_F64), f64Bits(-INF_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MaxF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(0.0), f64Bits(0.0), double{0.0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(3.0), f64Bits(5.0), double{5.0}},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(5.0), f64Bits(3.0), double{5.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(-1.0), f64Bits(1.0), double{1.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(-5.0), f64Bits(-3.0), double{-3.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(INF_F64), f64Bits(1.0), INF_F64},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(-INF_F64), f64Bits(1.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(1.0), f64Bits(INF_F64), INF_F64},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(1.0), f64Bits(-INF_F64), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(INF_F64), f64Bits(INF_F64), INF_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(NAN_F64), f64Bits(1.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(1.0), f64Bits(NAN_F64), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MAX_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MinF64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(0.0), f64Bits(0.0), double{0.0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(3.0), f64Bits(5.0), double{3.0}},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(5.0), f64Bits(3.0), double{3.0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(-1.0), f64Bits(1.0), double{-1.0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(-5.0), f64Bits(-3.0), double{-5.0}},
+ // Infinity
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(INF_F64), f64Bits(1.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(-INF_F64), f64Bits(1.0), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(1.0), f64Bits(INF_F64), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(1.0), f64Bits(-INF_F64), -INF_F64},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), -INF_F64},
+ // NaN
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(NAN_F64), f64Bits(1.0), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(1.0), f64Bits(NAN_F64), double{1.0}},
+ ThreeOperandInstructionParams{OpCode::MIN_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), NAN_F64}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(AbsF64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(
+ // Zero
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(0.0), double{0.0}},
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(-0.0), double{0.0}},
+ // Basic positive
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(3.0), double{3.0}},
+ // Basic negative
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(-3.0), double{3.0}},
+ // Infinity
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(INF_F64), double{INF_F64}},
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(-INF_F64), double{INF_F64}},
+ // NaN
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(NAN_F64), double{NAN_F64}},
+ TwoOperandInstructionParams{OpCode::ABS_F64, f64Bits(-NAN_F64), double{NAN_F64}}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(NegF64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(
+ // Zero
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(0.0), double{-0.0}},
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(-0.0), double{0.0}},
+ // Basic positive
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(3.0), double{-3.0}},
+ // Basic negative
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(-3.0), double{3.0}},
+ // Infinity
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(INF_F64), double{-INF_F64}},
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(-INF_F64), double{INF_F64}},
+ // NaN
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(NAN_F64), double{NAN_F64}},
+ TwoOperandInstructionParams{OpCode::NEG_F64, f64Bits(-NAN_F64), double{NAN_F64}}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(CeilF64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(
+ // Zero
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(0.0), double{0.0}},
+ // Basic positive
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(1.1), double{2.0}},
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(2.0), double{2.0}},
+ // Basic negative
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(-1.1), double{-1.0}},
+ // Infinity
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(INF_F64), double{INF_F64}},
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(-INF_F64), double{-INF_F64}},
+ // NaN
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(NAN_F64), double{NAN_F64}},
+ TwoOperandInstructionParams{OpCode::CEIL_F64, f64Bits(-NAN_F64), double{NAN_F64}}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(FloorF64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(
+ // Zero
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(0.0), double{0.0}},
+ // Basic positive
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(1.9), double{1.0}},
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(2.0), double{2.0}},
+ // Basic negative
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(-1.1), double{-2.0}},
+ // Infinity
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(INF_F64), double{INF_F64}},
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(-INF_F64), double{-INF_F64}},
+ // NaN
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(NAN_F64), double{NAN_F64}},
+ TwoOperandInstructionParams{OpCode::FLOOR_F64, f64Bits(-NAN_F64), double{NAN_F64}}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RoundF64_RNE, VirtualMachineRoundF64Test,
+ testing::Values(RoundF64Params{f64Bits(1.5), RoundingMode::RNE, 2.0},
+ RoundF64Params{f64Bits(2.5), RoundingMode::RNE, 2.0},
+ RoundF64Params{f64Bits(-1.5), RoundingMode::RNE, -2.0},
+ RoundF64Params{f64Bits(-2.5), RoundingMode::RNE, -2.0},
+ RoundF64Params{f64Bits(1.4), RoundingMode::RNE, 1.0},
+ RoundF64Params{f64Bits(1.0), RoundingMode::RNE, 1.0},
+ RoundF64Params{f64Bits(INF_F64), RoundingMode::RNE, INF_F64},
+ RoundF64Params{f64Bits(NAN_F64), RoundingMode::RNE, NAN_F64}),
+ VirtualMachineRoundF64Test::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RoundF64_RNA, VirtualMachineRoundF64Test,
+ testing::Values(RoundF64Params{f64Bits(1.5), RoundingMode::RNA, 2.0},
+ RoundF64Params{f64Bits(2.5), RoundingMode::RNA, 3.0},
+ RoundF64Params{f64Bits(-1.5), RoundingMode::RNA, -2.0},
+ RoundF64Params{f64Bits(-2.5), RoundingMode::RNA, -3.0},
+ RoundF64Params{f64Bits(1.4), RoundingMode::RNA, 1.0},
+ RoundF64Params{f64Bits(1.0), RoundingMode::RNA, 1.0},
+ RoundF64Params{f64Bits(INF_F64), RoundingMode::RNA, INF_F64},
+ RoundF64Params{f64Bits(NAN_F64), RoundingMode::RNA, NAN_F64}),
+ VirtualMachineRoundF64Test::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RoundF64_RDN, VirtualMachineRoundF64Test,
+ testing::Values(RoundF64Params{f64Bits(1.5), RoundingMode::RDN, 1.0},
+ RoundF64Params{f64Bits(-1.1), RoundingMode::RDN, -2.0},
+ RoundF64Params{f64Bits(2.0), RoundingMode::RDN, 2.0},
+ RoundF64Params{f64Bits(INF_F64), RoundingMode::RDN, INF_F64},
+ RoundF64Params{f64Bits(NAN_F64), RoundingMode::RDN, NAN_F64}),
+ VirtualMachineRoundF64Test::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RoundF64_RUP, VirtualMachineRoundF64Test,
+ testing::Values(RoundF64Params{f64Bits(1.1), RoundingMode::RUP, 2.0},
+ RoundF64Params{f64Bits(-1.5), RoundingMode::RUP, -1.0},
+ RoundF64Params{f64Bits(2.0), RoundingMode::RUP, 2.0},
+ RoundF64Params{f64Bits(INF_F64), RoundingMode::RUP, INF_F64},
+ RoundF64Params{f64Bits(NAN_F64), RoundingMode::RUP, NAN_F64}),
+ VirtualMachineRoundF64Test::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RoundF64_RTZ, VirtualMachineRoundF64Test,
+ testing::Values(RoundF64Params{f64Bits(1.9), RoundingMode::RTZ, 1.0},
+ RoundF64Params{f64Bits(-1.9), RoundingMode::RTZ, -1.0},
+ RoundF64Params{f64Bits(2.0), RoundingMode::RTZ, 2.0},
+ RoundF64Params{f64Bits(INF_F64), RoundingMode::RTZ, INF_F64},
+ RoundF64Params{f64Bits(NAN_F64), RoundingMode::RTZ, NAN_F64}),
+ VirtualMachineRoundF64Test::getTestCaseName);
+
+// NOLINTEND(cppcoreguidelines-avoid-magic-numbers)
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_integers.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_integers.cpp
new file mode 100644
index 00000000000..ba51ee8dd9b
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/arithmetic_integers.cpp
@@ -0,0 +1,313 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+#include <string>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+INSTANTIATE_TEST_SUITE_P(AddI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 1, 1, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 10, 32, int64_t{42}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::ADD_I64, -5, 5, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 100, -1, int64_t{99}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::ADD_I64, -10, -20, int64_t{-30}},
+ // Identity: adding zero
+ ThreeOperandInstructionParams{OpCode::ADD_I64, std::numeric_limits<int64_t>::max(), 0,
+ std::numeric_limits<int64_t>::max()},
+ ThreeOperandInstructionParams{OpCode::ADD_I64, std::numeric_limits<int64_t>::min(), 0,
+ std::numeric_limits<int64_t>::min()},
+ // Signed overflow wraps to INT64_MIN (two's complement)
+ ThreeOperandInstructionParams{OpCode::ADD_I64, std::numeric_limits<int64_t>::max(), 1,
+ std::numeric_limits<int64_t>::min()}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(SubI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::SUB_I64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::SUB_I64, 1, 1, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::SUB_I64, 32, 10, int64_t{22}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::SUB_I64, -5, 5, int64_t{-10}},
+ ThreeOperandInstructionParams{OpCode::SUB_I64, 100, -1, int64_t{101}},
+ ThreeOperandInstructionParams{OpCode::SUB_I64, -10, -20, int64_t{10}},
+ // Identity: subtracting zero
+ ThreeOperandInstructionParams{OpCode::SUB_I64, std::numeric_limits<int64_t>::max(), 0,
+ std::numeric_limits<int64_t>::max()},
+ ThreeOperandInstructionParams{OpCode::SUB_I64, std::numeric_limits<int64_t>::min(), 0,
+ std::numeric_limits<int64_t>::min()},
+ // Signed overflow wraps to INT64_MAX (two's complement)
+ ThreeOperandInstructionParams{OpCode::SUB_I64, std::numeric_limits<int64_t>::min(), 1,
+ std::numeric_limits<int64_t>::max()}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MulI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MUL_I64, 0, 0, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::MUL_I64, 12345, 0, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::MUL_I64, -67890, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MUL_I64, 2, 3, int64_t{6}},
+ ThreeOperandInstructionParams{OpCode::MUL_I64, 10, 32, int64_t{320}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MUL_I64, -5, 5, int64_t{-25}},
+ ThreeOperandInstructionParams{OpCode::MUL_I64, 100, -1, int64_t{-100}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::MUL_I64, -10, -20, int64_t{200}},
+ // Identity: multiplying by one
+ ThreeOperandInstructionParams{OpCode::MUL_I64, std::numeric_limits<int64_t>::max(), 1,
+ std::numeric_limits<int64_t>::max()},
+ ThreeOperandInstructionParams{OpCode::MUL_I64, std::numeric_limits<int64_t>::min(), 1,
+ std::numeric_limits<int64_t>::min()},
+ // Signed overflow wraps (two's complement)
+ ThreeOperandInstructionParams{OpCode::MUL_I64, std::numeric_limits<int64_t>::max(), 2,
+ static_cast<int64_t>(-2)}, // INT64_MAX * 2 -> -2 in two's complement
+ ThreeOperandInstructionParams{OpCode::MUL_I64, std::numeric_limits<int64_t>::min(), 2,
+ static_cast<int64_t>(0)} // INT64_MIN * 2 -> 0 in two's complement
+ ),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ DivI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::DIV_I64, 6, 3, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::DIV_I64, 10, 32, int64_t{0}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::DIV_I64, -25, 5, int64_t{-5}},
+ ThreeOperandInstructionParams{OpCode::DIV_I64, 100, -1, int64_t{-100}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::DIV_I64, -200, -10, int64_t{20}},
+ // Identity: dividing by one
+ ThreeOperandInstructionParams{OpCode::DIV_I64, std::numeric_limits<int64_t>::max(), 1,
+ std::numeric_limits<int64_t>::max()},
+ ThreeOperandInstructionParams{OpCode::DIV_I64, std::numeric_limits<int64_t>::min(), 1,
+ std::numeric_limits<int64_t>::min()},
+ // Division overflow: INT64_MIN / -1 -> INT64_MIN (defined behavior to avoid undefined behavior)
+ ThreeOperandInstructionParams{OpCode::DIV_I64, std::numeric_limits<int64_t>::min(), -1,
+ std::numeric_limits<int64_t>::min()}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ RemI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::REM_I64, 5, 3, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::REM_I64, 10, 32, int64_t{10}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::REM_I64, -25, 5, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::REM_I64, 100, -1, int64_t{0}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::REM_I64, -200, -10, int64_t{0}},
+ // Identity: remainder by one is always zero
+ ThreeOperandInstructionParams{OpCode::REM_I64, std::numeric_limits<int64_t>::max(), 1, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::REM_I64, std::numeric_limits<int64_t>::min(), 1, int64_t{0}},
+ // Division overflow: INT64_MIN / -1 -> INT64_MIN -> remainder is 0 (defined behavior to avoid undefined
+ // behavior)
+ ThreeOperandInstructionParams{OpCode::REM_I64, std::numeric_limits<int64_t>::min(), -1, int64_t{0}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ DivU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::DIV_U64, 6, 3, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::DIV_U64, 10, 32, int64_t{0}},
+ // Large unsigned values (high bit set, interpreted as large positive when unsigned)
+ ThreeOperandInstructionParams{OpCode::DIV_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 2,
+ static_cast<int64_t>(0x7FFFFFFFFFFFFFFFULL)},
+ // UINT64_MAX / 1 = UINT64_MAX
+ ThreeOperandInstructionParams{OpCode::DIV_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1,
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // UINT64_MAX / UINT64_MAX = 1
+ ThreeOperandInstructionParams{OpCode::DIV_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), int64_t{1}},
+ // Value with high bit set divided by large divisor
+ ThreeOperandInstructionParams{OpCode::DIV_U64, static_cast<int64_t>(0x8000000000000000ULL), 2,
+ static_cast<int64_t>(0x4000000000000000ULL)},
+ // Identity: dividing by one
+ ThreeOperandInstructionParams{OpCode::DIV_U64, 100, 1, int64_t{100}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MinU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MIN_U64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MIN_U64, 1, 2, int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::MIN_U64, 100, 50, int64_t{50}},
+ // Large unsigned values (high bit set, interpreted as large positive when unsigned)
+ ThreeOperandInstructionParams{OpCode::MIN_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1,
+ int64_t{1}},
+ // Both large unsigned values
+ ThreeOperandInstructionParams{OpCode::MIN_U64, static_cast<int64_t>(0x8000000000000000ULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL),
+ static_cast<int64_t>(0x8000000000000000ULL)},
+ // UINT64_MAX vs UINT64_MAX
+ ThreeOperandInstructionParams{OpCode::MIN_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // Signed negative is large unsigned
+ ThreeOperandInstructionParams{OpCode::MIN_U64, -1, 5, int64_t{5}},
+ // Identity
+ ThreeOperandInstructionParams{OpCode::MIN_U64, 42, 42, int64_t{42}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(AddU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::ADD_U64, 3, 4, int64_t{7}},
+ ThreeOperandInstructionParams{OpCode::ADD_U64, 0, 0, int64_t{0}},
+ // Large unsigned values
+ ThreeOperandInstructionParams{
+ OpCode::ADD_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1, int64_t{0}},
+ // Wrapping overflow
+ ThreeOperandInstructionParams{OpCode::ADD_U64,
+ static_cast<int64_t>(0x8000000000000000ULL), 1,
+ static_cast<int64_t>(0x8000000000000001ULL)},
+ // Identity: adding zero
+ ThreeOperandInstructionParams{OpCode::ADD_U64, 100, 0, int64_t{100}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ MaxU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MAX_U64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MAX_U64, 1, 2, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::MAX_U64, 100, 50, int64_t{100}},
+ // Large unsigned values (high bit set, interpreted as large positive when unsigned)
+ ThreeOperandInstructionParams{OpCode::MAX_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1,
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // Both large unsigned values
+ ThreeOperandInstructionParams{OpCode::MAX_U64, static_cast<int64_t>(0x8000000000000000ULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL),
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // Signed negative is large unsigned
+ ThreeOperandInstructionParams{OpCode::MAX_U64, -1, 5, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // Identity
+ ThreeOperandInstructionParams{OpCode::MAX_U64, 42, 42, int64_t{42}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(MulU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MUL_U64, 3, 4, int64_t{12}},
+ ThreeOperandInstructionParams{OpCode::MUL_U64, 0, 100, int64_t{0}},
+ // Identity: multiply by one
+ ThreeOperandInstructionParams{OpCode::MUL_U64, 100, 1, int64_t{100}},
+ // Large unsigned values with wrapping
+ ThreeOperandInstructionParams{
+ OpCode::MUL_U64, static_cast<int64_t>(0x8000000000000000ULL), 2, int64_t{0}},
+ // UINT64_MAX * 1 = UINT64_MAX
+ ThreeOperandInstructionParams{OpCode::MUL_U64,
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1,
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(RemU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::REM_U64, 7, 3, int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::REM_U64, 10, 5, int64_t{0}},
+ // Large unsigned values
+ ThreeOperandInstructionParams{
+ OpCode::REM_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 2, int64_t{1}},
+ // Modulo by 1 = 0
+ ThreeOperandInstructionParams{OpCode::REM_U64, 100, 1, int64_t{0}},
+ // Value with high bit set
+ ThreeOperandInstructionParams{
+ OpCode::REM_U64, static_cast<int64_t>(0x8000000000000000ULL), 3, int64_t{2}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ SubU64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::SUB_U64, 10, 3, int64_t{7}},
+ ThreeOperandInstructionParams{OpCode::SUB_U64, 0, 0, int64_t{0}},
+ // Wrapping underflow (0 - 1 = UINT64_MAX)
+ ThreeOperandInstructionParams{OpCode::SUB_U64, 0, 1, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL)},
+ // Large unsigned values
+ ThreeOperandInstructionParams{OpCode::SUB_U64, static_cast<int64_t>(0xFFFFFFFFFFFFFFFFULL), 1,
+ static_cast<int64_t>(0xFFFFFFFFFFFFFFFEULL)},
+ // Identity: subtracting zero
+ ThreeOperandInstructionParams{OpCode::SUB_U64, 100, 0, int64_t{100}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(MinI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MIN_I64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MIN_I64, 1, 2, int64_t{1}},
+ // Basic negative
+ ThreeOperandInstructionParams{OpCode::MIN_I64, -10, -20, int64_t{-20}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MIN_I64, -5, 5, int64_t{-5}},
+ ThreeOperandInstructionParams{OpCode::MIN_I64, 100, -1, int64_t{-1}},
+ // Boundary
+ ThreeOperandInstructionParams{OpCode::MIN_I64, std::numeric_limits<int64_t>::min(), 1,
+ std::numeric_limits<int64_t>::min()},
+ ThreeOperandInstructionParams{OpCode::MIN_I64, std::numeric_limits<int64_t>::max(), 1,
+ int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::MIN_I64, std::numeric_limits<int64_t>::max(),
+ std::numeric_limits<int64_t>::min(),
+ std::numeric_limits<int64_t>::min()}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(MaxI64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::MAX_I64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::MAX_I64, 1, 2, int64_t{2}},
+ // Basic negative
+ ThreeOperandInstructionParams{OpCode::MAX_I64, -10, -20, int64_t{-10}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::MAX_I64, -5, 5, int64_t{5}},
+ ThreeOperandInstructionParams{OpCode::MAX_I64, 100, -1, int64_t{100}},
+ // Boundary
+ ThreeOperandInstructionParams{OpCode::MAX_I64, std::numeric_limits<int64_t>::min(), 1,
+ int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::MAX_I64, std::numeric_limits<int64_t>::max(), 1,
+ std::numeric_limits<int64_t>::max()},
+ ThreeOperandInstructionParams{OpCode::MAX_I64, std::numeric_limits<int64_t>::max(),
+ std::numeric_limits<int64_t>::min(),
+ std::numeric_limits<int64_t>::max()}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ AbsI64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(TwoOperandInstructionParams{OpCode::ABS_I64, 0, int64_t{0}},
+ TwoOperandInstructionParams{OpCode::ABS_I64, 12345, int64_t{12345}},
+ TwoOperandInstructionParams{OpCode::ABS_I64, -67890, int64_t{67890}},
+ // Identity: abs of INT64_MIN is INT64_MIN (defined behavior to avoid undefined behavior)
+ TwoOperandInstructionParams{OpCode::ABS_I64, std::numeric_limits<int64_t>::min(),
+ std::numeric_limits<int64_t>::min()}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/bitwise.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/bitwise.cpp
new file mode 100644
index 00000000000..566b35c4437
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/bitwise.cpp
@@ -0,0 +1,75 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <string>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+INSTANTIATE_TEST_SUITE_P(And64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::AND_64, 0b1100, 0b1010, int64_t{0b1000}},
+ ThreeOperandInstructionParams{OpCode::AND_64, 0b1111, 0b0000, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::AND_64, 0b1010, 0b0101, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::AND_64, 0b1111'1111, 0b1010'1010,
+ int64_t{0b1010'1010}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Not64, VirtualMachineTwoOperandInstructionTest,
+ testing::Values(TwoOperandInstructionParams{OpCode::NOT_64, 0b1100, int64_t{~0b1100}},
+ TwoOperandInstructionParams{OpCode::NOT_64, 0b1010, int64_t{~0b1010}},
+ TwoOperandInstructionParams{OpCode::NOT_64, 0b1111'0000,
+ int64_t{~0b1111'0000}}),
+ VirtualMachineTwoOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Or64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::OR_64, 0b1100, 0b1010, int64_t{0b1110}},
+ ThreeOperandInstructionParams{OpCode::OR_64, 0b1111, 0b0000, int64_t{0b1111}},
+ ThreeOperandInstructionParams{OpCode::OR_64, 0b1010, 0b0101, int64_t{0b1111}},
+ ThreeOperandInstructionParams{OpCode::OR_64, 0b1111'1111, 0b1010'1010,
+ int64_t{0b1111'1111}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Xor64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::XOR_64, 0b1100, 0b1010, int64_t{0b0110}},
+ ThreeOperandInstructionParams{OpCode::XOR_64, 0b1111, 0b0000, int64_t{0b1111}},
+ ThreeOperandInstructionParams{OpCode::XOR_64, 0b1010, 0b0101, int64_t{0b1111}},
+ ThreeOperandInstructionParams{OpCode::XOR_64, 0b1111'1111, 0b1010'1010,
+ int64_t{0b0101'0101}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Sll64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::SLL_64, 1, 1, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::SLL_64, 1, 63, INT64_MIN},
+ ThreeOperandInstructionParams{OpCode::SLL_64, 1, 64,
+ int64_t{1}}, // shift count masked by 63
+ ThreeOperandInstructionParams{OpCode::SLL_64, -1, 1, int64_t{-2}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Srl64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::SRL_64, 2, 1, int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::SRL_64, INT64_MIN, 63, int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::SRL_64, INT64_MIN, 64,
+ INT64_MIN}, // shift count masked by 63
+ ThreeOperandInstructionParams{OpCode::SRL_64, -2, 1,
+ static_cast<int64_t>(UINT64_MAX >> 1)}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(Sra64, VirtualMachineThreeOperandInstructionTest,
+ testing::Values(ThreeOperandInstructionParams{OpCode::SRA_64, 2, 1, int64_t{1}},
+ ThreeOperandInstructionParams{OpCode::SRA_64, INT64_MIN, 63, int64_t{-1}},
+ ThreeOperandInstructionParams{OpCode::SRA_64, INT64_MIN, 64,
+ INT64_MIN}, // shift count masked by 63
+ ThreeOperandInstructionParams{OpCode::SRA_64, -2, 1, int64_t{-1}}),
+ VirtualMachineThreeOperandInstructionTest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/buffers.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/buffers.cpp
new file mode 100644
index 00000000000..ec432503bbc
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/buffers.cpp
@@ -0,0 +1,525 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers)
+
+TEST_F(VirtualMachineInstructionTest, BufferCreateGetDim) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/9,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/4)
+ .setImm(/*dst=*/2, /*imm=*/6)
+ .setImm(/*dst=*/3, /*imm=*/6)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/1, 2,
+ /*strides=*/3, 4})
+ .setImm(/*dst=*/5, /*imm=*/0)
+ .setImm(/*dst=*/6, /*imm=*/1)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/7, /*buffer=*/0, /*dim=*/5})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/8, /*buffer=*/0, /*dim=*/6})
+ .retv({7, 8});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 4);
+ EXPECT_EQ(results.at(1).i64, 6);
+}
+
+TEST_F(VirtualMachineInstructionTest, BufferSubviewMatchesRequestedSizes) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/16,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/4)
+ .setImm(/*dst=*/2, /*imm=*/6)
+ .setImm(/*dst=*/3, /*imm=*/6)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/1, 2,
+ /*strides=*/3, 4})
+ .setImm(/*dst=*/5, /*imm=*/1)
+ .setImm(/*dst=*/6, /*imm=*/1)
+ .setImm(/*dst=*/7, /*imm=*/2)
+ .setImm(/*dst=*/8, /*imm=*/3)
+ .setImm(/*dst=*/9, /*imm=*/1)
+ .setImm(/*dst=*/10, /*imm=*/1)
+ .instruction(OpCode::BUFFER_SUBVIEW, {/*dst=*/11, /*src=*/0, /*rank=*/2,
+ /*offsets=*/5, 6,
+ /*sizes=*/7, 8,
+ /*strides=*/9, 10})
+ .setImm(/*dst=*/12, /*imm=*/0)
+ .setImm(/*dst=*/13, /*imm=*/1)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/14, /*buffer=*/11, /*dim=*/12})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/15, /*buffer=*/11, /*dim=*/13})
+ .retv({14, 15});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 2);
+ EXPECT_EQ(results.at(1).i64, 3);
+}
+
+// Smoke test for buffer.store: build a function that allocates an owned i64 memref via buffer.create, stores a
+// parameter value at static indices, and returns. Asserts the VM finalizes without halting. No buffer.load opcode
+// exists yet, so the stored value cannot be read back; this exercises the executor's metadata lookup, bounds checking,
+// permission check, and write path end-to-end through bytecode parsing and execution.
+TEST_F(VirtualMachineInstructionTest, BufferStoreExecutes) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int16_t kValueParamReg = 7;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/8,
+ /*paramTypes=*/{i64},
+ /*resultTypes=*/{},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/4)
+ .setImm(/*dst=*/2, /*imm=*/6)
+ .setImm(/*dst=*/3, /*imm=*/6)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/1, 2,
+ /*strides=*/3, 4})
+ .setImm(/*dst=*/5, /*imm=*/1)
+ .setImm(/*dst=*/6, /*imm=*/2)
+ .instruction(OpCode::BUFFER_STORE, {/*buffer=*/0, /*value=*/kValueParamReg, /*rank=*/2,
+ /*indices=*/5, 6})
+ .ret();
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(static_cast<int64_t>(0x123456789ABCDEF))};
+ std::vector<npu_vm_value> results = {};
+ EXPECT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+}
+
+// Smoke test for buffer.store and buffer.load: build a function that allocates an owned i64 memref via buffer.create,
+// stores a parameter value at static indices, reads it back, and returns it. This exercises the executor's metadata
+// lookup, bounds checking, permission check, and both read/write paths end-to-end through bytecode parsing and
+// execution
+TEST_F(VirtualMachineInstructionTest, BufferStoreAndLoadRoundTripsValue) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int16_t kValueParamReg = 9;
+ constexpr int16_t kLoadedValueReg = 7;
+ const auto storedValue = intel_npu::vm::makeI64(static_cast<int64_t>(0x123456789ABCDEF));
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/10,
+ /*paramTypes=*/{i64},
+ /*resultTypes=*/{i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/1)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .setImm(/*dst=*/3, /*imm=*/1)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .setImm(/*dst=*/5, /*imm=*/0)
+ .setImm(/*dst=*/6, /*imm=*/0)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/1, 2,
+ /*strides=*/3, 4})
+ .instruction(OpCode::BUFFER_STORE, {/*buffer=*/0, /*value=*/kValueParamReg, /*rank=*/2,
+ /*indices=*/5, 6})
+ .instruction(OpCode::BUFFER_LOAD, {/*dst=*/kLoadedValueReg, /*buffer=*/0, /*rank=*/2,
+ /*indices=*/5, 6})
+ .retv({kLoadedValueReg});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {storedValue};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ EXPECT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, storedValue.i64);
+}
+
+// Build a buffer whose shape is supplied as i64 parameters at call time, then read each dimension back through
+// buffer.get_dim. This exercises the runtime path for dynamically-shaped buffers: : the dim values stored in the buffer
+// descriptor are whatever shape registers held at buffer.create time, and buffer.get_dim returns those runtime values.
+TEST_F(VirtualMachineInstructionTest, BufferCreateGetDimDynamicShape) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int16_t kDim0ParamReg = 10;
+ constexpr int16_t kDim1ParamReg = 11;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/12,
+ /*paramTypes=*/{i64, i64},
+ /*resultTypes=*/{i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/kDim0ParamReg, kDim1ParamReg,
+ /*strides=*/kDim1ParamReg, 2})
+ .setImm(/*dst=*/3, /*imm=*/0)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/5, /*buffer=*/0, /*dim=*/3})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/6, /*buffer=*/0, /*dim=*/4})
+ .retv({5, 6});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(7), intel_npu::vm::makeI64(11)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 7);
+ EXPECT_EQ(results.at(1).i64, 11);
+}
+
+// The source memref's dim 2 and the subview's dim-2 offset are both runtime values; sizes and strides are static.
+// This builds a buffer.create with a parameter register in the dim-2 slot followed by a buffer.subview whose dim-2
+// offset is the second parameter register. The view's dims must equal the requested sizes [1, 16, 31, 1280] regardless
+// of the runtime input values.
+TEST_F(VirtualMachineInstructionTest, BufferSubviewDynamicOffsetReturnsRequestedSizes) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int16_t kDynSrcDim2ParamReg = 28;
+ constexpr int16_t kDynOffsetParamReg = 29;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/30,
+ /*paramTypes=*/{i64, i64},
+ /*resultTypes=*/{i64, i64, i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/1)
+ .setImm(/*dst=*/2, /*imm=*/16)
+ .setImm(/*dst=*/3, /*imm=*/1280)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/4,
+ /*shape=*/1, 2, kDynSrcDim2ParamReg, 3,
+ /*strides=*/4, 4, 4, 4})
+ .setImm(/*dst=*/6, /*imm=*/0)
+ .setImm(/*dst=*/7, /*imm=*/0)
+ .setImm(/*dst=*/8, /*imm=*/0)
+ .setImm(/*dst=*/9, /*imm=*/1)
+ .setImm(/*dst=*/10, /*imm=*/16)
+ .setImm(/*dst=*/11, /*imm=*/31)
+ .setImm(/*dst=*/12, /*imm=*/1280)
+ .setImm(/*dst=*/13, /*imm=*/1)
+ .setImm(/*dst=*/14, /*imm=*/1)
+ .setImm(/*dst=*/15, /*imm=*/1)
+ .setImm(/*dst=*/16, /*imm=*/1)
+ .instruction(OpCode::BUFFER_SUBVIEW, {/*dst=*/5, /*src=*/0, /*rank=*/4,
+ /*offsets=*/6, 7, kDynOffsetParamReg, 8,
+ /*sizes=*/9, 10, 11, 12,
+ /*strides=*/13, 14, 15, 16})
+ .setImm(/*dst=*/17, /*imm=*/0)
+ .setImm(/*dst=*/18, /*imm=*/1)
+ .setImm(/*dst=*/19, /*imm=*/2)
+ .setImm(/*dst=*/20, /*imm=*/3)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/21, /*buffer=*/5, /*dim=*/17})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/22, /*buffer=*/5, /*dim=*/18})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/23, /*buffer=*/5, /*dim=*/19})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/24, /*buffer=*/5, /*dim=*/20})
+ .retv({21, 22, 23, 24});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(100), intel_npu::vm::makeI64(31)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0),
+ intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 1);
+ EXPECT_EQ(results.at(1).i64, 16);
+ EXPECT_EQ(results.at(2).i64, 31);
+ EXPECT_EQ(results.at(3).i64, 1280);
+}
+
+// Verify that buffer.view creates a view with the exact shape and strides provided.
+// Source is a flat 8-element i64 buffer reinterpreted as a 2x4 row-major view.
+TEST_F(VirtualMachineInstructionTest, BufferViewMatchesRequestedShape) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/13,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/8)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/1,
+ /*shape=*/1,
+ /*strides=*/2})
+ .setImm(/*dst=*/3, /*imm=*/0)
+ .setImm(/*dst=*/4, /*imm=*/2)
+ .setImm(/*dst=*/5, /*imm=*/4)
+ .setImm(/*dst=*/6, /*imm=*/4)
+ .setImm(/*dst=*/7, /*imm=*/1)
+ .instruction(OpCode::BUFFER_VIEW,
+ {/*dst=*/8, /*src=*/0, /*byteOffset=*/3, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/4, 5,
+ /*strides=*/6, 7})
+ .setImm(/*dst=*/9, /*imm=*/0)
+ .setImm(/*dst=*/10, /*imm=*/1)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/11, /*buffer=*/8, /*dim=*/9})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/12, /*buffer=*/8, /*dim=*/10})
+ .retv({11, 12});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 2);
+ EXPECT_EQ(results.at(1).i64, 4);
+}
+
+// Verify buffer.view with runtime-supplied shape registers: both shape dims are function parameters,
+// exercising the dynamic-register path through the VM's buffer.view handler.
+// Source is a flat 16-element i64 buffer; view shape {rows, cols} = {4, 4} is passed at call time.
+TEST_F(VirtualMachineInstructionTest, BufferViewDynamicShapeMatchesRuntimeValues) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int16_t kRowsParamReg = 12;
+ constexpr int16_t kColsParamReg = 13;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/14,
+ /*paramTypes=*/{i64, i64},
+ /*resultTypes=*/{i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/16)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/1,
+ /*shape=*/1,
+ /*strides=*/2})
+ .setImm(/*dst=*/3, /*imm=*/0)
+ .setImm(/*dst=*/4, /*imm=*/1)
+ .instruction(OpCode::BUFFER_VIEW,
+ {/*dst=*/5, /*src=*/0, /*byteOffset=*/3, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/kRowsParamReg, kColsParamReg,
+ /*strides=*/kColsParamReg, 4})
+ .setImm(/*dst=*/6, /*imm=*/0)
+ .setImm(/*dst=*/7, /*imm=*/1)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/8, /*buffer=*/5, /*dim=*/6})
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/9, /*buffer=*/5, /*dim=*/7})
+ .retv({8, 9});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(4), intel_npu::vm::makeI64(4)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 4);
+ EXPECT_EQ(results.at(1).i64, 4);
+}
+
+TEST_F(VirtualMachineInstructionTest, BufferViewWithNonZeroByteOffset) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/9,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{i64},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/4)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/1,
+ /*shape=*/1,
+ /*strides=*/2})
+ // Byte offset 16 skips two i64 elements (2x8 bytes), leaving a 2-element view.
+ .setImm(/*dst=*/3, /*imm=*/16)
+ .setImm(/*dst=*/4, /*imm=*/2)
+ .setImm(/*dst=*/5, /*imm=*/1)
+ .instruction(OpCode::BUFFER_VIEW,
+ {/*dst=*/6, /*src=*/0, /*byteOffset=*/3, kElemI64TypeIndex, /*rank=*/1,
+ /*shape=*/4,
+ /*strides=*/5})
+ .setImm(/*dst=*/7, /*imm=*/0)
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/8, /*buffer=*/6, /*dim=*/7})
+ .retv({8});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(results.at(0).i64, 2);
+}
+
+// Exercise the whole buffer instruction set against a single strided buffer in one function
+TEST_F(VirtualMachineInstructionTest, BufferStoreLoadGetDimAndSubviewCompose) {
+ const auto i64 = getInt64Type();
+ constexpr int16_t kElemI64TypeIndex = 0;
+
+ constexpr int16_t kBufReg = 0;
+ constexpr int16_t kViewReg = 1;
+ constexpr int16_t kDim0Reg = 2;
+ constexpr int16_t kDim1Reg = 3;
+ constexpr int16_t kStride0Reg = 4;
+ constexpr int16_t kStride1Reg = 5;
+ constexpr int16_t kOffset0Reg = 6;
+ constexpr int16_t kOffset1Reg = 7;
+ constexpr int16_t kSrcDimReg = 8;
+ constexpr int16_t kViewDimReg = 9;
+ constexpr int16_t kLoadedReg = 10;
+ constexpr int16_t kStoredReg = 11;
+ constexpr int16_t kLoadIdx0Reg = 12;
+ constexpr int16_t kLoadIdx1Reg = 13;
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/14,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{i64, i64, i64},
+ /*isEntrypoint=*/true)
+ .setImm(kDim0Reg, /*imm=*/2)
+ .setImm(kDim1Reg, /*imm=*/3)
+ .setImm(kStride0Reg, /*imm=*/3)
+ .setImm(kStride1Reg, /*imm=*/1)
+ .setImm(kOffset0Reg, /*imm=*/1)
+ .setImm(kOffset1Reg, /*imm=*/1)
+ .setImm(kStoredReg, /*imm=*/42)
+ .setImm(kLoadIdx0Reg, /*imm=*/1)
+ .setImm(kLoadIdx1Reg, /*imm=*/2)
+ // buf = int64_t[2][3], row-major strides (3, 1)
+ .instruction(OpCode::BUFFER_CREATE, {kBufReg, kElemI64TypeIndex, /*rank=*/2,
+ /*shape=*/kDim0Reg, kDim1Reg,
+ /*strides=*/kStride0Reg, kStride1Reg})
+ // buf[1][2] = 42
+ .instruction(OpCode::BUFFER_STORE, {kBufReg, /*value=*/kStoredReg, /*rank=*/2,
+ /*indices=*/kLoadIdx0Reg, kLoadIdx1Reg})
+ // loaded = buf[1][2] -> 42
+ .instruction(OpCode::BUFFER_LOAD, {/*dst=*/kLoadedReg, kBufReg, /*rank=*/2,
+ /*indices=*/kLoadIdx0Reg, kLoadIdx1Reg})
+ // srcDim = buf.shape[1] -> 3
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/kSrcDimReg, kBufReg, /*dim=*/kOffset1Reg})
+ // view = buf[1:2, 1:3] -> shape (1, 2)
+ .instruction(OpCode::BUFFER_SUBVIEW, {/*dst=*/kViewReg, /*src=*/kBufReg, /*rank=*/2,
+ /*offsets=*/kOffset0Reg, kOffset1Reg,
+ /*sizes=*/kOffset1Reg, kDim0Reg,
+ /*strides=*/kOffset1Reg, kOffset1Reg})
+ // viewDim = view.shape[1] -> 2
+ .instruction(OpCode::BUFFER_GET_DIM, {/*dst=*/kViewDimReg, kViewReg, /*dim=*/kOffset1Reg})
+ .retv({kSrcDimReg, kViewDimReg, kLoadedReg});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {};
+ auto results = std::vector<npu_vm_value>(3, intel_npu::vm::makeI64(0));
+ ASSERT_EQ(callWithResults(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME, args, results), NPU_VM_SUCCESS);
+
+ // Source dim 1 of the 2x3 buffer
+ EXPECT_EQ(results.at(0).i64, 3);
+ // Subview dim 1 comes from the requested size, not the source
+ EXPECT_EQ(results.at(1).i64, 2);
+ // Value round-tripped through buffer.store / buffer.load
+ EXPECT_EQ(results.at(2).i64, 42);
+}
+
+// buffer.copy accepts a copy only when the two buffer descriptors agree, element type included. A memref
+// parameter's descriptor is built by extractMemRef rather than by an opcode, so it has to name its element type
+// the same way buffer.create / buffer.view / buffer.from_const do. addFunction interns a function's parameter
+// types, then its result types, then its function type, in the order functions are added, so the leading helper
+// pins i64 to index 0 and leaves the entrypoint's BufferType at index 2. Naming the wrong one therefore fails
+// this test instead of passing by coincidence.
+TEST_F(VirtualMachineInstructionTest, BufferCopyIntoMemRefParameterMatchesBytecodeBuiltDescriptor) {
+ const auto i64 = getInt64Type();
+
+ constexpr int16_t kElemI64TypeIndex = 0;
+ constexpr int64_t kNumElements = 4;
+ constexpr int64_t kStoredValue = 0x123456789ABCDEF;
+ constexpr int16_t kOutputParamReg = 7;
+
+ intel_npu::vm::BufferType bufferType{};
+ bufferType.dataTypeIndex = kElemI64TypeIndex;
+ bufferType.rank = 1;
+ bufferType.shape = {kNumElements};
+ bufferType.strides = {1};
+
+ auto elemTypeHolder = BytecodeBuilder::FunctionBuilder("elem_type_holder", /*numGeneralRegisters=*/1,
+ /*paramTypes=*/{i64},
+ /*resultTypes=*/{},
+ /*isEntrypoint=*/false)
+ .ret();
+
+ auto function = BytecodeBuilder::FunctionBuilder(NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ /*numGeneralRegisters=*/8,
+ /*paramTypes=*/{intel_npu::vm::Type{bufferType}},
+ /*resultTypes=*/{},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/kNumElements)
+ .setImm(/*dst=*/2, /*imm=*/1)
+ .instruction(OpCode::BUFFER_CREATE, {/*dst=*/0, kElemI64TypeIndex, /*rank=*/1,
+ /*shape=*/1,
+ /*strides=*/2})
+ .setImm(/*dst=*/3, /*imm=*/kStoredValue)
+ .setImm(/*dst=*/4, /*imm=*/0)
+ .instruction(OpCode::BUFFER_STORE, {/*buffer=*/0, /*value=*/3, /*rank=*/1, /*indices=*/4})
+ .instruction(OpCode::BUFFER_COPY, {/*dst=*/kOutputParamReg, /*src=*/0})
+ .ret();
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(elemTypeHolder).addFunction(function).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME), NPU_VM_SUCCESS);
+
+ std::vector<int64_t> output(kNumElements, 0);
+ std::vector<int64_t> sizes = {kNumElements};
+ std::vector<int64_t> strides = {1};
+
+ // Destroy on scope exit so a failing assertion below does not leak the memref
+ npu_vm_runtime_mem_ref_handle_t outputMemRef = nullptr;
+ ASSERT_EQ(npuVMRuntimeCreateMemRef(/*dimsCount=*/1, &outputMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+ ASSERT_EQ(npuVMRuntimeSetMemRef(outputMemRef, output.data(), output.data(), /*offset=*/0, sizes.data(),
+ strides.data(), /*dimsCount=*/1),
+ NPU_VM_RUNTIME_RESULT_SUCCESS);
+
+ npu_vm_runtime_execute_params_t params{};
+ params.pOutputs = &outputMemRef;
+ params.numOfOutputs = 1;
+
+ EXPECT_EQ(npu_vm_infer(engine, &params), NPU_VM_SUCCESS);
+ EXPECT_EQ(output.at(0), kStoredValue);
+
+ EXPECT_EQ(npuVMRuntimeDestroyMemRef(outputMemRef), NPU_VM_RUNTIME_RESULT_SUCCESS);
+}
+
+// NOLINTEND(cppcoreguidelines-avoid-magic-numbers)
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/comparison.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/comparison.cpp
new file mode 100644
index 00000000000..779d21368f4
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/comparison.cpp
@@ -0,0 +1,299 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <initializer_list>
+#include <optional>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+namespace {
+
+struct CmpInstructionParams {
+ OpCode opcode;
+ int64_t lhs;
+ int64_t rhs;
+ CmpPredicate predicate;
+ std::optional<bool> isSigned;
+ bool expected;
+
+ CmpInstructionParams(OpCode opcode, int64_t lhs, int64_t rhs, CmpPredicate predicate, bool isSigned, bool expected)
+ : opcode(opcode), lhs(lhs), rhs(rhs), predicate(predicate), isSigned(isSigned), expected(expected) {
+ }
+ CmpInstructionParams(OpCode opcode, int64_t lhs, int64_t rhs, CmpPredicate predicate, bool expected)
+ : opcode(opcode), lhs(lhs), rhs(rhs), predicate(predicate), isSigned(std::nullopt), expected(expected) {
+ }
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const CmpInstructionParams& params) {
+ os << "{ opcode=" << static_cast<uint16_t>(params.opcode) << ", lhs=" << params.lhs << ", rhs=" << params.rhs
+ << ", predicate=" << static_cast<uint16_t>(params.predicate)
+ << ", isSigned=" << (params.isSigned.has_value() ? std::to_string(*params.isSigned) : "none")
+ << ", expected=" << params.expected << "}";
+ return os;
+ }
+};
+
+class VirtualMachineComparisonInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<CmpInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<CmpInstructionParams>& obj) {
+ const auto predicateToStr = [](CmpPredicate predicate) {
+ switch (predicate) {
+ case CmpPredicate::EQ:
+ return "EQ";
+ case CmpPredicate::NE:
+ return "NE";
+ case CmpPredicate::GT:
+ return "GT";
+ case CmpPredicate::GTE:
+ return "GTE";
+ case CmpPredicate::LT:
+ return "LT";
+ case CmpPredicate::LTE:
+ return "LTE";
+ default:
+ return "unknown";
+ }
+ };
+
+ std::ostringstream result;
+ result << "opcode=" << static_cast<uint16_t>(obj.param.opcode) << "_";
+ result << "lhs=" << obj.param.lhs << "_";
+ result << "rhs=" << obj.param.rhs << "_";
+ result << "predicate=" << predicateToStr(obj.param.predicate) << "_";
+ result << "isSigned=" << (obj.param.isSigned.has_value() ? std::to_string(*obj.param.isSigned) : "none") << "_";
+ result << "expected=" << obj.param.expected;
+ return result.str();
+ }
+};
+
+} // namespace
+
+TEST_P(VirtualMachineComparisonInstructionTest, Execute) {
+ const auto& params = GetParam();
+
+ auto flag = static_cast<int16_t>(params.predicate);
+ if (params.isSigned.value_or(false)) {
+ constexpr auto numBitsCmpFn = 8;
+ flag |= (1 << numBitsCmpFn);
+ }
+
+ const auto funcName = "test";
+ auto bytecode =
+ BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .instruction(params.opcode, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2, /*flag=*/flag})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(params.lhs), intel_npu::vm::makeI64(params.rhs)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(static_cast<bool>(results.at(0).i64), params.expected);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ CMP_I64, VirtualMachineComparisonInstructionTest,
+ testing::Values(
+ // Equal
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::EQ, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::EQ, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::EQ, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::EQ, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::EQ, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::EQ, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -5, CmpPredicate::EQ, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::EQ, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::EQ, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::EQ, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::EQ, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::EQ,
+ /*isSigned=*/false, false}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::EQ,
+ /*isSigned=*/true, false}, // 0xFFFFFFFFFFFFFFFF is -1
+ // Not equal
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::NE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::NE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::NE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::NE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::NE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::NE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -5, CmpPredicate::NE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::NE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::NE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::NE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::NE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::NE,
+ /*isSigned=*/false, true}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::NE,
+ /*isSigned=*/true, true}, // 0xFFFFFFFFFFFFFFFF is -1
+ // Greater than
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::GT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::GT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::GT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::GT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::GT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::GT, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -6, CmpPredicate::GT, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::GT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::GT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::GT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::GT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MIN_I64, CmpPredicate::GT, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::GT,
+ /*isSigned=*/false, false}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::GT,
+ /*isSigned=*/true, true}, // 0xFFFFFFFFFFFFFFFF is -1
+ // Greater than or equal
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::GTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::GTE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::GTE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::GTE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::GTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::GTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -6, CmpPredicate::GTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::GTE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::GTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::GTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::GTE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MIN_I64, CmpPredicate::GTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::GTE,
+ /*isSigned=*/false, false}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::GTE,
+ /*isSigned=*/true, true}, // 0xFFFFFFFFFFFFFFFF is -1
+ // Less than
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::LT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::LT, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::LT, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::LT, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::LT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::LT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -6, CmpPredicate::LT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::LT, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::LT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::LT, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::LT, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MIN_I64, CmpPredicate::LT, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::LT,
+ /*isSigned=*/false, true}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::LT,
+ /*isSigned=*/true, false}, // 0xFFFFFFFFFFFFFFFF is -1
+ // Less than or equal
+ CmpInstructionParams{OpCode::CMP_I64, 0, 0, CmpPredicate::LTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 0, 5, CmpPredicate::LTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, -5, 0, CmpPredicate::LTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 6, CmpPredicate::LTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 5, 5, CmpPredicate::LTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, 6, 5, CmpPredicate::LTE, /*isSigned=*/false, false},
+ CmpInstructionParams{OpCode::CMP_I64, -5, -6, CmpPredicate::LTE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, -6, -5, CmpPredicate::LTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MIN_I64, CmpPredicate::LTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MAX_I64, CmpPredicate::LTE, /*isSigned=*/false, true},
+ CmpInstructionParams{OpCode::CMP_I64, MIN_I64, MAX_I64, CmpPredicate::LTE, /*isSigned=*/true, true},
+ CmpInstructionParams{OpCode::CMP_I64, MAX_I64, MIN_I64, CmpPredicate::LTE, /*isSigned=*/true, false},
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::LTE,
+ /*isSigned=*/false, true}, // 0xFFFFFFFFFFFFFFFF is a large unsigned value
+ CmpInstructionParams{OpCode::CMP_I64, 0, static_cast<int64_t>(0xFFFFFFFFFFFFFFFF), CmpPredicate::LTE,
+ /*isSigned=*/true, false}), // 0xFFFFFFFFFFFFFFFF is -1
+ VirtualMachineComparisonInstructionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(
+ CMP_F64, VirtualMachineComparisonInstructionTest,
+ testing::Values(
+ // Equal
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::EQ, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::EQ, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::EQ, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::EQ, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::EQ, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::EQ, false},
+ // Not equal
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::NE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::NE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::NE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::NE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::NE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::NE, true},
+ // Greater than
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::GT, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::GT, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::GT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::GT, false},
+ // Greater than or equal
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::GTE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::GTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::GTE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::GTE, false},
+ // Less than
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::LT, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::LT, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::LT, false},
+ // Less than or equal
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(0.0), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(0.0), f64Bits(-0.0), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(1.0), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(-1.0), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-1.0), f64Bits(1.0), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(1.0), f64Bits(-1.0), CmpPredicate::LTE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(INF_F64), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(-INF_F64), f64Bits(-INF_F64), CmpPredicate::LTE, true},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(INF_F64), f64Bits(-INF_F64), CmpPredicate::LTE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(NAN_F64), CmpPredicate::LTE, false},
+ CmpInstructionParams{OpCode::CMP_F64, f64Bits(NAN_F64), f64Bits(1.0), CmpPredicate::LTE, false}),
+ VirtualMachineComparisonInstructionTest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/conditional_assignment.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/conditional_assignment.cpp
new file mode 100644
index 00000000000..9824be1be1b
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/conditional_assignment.cpp
@@ -0,0 +1,92 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <initializer_list>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+namespace {
+
+struct SelectInstructionParams {
+ int64_t condition;
+ int64_t trueValue;
+ int64_t falseValue;
+ int64_t expected;
+
+ SelectInstructionParams(int64_t condition, int64_t trueValue, int64_t falseValue, int64_t expected)
+ : condition(condition), trueValue(trueValue), falseValue(falseValue), expected(expected) {
+ }
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const SelectInstructionParams& params) {
+ os << "{ condition=" << params.condition << ", trueValue=" << params.trueValue
+ << ", falseValue=" << params.falseValue << ", expected=" << params.expected << " }";
+ return os;
+ }
+};
+
+class VirtualMachineSelectInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<SelectInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<SelectInstructionParams>& obj) {
+ std::ostringstream result;
+ result << "condition=" << obj.param.condition << "_";
+ result << "trueValue=" << obj.param.trueValue << "_";
+ result << "falseValue=" << obj.param.falseValue << "_";
+ result << "expected=" << obj.param.expected;
+ return result.str();
+ }
+};
+
+} // namespace
+
+TEST_P(VirtualMachineSelectInstructionTest, Execute) {
+ const auto& params = GetParam();
+
+ const auto funcName = "test";
+ auto bytecode =
+ BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/4,
+ {getInt64Type(), getInt64Type(), getInt64Type()},
+ {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .instruction(OpCode::SELECT, {/*dst=*/0, /*cond=*/1, /*true=*/2, /*false=*/3})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(params.condition),
+ intel_npu::vm::makeI64(params.trueValue),
+ intel_npu::vm::makeI64(params.falseValue)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, params.expected);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ Select, VirtualMachineSelectInstructionTest,
+ testing::Values(SelectInstructionParams{/*condition=*/0, /*trueValue=*/42, /*falseValue=*/84, /*expected=*/84},
+ SelectInstructionParams{/*condition=*/1, /*trueValue=*/42, /*falseValue=*/84, /*expected=*/42},
+ SelectInstructionParams{/*condition=*/-1, /*trueValue=*/42, /*falseValue=*/84,
+ /*expected=*/42}),
+ VirtualMachineSelectInstructionTest::getTestCaseName);
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/control_flow.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/control_flow.cpp
new file mode 100644
index 00000000000..2bbca9ff2c5
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/control_flow.cpp
@@ -0,0 +1,742 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <functional>
+#include <initializer_list>
+#include <optional>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+namespace {
+
+class VirtualMachineCallInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<ThreeOperandInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<ThreeOperandInstructionParams>& obj) {
+ return VirtualMachineThreeOperandInstructionTest::getTestCaseName(obj);
+ }
+};
+
+using VirtualMachineJmpInstructionTest = VirtualMachineInstructionTest;
+
+struct JmpSelectTestParams {
+ int64_t input;
+ int64_t expected;
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const JmpSelectTestParams& params) {
+ os << "{ input=" << params.input << ", expected=" << params.expected << " }";
+ return os;
+ }
+};
+
+// Shared base for the jump/branch fixtures. Each derived fixture keeps a distinct type so that
+// its own TEST_P body is instantiated independently, while reusing a single test-name formatter.
+class JmpSelectTestBase :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<JmpSelectTestParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<JmpSelectTestParams>& obj) {
+ std::ostringstream result;
+ result << "input=" << obj.param.input << "_expected=" << obj.param.expected;
+ return result.str();
+ }
+};
+
+class VirtualMachineJmpTest : public JmpSelectTestBase {};
+
+class VirtualMachineJmpBackwardTest : public JmpSelectTestBase {};
+
+// Registers (3 total: 2 value + 1 param):
+// firstParamRegIndex = numRegisters - numParams = 3 - 1 = 2
+// 0=rZero 1=rResult 2=rA (input param, last reg)
+// Byte layout:
+// [ 0] set_imm rZero, 0 (12B)
+// [12] je 36, rA, rZero (14B) if rA == 0: jump to [48]
+// [26] set_imm rResult, 2 (12B) not-taken (rA != 0)
+// [38] jmp 22 (10B) -> [60] (retv)
+// [48] set_imm rResult, 1 (12B) taken (rA == 0)
+// [60] retv rResult (6B)
+class VirtualMachineJETest : public JmpSelectTestBase {};
+
+class VirtualMachineJNETest : public JmpSelectTestBase {};
+
+struct JumpBoundsCheckParams {
+ std::string testName;
+ std::function<std::vector<uint8_t>()> buildBytecode;
+};
+
+class VirtualMachineJumpBoundsCheckTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<JumpBoundsCheckParams> {};
+
+struct AssertInstructionParams {
+ int64_t condition;
+ int16_t messageIndex;
+ npu_vm_result expectedStatus;
+ std::optional<int64_t> expectedResult;
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const AssertInstructionParams& params) {
+ os << "{ condition=" << params.condition << ", messageIndex=" << params.messageIndex
+ << ", expectedStatus=" << static_cast<uint32_t>(params.expectedStatus) << ", expectedResult="
+ << (params.expectedResult.has_value() ? std::to_string(*params.expectedResult) : "none")
+ << " }";
+ return os;
+ }
+};
+
+class VirtualMachineAssertInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<AssertInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<AssertInstructionParams>& obj) {
+ std::ostringstream result;
+ result << "condition=" << obj.param.condition << "_";
+ result << "messageIndex=" << obj.param.messageIndex << "_";
+ result << "status=" << static_cast<uint32_t>(obj.param.expectedStatus) << "_";
+ result << "result=";
+ if (obj.param.expectedResult.has_value()) {
+ result << *obj.param.expectedResult;
+ } else {
+ result << "none";
+ }
+ return result.str();
+ }
+};
+
+} // namespace
+
+// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers)
+
+// Program layout (3 registers):
+// func(%0 = opcode(%1, %2)):
+// opcode %0, %1, %2
+// Entrypoint that calls func:
+// set.imm 0, callee_idx
+// call 0, 1, {dst_regs}, 2, {arg_regs} (callee index is held in register 0)
+// retv 1, %0
+TEST_P(VirtualMachineCallInstructionTest, Execute) {
+ const auto& params = GetParam();
+
+ auto builder = BytecodeBuilder{}.addFunction(BytecodeBuilder::FunctionBuilder("callee", /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type()})
+ .instruction(params.opcode, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}));
+ const auto calleeIndex = builder.getFunctionIndex("callee");
+ ASSERT_TRUE(calleeIndex.has_value());
+
+ const auto entryFuncName = "entry";
+ const auto functionIndexReg = 0;
+ const auto bytecode =
+ builder.addFunction(
+ BytecodeBuilder::FunctionBuilder(entryFuncName, /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/functionIndexReg, /*imm=*/static_cast<int64_t>(calleeIndex.value()))
+ .call(functionIndexReg, /*dstRegs=*/{0}, /*argRegs=*/{1, 2})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+
+ ASSERT_EQ(loadEntrypoint(bytecode, entryFuncName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(params.lhs), intel_npu::vm::makeI64(params.rhs)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(entryFuncName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, std::get<int64_t>(params.expected));
+}
+
+// Program layout (4 registers):
+// func:
+// opcode %0, %1, %2
+// Entrypoint that calls func:
+// set.imm 1, callee_idx
+// call 1, 1, {dst_regs}, 2, {arg_regs} (function that contains an arith op [like Add])
+// set.imm 1, callee_idx
+// call 1, 1, {dst_regs}, 2, {arg_regs} (function that contains an arith op [like Add] - result of the
+// previous add and second attr: add(dst, %1) to test caller state across multiple calls) retv 1, %0
+TEST_P(VirtualMachineCallInstructionTest, ExecuteTwice) {
+ const auto& params = GetParam();
+
+ auto builder = BytecodeBuilder{}.addFunction(BytecodeBuilder::FunctionBuilder("callee", /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type()})
+ .instruction(params.opcode, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}));
+ const auto calleeIndex = builder.getFunctionIndex("callee");
+ ASSERT_TRUE(calleeIndex.has_value());
+
+ const auto entryFuncName = "entry_twice";
+ const auto functionIndexReg = 1;
+ const auto bytecode =
+ builder.addFunction(
+ BytecodeBuilder::FunctionBuilder(entryFuncName, /*numGeneralRegisters=*/4,
+ {getInt64Type(), getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/functionIndexReg, /*imm=*/static_cast<int64_t>(calleeIndex.value()))
+ .call(functionIndexReg, /*dstRegs=*/{0}, /*argRegs=*/{2, 3})
+ .call(functionIndexReg, /*dstRegs=*/{0}, /*argRegs=*/{0, 2})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, entryFuncName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(params.lhs), intel_npu::vm::makeI64(params.rhs)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(entryFuncName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, std::get<int64_t>(params.expected) + params.lhs);
+}
+
+// Program layout (4 registers):
+// func_add:
+// opcode %0, %1, %2
+// func_mul:
+// opcode %0, %1, %2
+// Entrypoint that calls func:
+// set.imm 1, add_callee_idx
+// call 1, 1, {dst_regs}, 2, {arg_regs} (function that contains an arith op [like Add])
+// set.imm 1, mul_callee_idx
+// call 1, 1, {dst_regs}, 2, {arg_regs} (function that contains an arith op [like Mul] - result of the
+// previous add and second attr: mul(dst, %1) to test caller state across multiple calls) retv 1, %0
+TEST_P(VirtualMachineCallInstructionTest, ExecuteTwiceDifferentFunctions) {
+ const auto& params = GetParam();
+
+ auto builder = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder("callee", /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type()}, /*isEntrypoint=*/false)
+ .instruction(params.opcode, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}))
+ .addFunction(BytecodeBuilder::FunctionBuilder("callee2", /*numGeneralRegisters=*/3,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type()}, /*isEntrypoint=*/false)
+ .instruction(OpCode::MUL_I64, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}));
+ const auto firstCalleeIndex = builder.getFunctionIndex("callee");
+ ASSERT_TRUE(firstCalleeIndex.has_value());
+ const auto secondCalleeIndex = builder.getFunctionIndex("callee2");
+ ASSERT_TRUE(secondCalleeIndex.has_value());
+
+ const auto entryFuncName = "entry_twice_different_callees";
+ const auto functionIndexReg = 1;
+ const auto bytecode = builder.addFunction(BytecodeBuilder::FunctionBuilder(entryFuncName, /*numGeneralRegisters=*/4,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type()}, /*isEntrypoint=*/true)
+ .setImm(/*dst=*/functionIndexReg,
+ /*imm=*/static_cast<int64_t>(firstCalleeIndex.value()))
+ .call(functionIndexReg, /*dstRegs=*/{0}, /*argRegs=*/{2, 3})
+ .setImm(/*dst=*/functionIndexReg,
+ /*imm=*/static_cast<int64_t>(secondCalleeIndex.value()))
+ .call(functionIndexReg, /*dstRegs=*/{0}, /*argRegs=*/{0, 2})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, entryFuncName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(params.lhs), intel_npu::vm::makeI64(params.rhs)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(entryFuncName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, std::get<int64_t>(params.expected) * params.lhs);
+}
+
+INSTANTIATE_TEST_SUITE_P(CallOpTests, VirtualMachineCallInstructionTest,
+ testing::Values(
+ // Zero
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 0, 0, int64_t{0}},
+ // Basic positive
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 1, 1, int64_t{2}},
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 10, 32, int64_t{42}},
+ // Mixed signs
+ ThreeOperandInstructionParams{OpCode::ADD_I64, -5, 5, int64_t{0}},
+ ThreeOperandInstructionParams{OpCode::ADD_I64, 100, -1, int64_t{99}},
+ // Both negative
+ ThreeOperandInstructionParams{OpCode::ADD_I64, -10, -20, int64_t{-30}}),
+ VirtualMachineCallInstructionTest::getTestCaseName);
+
+TEST_F(VirtualMachineCallInstructionTest, CallChainThreeLevelsDeepPropagatesResult) {
+ auto builder = BytecodeBuilder{}.addFunction(
+ BytecodeBuilder::FunctionBuilder("inner", /*numGeneralRegisters=*/3, {getInt64Type(), getInt64Type()},
+ {getInt64Type()})
+ .instruction(OpCode::ADD_I64, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}));
+ const auto innerIndex = builder.getFunctionIndex("inner");
+ ASSERT_TRUE(innerIndex.has_value());
+
+ // middle has 4 registers: params occupy regs [2, 3], general regs are [0, 1]. Reg 1 holds the callee index
+ builder.addFunction(BytecodeBuilder::FunctionBuilder("middle", /*numGeneralRegisters=*/4,
+ {getInt64Type(), getInt64Type()}, {getInt64Type()})
+ .setImm(/*dst=*/1, /*imm=*/static_cast<int64_t>(innerIndex.value()))
+ .call(/*functionIndexReg=*/1, /*dstRegs=*/{0}, /*argRegs=*/{2, 3})
+ .retv(/*resultRegs=*/{0}));
+ const auto middleIndex = builder.getFunctionIndex("middle");
+ ASSERT_TRUE(middleIndex.has_value());
+
+ const auto entryFuncName = "entry";
+ const auto bytecode =
+ builder.addFunction(BytecodeBuilder::FunctionBuilder(entryFuncName, /*numGeneralRegisters=*/4,
+ {getInt64Type(), getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/1, /*imm=*/static_cast<int64_t>(middleIndex.value()))
+ .call(/*functionIndexReg=*/1, /*dstRegs=*/{0}, /*argRegs=*/{2, 3})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+
+ ASSERT_EQ(loadEntrypoint(bytecode, entryFuncName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(20), intel_npu::vm::makeI64(22)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(entryFuncName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, 42);
+}
+
+TEST_F(VirtualMachineCallInstructionTest, RetvRoutesMultipleResultsToCallerDestinationRegisters) {
+ // swap has 2 registers, both parameters [0, 1]; retv returns them reversed
+ auto builder = BytecodeBuilder{}.addFunction(BytecodeBuilder::FunctionBuilder("swap", /*numGeneralRegisters=*/2,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type(), getInt64Type()})
+ .retv(/*resultRegs=*/{1, 0}));
+ const auto swapIndex = builder.getFunctionIndex("swap");
+ ASSERT_TRUE(swapIndex.has_value());
+
+ // entry has 5 registers: params occupy regs [3, 4], general regs are [0, 1, 2]. Reg 2 holds the callee index
+ const auto entryFuncName = "entry";
+ const auto bytecode =
+ builder.addFunction(BytecodeBuilder::FunctionBuilder(entryFuncName, /*numGeneralRegisters=*/5,
+ {getInt64Type(), getInt64Type()},
+ {getInt64Type(), getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(/*dst=*/2, /*imm=*/static_cast<int64_t>(swapIndex.value()))
+ .call(/*functionIndexReg=*/2, /*dstRegs=*/{0, 1},
+ /*argRegs=*/{3, 4})
+ .retv(/*resultRegs=*/{0, 1}))
+ .build();
+
+ ASSERT_EQ(loadEntrypoint(bytecode, entryFuncName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(7), intel_npu::vm::makeI64(9)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0), intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(entryFuncName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, 9);
+ EXPECT_EQ(results.at(1).i64, 7);
+}
+
+TEST_F(VirtualMachineCallInstructionTest, SelfRecursiveFunctionComputesTriangularNumber) {
+ // The `sum` function computes sum(n) = n + sum(n - 1) with base case sum(0) = 0, pushing one frame per recursion
+ // level.
+ // Byte layout (offsets are PC-relative from the function body start):
+ // [ 0] set_imm rZero, 0 (12B)
+ // [12] je 72, rN, rZero -> base case (14B)
+ // [26] set_imm rOne, 1 (12B)
+ // [38] sub.i64 rRec, rN, rOne (8B)
+ // [46] set_imm rFunc, sumFnIndex (12B)
+ // [58] call rFunc, {rRec}, {rRec} (12B)
+ // [70] add.i64 rResult, rN, rRec (8B)
+ // [78] retv {rResult} (6B)
+ // [84] set_imm rResult, 0 (base case) (12B)
+ // [96] retv {rResult} (6B)
+
+ constexpr int64_t sumFnIndex = 0; // The index of the sum function within the function section
+ constexpr int64_t jumpToBaseCase = 72; // The relative offset to the base case
+ constexpr int64_t numRegs = 6; // Total number of registers used by the function (general: [0-4], params: [5])
+
+ constexpr int16_t rResult = 0; // The result register
+ constexpr int16_t rFunc = 1; // The register to hold the function index for the recursive call
+ constexpr int16_t rZero = 2; // The register to hold the constant zero for the base case comparison
+ constexpr int16_t rOne = 3; // The register to hold the constant one for decrementing n in the recursive case
+ constexpr int16_t rRec = 4; // The register to hold the result of the recursive call sum(n - 1)
+ constexpr int16_t rN = 5; // The register to hold the input parameter n
+
+ const auto funcName = "sum";
+ auto builder = BytecodeBuilder{};
+ builder.addFunction(BytecodeBuilder::FunctionBuilder(funcName, numRegs, {getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(rZero, 0)
+ .je(jumpToBaseCase, rN, rZero)
+ .setImm(rOne, 1)
+ .instruction(OpCode::SUB_I64, {rRec, rN, rOne})
+ .setImm(rFunc, sumFnIndex)
+ .call(/*functionIndexReg=*/rFunc, /*dstRegs=*/{rRec}, /*argRegs=*/{rRec})
+ .instruction(OpCode::ADD_I64, {rResult, rN, rRec})
+ .retv(/*resultRegs=*/{rResult})
+ .setImm(rResult, 0)
+ .retv(/*resultRegs=*/{rResult}));
+ const auto resolvedIndex = builder.getFunctionIndex(funcName);
+ ASSERT_TRUE(resolvedIndex.has_value());
+ ASSERT_EQ(resolvedIndex.value(), static_cast<uint64_t>(sumFnIndex));
+
+ const auto bytecode = builder.build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ struct RecursionCase {
+ int64_t n;
+ int64_t expected;
+ };
+ for (const auto& testCase : {RecursionCase{0, 0}, RecursionCase{1, 1}, RecursionCase{5, 15}, RecursionCase{10, 55},
+ RecursionCase{1000, 500500}}) {
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(testCase.n)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(-1)};
+ ASSERT_EQ(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS) << "n=" << testCase.n;
+ EXPECT_EQ(results.at(0).i64, testCase.expected) << "n=" << testCase.n;
+ ASSERT_EQ(npu_vm_reset_state(engine, /*resetExecutionContext=*/false), NPU_VM_SUCCESS);
+ }
+
+ const auto overMaxDepthTestCase = 1001;
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(overMaxDepthTestCase)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(-1)};
+ ASSERT_NE(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS) << "n=" << overMaxDepthTestCase;
+}
+
+// Registers (3 total: 2 value + 1 param):
+// firstParamRegIndex = numRegisters - numParams = 3 - 1 = 2
+// 0=rZero 1=rResult 2=rA (input param, last reg)
+// Byte layout:
+// [ 0] set_imm rZero, 0 (12B)
+// [12] jne 36, rA, rZero (14B) if rA != 0: jump to [48]
+// [26] set_imm rResult, 1 (12B) not-taken (rA == 0)
+// [38] jmp 22 (10B) -> [60] (retv)
+// [48] set_imm rResult, 2 (12B) taken (rA != 0)
+// [60] retv rResult (6B)
+TEST_P(VirtualMachineJmpTest, SelectJmp) {
+ constexpr int16_t rZero = 0;
+ constexpr int16_t rResult = 1;
+ constexpr int16_t rA = 2; // input param: firstParamRegIndex = numRegs(3) - numParams(1) = 2
+
+ const auto funcName = "jmp_select_test";
+ const auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/3,
+ {getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(rZero, 0)
+ .jne(36, rA, rZero)
+ .setImm(rResult, 1)
+ .jmp(22)
+ .setImm(rResult, 2)
+ .retv({rResult}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(GetParam().input)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, GetParam().expected);
+}
+
+INSTANTIATE_TEST_SUITE_P(JmpSelect, VirtualMachineJmpTest,
+ testing::Values(JmpSelectTestParams{0, 1}, JmpSelectTestParams{1, 2}),
+ VirtualMachineJmpTest::getTestCaseName);
+
+TEST_P(VirtualMachineJETest, ConditionalJump) {
+ constexpr int16_t rZero = 0;
+ constexpr int16_t rResult = 1;
+ constexpr int16_t rA = 2; // input param: firstParamRegIndex = numRegs(3) - numParams(1) = 2
+
+ const auto funcName = "je_test";
+ const auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/3,
+ {getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(rZero, 0)
+ .je(36, rA, rZero)
+ .setImm(rResult, 2)
+ .jmp(22)
+ .setImm(rResult, 1)
+ .retv({rResult}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(GetParam().input)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, GetParam().expected);
+}
+
+// Same layout as JE test, but jne instead of je.
+// When rA != 0: jne taken → result = 1
+// When rA == 0: jne not taken → result = 2
+TEST_P(VirtualMachineJNETest, ConditionalJump) {
+ constexpr int16_t rZero = 0;
+ constexpr int16_t rResult = 1;
+ constexpr int16_t rA = 2; // input param: firstParamRegIndex = numRegs(3) - numParams(1) = 2
+
+ const auto funcName = "jne_test";
+ const auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/3,
+ {getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .setImm(rZero, 0)
+ .jne(36, rA, rZero)
+ .setImm(rResult, 2)
+ .jmp(22)
+ .setImm(rResult, 1)
+ .retv({rResult}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(GetParam().input)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, GetParam().expected);
+}
+
+INSTANTIATE_TEST_SUITE_P(JEConditionalJump, VirtualMachineJETest,
+ testing::Values(JmpSelectTestParams{0, 1}, JmpSelectTestParams{5, 2},
+ JmpSelectTestParams{-1, 2}),
+ VirtualMachineJETest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(JNEConditionalJump, VirtualMachineJNETest,
+ testing::Values(JmpSelectTestParams{5, 1}, JmpSelectTestParams{-1, 1},
+ JmpSelectTestParams{0, 2}),
+ VirtualMachineJNETest::getTestCaseName);
+
+// Registers (4 total: 3 value + 1 param):
+// firstParamRegIndex = numRegisters - numParams = 4 - 1 = 3
+// 0=rCounter 1=rOne 2=rZero 3=rA (input param, last reg)
+// Byte layout:
+// [ 0] set rCounter, rA copy param into working register ( 6B)
+// [ 6] set_imm rOne, 1 (12B)
+// [18] set_imm rZero, 0 (12B)
+// [30] sub_i64 rCounter, rCounter, rOne ( 8B)
+// [38] jne -8, rCounter, rZero if != 0: _pc += -8 → [30] (14B)
+// [52] retv rCounter returns 0 when loop exits ( 6B)
+TEST_P(VirtualMachineJmpBackwardTest, BackwardJump) {
+ constexpr int16_t rCounter = 0;
+ constexpr int16_t rOne = 1;
+ constexpr int16_t rZero = 2;
+ constexpr int16_t rA = 3; // input param: firstParamRegIndex = numRegs(4) - numParams(1) = 3
+
+ const auto funcName = "jmp_backward_test";
+ const auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/4,
+ {getInt64Type()}, {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .instruction(OpCode::SET, {rCounter, rA})
+ .setImm(rOne, 1)
+ .setImm(rZero, 0)
+ .instruction(OpCode::SUB_I64, {rCounter, rCounter, rOne})
+ .jne(-8, rCounter, rZero)
+ .retv({rCounter}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(GetParam().input)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, parameters, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, GetParam().expected);
+}
+
+INSTANTIATE_TEST_SUITE_P(JmpBackward, VirtualMachineJmpBackwardTest,
+ testing::Values(JmpSelectTestParams{1, 0}, JmpSelectTestParams{3, 0},
+ JmpSelectTestParams{5, 0}),
+ VirtualMachineJmpBackwardTest::getTestCaseName);
+
+// Regression test: before the 64-bit offset fix, getRelativeOffset() used checked_cast<int16_t>
+// which would abort on any jump offset > INT16_MAX (32767).
+// Layout:
+// [ 0] jmp 32788 (10B) — forward jump past all padding
+// [ 10] set rResult, rResult × 5463 (32778B) — unreachable padding
+// [32788] set_imm rResult, 1 (12B) — jump lands here
+// [32800] retv {rResult} (6B)
+TEST_F(VirtualMachineJmpInstructionTest, JmpForwardOffsetExceedsInt16Range) {
+ constexpr int16_t rResult = 0;
+ const auto funcName = "large_jmp_test";
+
+ constexpr int64_t padCount = 5463; // 5463 * 6 = 32778 bytes > INT16_MAX
+ constexpr int64_t setInstrSize = 6;
+ constexpr int64_t jmpInstrSize = 10;
+ const int64_t jmpOffset = jmpInstrSize + padCount * setInstrSize; // 32788
+
+ auto fb = BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/1, {}, {getInt64Type()},
+ /*isEntrypoint=*/true);
+ fb.jmp(jmpOffset);
+ for (int64_t i = 0; i < padCount; ++i) {
+ fb.instruction(OpCode::SET, {rResult, rResult});
+ }
+ fb.setImm(rResult, 1);
+ fb.retv({rResult});
+
+ const auto bytecode = BytecodeBuilder{}.addFunction(fb).build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, /*args=*/{}, results), NPU_VM_SUCCESS);
+ EXPECT_EQ(results.at(0).i64, 1);
+}
+
+TEST_P(VirtualMachineJumpBoundsCheckTest, Execute) {
+ const auto& p = GetParam();
+ const auto bytecode = p.buildBytecode();
+ const auto funcName = "test";
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+ EXPECT_FALSE(npu_vm_call(engine, funcName, /*num_arguments=*/0, /*arguments=*/nullptr) == NPU_VM_SUCCESS);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ JumpBoundsCheck, VirtualMachineJumpBoundsCheckTest,
+ testing::Values(JumpBoundsCheckParams{"JmpPositiveOffsetBeyondEnd",
+ [] {
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/0, {},
+ {}, /*isEntrypoint=*/true)
+ .jmp(10000)
+ .ret())
+ .build();
+ }},
+ JumpBoundsCheckParams{"JmpNegativeOffsetBeforeStart",
+ [] {
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/0, {},
+ {}, /*isEntrypoint=*/true)
+ .jmp(-10000)
+ .ret())
+ .build();
+ }},
+ JumpBoundsCheckParams{"JmpZeroOffsetInfiniteLoopGuard",
+ [] {
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/0, {},
+ {}, /*isEntrypoint=*/true)
+ .jmp(0)
+ .ret())
+ .build();
+ }},
+ JumpBoundsCheckParams{"JETakenOffsetBeyondEnd",
+ [] {
+ constexpr int16_t r0 = 0;
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/1, {},
+ {}, /*isEntrypoint=*/true)
+ .je(10000, r0, r0)
+ .ret())
+ .build();
+ }},
+ JumpBoundsCheckParams{"JNETakenOffsetBeyondEnd",
+ [] {
+ constexpr int16_t rZero = 0;
+ constexpr int16_t rOne = 1;
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/2, {},
+ {}, /*isEntrypoint=*/true)
+ .setImm(rOne, 1)
+ .jne(10000, rZero, rOne)
+ .ret())
+ .build();
+ }},
+ // Body layout: [0] jmp +3 (10B), [10] ret (2B). Valid instruction offsets are {0, 10};
+ // offset 3 lands inside the jmp instruction and must be rejected.
+ JumpBoundsCheckParams{"JmpForwardMidInstruction",
+ [] {
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/0, {},
+ {}, /*isEntrypoint=*/true)
+ .jmp(3)
+ .ret())
+ .build();
+ }},
+ // Body layout: [0] set_imm r0, 0 (12B), [12] jmp -3 (10B), [22] ret (2B). Target = 12 - 3 = 9,
+ // which lands inside the set_imm at offset 0 and must be rejected.
+ JumpBoundsCheckParams{"JmpBackwardMidInstruction",
+ [] {
+ constexpr int16_t r0 = 0;
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/1, {},
+ {}, /*isEntrypoint=*/true)
+ .setImm(r0, 0)
+ .jmp(-3)
+ .ret())
+ .build();
+ }},
+ // Body layout: [0] je +3, r0, r0 (14B), [14] ret (2B). Predicate is always taken, target = 3
+ // lands inside the je instruction and must be rejected.
+ JumpBoundsCheckParams{"JETakenMidInstruction",
+ [] {
+ constexpr int16_t r0 = 0;
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/1, {},
+ {}, /*isEntrypoint=*/true)
+ .je(3, r0, r0)
+ .ret())
+ .build();
+ }},
+ // Body layout: [0] set_imm r1, 1 (12B), [12] jne +3, r0, r1 (14B), [26] ret (2B). Target =
+ // 12 + 3 = 15, which lands inside the jne instruction and must be rejected.
+ JumpBoundsCheckParams{"JNETakenMidInstruction",
+ [] {
+ constexpr int16_t rZero = 0;
+ constexpr int16_t rOne = 1;
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(
+ "test", /*numGeneralRegisters=*/2, {},
+ {}, /*isEntrypoint=*/true)
+ .setImm(rOne, 1)
+ .jne(3, rZero, rOne)
+ .ret())
+ .build();
+ }}),
+ [](const testing::TestParamInfo<JumpBoundsCheckParams>& info) {
+ return info.param.testName;
+ });
+
+TEST_P(VirtualMachineAssertInstructionTest, Execute) {
+ const auto& params = GetParam();
+
+ const auto funcName = "assert_test";
+ const auto bytecode =
+ BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/2, {getInt64Type()},
+ {getInt64Type()},
+ /*isEntrypoint=*/true)
+ .instruction(OpCode::ASSERT, {/*condition=*/1, params.messageIndex})
+ .setImm(/*dst=*/0, /*imm=*/42)
+ .retv({0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> parameters = {intel_npu::vm::makeI64(params.condition)};
+ std::vector<npu_vm_value> results = {intel_npu::vm::makeI64(-1)};
+ const auto status = callWithResults(funcName, parameters, results);
+
+ EXPECT_EQ(status, params.expectedStatus);
+ if (params.expectedResult.has_value()) {
+ EXPECT_EQ(results.at(0).i64, *params.expectedResult);
+ }
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ Assert, VirtualMachineAssertInstructionTest,
+ testing::Values(AssertInstructionParams{/*condition=*/1, /*messageIndex=*/0, NPU_VM_SUCCESS,
+ /*expectedResult=*/42},
+ AssertInstructionParams{/*condition=*/-1, /*messageIndex=*/0, NPU_VM_SUCCESS,
+ /*expectedResult=*/42},
+ AssertInstructionParams{/*condition=*/0, /*messageIndex=*/0, NPU_VM_ERROR_FUNCTION_CALL_FAILED,
+ /*expectedResult=*/std::nullopt},
+ AssertInstructionParams{/*condition=*/0, /*messageIndex=*/7, NPU_VM_ERROR_FUNCTION_CALL_FAILED,
+ /*expectedResult=*/std::nullopt}),
+ VirtualMachineAssertInstructionTest::getTestCaseName);
+
+// NOLINTEND(cppcoreguidelines-avoid-magic-numbers)
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/conversion.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/conversion.cpp
new file mode 100644
index 00000000000..48d2b6d9295
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/conversion.cpp
@@ -0,0 +1,466 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "utils/common.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest-param-test.h>
+#include <gtest/gtest.h>
+#include <common_test_utils/test_common.hpp>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <initializer_list>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+namespace {
+
+std::string typeToStr(const intel_npu::vm::Type& type) {
+ const auto typeCode = intel_npu::vm::getTypeCode(type);
+ const auto bitWidth = intel_npu::vm::getBitWidth(type);
+ switch (typeCode) {
+ case intel_npu::vm::TypeCode::INTEGER: {
+ if (bitWidth == sizeof(int8_t) * CHAR_BIT) {
+ return "INT8";
+ } else if (bitWidth == sizeof(int16_t) * CHAR_BIT) {
+ return "INT16";
+ } else if (bitWidth == sizeof(int32_t) * CHAR_BIT) {
+ return "INT32";
+ } else if (bitWidth == sizeof(int64_t) * CHAR_BIT) {
+ return "INT64";
+ } else {
+ return "INT";
+ }
+ }
+ case intel_npu::vm::TypeCode::FLOAT: {
+ if (bitWidth == sizeof(float) * CHAR_BIT) {
+ return "FP32";
+ } else if (bitWidth == sizeof(double) * CHAR_BIT) {
+ return "FP64";
+ } else {
+ return "FP";
+ }
+ }
+ case intel_npu::vm::TypeCode::OPAQUE:
+ return "OPAQUE" + std::to_string(bitWidth) + "b";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+std::string valueToStr(const npu_vm_value& value, const intel_npu::vm::Type& type) {
+ std::ostringstream ss;
+ const auto typeCode = intel_npu::vm::getTypeCode(type);
+ if (typeCode == intel_npu::vm::TypeCode::INTEGER) {
+ ss << value.i64;
+ } else if (typeCode == intel_npu::vm::TypeCode::FLOAT) {
+ const auto bitWidth = intel_npu::vm::getBitWidth(type);
+ if (bitWidth == sizeof(float) * CHAR_BIT) {
+ ss << value.f32;
+ } else {
+ ss << value.f64;
+ }
+ } else {
+ ss << "<unsupported>";
+ }
+ return ss.str();
+}
+
+struct ConvertInstructionParams {
+ OpCode opcode;
+ intel_npu::vm::Type srcType;
+ intel_npu::vm::Type dstType;
+ npu_vm_value src;
+ npu_vm_value expected;
+
+ [[maybe_unused]] friend std::ostream& operator<<(std::ostream& os, const ConvertInstructionParams& params) {
+ os << "{ opcode=" << static_cast<uint16_t>(params.opcode) << ", srcType=" << typeToStr(params.srcType)
+ << ", dstType=" << typeToStr(params.dstType) << ", src=" << valueToStr(params.src, params.srcType)
+ << ", expected=" << valueToStr(params.expected, params.dstType) << " }";
+ return os;
+ }
+};
+
+class VirtualMachineConvertInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<ConvertInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<ConvertInstructionParams>& obj) {
+ std::ostringstream result;
+ result << "opcode_" << static_cast<uint16_t>(obj.param.opcode) << "_srcType_" << typeToStr(obj.param.srcType)
+ << "_dstType_" << typeToStr(obj.param.dstType) << "_src_" << valueToStr(obj.param.src, obj.param.srcType)
+ << "_expected_" << valueToStr(obj.param.expected, obj.param.dstType) << "_idx_" << obj.index;
+ return result.str();
+ }
+};
+
+ConvertInstructionParams intToInt(OpCode op, int64_t src, int64_t expected) {
+ return {op, getInt64Type(), getInt64Type(), intel_npu::vm::makeI64(src), intel_npu::vm::makeI64(expected)};
+}
+ConvertInstructionParams intToF32(OpCode op, int64_t src, float expected) {
+ return {op, getInt64Type(), getF32Type(), intel_npu::vm::makeI64(src), intel_npu::vm::makeF32(expected)};
+}
+ConvertInstructionParams intToF64(OpCode op, int64_t src, double expected) {
+ return {op, getInt64Type(), getF64Type(), intel_npu::vm::makeI64(src), intel_npu::vm::makeF64(expected)};
+}
+ConvertInstructionParams f32ToInt(OpCode op, float src, int64_t expected) {
+ return {op, getF32Type(), getInt64Type(), intel_npu::vm::makeF32(src), intel_npu::vm::makeI64(expected)};
+}
+ConvertInstructionParams f32ToF64(OpCode op, float src, double expected) {
+ return {op, getF32Type(), getF64Type(), intel_npu::vm::makeF32(src), intel_npu::vm::makeF64(expected)};
+}
+ConvertInstructionParams f64ToInt(OpCode op, double src, int64_t expected) {
+ return {op, getF64Type(), getInt64Type(), intel_npu::vm::makeF64(src), intel_npu::vm::makeI64(expected)};
+}
+ConvertInstructionParams f64ToF32(OpCode op, double src, float expected) {
+ return {op, getF64Type(), getF32Type(), intel_npu::vm::makeF64(src), intel_npu::vm::makeF32(expected)};
+}
+
+} // namespace
+
+// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers)
+
+// Execute a single two-operand conversion instruction and compare the result.
+// The function signature uses srcType/dstType so that npu_vm_call_with_results
+// marshals values correctly (i64, f32, or f64).
+TEST_P(VirtualMachineConvertInstructionTest, Execute) {
+ const auto& params = GetParam();
+
+ const auto funcName = "test_convert";
+ auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/2,
+ {params.srcType}, {params.dstType},
+ /*isEntrypoint=*/true)
+ .instruction(params.opcode, {/*dst=*/0, /*src=*/1})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {params.src};
+ npu_vm_value resultInit{};
+ std::vector<npu_vm_value> results = {resultInit};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+
+ const auto dstTypeCode = intel_npu::vm::getTypeCode(params.dstType);
+ if (dstTypeCode == intel_npu::vm::TypeCode::INTEGER) {
+ EXPECT_EQ(results.at(0).i64, params.expected.i64);
+ } else {
+ const auto dstBitWidth = intel_npu::vm::getBitWidth(params.dstType);
+ if (dstBitWidth == sizeof(float) * CHAR_BIT) {
+ expectF32Eq(results.at(0).f32, params.expected.f32);
+ } else {
+ expectF64Eq(results.at(0).f64, params.expected.f64);
+ }
+ }
+}
+
+// CONVERT_I8_TO_F32: sign-extend low 8 bits to i8, then convert to float32
+INSTANTIATE_TEST_SUITE_P(ConvertI8ToF32, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF32(OpCode::CONVERT_I8_TO_F32, 0, 0.0f),
+ intToF32(OpCode::CONVERT_I8_TO_F32, 1, 1.0f),
+ intToF32(OpCode::CONVERT_I8_TO_F32, MAX_I8, static_cast<float>(MAX_I8)),
+ intToF32(OpCode::CONVERT_I8_TO_F32, -1, -1.0f),
+ intToF32(OpCode::CONVERT_I8_TO_F32, MIN_I8, static_cast<float>(MIN_I8)),
+ // 0xFF low byte → i8(-1) → -1.0f
+ intToF32(OpCode::CONVERT_I8_TO_F32, static_cast<int64_t>(0xFF), -1.0f)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I8_TO_F64: sign-extend low 8 bits to i8, then convert to float64
+INSTANTIATE_TEST_SUITE_P(ConvertI8ToF64, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF64(OpCode::CONVERT_I8_TO_F64, 0, 0.0),
+ intToF64(OpCode::CONVERT_I8_TO_F64, 1, 1.0),
+ intToF64(OpCode::CONVERT_I8_TO_F64, MAX_I8, static_cast<double>(MAX_I8)),
+ intToF64(OpCode::CONVERT_I8_TO_F64, -1, -1.0),
+ intToF64(OpCode::CONVERT_I8_TO_F64, MIN_I8, static_cast<double>(MIN_I8)),
+ intToF64(OpCode::CONVERT_I8_TO_F64, static_cast<int64_t>(0xFF), -1.0),
+ intToF64(OpCode::CONVERT_I8_TO_F64, static_cast<int64_t>(0x1FF), -1.0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I16_TO_I8: truncate i16 to i8 (low 8 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(
+ ConvertI16ToI8, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I16_TO_I8, 0, 0), intToInt(OpCode::CONVERT_I16_TO_I8, 1, 1),
+ intToInt(OpCode::CONVERT_I16_TO_I8, MAX_I8, MAX_I8),
+ // 128 as i16 → low 8 bits = 0x80 = i8(-128)
+ intToInt(OpCode::CONVERT_I16_TO_I8, 128, MIN_I8), intToInt(OpCode::CONVERT_I16_TO_I8, -1, -1),
+ // 256 → low 8 bits = 0x00 = 0
+ intToInt(OpCode::CONVERT_I16_TO_I8, 256, 0), intToInt(OpCode::CONVERT_I16_TO_I8, MAX_I16, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I16_TO_F32: sign-extend low 16 bits to i16, then convert to float32
+INSTANTIATE_TEST_SUITE_P(ConvertI16ToF32, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF32(OpCode::CONVERT_I16_TO_F32, 0, 0.0f),
+ intToF32(OpCode::CONVERT_I16_TO_F32, 1, 1.0f),
+ intToF32(OpCode::CONVERT_I16_TO_F32, MAX_I16, static_cast<float>(MAX_I16)),
+ intToF32(OpCode::CONVERT_I16_TO_F32, -1, -1.0f),
+ intToF32(OpCode::CONVERT_I16_TO_F32, MIN_I16, static_cast<float>(MIN_I16)),
+ intToF32(OpCode::CONVERT_I16_TO_F32, static_cast<int64_t>(0xFFFF), -1.0f),
+ intToF32(OpCode::CONVERT_I16_TO_F32, static_cast<int64_t>(0x8000), -32768.0f)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I16_TO_F64: sign-extend low 16 bits to i16, then convert to float64
+INSTANTIATE_TEST_SUITE_P(ConvertI16ToF64, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF64(OpCode::CONVERT_I16_TO_F64, 0, 0.0),
+ intToF64(OpCode::CONVERT_I16_TO_F64, 1, 1.0),
+ intToF64(OpCode::CONVERT_I16_TO_F64, MAX_I16, static_cast<double>(MAX_I16)),
+ intToF64(OpCode::CONVERT_I16_TO_F64, -1, -1.0),
+ intToF64(OpCode::CONVERT_I16_TO_F64, MIN_I16, static_cast<double>(MIN_I16)),
+ intToF64(OpCode::CONVERT_I16_TO_F64, static_cast<int64_t>(0xFFFF), -1.0),
+ intToF64(OpCode::CONVERT_I16_TO_F64, static_cast<int64_t>(0x18000), -32768.0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I32_TO_I8: truncate i32 to i8 (low 8 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(ConvertI32ToI8, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I32_TO_I8, 0, 0),
+ intToInt(OpCode::CONVERT_I32_TO_I8, 1, 1),
+ intToInt(OpCode::CONVERT_I32_TO_I8, MAX_I8, MAX_I8),
+ intToInt(OpCode::CONVERT_I32_TO_I8, 128, MIN_I8),
+ intToInt(OpCode::CONVERT_I32_TO_I8, -1, -1),
+ intToInt(OpCode::CONVERT_I32_TO_I8, 256, 0),
+ // INT32_MAX low 8 bits = 0xFF → i8(-1)
+ intToInt(OpCode::CONVERT_I32_TO_I8, MAX_I32, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I32_TO_I16: truncate i32 to i16 (low 16 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(ConvertI32ToI16, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I32_TO_I16, 0, 0),
+ intToInt(OpCode::CONVERT_I32_TO_I16, 1, 1),
+ intToInt(OpCode::CONVERT_I32_TO_I16, MAX_I16, MAX_I16),
+ // 32768 = 0x8000 as i16 → i16(-32768)
+ intToInt(OpCode::CONVERT_I32_TO_I16, 32768, MIN_I16),
+ intToInt(OpCode::CONVERT_I32_TO_I16, -1, -1),
+ intToInt(OpCode::CONVERT_I32_TO_I16, 65536, 0),
+ // INT32_MAX low 16 bits = 0xFFFF → i16(-1)
+ intToInt(OpCode::CONVERT_I32_TO_I16, MAX_I32, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I32_TO_F32: sign-extend low 32 bits to i32, then convert to float32
+INSTANTIATE_TEST_SUITE_P(ConvertI32ToF32, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF32(OpCode::CONVERT_I32_TO_F32, 0, 0.0f),
+ intToF32(OpCode::CONVERT_I32_TO_F32, 1, 1.0f),
+ intToF32(OpCode::CONVERT_I32_TO_F32, -1, -1.0f),
+ intToF32(OpCode::CONVERT_I32_TO_F32, MAX_I32, static_cast<float>(MAX_I32)),
+ intToF32(OpCode::CONVERT_I32_TO_F32, MIN_I32, static_cast<float>(MIN_I32)),
+ intToF32(OpCode::CONVERT_I32_TO_F32, static_cast<int64_t>(0xFFFFFFFF), -1.0f),
+ intToF32(OpCode::CONVERT_I32_TO_F32, static_cast<int64_t>(0x80000000),
+ static_cast<float>(MIN_I32))),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I32_TO_F64: sign-extend low 32 bits to i32, then convert to float64
+INSTANTIATE_TEST_SUITE_P(ConvertI32ToF64, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF64(OpCode::CONVERT_I32_TO_F64, 0, 0.0),
+ intToF64(OpCode::CONVERT_I32_TO_F64, 1, 1.0),
+ intToF64(OpCode::CONVERT_I32_TO_F64, -1, -1.0),
+ intToF64(OpCode::CONVERT_I32_TO_F64, MAX_I32, static_cast<double>(MAX_I32)),
+ intToF64(OpCode::CONVERT_I32_TO_F64, MIN_I32, static_cast<double>(MIN_I32)),
+ intToF64(OpCode::CONVERT_I32_TO_F64, static_cast<int64_t>(0xFFFFFFFF), -1.0),
+ intToF64(OpCode::CONVERT_I32_TO_F64, static_cast<int64_t>(0x1FFFFFFFF), -1.0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I64_TO_I8: truncate i64 to i8 (low 8 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(ConvertI64ToI8, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I64_TO_I8, 0, 0),
+ intToInt(OpCode::CONVERT_I64_TO_I8, 1, 1),
+ intToInt(OpCode::CONVERT_I64_TO_I8, MAX_I8, MAX_I8),
+ intToInt(OpCode::CONVERT_I64_TO_I8, 128, MIN_I8),
+ intToInt(OpCode::CONVERT_I64_TO_I8, -1, -1),
+ // INT64_MAX low 8 bits = 0xFF → i8(-1)
+ intToInt(OpCode::CONVERT_I64_TO_I8, MAX_I64, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I64_TO_I16: truncate i64 to i16 (low 16 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(ConvertI64ToI16, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I64_TO_I16, 0, 0),
+ intToInt(OpCode::CONVERT_I64_TO_I16, 1, 1),
+ intToInt(OpCode::CONVERT_I64_TO_I16, MAX_I16, MAX_I16),
+ intToInt(OpCode::CONVERT_I64_TO_I16, 32768, MIN_I16),
+ intToInt(OpCode::CONVERT_I64_TO_I16, -1, -1),
+ // INT64_MAX low 16 bits = 0xFFFF → i16(-1)
+ intToInt(OpCode::CONVERT_I64_TO_I16, MAX_I64, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I64_TO_I32: truncate i64 to i32 (low 32 bits), sign-extend to i64
+INSTANTIATE_TEST_SUITE_P(ConvertI64ToI32, VirtualMachineConvertInstructionTest,
+ testing::Values(intToInt(OpCode::CONVERT_I64_TO_I32, 0, 0),
+ intToInt(OpCode::CONVERT_I64_TO_I32, 1, 1),
+ intToInt(OpCode::CONVERT_I64_TO_I32, MAX_I32, MAX_I32),
+ intToInt(OpCode::CONVERT_I64_TO_I32, MIN_I32, MIN_I32),
+ intToInt(OpCode::CONVERT_I64_TO_I32, -1, -1),
+ // INT64_MAX low 32 bits = 0xFFFFFFFF → i32(-1)
+ intToInt(OpCode::CONVERT_I64_TO_I32, MAX_I64, -1)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I64_TO_F32: i64 to float32
+INSTANTIATE_TEST_SUITE_P(ConvertI64ToF32, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF32(OpCode::CONVERT_I64_TO_F32, 0, 0.0f),
+ intToF32(OpCode::CONVERT_I64_TO_F32, 1, 1.0f),
+ intToF32(OpCode::CONVERT_I64_TO_F32, -1, -1.0f),
+ intToF32(OpCode::CONVERT_I64_TO_F32, MAX_I64, static_cast<float>(MAX_I64)),
+ intToF32(OpCode::CONVERT_I64_TO_F32, MIN_I64, static_cast<float>(MIN_I64))),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_I64_TO_F64: i64 to float64
+INSTANTIATE_TEST_SUITE_P(ConvertI64ToF64, VirtualMachineConvertInstructionTest,
+ testing::Values(intToF64(OpCode::CONVERT_I64_TO_F64, 0, 0.0),
+ intToF64(OpCode::CONVERT_I64_TO_F64, 1, 1.0),
+ intToF64(OpCode::CONVERT_I64_TO_F64, -1, -1.0),
+ intToF64(OpCode::CONVERT_I64_TO_F64, MAX_I64, static_cast<double>(MAX_I64)),
+ intToF64(OpCode::CONVERT_I64_TO_F64, MIN_I64, static_cast<double>(MIN_I64))),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// Float-to-integer conversions use saturating semantics: NaN → 0, overflow → INT_MAX/MIN.
+
+// CONVERT_F32_TO_I8
+INSTANTIATE_TEST_SUITE_P(ConvertF32ToI8, VirtualMachineConvertInstructionTest,
+ testing::Values(f32ToInt(OpCode::CONVERT_F32_TO_I8, 0.0f, 0),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, 1.0f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, -1.0f, -1),
+ // Truncation toward zero
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, 1.9f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, -1.9f, -1),
+ // In-range boundaries
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, static_cast<float>(MAX_I8), MAX_I8),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, static_cast<float>(MIN_I8), MIN_I8),
+ // Overflow saturation
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, 128.0f, MAX_I8),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, -129.0f, MIN_I8),
+ // Special values
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, INF_F32, MAX_I8),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, -INF_F32, MIN_I8),
+ f32ToInt(OpCode::CONVERT_F32_TO_I8, NAN_F32, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F32_TO_I16
+INSTANTIATE_TEST_SUITE_P(ConvertF32ToI16, VirtualMachineConvertInstructionTest,
+ testing::Values(f32ToInt(OpCode::CONVERT_F32_TO_I16, 0.0f, 0),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, 1.0f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, -1.0f, -1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, 1.9f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, -1.9f, -1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, static_cast<float>(MAX_I16), MAX_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, static_cast<float>(MIN_I16), MIN_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, 32768.0f, MAX_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, -32769.0f, MIN_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, INF_F32, MAX_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, -INF_F32, MIN_I16),
+ f32ToInt(OpCode::CONVERT_F32_TO_I16, NAN_F32, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F32_TO_I32
+INSTANTIATE_TEST_SUITE_P(
+ ConvertF32ToI32, VirtualMachineConvertInstructionTest,
+ testing::Values(f32ToInt(OpCode::CONVERT_F32_TO_I32, 0.0f, 0), f32ToInt(OpCode::CONVERT_F32_TO_I32, 1.5f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, -1.5f, -1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, 1.0e9f, 1000000000),
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, 1.0e10f, MAX_I32), // overflow saturation
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, -1.0e10f, MIN_I32), // overflow saturation
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, INF_F32, MAX_I32),
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, -INF_F32, MIN_I32),
+ f32ToInt(OpCode::CONVERT_F32_TO_I32, NAN_F32, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F32_TO_I64
+INSTANTIATE_TEST_SUITE_P(ConvertF32ToI64, VirtualMachineConvertInstructionTest,
+ testing::Values(f32ToInt(OpCode::CONVERT_F32_TO_I64, 0.0f, 0),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, 1.0f, 1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, -1.0f, -1),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, 1.0e18f, static_cast<int64_t>(1.0e18f)),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, INF_F32, MAX_I64),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, -INF_F32, MIN_I64),
+ f32ToInt(OpCode::CONVERT_F32_TO_I64, NAN_F32, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F32_TO_F64: widen float32 to float64
+INSTANTIATE_TEST_SUITE_P(ConvertF32ToF64, VirtualMachineConvertInstructionTest,
+ testing::Values(f32ToF64(OpCode::CONVERT_F32_TO_F64, 0.0f, 0.0),
+ f32ToF64(OpCode::CONVERT_F32_TO_F64, 1.5f, static_cast<double>(1.5f)),
+ f32ToF64(OpCode::CONVERT_F32_TO_F64, -3.14f, static_cast<double>(-3.14f)),
+ f32ToF64(OpCode::CONVERT_F32_TO_F64, INF_F32, INF_F64),
+ f32ToF64(OpCode::CONVERT_F32_TO_F64, -INF_F32, -INF_F64),
+ f32ToF64(OpCode::CONVERT_F32_TO_F64, NAN_F32, NAN_F64)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F64_TO_I8
+INSTANTIATE_TEST_SUITE_P(ConvertF64ToI8, VirtualMachineConvertInstructionTest,
+ testing::Values(f64ToInt(OpCode::CONVERT_F64_TO_I8, 0.0, 0),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, 1.0, 1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, -1.0, -1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, 1.9, 1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, -1.9, -1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, static_cast<double>(MAX_I8), MAX_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, static_cast<double>(MIN_I8), MIN_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, 128.0, MAX_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, -129.0, MIN_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, INF_F64, MAX_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, -INF_F64, MIN_I8),
+ f64ToInt(OpCode::CONVERT_F64_TO_I8, NAN_F64, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F64_TO_I16
+INSTANTIATE_TEST_SUITE_P(ConvertF64ToI16, VirtualMachineConvertInstructionTest,
+ testing::Values(f64ToInt(OpCode::CONVERT_F64_TO_I16, 0.0, 0),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, 1.0, 1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, -1.0, -1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, static_cast<double>(MAX_I16), MAX_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, static_cast<double>(MIN_I16), MIN_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, 32768.0, MAX_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, -32769.0, MIN_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, INF_F64, MAX_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, -INF_F64, MIN_I16),
+ f64ToInt(OpCode::CONVERT_F64_TO_I16, NAN_F64, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F64_TO_I32
+INSTANTIATE_TEST_SUITE_P(ConvertF64ToI32, VirtualMachineConvertInstructionTest,
+ testing::Values(f64ToInt(OpCode::CONVERT_F64_TO_I32, 0.0, 0),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, 1.5, 1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, -1.5, -1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, 1.0e9, 1000000000),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, 1.0e10, MAX_I32),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, -1.0e10, MIN_I32),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, INF_F64, MAX_I32),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, -INF_F64, MIN_I32),
+ f64ToInt(OpCode::CONVERT_F64_TO_I32, NAN_F64, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F64_TO_I64
+INSTANTIATE_TEST_SUITE_P(ConvertF64ToI64, VirtualMachineConvertInstructionTest,
+ testing::Values(f64ToInt(OpCode::CONVERT_F64_TO_I64, 0.0, 0),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, 1.0, 1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, -1.0, -1),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, 1.0e18, static_cast<int64_t>(1.0e18)),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, INF_F64, MAX_I64),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, -INF_F64, MIN_I64),
+ f64ToInt(OpCode::CONVERT_F64_TO_I64, NAN_F64, 0)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// CONVERT_F64_TO_F32: narrow float64 to float32
+INSTANTIATE_TEST_SUITE_P(ConvertF64ToF32, VirtualMachineConvertInstructionTest,
+ testing::Values(f64ToF32(OpCode::CONVERT_F64_TO_F32, 0.0, 0.0f),
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, 1.5, 1.5f),
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, -3.14, static_cast<float>(-3.14)),
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, INF_F64, INF_F32),
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, -INF_F64, -INF_F32),
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, NAN_F64, NAN_F32),
+ // Rounding: midpoint between 1.0f and nextafterf(1.0f, 2.0f)
+ // ties-to-even rounds to 1.0f (even mantissa LSB)
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, 0x1.0000010000000p+0, 1.0f),
+ // Midpoint between 0x1.000002p+0 and 0x1.000004p+0
+ // ties-to-even rounds to 0x1.000004p+0 (even mantissa LSB)
+ f64ToF32(OpCode::CONVERT_F64_TO_F32, 0x1.0000030000000p+0, 0x1.000004p+0f)),
+ VirtualMachineConvertInstructionTest::getTestCaseName);
+
+// NOLINTEND(cppcoreguidelines-avoid-magic-numbers)
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.cpp b/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.cpp
new file mode 100644
index 00000000000..a04e992d364
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.cpp
@@ -0,0 +1,196 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common.hpp"
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "vm_runtime/virtual_machine.h"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest.h>
+
+#include <climits>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <ostream>
+#include <sstream>
+#include <string>
+#include <variant>
+#include <vector>
+
+namespace {
+
+void expectResultEq(const npu_vm_value& result, const std::variant<int64_t, double>& expected) {
+ if (std::holds_alternative<double>(expected)) {
+ utils::expectF64Eq(result.f64, std::get<double>(expected));
+ } else {
+ EXPECT_EQ(result.i64, std::get<int64_t>(expected));
+ }
+}
+
+std::string expectedToString(const std::variant<int64_t, double>& expected) {
+ std::ostringstream result;
+ std::visit(
+ [&result](auto value) {
+ result << value;
+ },
+ expected);
+ return result.str();
+}
+
+} // namespace
+
+namespace utils {
+
+std::ostream& operator<<(std::ostream& os, const TwoOperandInstructionParams& params) {
+ os << "{ opcode=" << static_cast<uint16_t>(params.opcode) << ", src=" << params.src
+ << ", expected=" << expectedToString(params.expected) << " }";
+ return os;
+}
+
+std::ostream& operator<<(std::ostream& os, const ThreeOperandInstructionParams& params) {
+ os << "{ opcode=" << static_cast<uint16_t>(params.opcode) << ", lhs=" << params.lhs << ", rhs=" << params.rhs
+ << ", expected=" << expectedToString(params.expected) << " }";
+ return os;
+}
+
+} // namespace utils
+
+int64_t utils::f64Bits(double v) {
+ int64_t bits{};
+ std::memcpy(&bits, &v, sizeof(v));
+ return bits;
+}
+
+intel_npu::vm::Type utils::getInt64Type() {
+ return intel_npu::vm::Type{intel_npu::vm::IntegerType{sizeof(int64_t) * CHAR_BIT, true}};
+}
+
+intel_npu::vm::Type utils::getF32Type() {
+ return intel_npu::vm::Type{
+ intel_npu::vm::FloatType{sizeof(float) * CHAR_BIT, intel_npu::vm::FloatTypeFormat::IEEE754}};
+}
+
+intel_npu::vm::Type utils::getF64Type() {
+ return intel_npu::vm::Type{
+ intel_npu::vm::FloatType{sizeof(double) * CHAR_BIT, intel_npu::vm::FloatTypeFormat::IEEE754}};
+}
+
+void utils::expectF64Eq(double actual, double expected) {
+ if (std::isnan(expected)) {
+ EXPECT_TRUE(std::isnan(actual));
+ } else if (std::isinf(expected)) {
+ EXPECT_TRUE(std::isinf(actual));
+ EXPECT_EQ(std::signbit(actual), std::signbit(expected));
+ } else {
+ EXPECT_DOUBLE_EQ(actual, expected);
+ }
+}
+
+void utils::expectF32Eq(float actual, float expected) {
+ if (std::isnan(expected)) {
+ EXPECT_TRUE(std::isnan(actual));
+ } else if (std::isinf(expected)) {
+ EXPECT_TRUE(std::isinf(actual));
+ EXPECT_EQ(std::signbit(actual), std::signbit(expected));
+ } else {
+ EXPECT_FLOAT_EQ(actual, expected);
+ }
+}
+
+npu_vm_result utils::VirtualMachineInstructionTest::loadEntrypoint(const std::vector<uint8_t>& bytecode,
+ const char* funcName) {
+ if (const auto status = npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module); status != NPU_VM_SUCCESS) {
+ return status;
+ }
+ if (const auto status = npu_vm_get_function_info(module, funcName, &funcInfo); status != NPU_VM_SUCCESS) {
+ return status;
+ }
+ if (const auto status = npu_vm_new_engine(&engine); status != NPU_VM_SUCCESS) {
+ return status;
+ }
+ return npu_vm_load_module(engine, /*moduleParams*/ nullptr, module);
+}
+
+npu_vm_result utils::VirtualMachineInstructionTest::callWithResults(const char* funcName,
+ const std::vector<npu_vm_value>& args,
+ std::vector<npu_vm_value>& results) {
+ return npu_vm_call_with_results(engine, funcName, static_cast<uint32_t>(args.size()), args.data(),
+ static_cast<uint32_t>(results.size()), results.data());
+}
+
+std::string utils::VirtualMachineThreeOperandInstructionTest::getTestCaseName(
+ const testing::TestParamInfo<ThreeOperandInstructionParams>& obj) {
+ std::ostringstream result;
+ result << "opcode=" << static_cast<uint16_t>(obj.param.opcode) << "_";
+ result << "lhs=" << obj.param.lhs << "_";
+ result << "rhs=" << obj.param.rhs << "_";
+ result << "expected=" << expectedToString(obj.param.expected);
+ return result.str();
+}
+
+std::string utils::VirtualMachineTwoOperandInstructionTest::getTestCaseName(
+ const testing::TestParamInfo<TwoOperandInstructionParams>& obj) {
+ std::ostringstream result;
+ result << "opcode=" << static_cast<uint16_t>(obj.param.opcode) << "_";
+ result << "src=" << obj.param.src << "_";
+ result << "expected=" << expectedToString(obj.param.expected);
+ return result.str();
+}
+
+namespace utils {
+
+TEST_P(VirtualMachineTwoOperandInstructionTest, Execute) {
+ const auto& params = GetParam();
+ const bool isFp = std::holds_alternative<double>(params.expected);
+
+ const auto paramType = getInt64Type();
+ const auto resultType = isFp ? getF64Type() : getInt64Type();
+
+ const auto funcName = "test";
+ auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/2,
+ {paramType}, {resultType},
+ /*isEntrypoint=*/true)
+ .instruction(params.opcode, {/*dst=*/0, /*src=*/1})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(params.src)};
+ std::vector<npu_vm_value> results = {isFp ? intel_npu::vm::makeF64(0.0) : intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+
+ expectResultEq(results.at(0), params.expected);
+}
+
+// Program layout (3 registers):
+// opcode %0, %1, %2
+// retv 1, %0
+TEST_P(VirtualMachineThreeOperandInstructionTest, Execute) {
+ const auto& params = GetParam();
+ const bool isFp = std::holds_alternative<double>(params.expected);
+
+ const auto paramType = getInt64Type();
+ const auto resultType = isFp ? getF64Type() : getInt64Type();
+
+ const auto funcName = "test";
+ auto bytecode = BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(funcName, /*numGeneralRegisters=*/3,
+ {paramType, paramType}, {resultType},
+ /*isEntrypoint=*/true)
+ .instruction(params.opcode, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv(/*resultRegs=*/{0}))
+ .build();
+ ASSERT_EQ(loadEntrypoint(bytecode, funcName), NPU_VM_SUCCESS);
+
+ std::vector<npu_vm_value> args = {intel_npu::vm::makeI64(params.lhs), intel_npu::vm::makeI64(params.rhs)};
+ std::vector<npu_vm_value> results = {isFp ? intel_npu::vm::makeF64(0.0) : intel_npu::vm::makeI64(0)};
+ ASSERT_EQ(callWithResults(funcName, args, results), NPU_VM_SUCCESS);
+
+ expectResultEq(results.at(0), params.expected);
+}
+
+} // namespace utils
diff --git a/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.hpp b/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.hpp
new file mode 100644
index 00000000000..04aa0f64c53
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/instructions/utils/common.hpp
@@ -0,0 +1,109 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "vm_runtime/virtual_machine.h"
+
+#include <gtest/gtest.h>
+
+#include <climits>
+#include <cstdint>
+#include <limits>
+#include <ostream>
+#include <string>
+#include <variant>
+#include <vector>
+
+namespace utils {
+
+constexpr int64_t MIN_I8 = std::numeric_limits<int8_t>::min();
+constexpr int64_t MAX_I8 = std::numeric_limits<int8_t>::max();
+constexpr int64_t MIN_I16 = std::numeric_limits<int16_t>::min();
+constexpr int64_t MAX_I16 = std::numeric_limits<int16_t>::max();
+constexpr int64_t MIN_I32 = std::numeric_limits<int32_t>::min();
+constexpr int64_t MAX_I32 = std::numeric_limits<int32_t>::max();
+constexpr int64_t MIN_I64 = std::numeric_limits<int64_t>::min();
+constexpr int64_t MAX_I64 = std::numeric_limits<int64_t>::max();
+
+constexpr float INF_F32 = std::numeric_limits<float>::infinity();
+constexpr float NAN_F32 = std::numeric_limits<float>::quiet_NaN();
+constexpr double INF_F64 = std::numeric_limits<double>::infinity();
+constexpr double NAN_F64 = std::numeric_limits<double>::quiet_NaN();
+
+int64_t f64Bits(double v);
+
+intel_npu::vm::Type getInt64Type();
+intel_npu::vm::Type getF32Type();
+intel_npu::vm::Type getF64Type();
+
+// Compares a floating-point result against an expected value, tolerating NaN payload differences
+// and checking the sign of infinities
+void expectF32Eq(float actual, float expected);
+void expectF64Eq(double actual, double expected);
+
+// Base fixture for VM instruction execution tests
+// Each test case receives a freshly default-constructed VirtualMachine
+class VirtualMachineInstructionTest : public testing::Test {
+public:
+ npu_vm_module* module{nullptr};
+ npu_vm_engine* engine{nullptr};
+ npu_vm_function_info* funcInfo{nullptr};
+
+ // Parses the bytecode, resolves the named function, and creates and loads an engine
+ // Returns NPU_VM_SUCCESS on full success, otherwise the first failing status
+ npu_vm_result loadEntrypoint(const std::vector<uint8_t>& bytecode, const char* funcName);
+
+ // Marshals the arguments and results through the VM call API and returns the raw status
+ npu_vm_result callWithResults(const char* funcName, const std::vector<npu_vm_value>& args,
+ std::vector<npu_vm_value>& results);
+
+protected:
+ void TearDown() override {
+ if (funcInfo != nullptr) {
+ npu_vm_destroy_function_info(funcInfo);
+ }
+ if (engine != nullptr) {
+ npu_vm_destroy_engine(engine);
+ }
+ if (module != nullptr) {
+ npu_vm_destroy_module(module);
+ }
+ }
+};
+
+struct TwoOperandInstructionParams {
+ intel_npu::vm::OpCode opcode;
+ int64_t src;
+ std::variant<int64_t, double> expected;
+
+ friend std::ostream& operator<<(std::ostream& os, const TwoOperandInstructionParams& params);
+};
+
+struct ThreeOperandInstructionParams {
+ intel_npu::vm::OpCode opcode;
+ int64_t lhs;
+ int64_t rhs;
+ std::variant<int64_t, double> expected;
+
+ friend std::ostream& operator<<(std::ostream& os, const ThreeOperandInstructionParams& params);
+};
+
+class VirtualMachineThreeOperandInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<ThreeOperandInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<ThreeOperandInstructionParams>& obj);
+};
+
+class VirtualMachineTwoOperandInstructionTest :
+ public VirtualMachineInstructionTest,
+ public testing::WithParamInterface<TwoOperandInstructionParams> {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<TwoOperandInstructionParams>& obj);
+};
+
+} // namespace utils
diff --git a/src/plugins/intel_npu/tests/unit/vm/span.cpp b/src/plugins/intel_npu/tests/unit/vm/span.cpp
new file mode 100644
index 00000000000..36ec543f2f7
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/span.cpp
@@ -0,0 +1,225 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/span.hpp"
+
+#include <gtest/gtest.h>
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <iterator>
+#include <numeric>
+#include <type_traits>
+
+using namespace intel_npu::vm;
+
+namespace {
+
+TEST(VirtualMachineSpanTest, ExposesStdSpanLikeTypeAliases) {
+ using IntSpan = Span<int>;
+
+ static_assert(dynamic_extent == static_cast<size_t>(-1));
+ static_assert(std::is_same_v<IntSpan::element_type, int>);
+ static_assert(std::is_same_v<IntSpan::value_type, int>);
+ static_assert(std::is_same_v<IntSpan::size_type, size_t>);
+ static_assert(std::is_same_v<IntSpan::difference_type, std::ptrdiff_t>);
+ static_assert(std::is_same_v<IntSpan::pointer, int*>);
+ static_assert(std::is_same_v<IntSpan::const_pointer, const int*>);
+ static_assert(std::is_same_v<IntSpan::reference, int&>);
+ static_assert(std::is_same_v<IntSpan::const_reference, const int&>);
+ static_assert(IntSpan::extent == dynamic_extent);
+}
+
+TEST(VirtualMachineSpanTest, DefaultConstructedSpanIsEmpty) {
+ Span<int> span;
+
+ EXPECT_TRUE(span.empty());
+ EXPECT_EQ(span.size(), 0u);
+ EXPECT_EQ(span.size_bytes(), 0u);
+ EXPECT_EQ(span.data(), nullptr);
+ EXPECT_EQ(span.begin(), span.end());
+}
+
+TEST(VirtualMachineSpanTest, ConstructsFromPointerAndSize) {
+ constexpr int32_t value0 = 10;
+ constexpr int32_t value1 = 20;
+ constexpr int32_t value2 = 30;
+ constexpr int32_t value3 = 40;
+ std::array<int32_t, 4> values = {value0, value1, value2, value3};
+
+ Span<int32_t> span(values.data(), values.size());
+
+ ASSERT_FALSE(span.empty());
+ EXPECT_EQ(span.data(), values.data());
+ EXPECT_EQ(span.size(), values.size());
+ EXPECT_EQ(span.size_bytes(), values.size() * sizeof(int32_t));
+ EXPECT_EQ(span.front(), value0);
+ EXPECT_EQ(span.back(), value3);
+
+ const auto iter = std::next(span.begin());
+ ASSERT_NE(iter, span.end());
+ EXPECT_EQ(*iter, value1);
+}
+
+TEST(VirtualMachineSpanTest, ConstructsFromStdArrayMutableAndConst) {
+ constexpr int64_t mutable0 = 7;
+ constexpr int64_t mutable1 = 8;
+ constexpr int64_t mutable2 = 9;
+ constexpr int64_t const0 = 11;
+ constexpr int64_t const1 = 12;
+ std::array<int64_t, 3> mutableValues = {mutable0, mutable1, mutable2};
+ const std::array<int64_t, 2> constValues = {const0, const1};
+
+ Span<int64_t> mutableSpan(mutableValues);
+ Span<const int64_t> constSpan(constValues);
+
+ ASSERT_EQ(mutableSpan.size(), 3u);
+ EXPECT_EQ(mutableSpan.front(), mutable0);
+ EXPECT_EQ(mutableSpan.back(), mutable2);
+
+ ASSERT_EQ(constSpan.size(), 2u);
+ EXPECT_EQ(constSpan.front(), const0);
+ EXPECT_EQ(constSpan.back(), const1);
+}
+
+TEST(VirtualMachineSpanTest, ConstructsFromCArray) {
+ constexpr int value0 = 1;
+ constexpr int value1 = 2;
+ constexpr int value2 = 3;
+ int values[] = {value0, value1, value2}; // NOLINT(cppcoreguidelines-avoid-c-arrays)
+
+ Span<int> span(values);
+
+ ASSERT_EQ(span.size(), 3u);
+ EXPECT_EQ(span.front(), value0);
+ EXPECT_EQ(span.back(), value2);
+}
+
+TEST(VirtualMachineSpanTest, AllowsConvertingCtorFromMutableToConst) {
+ constexpr int firstValue = 3;
+ constexpr int lastValue = 5;
+ std::array<int, 3> values = {firstValue, 4, lastValue};
+ Span<int> mutableSpan(values);
+
+ Span<const int> constSpan(mutableSpan);
+
+ EXPECT_EQ(constSpan.data(), values.data());
+ EXPECT_EQ(constSpan.size(), values.size());
+ EXPECT_EQ(constSpan.front(), firstValue);
+ EXPECT_EQ(constSpan.back(), lastValue);
+}
+
+TEST(VirtualMachineSpanTest, SupportsFirstLastAndSubspan) {
+ constexpr size_t numValues = 6;
+ constexpr int lastValue = 5;
+ std::array<int, numValues> values = {0, 1, 2, 3, 4, lastValue};
+ Span<int> span(values);
+
+ constexpr size_t firstCount = 2;
+ constexpr size_t lastCount = 3;
+ constexpr size_t middleOffset = 2;
+ constexpr size_t middleCount = 3;
+ constexpr size_t tailOffset = 4;
+
+ auto firstTwo = span.first(firstCount);
+ auto lastThree = span.last(lastCount);
+ auto middle = span.subspan(middleOffset, middleCount);
+ auto tail = span.subspan(tailOffset);
+ auto middleCt = span.subspan<middleOffset, middleCount>();
+ auto tailCt = span.subspan<tailOffset>();
+
+ ASSERT_EQ(firstTwo.size(), 2u);
+ EXPECT_EQ(firstTwo.front(), 0);
+ EXPECT_EQ(firstTwo.back(), 1);
+
+ ASSERT_EQ(lastThree.size(), 3u);
+ EXPECT_EQ(lastThree.front(), 3);
+ EXPECT_EQ(lastThree.back(), lastValue);
+
+ ASSERT_EQ(middle.size(), 3u);
+ EXPECT_EQ(middle.front(), 2);
+ EXPECT_EQ(middle.back(), 4);
+
+ ASSERT_EQ(tail.size(), 2u);
+ EXPECT_EQ(tail.front(), 4);
+ EXPECT_EQ(tail.back(), lastValue);
+
+ ASSERT_EQ(middleCt.size(), 3u);
+ EXPECT_EQ(middleCt.front(), 2);
+ EXPECT_EQ(middleCt.back(), 4);
+
+ ASSERT_EQ(tailCt.size(), 2u);
+ EXPECT_EQ(tailCt.front(), 4);
+ EXPECT_EQ(tailCt.back(), lastValue);
+}
+
+TEST(VirtualMachineSpanTest, SupportsZeroLengthSlicingWithoutNullifyingData) {
+ std::array<int, 4> values = {1, 2, 3, 4};
+ Span<int> span(values);
+
+ const auto firstZero = span.first(0);
+ const auto lastZero = span.last(0);
+ const auto subspanAtEnd = span.subspan(span.size());
+ const auto subspanZeroCount = span.subspan(2, 0);
+
+ EXPECT_TRUE(firstZero.empty());
+ EXPECT_EQ(firstZero.data(), values.data());
+
+ EXPECT_TRUE(lastZero.empty());
+ EXPECT_EQ(lastZero.data(), std::next(values.data(), static_cast<std::ptrdiff_t>(values.size())));
+
+ EXPECT_TRUE(subspanAtEnd.empty());
+ EXPECT_EQ(subspanAtEnd.data(), std::next(values.data(), static_cast<std::ptrdiff_t>(values.size())));
+
+ EXPECT_TRUE(subspanZeroCount.empty());
+ EXPECT_EQ(subspanZeroCount.data(), std::next(values.data(), 2));
+}
+
+TEST(VirtualMachineSpanTest, IteratorsMatchUnderlyingBufferOrder) {
+ constexpr size_t numValues = 5;
+ constexpr int value0 = 2;
+ constexpr int value1 = 4;
+ constexpr int value2 = 6;
+ constexpr int value3 = 8;
+ constexpr int value4 = 10;
+ constexpr int expectedSum = 30;
+ std::array<int, numValues> values = {value0, value1, value2, value3, value4};
+ Span<int> span(values);
+
+ const int forwardSum = std::accumulate(span.begin(), span.end(), 0);
+
+ int reverseSum = 0;
+ for (auto it = span.rbegin(); it != span.rend(); ++it) {
+ reverseSum += *it;
+ }
+
+ const int constForwardSum = std::accumulate(span.cbegin(), span.cend(), 0);
+ int constReverseSum = 0;
+ for (auto it = span.crbegin(); it != span.crend(); ++it) {
+ constReverseSum += *it;
+ }
+
+ EXPECT_EQ(forwardSum, expectedSum);
+ EXPECT_EQ(reverseSum, expectedSum);
+ EXPECT_EQ(constForwardSum, expectedSum);
+ EXPECT_EQ(constReverseSum, expectedSum);
+}
+
+TEST(VirtualMachineSpanTest, ExposesByteViewsLikeStdSpan) {
+ constexpr uint32_t value0 = 0x11223344U;
+ constexpr uint32_t value1 = 0x55667788U;
+ std::array<uint32_t, 2> values = {value0, value1};
+ Span<uint32_t> span(values);
+
+ const auto readOnlyBytes = as_bytes(span);
+ auto writableBytes = as_writable_bytes(span);
+
+ EXPECT_EQ(readOnlyBytes.size(), span.size_bytes());
+ EXPECT_EQ(writableBytes.size(), span.size_bytes());
+ EXPECT_EQ(readOnlyBytes.data(), static_cast<const std::byte*>(static_cast<const void*>(values.data())));
+ EXPECT_EQ(writableBytes.data(), static_cast<std::byte*>(static_cast<void*>(values.data())));
+}
+
+} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/vm/version_compatibility_check.cpp b/src/plugins/intel_npu/tests/unit/vm/version_compatibility_check.cpp
new file mode 100644
index 00000000000..ac50ce11d8a
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/version_compatibility_check.cpp
@@ -0,0 +1,173 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/bytecode_reader.hpp"
+#include "npu_bytecode_utils/span.hpp"
+#include "npu_bytecode_utils/version.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <vector>
+
+using namespace intel_npu::vm;
+
+namespace {
+
+// Builds minimal valid bytecode with the specified version
+std::vector<uint8_t> buildBytecodeWithVersion(Version version) {
+ return utils::BytecodeBuilder{}
+ .setVersion(version)
+ .addFunction(utils::BytecodeBuilder::FunctionBuilder("main", /*numGeneralRegisters=*/1,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{},
+ /*isEntrypoint=*/true)
+ .ret())
+ .build();
+}
+
+// Checks if bytecode with given version is compatible with the specified VM range
+bool isCompatible(Version version, Version vmMin, Version vmMax) {
+ auto bytecode = buildBytecodeWithVersion(version);
+ const auto bytecodeView = Span<uint8_t>{bytecode.data(), bytecode.size()};
+ return BytecodeReader::isVersionSupported(bytecodeView, vmMin, vmMax);
+}
+
+// --- Tests with production VM version (1.0.0) ---
+
+TEST(VirtualMachineCompatibilityCheck, ExactVersionMatch) {
+ EXPECT_TRUE(isCompatible(Version{1, 0, 0}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, PatchVersionIsIgnored) {
+ EXPECT_TRUE(isCompatible(Version{1, 0, 5}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, HigherMinorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 1, 0}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, HigherMajorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{2, 0, 0}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, LowerMajorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{0, 9, 0}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, ZeroVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{0, 0, 0}, Version{1, 0, 0}, Version{1, 0, 0}));
+}
+
+// --- Tests simulating VM version increase ---
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionOldBytecodeStillSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 0, 0}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionIntermediateMinorVersionSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 2, 0}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionCurrentVmMinorVersionSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 3, 0}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionFutureMinorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 4, 0}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionFutureMajorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{2, 0, 0}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, IncreasedVmVersionPatchVersionIgnoredAtMaxMinor) {
+ EXPECT_TRUE(isCompatible(Version{1, 3, 99}, Version{1, 0, 0}, Version{1, 3, 0}));
+}
+
+// --- Tests simulating backward compatibility floor being raised ---
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionBytecodeBelowFloorRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 1, 0}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionBytecodeAtFloorSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 2, 0}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionBytecodeAboveFloorSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 4, 0}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionBytecodeAtMaxSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 5, 0}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionBytecodeAboveMaxRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 6, 0}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, RaisedMinVersionDeprecatedVersionWithHighPatchStillRejected) {
+ // Version 1.1.99 is below the floor 1.2.0 regardless of patch
+ EXPECT_FALSE(isCompatible(Version{1, 1, 99}, Version{1, 2, 0}, Version{1, 5, 0}));
+}
+
+// --- Tests simulating major version bump ---
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpOldMajorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 0, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpOldMajorHighMinorRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 9, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpNewMajorAtMinSupported) {
+ EXPECT_TRUE(isCompatible(Version{2, 0, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpNewMajorAtMaxSupported) {
+ EXPECT_TRUE(isCompatible(Version{2, 1, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpNewMajorAboveMaxRejected) {
+ EXPECT_FALSE(isCompatible(Version{2, 2, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, MajorVersionBumpFutureMajorVersionRejected) {
+ EXPECT_FALSE(isCompatible(Version{3, 0, 0}, Version{2, 0, 0}, Version{2, 1, 0}));
+}
+
+// --- Tests simulating cross-major backward compatibility ---
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatOldMajorAboveFloorSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 7, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatOldMajorAtFloorSupported) {
+ EXPECT_TRUE(isCompatible(Version{1, 5, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatOldMajorBelowFloorRejected) {
+ EXPECT_FALSE(isCompatible(Version{1, 4, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatNewMajorSupported) {
+ EXPECT_TRUE(isCompatible(Version{2, 1, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatNewMajorAtMaxSupported) {
+ EXPECT_TRUE(isCompatible(Version{2, 2, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatNewMajorAboveMaxRejected) {
+ EXPECT_FALSE(isCompatible(Version{2, 3, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+TEST(VirtualMachineCompatibilityCheck, CrossMajorBackwardCompatVeryOldMajorRejected) {
+ EXPECT_FALSE(isCompatible(Version{0, 9, 0}, Version{1, 5, 0}, Version{2, 2, 0}));
+}
+
+} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/vm/virtual_machine.cpp b/src/plugins/intel_npu/tests/unit/vm/virtual_machine.cpp
new file mode 100644
index 00000000000..6697ec905c4
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/virtual_machine.cpp
@@ -0,0 +1,406 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "vm_runtime/virtual_machine.h"
+#include "bytecode_builder.hpp"
+#include "npu_bytecode_utils/instructions.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "vm_value_helpers.hpp"
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <array>
+#include <climits>
+#include <cstdint>
+#include <cstdlib>
+#include <numeric>
+#include <string>
+#include <vector>
+
+using namespace intel_npu::vm;
+using namespace utils;
+
+constexpr auto ENTRY_FUNC_NAME = "main";
+constexpr auto ADD_FUNC_NAME = "add_i64";
+constexpr auto UINT32_IDENTITY_FUNC_NAME = "identity_u32";
+constexpr auto BUFFER_IDENTITY_FUNC_NAME = "buffer_identity";
+constexpr auto MISSING_FUNC_NAME = "missing";
+
+namespace {
+
+class VirtualMachineApiTest : public testing::Test {
+protected:
+ npu_vm_module* module{nullptr};
+ npu_vm_engine* engine{nullptr};
+
+ void TearDown() override {
+ if (engine != nullptr) {
+ npu_vm_destroy_engine(engine);
+ }
+ if (module != nullptr) {
+ npu_vm_destroy_module(module);
+ }
+ }
+
+ std::vector<uint8_t> makeValidBytecode() {
+ const auto int64Type = Type{IntegerType{sizeof(int64_t) * CHAR_BIT, /*isSigned=*/true}};
+ const auto uint32Type = Type{IntegerType{sizeof(uint32_t) * CHAR_BIT, /*isSigned=*/false}};
+ const auto bufferType = Type{BufferType{/*dataTypeIndex=*/0, /*rank=*/1, /*shape=*/{1}, /*strides=*/{1}}};
+ return BytecodeBuilder{}
+ .addFunction(BytecodeBuilder::FunctionBuilder(ENTRY_FUNC_NAME, /*numGeneralRegisters=*/1,
+ /*paramTypes=*/{},
+ /*resultTypes=*/{},
+ /*isEntrypoint=*/true)
+ .ret())
+ .addFunction(BytecodeBuilder::FunctionBuilder(ADD_FUNC_NAME, /*numGeneralRegisters=*/3,
+ /*paramTypes=*/{int64Type, int64Type},
+ /*resultTypes=*/{int64Type})
+ .instruction(OpCode::ADD_I64, {/*dst=*/0, /*lhs=*/1, /*rhs=*/2})
+ .retv({0}))
+ .addFunction(BytecodeBuilder::FunctionBuilder(UINT32_IDENTITY_FUNC_NAME, /*numGeneralRegisters=*/1,
+ /*paramTypes=*/{uint32Type},
+ /*resultTypes=*/{uint32Type})
+ .retv({0}))
+ .addFunction(BytecodeBuilder::FunctionBuilder(BUFFER_IDENTITY_FUNC_NAME, /*numGeneralRegisters=*/1,
+ /*paramTypes=*/{bufferType},
+ /*resultTypes=*/{bufferType})
+ .retv({0}))
+ .build();
+ }
+};
+
+TEST_F(VirtualMachineApiTest, ParseReturnsInvalidNullPointerForNullModulePointer) {
+ const auto bytecode = makeValidBytecode();
+ EXPECT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, ParseSucceedsForValidBytecode) {
+ const auto bytecode = makeValidBytecode();
+ EXPECT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, ParseFailsForInvalidBytecode) {
+ const std::array<uint8_t, 4> badBytecode{0x01, 0x02, 0x03, 0x04};
+ EXPECT_EQ(npu_vm_parse_module(badBytecode.data(), static_cast<uint32_t>(badBytecode.size()), &module), NPU_VM_ERROR_UNKNOWN);
+}
+
+TEST_F(VirtualMachineApiTest, DestroyModuleReturnsInvalidNullPointerForNullModule) {
+ EXPECT_EQ(npu_vm_destroy_module(nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, DestroyModuleSucceedsForValidModule) {
+ const auto bytecode = makeValidBytecode();
+ npu_vm_module* localModule{nullptr};
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &localModule), NPU_VM_SUCCESS);
+ ASSERT_NE(localModule, nullptr);
+ EXPECT_EQ(npu_vm_destroy_module(localModule), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, PrintSucceedsForValidBytecode) {
+ const auto bytecode = makeValidBytecode();
+ EXPECT_EQ(npu_vm_print(bytecode.data(), static_cast<uint32_t>(bytecode.size()), /*print_full=*/false, /*indent_level=*/0), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, PrintFailsForInvalidBytecode) {
+ const std::array<uint8_t, 2> badBytecode{0x0A, 0x0B};
+ EXPECT_EQ(npu_vm_print(badBytecode.data(), static_cast<uint32_t>(badBytecode.size()), /*print_full=*/false, /*indent_level=*/0),
+ NPU_VM_ERROR_UNKNOWN);
+}
+
+TEST_F(VirtualMachineApiTest, GetFunctionInfoReturnsInvalidNullPointerForNullInputs) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+
+ npu_vm_function_info* info{nullptr};
+ EXPECT_EQ(npu_vm_get_function_info(nullptr, ADD_FUNC_NAME, &info), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ EXPECT_EQ(npu_vm_get_function_info(module, nullptr, &info), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ EXPECT_EQ(npu_vm_get_function_info(module, ADD_FUNC_NAME, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, GetFunctionInfoReturnsNotFoundForMissingFunction) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+
+ npu_vm_function_info* info{nullptr};
+ EXPECT_EQ(npu_vm_get_function_info(module, MISSING_FUNC_NAME, &info), NPU_VM_ERROR_FUNCTION_NOT_FOUND);
+}
+
+TEST_F(VirtualMachineApiTest, GetFunctionInfoReturnsFunctionSignature) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+
+ npu_vm_function_info* info{nullptr};
+ ASSERT_EQ(npu_vm_get_function_info(module, ADD_FUNC_NAME, &info), NPU_VM_SUCCESS);
+ ASSERT_NE(info, nullptr);
+ const std::string expectedName(ADD_FUNC_NAME);
+ EXPECT_STREQ(info->name, expectedName.c_str());
+ EXPECT_EQ(info->num_params, 2u);
+ EXPECT_EQ(info->num_results, 1u);
+ EXPECT_EQ(info->param_types[0], npu_vm_type_int64);
+ EXPECT_EQ(info->param_types[1], npu_vm_type_int64);
+ EXPECT_EQ(info->result_types[0], npu_vm_type_int64);
+ EXPECT_EQ(npu_vm_destroy_function_info(info), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, GetFunctionInfoReturnsBufferSignature) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+
+ npu_vm_function_info* info{nullptr};
+ ASSERT_EQ(npu_vm_get_function_info(module, BUFFER_IDENTITY_FUNC_NAME, &info), NPU_VM_SUCCESS);
+ ASSERT_NE(info, nullptr);
+ EXPECT_EQ(info->num_params, 1u);
+ EXPECT_EQ(info->num_results, 1u);
+ EXPECT_EQ(info->param_types[0], npu_vm_type_buffer);
+ EXPECT_EQ(info->result_types[0], npu_vm_type_buffer);
+ EXPECT_EQ(npu_vm_destroy_function_info(info), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, GetFunctionInfoReturnsUnsignedIntegerSignature) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+
+ npu_vm_function_info* info{nullptr};
+ ASSERT_EQ(npu_vm_get_function_info(module, UINT32_IDENTITY_FUNC_NAME, &info), NPU_VM_SUCCESS);
+ ASSERT_NE(info, nullptr);
+ EXPECT_EQ(info->num_params, 1u);
+ EXPECT_EQ(info->num_results, 1u);
+ EXPECT_EQ(info->param_types[0], npu_vm_type_uint32);
+ EXPECT_EQ(info->result_types[0], npu_vm_type_uint32);
+ EXPECT_EQ(npu_vm_destroy_function_info(info), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, DestroyFunctionInfoReturnsInvalidNullPointerForNullInfo) {
+ EXPECT_EQ(npu_vm_destroy_function_info(nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, CreateNewEngineReturnsInvalidNullPointerForNullEngineHandle) {
+ EXPECT_EQ(npu_vm_new_engine(nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, CreateNewEngineSucceeds) {
+ EXPECT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ EXPECT_NE(engine, nullptr);
+}
+
+TEST_F(VirtualMachineApiTest, DestroyEngineReturnsInvalidNullPointerForNullEngine) {
+ EXPECT_EQ(npu_vm_destroy_engine(nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, LoadModuleReturnsInvalidNullPointerForNullEngineOrModule) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(npu_vm_load_module(nullptr, /*moduleParams*/ nullptr, module), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ EXPECT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, LoadModuleSucceedsForValidEngineAndModule) {
+ const auto bytecode = makeValidBytecode();
+ npu_vm_module* localModule{nullptr};
+ npu_vm_engine* localEngine{nullptr};
+
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &localModule), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&localEngine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(localEngine, /*moduleParams*/ nullptr, localModule), NPU_VM_SUCCESS);
+
+ EXPECT_EQ(npu_vm_destroy_engine(localEngine), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_destroy_module(localModule), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, ResetStateReturnsInvalidNullPointerForNullEngine) {
+ EXPECT_EQ(npu_vm_reset_state(nullptr, /*resetExecutionContext=*/false), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, ResetStateSucceedsForValidEngine) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_reset_state(engine, /*resetExecutionContext=*/false), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_reset_state(engine, /*resetExecutionContext=*/true), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, CallReturnsInvalidNullPointerForNullEngineOrName) {
+ npu_vm_value arg = intel_npu::vm::makeI64(1);
+ EXPECT_EQ(npu_vm_call(nullptr, ENTRY_FUNC_NAME, 1, &arg), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_call(engine, nullptr, 1, &arg), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, CallReturnsFunctionNotFoundForMissingFunction) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_call(engine, MISSING_FUNC_NAME, 0, nullptr), NPU_VM_ERROR_FUNCTION_NOT_FOUND);
+}
+
+TEST_F(VirtualMachineApiTest, CallExecutesFunctionWithoutResults) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_call(engine, ENTRY_FUNC_NAME, 0, nullptr), NPU_VM_SUCCESS);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsReturnsInvalidNullPointerForNullEngineOrName) {
+ const std::array<npu_vm_value, 2> args = {intel_npu::vm::makeI64(1), intel_npu::vm::makeI64(2)};
+ npu_vm_value result = intel_npu::vm::makeI64(0);
+ EXPECT_EQ(npu_vm_call_with_results(nullptr, ADD_FUNC_NAME, static_cast<uint32_t>(args.size()), args.data(), 1, &result),
+ NPU_VM_ERROR_INVALID_NULL_POINTER);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_call_with_results(engine, nullptr, static_cast<uint32_t>(args.size()), args.data(), 1, &result),
+ NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsReturnsFunctionCallFailedForSignatureMismatch) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+ // Note: Function expects two arguments, but only one is provided
+ const std::array<npu_vm_value, 1> args = {intel_npu::vm::makeI64(1)};
+ npu_vm_value result = intel_npu::vm::makeI64(0);
+ EXPECT_EQ(npu_vm_call_with_results(engine, ADD_FUNC_NAME, static_cast<uint32_t>(args.size()), args.data(), 1, &result),
+ NPU_VM_ERROR_FUNCTION_CALL_FAILED);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsExecutesFunctionAndWritesResults) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ constexpr int64_t firstArg = 10;
+ constexpr int64_t secondArg = 11;
+ const std::array<npu_vm_value, 2> args = {intel_npu::vm::makeI64(firstArg), intel_npu::vm::makeI64(secondArg)};
+ npu_vm_value result = intel_npu::vm::makeI64(0);
+ ASSERT_EQ(npu_vm_call_with_results(engine, ADD_FUNC_NAME, static_cast<uint32_t>(args.size()), args.data(), 1, &result), NPU_VM_SUCCESS);
+ EXPECT_EQ(result.i64, firstArg + secondArg);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsSucceedsForTwoConsecutiveCallsWithDifferentArguments) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ {
+ const std::array<npu_vm_value, 2> args = {intel_npu::vm::makeI64(2), intel_npu::vm::makeI64(3)};
+ npu_vm_value result = intel_npu::vm::makeI64(0);
+ ASSERT_EQ(npu_vm_call_with_results(engine, ADD_FUNC_NAME, static_cast<uint32_t>(args.size()), args.data(), 1, &result),
+ NPU_VM_SUCCESS);
+ EXPECT_EQ(result.i64, 5);
+ }
+ ASSERT_EQ(npu_vm_reset_state(engine, /*resetExecutionContext=*/false), NPU_VM_SUCCESS);
+ {
+ const std::array<npu_vm_value, 2> args = {intel_npu::vm::makeI64(10), intel_npu::vm::makeI64(20)};
+ npu_vm_value result = intel_npu::vm::makeI64(0);
+ ASSERT_EQ(npu_vm_call_with_results(engine, ADD_FUNC_NAME, static_cast<uint32_t>(args.size()), args.data(), 1, &result),
+ NPU_VM_SUCCESS);
+ EXPECT_EQ(result.i64, 30);
+ }
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsRoundTripsUnsignedValuesIncludingAboveSignedMax) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ const std::array<uint32_t, 5> values = {
+ 0U, 1U, static_cast<uint32_t>(INT32_MAX), static_cast<uint32_t>(INT32_MAX) + 1U, UINT32_MAX,
+ };
+
+ for (const auto value : values) {
+ npu_vm_value arg{};
+ arg.u32 = value;
+ npu_vm_value result{};
+ result.u32 = 0U;
+
+ ASSERT_EQ(npu_vm_call_with_results(engine, UINT32_IDENTITY_FUNC_NAME, 1, &arg, 1, &result), NPU_VM_SUCCESS);
+ EXPECT_EQ(result.u32, value);
+ }
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsSupportsBufferArgumentAndResult) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ std::array<uint8_t, 16> inputBuffer{};
+ std::iota(inputBuffer.begin(), inputBuffer.end(), 0); // Fill with sample data {0, 1, 2, ..., 15}
+ npu_vm_value arg = intel_npu::vm::makeBuffer(inputBuffer.data(), static_cast<uint32_t>(inputBuffer.size()));
+ std::array<uint8_t, 16> outputBuffer{}; // Pre-allocated output buffer
+ npu_vm_value result = intel_npu::vm::makeBuffer(outputBuffer.data(), static_cast<uint32_t>(outputBuffer.size()));
+ ASSERT_EQ(npu_vm_call_with_results(engine, BUFFER_IDENTITY_FUNC_NAME, 1, &arg, 1, &result), NPU_VM_SUCCESS);
+ EXPECT_NE(result.buffer.data, nullptr);
+ EXPECT_EQ(result.buffer.size, inputBuffer.size());
+ EXPECT_TRUE(std::equal(inputBuffer.begin(), inputBuffer.end(), static_cast<uint8_t*>(result.buffer.data)));
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsSupportsBufferArgumentAndInternallyAllocatedResult) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ std::array<uint8_t, 16> inputBuffer{};
+ std::iota(inputBuffer.begin(), inputBuffer.end(), 0); // Fill with sample data {0, 1, 2, ..., 15}
+ npu_vm_value arg = intel_npu::vm::makeBuffer(inputBuffer.data(), static_cast<uint32_t>(inputBuffer.size()));
+ npu_vm_value result = intel_npu::vm::makeBuffer(nullptr, 0);
+ ASSERT_EQ(npu_vm_call_with_results(engine, BUFFER_IDENTITY_FUNC_NAME, 1, &arg, 1, &result), NPU_VM_SUCCESS);
+ EXPECT_NE(result.buffer.data, nullptr);
+ EXPECT_EQ(result.buffer.size, inputBuffer.size());
+ EXPECT_TRUE(std::equal(inputBuffer.begin(), inputBuffer.end(), static_cast<uint8_t*>(result.buffer.data)));
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory, cppcoreguidelines-no-malloc)
+ free(result.buffer.data);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsFailsIfPreAllocatedBufferResultIsTooSmall) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ std::array<uint8_t, 16> inputBuffer{};
+ std::iota(inputBuffer.begin(), inputBuffer.end(), 0); // Fill with sample data {0, 1, 2, ..., 15}
+ npu_vm_value arg = intel_npu::vm::makeBuffer(inputBuffer.data(), static_cast<uint32_t>(inputBuffer.size()));
+ std::array<uint8_t, 8> outputBuffer{}; // Pre-allocated output buffer that is too small
+ npu_vm_value result = intel_npu::vm::makeBuffer(outputBuffer.data(), static_cast<uint32_t>(outputBuffer.size()));
+ EXPECT_EQ(npu_vm_call_with_results(engine, BUFFER_IDENTITY_FUNC_NAME, 1, &arg, 1, &result),
+ NPU_VM_ERROR_FUNCTION_CALL_FAILED);
+}
+
+TEST_F(VirtualMachineApiTest, CallWithResultsFailsIfBufferResultIsNullAndSizeIsNonZero) {
+ const auto bytecode = makeValidBytecode();
+ ASSERT_EQ(npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ ASSERT_EQ(npu_vm_load_module(engine, /*moduleParams*/ nullptr, module), NPU_VM_SUCCESS);
+
+ std::array<uint8_t, 16> inputBuffer{};
+ std::iota(inputBuffer.begin(), inputBuffer.end(), 0); // Fill with sample data {0, 1, 2, ..., 15}
+ npu_vm_value arg = intel_npu::vm::makeBuffer(inputBuffer.data(), static_cast<uint32_t>(inputBuffer.size()));
+ npu_vm_value result = intel_npu::vm::makeBuffer(nullptr, 16); // Invalid: null data pointer but non-zero size
+ EXPECT_EQ(npu_vm_call_with_results(engine, BUFFER_IDENTITY_FUNC_NAME, 1, &arg, 1, &result),
+ NPU_VM_ERROR_FUNCTION_CALL_FAILED);
+}
+
+TEST_F(VirtualMachineApiTest, InferReturnsInvalidNullPointerForNullEngineOrParams) {
+ EXPECT_EQ(npu_vm_infer(nullptr, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_infer(engine, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+TEST_F(VirtualMachineApiTest, PredictOutputShapeReturnsInvalidNullPointerForNullEngineOrParams) {
+ EXPECT_EQ(npu_vm_predict_output_shape(nullptr, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+ ASSERT_EQ(npu_vm_new_engine(&engine), NPU_VM_SUCCESS);
+ EXPECT_EQ(npu_vm_predict_output_shape(engine, nullptr), NPU_VM_ERROR_INVALID_NULL_POINTER);
+}
+
+} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/vm/virtual_machine_parse.cpp b/src/plugins/intel_npu/tests/unit/vm/virtual_machine_parse.cpp
new file mode 100644
index 00000000000..cf6d5886fcd
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/virtual_machine_parse.cpp
@@ -0,0 +1,137 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "npu_bytecode_utils/magic_number.hpp"
+#include "npu_bytecode_utils/network_description.hpp"
+#include "npu_bytecode_utils/section_header_table.hpp"
+#include "npu_bytecode_utils/serialization_utils.hpp"
+#include "npu_bytecode_utils/type_section.hpp"
+#include "npu_bytecode_utils/version.hpp"
+#include "vm_runtime/virtual_machine.h"
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+using namespace intel_npu::vm;
+
+namespace {
+
+SectionHeader makeTypeSectionHeader(const std::vector<uint8_t>& typeSection) {
+ details::DataSectionInfo sectionInfo;
+ sectionInfo.numData = 1;
+ sectionInfo.dataInfos.push_back({/*offset=*/0, /*size=*/static_cast<uint64_t>(typeSection.size())});
+
+ SectionHeader header{};
+ header.type = SectionType::TypeSection;
+ header.nameIndex = 0;
+ header.offset = 0;
+ header.size = static_cast<uint64_t>(typeSection.size());
+ header.info = std::make_unique<details::DataSectionInfo>(sectionInfo);
+ return header;
+}
+
+std::vector<uint8_t> makeBytecodeWithDuplicateTypeSections() {
+ std::vector<uint8_t> firstTypeSection;
+ IntegerType{/*bitWidth=*/32, true}.appendTo(firstTypeSection);
+
+ std::vector<uint8_t> secondTypeSection;
+ FloatType{/*bitWidth=*/32, /*format=*/FloatTypeFormat::IEEE754}.appendTo(secondTypeSection);
+
+ SectionHeaderTable sectionHeaderTable;
+ sectionHeaderTable.addSectionHeader(makeTypeSectionHeader(firstTypeSection));
+ sectionHeaderTable.addSectionHeader(makeTypeSectionHeader(secondTypeSection));
+ sectionHeaderTable.computeOffsets();
+
+ std::vector<uint8_t> bytecodeBuffer;
+ MagicNumber(MAGIC_NUMBER).appendTo(bytecodeBuffer);
+ Version(/*major=*/1, /*minor=*/0, /*patch=*/0).appendTo(bytecodeBuffer);
+ sectionHeaderTable.appendTo(bytecodeBuffer);
+ bytecodeBuffer.insert(bytecodeBuffer.end(), firstTypeSection.begin(), firstTypeSection.end());
+ bytecodeBuffer.insert(bytecodeBuffer.end(), secondTypeSection.begin(), secondTypeSection.end());
+ return bytecodeBuffer;
+}
+
+template <typename ElementType>
+void checkMetadataPrecision(const ElementType& elementType, ov::element::Type expectedPrecision) {
+ SCOPED_TRACE(expectedPrecision.get_type_name());
+ for (const auto recordKind : {MetadataRecordKind::Input, MetadataRecordKind::Output}) {
+ SCOPED_TRACE(static_cast<int>(recordKind));
+ std::vector<uint8_t> typeSection;
+ elementType.appendTo(typeSection);
+ std::vector<uint8_t> stringSection{'t', 'e', 'n', 's', 'o', 'r', 0};
+ std::vector<uint8_t> shapeSection;
+ appendValueTo(shapeSection, int64_t{2});
+ appendValueTo(shapeSection, int64_t{3});
+
+ std::vector<uint8_t> metadataSection;
+ appendValueTo(metadataSection, recordKind);
+ appendValueTo(metadataSection, uint64_t{0});
+ appendValueTo(metadataSection, uint64_t{0});
+ appendValueTo(metadataSection, uint64_t{0});
+ appendValueTo(metadataSection, uint32_t{0});
+ appendValueTo(metadataSection, uint8_t{0});
+ appendValueTo(metadataSection, uint8_t{0});
+ appendValueTo(metadataSection, uint8_t{0});
+ appendValueTo(metadataSection, uint8_t{0});
+
+ SectionHeaderTable sectionHeaderTable;
+ const auto addSection = [&](SectionType sectionType, const std::vector<uint8_t>& payload) {
+ auto header = makeTypeSectionHeader(payload);
+ header.type = sectionType;
+ sectionHeaderTable.addSectionHeader(std::move(header));
+ };
+ addSection(SectionType::TypeSection, typeSection);
+ addSection(SectionType::StringSection, stringSection);
+ addSection(SectionType::ConstantSection, shapeSection);
+ addSection(SectionType::MetadataSection, metadataSection);
+ sectionHeaderTable.computeOffsets();
+
+ std::vector<uint8_t> bytecode;
+ MagicNumber(MAGIC_NUMBER).appendTo(bytecode);
+ Version(1, 0, 0).appendTo(bytecode);
+ sectionHeaderTable.appendTo(bytecode);
+ for (const auto* payload : {&shapeSection, &stringSection, &typeSection, &metadataSection}) {
+ bytecode.insert(bytecode.end(), payload->begin(), payload->end());
+ }
+
+ const auto metadata = parseNetworkMetadata(bytecode.data(), bytecode.size());
+ ASSERT_TRUE(metadata.has_value());
+ const auto& descriptors = recordKind == MetadataRecordKind::Input ? metadata->inputs : metadata->outputs;
+ ASSERT_EQ(descriptors.size(), 1);
+ EXPECT_EQ(descriptors.front().precision, expectedPrecision);
+ EXPECT_EQ(descriptors.front().shapeFromCompiler, ov::PartialShape({2, 3}));
+ EXPECT_EQ(descriptors.front().nameFromCompiler, "tensor");
+ }
+}
+
+} // namespace
+
+TEST(VirtualMachineParseTest, RejectsDuplicateTypeSections) {
+ npu_vm_module* module{nullptr};
+ const auto bytecode = makeBytecodeWithDuplicateTypeSections();
+ auto status = npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &module);
+ EXPECT_FALSE(status == NPU_VM_SUCCESS);
+ if (status == NPU_VM_SUCCESS) {
+ npu_vm_destroy_module(module);
+ }
+}
+
+TEST(VirtualMachineParseTest, MetadataPreservesI4Precision) {
+ checkMetadataPrecision(IntegerType{4, true}, ov::element::i4);
+}
+
+TEST(VirtualMachineParseTest, MetadataPreservesU4Precision) {
+ checkMetadataPrecision(IntegerType{4, false}, ov::element::u4);
+}
+
+TEST(VirtualMachineParseTest, MetadataPreservesNF4Precision) {
+ checkMetadataPrecision(FloatType{4, FloatTypeFormat::NF4}, ov::element::nf4);
+}
+
+TEST(VirtualMachineParseTest, MetadataPreservesF16Precision) {
+ checkMetadataPrecision(FloatType{16, FloatTypeFormat::IEEE754}, ov::element::f16);
+}
diff --git a/src/plugins/intel_npu/tests/unit/vm/vm_value_helpers.hpp b/src/plugins/intel_npu/tests/unit/vm/vm_value_helpers.hpp
new file mode 100644
index 00000000000..123d3ea811e
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/vm/vm_value_helpers.hpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "vm_runtime/virtual_machine.h"
+
+#include <cstdint>
+#include <cstring>
+
+namespace intel_npu::vm {
+
+inline npu_vm_value makeI64(int64_t v) {
+ npu_vm_value val{};
+ val.i64 = v;
+ return val;
+}
+
+inline npu_vm_value makeF32(float v) {
+ npu_vm_value val{};
+ val.f32 = v;
+ return val;
+}
+
+inline npu_vm_value makeF64(double v) {
+ npu_vm_value val{};
+ val.f64 = v;
+ return val;
+}
+
+inline npu_vm_value makeBuffer(uint8_t* data, uint32_t size) {
+ npu_vm_value val{};
+ val.buffer.data = data;
+ val.buffer.size = size;
+ return val;
+}
+
+} // namespace intel_npu::vm
diff --git a/src/plugins/intel_npu/tools/CMakeLists.txt b/src/plugins/intel_npu/tools/CMakeLists.txt
index b91a6fc8e30..b97f63c64e5 100644
--- a/src/plugins/intel_npu/tools/CMakeLists.txt
+++ b/src/plugins/intel_npu/tools/CMakeLists.txt
@@ -1,8 +1,8 @@
-#
# Copyright (C) 2018-2026 Intel Corporation.
# SPDX-License-Identifier: Apache 2.0
#
+add_subdirectory(bytecode_interpreter)
add_subdirectory(common)
add_subdirectory(compile_tool)
add_subdirectory(single-image-test)
diff --git a/src/plugins/intel_npu/tools/bytecode_interpreter/CMakeLists.txt b/src/plugins/intel_npu/tools/bytecode_interpreter/CMakeLists.txt
new file mode 100644
index 00000000000..f5c86a4a62a
--- /dev/null
+++ b/src/plugins/intel_npu/tools/bytecode_interpreter/CMakeLists.txt
@@ -0,0 +1,30 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+#
+
+set(TARGET_NAME bytecode_interpreter)
+
+set(GFLAGS_USE_TARGET_NAMESPACE ON)
+find_package(gflags QUIET)
+
+ov_add_target(TYPE EXECUTABLE
+ NAME ${TARGET_NAME}
+ ROOT ${CMAKE_CURRENT_SOURCE_DIR}
+ LINK_LIBRARIES
+ PRIVATE
+ openvino::runtime::dev
+ gflags
+ openvino::intel_npu_vm_runtime
+ openvino::npu_zero_utils)
+
+set_target_properties(${TARGET_NAME} PROPERTIES
+ FOLDER intel_npu_tools
+ CXX_STANDARD 17)
+
+#
+# Install
+#
+
+install(TARGETS ${TARGET_NAME}
+ RUNTIME DESTINATION "tools/${TARGET_NAME}"
+ COMPONENT ${NPU_INTERNAL_COMPONENT})
diff --git a/src/plugins/intel_npu/tools/bytecode_interpreter/bytecode_interpreter.cpp b/src/plugins/intel_npu/tools/bytecode_interpreter/bytecode_interpreter.cpp
new file mode 100644
index 00000000000..a0bbc5f9a9e
--- /dev/null
+++ b/src/plugins/intel_npu/tools/bytecode_interpreter/bytecode_interpreter.cpp
@@ -0,0 +1,526 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "vm_runtime/virtual_machine.h"
+
+#include <gflags/gflags.h>
+
+#include <algorithm>
+#include <cerrno>
+#include <charconv>
+#include <climits>
+#include <cstddef>
+#include <cstdint>
+#include <cstdlib>
+#include <exception>
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+#include <iterator>
+#include <limits>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <system_error>
+#include <type_traits>
+#include <vector>
+
+DEFINE_string(path, "", "[Required] Path to the bytecode file");
+DEFINE_validator(path, [](const char* flagname, const std::string& value) {
+ if (value.empty()) {
+ std::cerr << "Error: the path to the bytecode file must be provided via the --" << flagname << " argument"
+ << std::endl;
+ return false;
+ }
+ if (!std::filesystem::exists(value)) {
+ std::cerr << "Error: the specified bytecode file does not exist: " << value << std::endl;
+ return false;
+ }
+ return true;
+});
+DEFINE_string(mode, "run",
+ "[Optional] Execution mode: 'run', 'print', 'print-full'. The 'print-full' mode includes the "
+ "content of binary sections, such as constants or kernels");
+DEFINE_validator(mode, [](const char* /*flagname*/, const std::string& value) {
+ if (value != "run" && value != "print" && value != "print-full") {
+ std::cerr << "Error: invalid execution mode '" << value << "'. Valid options are: run, print, print-full."
+ << std::endl;
+ return false;
+ }
+ return true;
+});
+DEFINE_string(function, NPU_VM_MAIN_INFERENCE_FUNCTION_NAME,
+ "[Optional] Name of the function to execute (default 'main'). Used if --mode=run");
+DEFINE_validator(function, [](const char* flagname, const std::string& value) {
+ if (FLAGS_mode == "run" && value.empty()) {
+ std::cerr << "Error: the name of the entrypoint function must be provided via the --" << flagname
+ << " argument when --mode=run" << std::endl;
+ return false;
+ }
+ return true;
+});
+DEFINE_string(params, "",
+ "[Optional] Comma-separated list of typed parameters to pass to the called function, in the format "
+ "'type:value,...' where type is one of: i8, i16, i32, i64, u8, u16, u32, u64, f32, f64, buffer. "
+ "For buffer, value has the format `byteSize|hexData`, where `byteSize` is the size of the buffer and "
+ "`hexData` is the content in hexadecimal format; if the content should have the same value repeated, a "
+ "single hex byte can be provided (e.g. `00` for a zero-initialized buffer)."
+ "If only a part of the hex data is given, the rest will be padded with zero"
+ "Example: --params 'i32:42,f32:3.14,i64:100,buffer:4|00010203'. Used if --mode=run");
+
+namespace {
+
+struct Values {
+ std::vector<npu_vm_value> values;
+ std::vector<std::vector<uint8_t>> ownedBuffers;
+};
+
+constexpr int HEX_BASE = 16;
+constexpr size_t HEX_CHARS_PER_BYTE = 2;
+
+template <typename T>
+std::optional<T> parseFromChars(std::string_view input, int base = 10) {
+ if constexpr (std::is_integral_v<T>) {
+ const auto* begin = input.data();
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - std::from_chars requires pointers
+ const auto* end = begin + input.size();
+ T parsed{};
+ const auto result = std::from_chars(begin, end, parsed, base);
+ if (result.ec != std::errc{} || result.ptr != end) {
+ return std::nullopt;
+ }
+ return parsed;
+ } else if constexpr (std::is_floating_point_v<T>) {
+ // std::from_chars(float/double) is not available on all C++17 standard libraries
+ std::string inputStr(input);
+ const auto* begin = inputStr.c_str();
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - checking full token consumption
+ const auto* end = begin + inputStr.size();
+ char* endPtr = nullptr;
+ errno = 0;
+ T parsed{};
+ if constexpr (std::is_same_v<T, float>) {
+ parsed = std::strtof(begin, &endPtr);
+ } else if constexpr (std::is_same_v<T, double>) {
+ parsed = std::strtod(begin, &endPtr);
+ } else {
+ parsed = static_cast<T>(std::strtold(begin, &endPtr));
+ }
+ if (endPtr == begin || endPtr != end || errno == ERANGE) {
+ return std::nullopt;
+ }
+ return parsed;
+ } else {
+ static_assert(std::is_integral_v<T> || std::is_floating_point_v<T>, "Unsupported type for parseFromChars");
+ return std::nullopt;
+ }
+}
+
+template <typename T>
+bool parseTypedValue(std::string_view valueStr, std::string_view typeName, T& outValue) {
+ const auto parsed = parseFromChars<T>(valueStr);
+ if (!parsed.has_value()) {
+ std::cerr << "Error: Invalid value '" << valueStr << "' for type '" << typeName << "'" << std::endl;
+ return false;
+ }
+ outValue = *parsed;
+ return true;
+}
+
+std::optional<uint8_t> parseHexByte(std::string_view hexByte) {
+ auto parsed = parseFromChars<unsigned int>(hexByte, HEX_BASE);
+ if (!parsed.has_value() || *parsed > std::numeric_limits<uint8_t>::max()) {
+ return std::nullopt;
+ }
+ return static_cast<uint8_t>(*parsed);
+}
+
+std::optional<Values> parseParams(const std::string& paramsStr) {
+ Values params;
+ if (paramsStr.empty()) {
+ return params;
+ }
+ std::istringstream ss(paramsStr);
+ std::string token;
+ while (std::getline(ss, token, ',')) {
+ const auto colonPos = token.find(':');
+ if (colonPos == std::string::npos) {
+ std::cerr << "Error: Invalid parameter format '" << token << "'. Expected 'type:value'" << std::endl;
+ return std::nullopt;
+ }
+ const auto type = token.substr(0, colonPos);
+ const auto valueStr = token.substr(colonPos + 1);
+ npu_vm_value value{};
+ if (type == "i8") {
+ if (!parseTypedValue(valueStr, "i8", value.i8)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "u8") {
+ if (!parseTypedValue(valueStr, "u8", value.u8)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "i16") {
+ if (!parseTypedValue(valueStr, "i16", value.i16)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "u16") {
+ if (!parseTypedValue(valueStr, "u16", value.u16)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "i32") {
+ if (!parseTypedValue(valueStr, "i32", value.i32)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "u32") {
+ if (!parseTypedValue(valueStr, "u32", value.u32)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "i64") {
+ if (!parseTypedValue(valueStr, "i64", value.i64)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "u64") {
+ if (!parseTypedValue(valueStr, "u64", value.u64)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "f32") {
+ if (!parseTypedValue(valueStr, "f32", value.f32)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "f64") {
+ if (!parseTypedValue(valueStr, "f64", value.f64)) {
+ return std::nullopt;
+ }
+ params.values.emplace_back(value);
+ } else if (type == "buffer") {
+ const auto pipePos = valueStr.find('|');
+ if (pipePos == std::string::npos) {
+ std::cerr << "Error: Buffer parameter must specify size and content in the format 'size|hexdata'"
+ << std::endl;
+ return std::nullopt;
+ }
+
+ const auto sizeStr = valueStr.substr(0, pipePos);
+ const auto contentStr = valueStr.substr(pipePos + 1);
+ const auto byteSize = parseFromChars<size_t>(sizeStr);
+ if (!byteSize.has_value()) {
+ std::cerr << "Error: Invalid buffer size '" << sizeStr << "'" << std::endl;
+ return std::nullopt;
+ }
+ if (*byteSize == 0) {
+ std::cerr << "Error: Buffer parameter size must be greater than 0" << std::endl;
+ return std::nullopt;
+ }
+ if (contentStr.empty()) {
+ std::cerr << "Error: Buffer parameter content cannot be empty. Use '00' for zero-initialized buffer."
+ << std::endl;
+ return std::nullopt;
+ }
+ if (contentStr.size() % HEX_CHARS_PER_BYTE != 0 || contentStr.size() / HEX_CHARS_PER_BYTE > *byteSize) {
+ std::cerr << "Error: Invalid buffer content size or format" << std::endl;
+ return std::nullopt;
+ }
+ const auto isSplat = contentStr.size() == HEX_CHARS_PER_BYTE;
+
+ params.ownedBuffers.emplace_back(*byteSize, uint8_t{0});
+ auto& buffer = params.ownedBuffers.back();
+ if (isSplat) {
+ const auto byte = parseHexByte(contentStr);
+ if (!byte.has_value()) {
+ std::cerr << "Error: Invalid hexadecimal buffer content '" << contentStr << "'" << std::endl;
+ return std::nullopt;
+ }
+ std::fill(buffer.begin(), buffer.end(), *byte);
+ } else {
+ for (size_t i = 0; i < contentStr.size(); i += HEX_CHARS_PER_BYTE) {
+ const auto hexPair = std::string_view(contentStr).substr(i, HEX_CHARS_PER_BYTE);
+ const auto byte = parseHexByte(hexPair);
+ if (!byte.has_value()) {
+ std::cerr << "Error: Invalid hexadecimal byte in buffer content at position " << i << std::endl;
+ return std::nullopt;
+ }
+ buffer.at(i / HEX_CHARS_PER_BYTE) = *byte;
+ }
+ }
+ value.buffer.data = buffer.data();
+ if (buffer.size() > std::numeric_limits<uint32_t>::max()) {
+ std::cerr << "Error: Buffer size exceeds maximum supported size of "
+ << std::numeric_limits<uint32_t>::max() << " bytes" << std::endl;
+ return std::nullopt;
+ }
+ value.buffer.size = static_cast<uint32_t>(buffer.size());
+ params.values.emplace_back(value);
+ } else {
+ std::cerr << "Error: Unknown parameter type '" << type
+ << "'. Valid types are: i8, i16, i32, i64, u8, u16, u32, u64, f32, f64, buffer" << std::endl;
+ return std::nullopt;
+ }
+ }
+ return params;
+}
+
+std::optional<Values> createResultStorage(npu_vm_function_info* functionInfo) {
+ const auto& resultTypes = functionInfo->result_types;
+ Values results;
+ results.values.reserve(functionInfo->num_results);
+ for (size_t i = 0; i < functionInfo->num_results; ++i) {
+ npu_vm_value value{};
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - using C API with raw pointers
+ const auto resultType = resultTypes[i];
+ switch (resultType) {
+ case npu_vm_type_int8: {
+ value.i8 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_uint8: {
+ value.u8 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_int16: {
+ value.i16 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_uint16: {
+ value.u16 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_int32: {
+ value.i32 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_uint32: {
+ value.u32 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_int64: {
+ value.i64 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_uint64: {
+ value.u64 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_float32: {
+ value.f32 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_float64: {
+ value.f64 = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ case npu_vm_type_buffer: {
+ value.buffer.data = nullptr;
+ value.buffer.size = 0;
+ results.values.emplace_back(value);
+ break;
+ }
+ default:
+ std::cerr << "Error: Unknown result type " << static_cast<int>(resultType) << " for result " << i
+ << std::endl;
+ return std::nullopt;
+ }
+ }
+ return results;
+}
+
+template <typename T>
+void printSpecificResult(size_t i, const T& value, std::string_view typeStr) {
+ std::cout << "Result[" << i << "] (" << typeStr << "): " << value << std::endl;
+}
+
+void printResults(npu_vm_function_info* functionInfo, const Values& results) {
+ const auto& resultTypes = functionInfo->result_types;
+ if (results.values.size() != functionInfo->num_results) {
+ std::cerr << "Warning: Number of results returned (" << results.values.size()
+ << ") does not match the function's declared number of result types (" << functionInfo->num_results
+ << "). Attempting to print results anyway." << std::endl;
+ }
+ for (size_t i = 0; i < functionInfo->num_results; ++i) {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - using C API with raw pointers
+ const auto resultType = resultTypes[i];
+ switch (resultType) {
+ case npu_vm_type_int8:
+ printSpecificResult(i, static_cast<int32_t>(results.values.at(i).i8), "i8");
+ break;
+ case npu_vm_type_uint8:
+ printSpecificResult(i, static_cast<uint32_t>(results.values.at(i).u8), "u8");
+ break;
+ case npu_vm_type_int16:
+ printSpecificResult(i, results.values.at(i).i16, "i16");
+ break;
+ case npu_vm_type_uint16:
+ printSpecificResult(i, results.values.at(i).u16, "u16");
+ break;
+ case npu_vm_type_int32:
+ printSpecificResult(i, results.values.at(i).i32, "i32");
+ break;
+ case npu_vm_type_uint32:
+ printSpecificResult(i, results.values.at(i).u32, "u32");
+ break;
+ case npu_vm_type_int64:
+ printSpecificResult(i, results.values.at(i).i64, "i64");
+ break;
+ case npu_vm_type_uint64:
+ printSpecificResult(i, results.values.at(i).u64, "u64");
+ break;
+ case npu_vm_type_float32:
+ printSpecificResult(i, results.values.at(i).f32, "f32");
+ break;
+ case npu_vm_type_float64:
+ printSpecificResult(i, results.values.at(i).f64, "f64");
+ break;
+ case npu_vm_type_buffer: {
+ std::cout << "Result[" << i << "] (buffer): ";
+ const auto bufferData = static_cast<const uint8_t*>(results.values.at(i).buffer.data);
+ const auto bufferSize = results.values.at(i).buffer.size;
+ if (bufferData == nullptr || bufferSize == 0) {
+ std::cout << "null or empty buffer" << std::endl;
+ break;
+ }
+ for (size_t j = 0; j < bufferSize; ++j) {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - using C API with raw pointers
+ std::cout << std::hex << static_cast<int>(bufferData[j]) << " ";
+ }
+ std::cout << std::dec << std::endl;
+ break;
+ }
+ default:
+ std::cout << "Result[" << i << "] (unknown): unknown" << std::endl;
+ break;
+ };
+ }
+}
+
+struct VMContext {
+ npu_vm_module* module{nullptr};
+ npu_vm_engine* engine{nullptr};
+ npu_vm_function_info* functionInfo{nullptr};
+};
+
+void freeResources(const VMContext& context, const std::optional<Values>& results = std::nullopt) {
+ if (context.engine != nullptr) {
+ npu_vm_destroy_engine(context.engine);
+ }
+ if (context.module != nullptr) {
+ npu_vm_destroy_module(context.module);
+ }
+ if (context.functionInfo != nullptr) {
+ if (results.has_value()) {
+ const auto& resultTypes = context.functionInfo->result_types;
+ if (context.functionInfo->num_results <= results->values.size()) {
+ for (size_t i = 0; i < context.functionInfo->num_results; ++i) {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - using C API with raw pointers
+ const auto resultType = resultTypes[i];
+ if (resultType == npu_vm_type_buffer) {
+ const auto& value = results->values.at(i);
+ if (value.buffer.data != nullptr) {
+ // NOLINTNEXTLINE(cppcoreguidelines-owning-memory, cppcoreguidelines-no-malloc)
+ free(value.buffer.data);
+ }
+ }
+ }
+ }
+ }
+ npu_vm_destroy_function_info(context.functionInfo);
+ }
+}
+
+int cleanupAndExitSuccess(const VMContext& context = {}, const std::optional<Values>& results = std::nullopt) {
+ freeResources(context, results);
+ return 0;
+}
+
+int cleanupAndExitFailure(const VMContext& context = {}, const std::optional<Values>& results = std::nullopt) {
+ freeResources(context, results);
+ return 1;
+}
+
+} // namespace
+
+int main(int argc, char* argv[]) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ const auto bytecodeFile = FLAGS_path;
+ std::ifstream input(bytecodeFile, std::ios::binary);
+ if (!input) {
+ std::cerr << "Error: Failed to open bytecode file: " << bytecodeFile << std::endl;
+ return 1;
+ }
+ std::cout << "Loading bytecode from file: " << bytecodeFile << std::endl;
+ std::vector<uint8_t> bytecode((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
+ std::cout << "Bytecode size: " << bytecode.size() << " bytes" << std::endl;
+ input.close();
+
+ const auto printOnly = FLAGS_mode == "print" || FLAGS_mode == "print-full";
+ if (printOnly) {
+ std::cout << "File content:" << std::endl;
+ if (npu_vm_print(bytecode.data(), static_cast<uint32_t>(bytecode.size()), FLAGS_mode == "print-full",
+ /*indent_level=*/1) != NPU_VM_SUCCESS) {
+ std::cerr << "Error: Failed to print bytecode." << std::endl;
+ return cleanupAndExitFailure();
+ }
+ return cleanupAndExitSuccess();
+ }
+
+ VMContext context;
+ try {
+ if (npu_vm_parse_module(bytecode.data(), static_cast<uint32_t>(bytecode.size()), &context.module) !=
+ NPU_VM_SUCCESS) {
+ std::cerr << "Error: Failed to parse bytecode." << std::endl;
+ return cleanupAndExitFailure();
+ }
+ if (npu_vm_get_function_info(context.module, FLAGS_function.c_str(), &context.functionInfo) != NPU_VM_SUCCESS) {
+ std::cerr << "Error: No function named '" << FLAGS_function << "' found in the bytecode." << std::endl;
+ return cleanupAndExitFailure(context);
+ }
+
+ auto arguments = parseParams(FLAGS_params);
+ if (!arguments) {
+ return cleanupAndExitFailure(context);
+ }
+ auto results = createResultStorage(context.functionInfo);
+ if (!results.has_value()) {
+ return cleanupAndExitFailure(context);
+ }
+ if (npu_vm_new_engine(&context.engine) != NPU_VM_SUCCESS) {
+ std::cerr << "Error: Failed to create VM engine." << std::endl;
+ return cleanupAndExitFailure(context, results);
+ }
+ if (npu_vm_load_module(context.engine, /*load_params*/ nullptr, context.module) != NPU_VM_SUCCESS) {
+ std::cerr << "Error: Failed to load module into VM engine." << std::endl;
+ return cleanupAndExitFailure(context, results);
+ }
+ if (npu_vm_call_with_results(context.engine, FLAGS_function.c_str(),
+ static_cast<uint32_t>(arguments->values.size()), arguments->values.data(),
+ static_cast<uint32_t>(results->values.size()),
+ results->values.data()) != NPU_VM_SUCCESS) {
+ std::cerr << "Error: Bytecode execution failed." << std::endl;
+ return cleanupAndExitFailure(context, results);
+ }
+ printResults(context.functionInfo, *results);
+ return cleanupAndExitSuccess(context, results);
+ } catch (const std::exception& ex) {
+ std::cerr << "Error during bytecode execution: " << ex.what() << std::endl;
+ return cleanupAndExitFailure(context);
+ }
+}