OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Introduce GGUF Frontend (#36579)
Maxim Vafin64fe9048c346
diff --git a/.github/workflows/job_cxx_unit_tests.yml b/.github/workflows/job_cxx_unit_tests.ymlindex 7fdf5d9a596..83850514077 100644--- a/.github/workflows/job_cxx_unit_tests.yml+++ b/.github/workflows/job_cxx_unit_tests.yml@@ -128,6 +128,11 @@ jobs:${{ env.SOURCE_COMMAND }} ${{ env.SETUPVARS }}${{ env.INSTALL_TEST_DIR }}/ov_ir_frontend_tests --gtest_print_time=1 --gtest_output=xml:${{ env.INSTALL_TEST_DIR }}/TEST-IRFrontend.xml+ - name: GGUF frontend tests+ run: |+ ${{ env.SOURCE_COMMAND }} ${{ env.SETUPVARS }}+ ${{ env.INSTALL_TEST_DIR }}/ov_gguf_frontend_tests --gtest_print_time=1 --gtest_output=xml:${{ env.INSTALL_TEST_DIR }}/TEST-GGUFFrontend.xml+- name: PaddlePaddle frontend testsif: ${{ fromJSON(inputs.affected-components).PDPD_FE.test && runner.os != 'Windows' }} # Ticket: 149651run: |diff --git a/.github/workflows/linux_arm64.yml b/.github/workflows/linux_arm64.ymlindex 8bcc5fdf62f..c1f7f85a1db 100644--- a/.github/workflows/linux_arm64.yml+++ b/.github/workflows/linux_arm64.yml@@ -114,6 +114,7 @@ jobs:-G 'Ninja Multi-Config'-DENABLE_NCC_STYLE=OFF-DENABLE_TESTS=ON+ -DENABLE_OV_GGUF_FRONTEND=ON-DENABLE_STRICT_DEPENDENCIES=OFF-DENABLE_SYSTEM_OPENCL=ON-DCMAKE_EXPORT_COMPILE_COMMANDS=ONdiff --git a/.github/workflows/mac_arm64.yml b/.github/workflows/mac_arm64.ymlindex de2fe7f15cd..ef1cd1dc7ac 100644--- a/.github/workflows/mac_arm64.yml+++ b/.github/workflows/mac_arm64.yml@@ -184,6 +184,7 @@ jobs:-G "${{ env.CMAKE_GENERATOR }}" \-DENABLE_NCC_STYLE=OFF \-DENABLE_TESTS=ON \+ -DENABLE_OV_GGUF_FRONTEND=ON \-DENABLE_WHEEL=OFF \-DCMAKE_COMPILE_WARNING_AS_ERROR=OFF \-DENABLE_STRICT_DEPENDENCIES=OFF \diff --git a/.github/workflows/ubuntu_22.yml b/.github/workflows/ubuntu_22.ymlindex df5c7d3ccaa..30576636c9f 100644--- a/.github/workflows/ubuntu_22.yml+++ b/.github/workflows/ubuntu_22.yml@@ -138,6 +138,7 @@ jobs:-DENABLE_TESTS=ON-DENABLE_STRICT_DEPENDENCIES=OFF-DENABLE_SYSTEM_OPENCL=ON+ -DENABLE_OV_GGUF_FRONTEND=ON-DCMAKE_EXPORT_COMPILE_COMMANDS=ON-DCPACK_GENERATOR=TGZ-DENABLE_WHEEL=ONdiff --git a/.github/workflows/ubuntu_24.yml b/.github/workflows/ubuntu_24.ymlindex b32fe9d000c..acc4ec98e47 100644--- a/.github/workflows/ubuntu_24.yml+++ b/.github/workflows/ubuntu_24.yml@@ -114,6 +114,7 @@ jobs:-G 'Ninja Multi-Config'-DENABLE_NCC_STYLE=OFF-DENABLE_TESTS=ON+ -DENABLE_OV_GGUF_FRONTEND=ON-DENABLE_STRICT_DEPENDENCIES=OFF-DENABLE_SYSTEM_OPENCL=ON-DCMAKE_EXPORT_COMPILE_COMMANDS=ONdiff --git a/.github/workflows/windows_vs2022_debug.yml b/.github/workflows/windows_vs2022_debug.ymlindex fab1c44b845..4e4450392b9 100644--- a/.github/workflows/windows_vs2022_debug.yml+++ b/.github/workflows/windows_vs2022_debug.yml@@ -73,6 +73,7 @@ jobs:-G 'Ninja'-DENABLE_PYTHON=OFF-DENABLE_TESTS=ON+ -DENABLE_OV_GGUF_FRONTEND=ON-DCMAKE_COMPILE_WARNING_AS_ERROR=ON-DENABLE_STRICT_DEPENDENCIES=OFF-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=ONdiff --git a/.github/workflows/windows_vs2022_release.yml b/.github/workflows/windows_vs2022_release.ymlindex c038687f207..53504e5324c 100644--- a/.github/workflows/windows_vs2022_release.yml+++ b/.github/workflows/windows_vs2022_release.yml@@ -76,6 +76,7 @@ jobs:-DENABLE_PYTHON=ON-DENABLE_WHEEL=OFF-DENABLE_TESTS=ON+ -DENABLE_OV_GGUF_FRONTEND=ON-DCMAKE_COMPILE_WARNING_AS_ERROR=ON-DENABLE_STRICT_DEPENDENCIES=OFF-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=ONdiff --git a/cmake/features.cmake b/cmake/features.cmakeindex 02295eabd77..d9240d0f098 100644--- a/cmake/features.cmake+++ b/cmake/features.cmake@@ -156,6 +156,7 @@ ov_option(ENABLE_OV_PYTORCH_FRONTEND "Enable PyTorch FrontEnd" ON)ov_option(ENABLE_OV_JAX_FRONTEND "Enable JAX FrontEnd" ON)ov_option(ENABLE_OV_TF_FRONTEND "Enable TensorFlow FrontEnd" ON)ov_option(ENABLE_OV_TF_LITE_FRONTEND "Enable TensorFlow Lite FrontEnd" ON)+ov_option(ENABLE_OV_GGUF_FRONTEND "Enable GGUF FrontEnd" OFF)if(WIN32 AND AARCH64 AND CMAKE_CL_64)# Failed: openvino/src/bindings/js/node/thirdparty/node-lib.def: no such file or directorydiff --git a/cmake/packaging/debian.cmake b/cmake/packaging/debian.cmakeindex dfd1053b7db..d7d72bdaffb 100644--- a/cmake/packaging/debian.cmake+++ b/cmake/packaging/debian.cmake@@ -328,6 +328,19 @@ macro(ov_cpack_settings)set(tensorflow_lite_copyright "generic")endif()+ if(ENABLE_OV_GGUF_FRONTEND)+ set(CPACK_COMPONENT_GGUF_DESCRIPTION "OpenVINO GGUF Frontend")+ set(CPACK_COMPONENT_GGUF_DEPENDS "${OV_CPACK_COMP_CORE}")+ set(CPACK_DEBIAN_GGUF_PACKAGE_NAME "libopenvino-gguf-frontend-${cpack_name_ver}")+ # since GGUF FE is a linkable target, we need to call ldconfig (i.e. `def_triggers`)+ set(CPACK_DEBIAN_GGUF_PACKAGE_CONTROL_EXTRA "${def_postinst};${def_postrm};${def_triggers}")+ ov_debian_add_lintian_suppression(gguf+ # we have different package name strategy; it suggests libopenvino-gguf-frontend202230+ "package-name-doesnt-match-sonames")+ list(APPEND frontends gguf)+ set(gguf_copyright "generic")+ endif()+## core_dev: depends on core and frontends (since frontends don't want to provide its own dev packages)#diff --git a/cmake/packaging/rpm.cmake b/cmake/packaging/rpm.cmakeindex 9719cb93afb..e7d7b269c11 100644--- a/cmake/packaging/rpm.cmake+++ b/cmake/packaging/rpm.cmake@@ -278,6 +278,15 @@ macro(ov_cpack_settings)set(tensorflow_lite_copyright "generic")endif()+ if(ENABLE_OV_GGUF_FRONTEND)+ set(CPACK_COMPONENT_GGUF_DESCRIPTION "OpenVINO GGUF Frontend")+ set(CPACK_RPM_GGUF_PACKAGE_NAME "libopenvino-gguf-frontend-${cpack_name_ver}")+ set(CPACK_RPM_GGUF_POST_INSTALL_SCRIPT_FILE "${def_triggers}")+ set(CPACK_RPM_GGUF_POST_UNINSTALL_SCRIPT_FILE "${def_triggers}")+ _ov_add_package(frontend_packages gguf)+ set(gguf_copyright "generic")+ endif()+## core_dev: depends on core and frontends (since frontends don't want to provide its own dev packages)#diff --git a/setup.py b/setup.pyindex 0c04e59f4ef..e8590057347 100644--- a/setup.py+++ b/setup.py@@ -184,6 +184,13 @@ LIB_INSTALL_CFG = {"install_dir": OV_RUNTIME_LIBS_DIR,"rpath": LIBS_RPATH,"binary_dir": OPENVINO_BINARY_DIR,+ },+ "gguf_libs": {+ "name": "gguf",+ "prefix": f"{BUILD_BASE}/libs.gguf",+ "install_dir": OV_RUNTIME_LIBS_DIR,+ "rpath": LIBS_RPATH,+ "binary_dir": OPENVINO_BINARY_DIR,}}diff --git a/src/frontends/CMakeLists.txt b/src/frontends/CMakeLists.txtindex bb0cf98dc9b..cf11c8d4112 100644--- a/src/frontends/CMakeLists.txt+++ b/src/frontends/CMakeLists.txt@@ -41,3 +41,7 @@ endif()if(ENABLE_OV_PADDLE_FRONTEND)add_subdirectory(paddle)endif()++if(ENABLE_OV_GGUF_FRONTEND)+ add_subdirectory(gguf)+endif()diff --git a/src/frontends/common/src/manager.cpp b/src/frontends/common/src/manager.cppindex d414854820b..a97616829fb 100644--- a/src/frontends/common/src/manager.cpp+++ b/src/frontends/common/src/manager.cpp@@ -4,6 +4,9 @@#include "openvino/frontend/manager.hpp"+#include <set>+#include <string>+#include "openvino/frontend/common/path_util.hpp"#include "openvino/frontend/exception.hpp"#include "openvino/util/env_util.hpp"@@ -15,6 +18,16 @@using namespace ov;using namespace ov::frontend;+namespace {+// Frontends for direct linkage only: loadable, but never listed by available_front_ends() nor+// auto-selected by load_by_model / load_by_framework. A manager-side list (not a plugin-info flag)+// keeps the public FrontEndPluginInfo struct / ABI unchanged.+bool is_hidden_frontend(const std::string& name) {+ static const std::set<std::string> hidden_frontends = {"gguf"};+ return hidden_frontends.count(name) != 0;+}+} // namespace+class FrontEndManager::Impl {std::mutex m_loading_mutex;std::vector<PluginInfo> m_plugins;@@ -58,6 +71,10 @@ public:// Load plugins until we found the right onefor (auto& plugin : m_plugins) {OPENVINO_ASSERT(plugin.load(), "Cannot load frontend ", plugin.get_name_from_file());+ // Hidden frontends are not selectable by name through the generic API.+ if (is_hidden_frontend(plugin.get_creator().m_name)) {+ continue;+ }if (plugin.get_creator().m_name == framework) {return make_frontend(plugin);}@@ -74,6 +91,10 @@ public:OPENVINO_DEBUG("Frontend load failed: ", plugin_info.m_file_path, "\n");continue;}+ // Hidden frontends are for direct linkage only; do not advertise them.+ if (is_hidden_frontend(plugin_info.get_creator().m_name)) {+ continue;+ }names.push_back(plugin_info.get_creator().m_name);}return names;@@ -91,6 +112,10 @@ public:if (!plugin.load()) {continue;}+ // Hidden frontends are for direct linkage only; never auto-select them.+ if (is_hidden_frontend(plugin.get_creator().m_name)) {+ continue;+ }auto fe = plugin.get_creator().m_creator();OPENVINO_ASSERT(fe, "Frontend error: frontend '", plugin.get_creator().m_name, "' created null FrontEnd");if (fe->supported(variants)) {diff --git a/src/frontends/gguf/CMakeLists.txt b/src/frontends/gguf/CMakeLists.txtnew file mode 100644index 00000000000..f919814e76c--- /dev/null+++ b/src/frontends/gguf/CMakeLists.txt@@ -0,0 +1,9 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#++add_subdirectory(src)++if(ENABLE_TESTS)+ add_subdirectory(tests)+endif()diff --git a/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hppnew file mode 100644index 00000000000..54f75c98812--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/decoder.hpp@@ -0,0 +1,124 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <functional>+#include <map>+#include <memory>+#include <string>+#include <vector>++#include "openvino/core/node.hpp"+#include "openvino/frontend/decoder.hpp"+#include "openvino/frontend/gguf/visibility.hpp"++namespace ov::frontend::gguf {++// Typed RoPE configuration, replacing the raw gguf `op_params`/`rope_params` int32 array+// the translators used to dereference by byte offset. A decoder is responsible for+// producing this (the llama.cpp cgraph decoder by parsing ggml's layout, a future+// gguf-file decoder by construction), so the op translators never need to know ggml's+// memory layout.+struct RopeConfig {+ int n_dims = 0; // 0 means the model uses no RoPE (replaces a separate has_rope() query)+ int n_ctx_orig = 0;+ float freq_base = 0.0f;+ float freq_scale = 0.0f;+ float ext_factor = 0.0f;+ float attn_factor = 0.0f;+ float beta_fast = 0.0f;+ float beta_slow = 0.0f;+ // When true, each ROPE op builds its own sin/cos from its per-op config (e.g. gemma4, where+ // SWA and global layers use different n_dims), so the shared rope_cos/rope_sin table that+ // TranslateSession::preprocess would otherwise pre-build is skipped.+ bool per_op = false;+};++// Decoder interface consumed by the gguf frontend translators.+//+// Following the established OpenVINO frontend pattern (cf. the PyTorch TorchDecoder + InputModel),+// the translators see a GgufDecoder as a NODE decoder: visit_subgraph hands the visitor a fresh+// decoder bound to a single node, and every per-node accessor (get_attribute, get_input_*,+// get_output_*, get_op_*) refers to that node -- no node index is threaded through. The+// MODEL-level questions (the graph's Parameter inputs, its output names, the shared RoPE config,+// and node iteration) are asked through ov::frontend::gguf::InputModel, not by treating a decoder+// instance as a "model decoder". The InputModel forwards those to the model-scope accessors below;+// a concrete decoder answers them when queried before visit_subgraph binds it to a node.+//+// This is a typed, ggml-free interface: operation parameters are exposed through+// get_attribute(name) / get_input_view_element_offset / get_output_shape / RopeConfig rather than+// raw ggml `op_params` int32 arrays. A concrete decoder (e.g. the llama.cpp cgraph decoder) only+// has to translate ggml's layout into these typed accessors -- the op translators never touch+// ggml memory.+class GGUF_FRONTEND_API GgufDecoder : public DecoderBase {+public:+ // ── Node scope (the bound node; used by the op translators) ──────────────────────────────++ // Typed attribute access. The op translators use this to read scalar operation parameters+ // (e.g. "eps", "scale", "bias", "swapped", "op_case", "output_type", "rope_config") without+ // dereferencing ggml's raw op_params layout.+ ov::Any get_attribute(const std::string& name) const override = 0;++ // Element offset of an input that is a ggml VIEW into a larger tensor (0 when the input+ // is not a view). The decoder converts the raw ggml byte offset to elements by dividing+ // by the element size, so translators never see byte-level ggml memory layout.+ virtual int64_t get_input_view_element_offset(const std::string& name) const = 0;++ // Static ggml shape of an input (from ggml's ne[], reversed to OV order). Needed by the+ // MUL_MAT / FLASH_ATTN_EXT translators for the batch/head/head-size dims: those are static+ // ggml facts, but the corresponding OV node dim is dynamic on the stateful KV-cache path+ // (K/V are fed by the cache concat), so it cannot be recovered from the live node's+ // get_partial_shape(). The decoder knows them by construction / from ggml.+ virtual PartialShape get_input_shape(const std::string& name) const = 0;++ size_t get_input_size() const override = 0;++ // DecoderBase override: GGUF resolves connectivity through the TensorMap (name-keyed),+ // not through port-to-port decoder traversal, so this is never called.+ void get_input_node(size_t,+ std::string&,+ std::string&,+ size_t&) const override {}++ virtual std::vector<std::string> get_input_names() const = 0;++ virtual PartialShape get_output_shape() const = 0;++ virtual std::vector<std::string> get_output_names() const = 0;++ const std::string& get_op_type() const override = 0;++ const std::string& get_op_name() const override = 0;++ // ── Model scope (asked via ov::frontend::gguf::InputModel, not by the translators) ─────────++ // Iterate the operation nodes in topological order, handing the visitor a decoder bound to+ // each node. This is the bridge from model scope to node scope.+ virtual void visit_subgraph(std::function<void(std::shared_ptr<GgufDecoder>)> node_visitor) const = 0;++ // All model-scope input nodes: both primary inputs (Parameters) and auxiliary inputs+ // (position IDs, KV-cache lengths, masks, etc.). Parameters are distinguished from auxiliary+ // nodes by the caller via dynamic_pointer_cast<ov::op::v0::Parameter>.+ virtual const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const = 0;+ virtual std::vector<std::string> get_model_output_names() const = 0;++ // NOTE: there is no get_model_weights(). A GGUF weight is surfaced as a regular node in+ // visit_subgraph with the genuine ggml leaf op type "GGML_OP_NONE": the decoder marks it as a+ // weight by exposing the raw weight bytes via get_attribute<ov::Tensor>("data"), the ggml+ // quant type name via get_attribute<std::string>("quant_type") (e.g. "Q4_K", "F16") and the+ // logical [rows, cols] shape via get_output_shape(). The frontend's translate_weight does the+ // dequant / repacking / requantization, so the decoder never builds OV nodes itself. (Model+ // inputs are also GGML_OP_NONE leaves, but they are returned via get_model_inputs() and+ // resolved to Parameters before the walk, so they carry no "data".)++ // RoPE configuration, exposed through get_attribute<RopeConfig>("rope_config"):+ // - at model scope (via InputModel::get_rope_config), used by TranslateSession::preprocess+ // to pre-build the shared rope sin/cos table (skipped when RopeConfig::n_dims == 0, i.e.+ // no RoPE, or per_op == true);+ // - at node scope, the ROPE translator reads the same key for the op's own config.+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hppnew file mode 100644index 00000000000..6a302edb7ea--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/frontend.hpp@@ -0,0 +1,66 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <string>++#include "openvino/frontend/frontend.hpp"+#include "openvino/frontend/gguf/visibility.hpp"++namespace ov::frontend::gguf {++class GGUF_FRONTEND_API FrontEnd : public ov::frontend::FrontEnd {+public:+ using Ptr = std::shared_ptr<FrontEnd>;+ FrontEnd();+ ~FrontEnd() override;++ /// \brief Completely convert the input model, producing a fully converted OV Model.+ /// \param model Input model+ /// \return fully converted OV Model+ std::shared_ptr<Model> convert(const InputModel::Ptr& model) const override;++ /// \brief Gets name of this FrontEnd. Can be used by clients+ /// if frontend is selected automatically by FrontEndManager::load_by_model+ /// \return GGUF frontend name.+ std::string get_name() const override;++ /// \brief Register an extension with this FrontEnd.+ ///+ /// Supported extension types:+ /// - `ov::frontend::ConversionExtension` — registers a custom op translator for the+ /// ggml op name given by `get_op_type()`. The converter receives an+ /// `ov::frontend::gguf::NodeContext` and returns an `ov::OutputVector`.+ /// - `ov::frontend::TelemetryExtension` — receives error / event callbacks.+ /// - `ov::detail::SOExtension` — shared-library extension; its inner extension is+ /// recursively registered.+ /// - `ov::BaseOpExtension` — op-level extension; all attached extensions are+ /// recursively registered.+ ///+ /// \param extension Extension to register.+ void add_extension(const std::shared_ptr<ov::Extension>& extension) override;++protected:+ /// \brief Check if FrontEnd can recognize model from given parts.+ /// \note Always returns false: this frontend is hidden from FrontEndManager and is never+ /// auto-selected. It is used only via direct linkage, by constructing FrontEnd and+ /// calling convert() on an InputModel built from a GgufDecoder.+ /// \param variants Unused.+ /// \return Always false.+ bool supported_impl(const std::vector<ov::Any>& variants) const override;++ /// \brief Load the input model from a GgufDecoder.+ /// \param variants A single GgufDecoder (a .gguf file path is not accepted; the caller supplies+ /// the decoder). variants[0] must hold a std::shared_ptr<GgufDecoder>.+ /// \return InputModel::Ptr+ InputModel::Ptr load_impl(const std::vector<ov::Any>& variants) const override;++private:+ struct Impl;+ std::shared_ptr<Impl> m_impl;+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/set_rows_op.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/set_rows_op.hppnew file mode 100644index 00000000000..4b050900194--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/set_rows_op.hpp@@ -0,0 +1,39 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/frontend/gguf/visibility.hpp"+#include "openvino/op/op.hpp"++namespace ov::frontend::gguf {++// Internal placeholder op for a ggml SET_ROWS (a scatter-write of rows into a destination+// tensor). translate_set_rows always emits this op instead of a device-specific ScatterUpdate,+// so conversion is identical regardless of execution mode. Inputs:+// input 0: data (rows to write, reshaped to the destination layout [1, 1, seq, emb])+// input 1: indices (destination row indices, squeezed)+// input 2: dst (the tensor written into -- a Parameter for a KV cache)+// The output is the updated tensor; both the cache Result and the attention read path consume it.+//+// A normalization-stage lowering replaces every SetRows: the built-in LowerSetRows (default)+// rebuilds the llama.cpp-faithful ScatterUpdate form. A caller may register (via+// DecoderTransformationExtension) an alternative lowering that recognizes the SetRows feeding+// attention as a KV-cache write and turns it into an OpenVINO stateful ReadValue/Concat/Assign+// subgraph. The op never reaches a compiled model. It is public so a caller-side lowering pass+// can match it by type.+class GGUF_FRONTEND_API SetRows : public ov::op::Op {+public:+ OPENVINO_OP("SetRows", "gguf");++ SetRows() = default;+ SetRows(const ov::Output<ov::Node>& data,+ const ov::Output<ov::Node>& indices,+ const ov::Output<ov::Node>& dst);++ void validate_and_infer_types() override;+ std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/include/openvino/frontend/gguf/visibility.hpp b/src/frontends/gguf/include/openvino/frontend/gguf/visibility.hppnew file mode 100644index 00000000000..41d60f1a280--- /dev/null+++ b/src/frontends/gguf/include/openvino/frontend/gguf/visibility.hpp@@ -0,0 +1,20 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/frontend/visibility.hpp"++#ifdef OPENVINO_STATIC_LIBRARY+# define GGUF_FRONTEND_API+# define GGUF_FRONTEND_C_API+#else+# ifdef openvino_gguf_frontend_EXPORTS+# define GGUF_FRONTEND_API OPENVINO_CORE_EXPORTS+# define GGUF_FRONTEND_C_API OPENVINO_EXTERN_C OPENVINO_CORE_EXPORTS+# else+# define GGUF_FRONTEND_API OPENVINO_CORE_IMPORTS+# define GGUF_FRONTEND_C_API OPENVINO_EXTERN_C OPENVINO_CORE_IMPORTS+# endif // openvino_gguf_frontend_EXPORTS+#endif // OPENVINO_STATIC_LIBRARYdiff --git a/src/frontends/gguf/src/CMakeLists.txt b/src/frontends/gguf/src/CMakeLists.txtnew file mode 100644index 00000000000..79b50f3e7e9--- /dev/null+++ b/src/frontends/gguf/src/CMakeLists.txt@@ -0,0 +1,17 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#++# LINKABLE_FRONTEND: installed alongside the other frontends so callers (the llama.cpp+# ggml-openvino backend, OpenVINO GenAI) can link openvino::frontend::gguf directly. It is kept+# out of the generic FrontEndManager loading API (FrontEndManager treats "gguf" as hidden); see+# the discoverability note in frontend.cpp.+ov_add_frontend(NAME gguf+ LINKABLE_FRONTEND+ FILEDESCRIPTION "FrontEnd to convert GGUF models"+ LINK_LIBRARIES openvino::util openvino::core::dev openvino::offline_transformations)++ov_build_target_faster(openvino_gguf_frontend PCH)++# ov::parallel_for (quant dequant) needs the threading (TBB) include directories.+ov_set_threading_interface_for(openvino_gguf_frontend)diff --git a/src/frontends/gguf/src/frontend.cpp b/src/frontends/gguf/src/frontend.cppnew file mode 100644index 00000000000..d501c011736--- /dev/null+++ b/src/frontends/gguf/src/frontend.cpp@@ -0,0 +1,131 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/gguf/frontend.hpp"++#include "input_model.hpp"+#include "op_table.hpp"+#include "openvino/core/so_extension.hpp"+#include "openvino/frontend/extension/conversion.hpp"+#include "openvino/frontend/extension/decoder_transformation.hpp"+#include "openvino/frontend/extension/telemetry.hpp"+#include "openvino/frontend/gguf/decoder.hpp"+#include "openvino/frontend/manager.hpp"+#include "translate_session.hpp"++namespace ov {+namespace frontend {+namespace gguf {++// Discoverability (intentional): consumed only by direct linkage -- a caller (the llama.cpp+// ggml-openvino backend, OpenVINO GenAI) links openvino::frontend::gguf and feeds FrontEnd a live+// GgufDecoder (no .gguf-path reader; see supported_impl / load_impl). It exports the standard+// plugin entry points so FrontEndManager can scan the frontend dir without error, but "gguf" is+// treated as hidden there (manager.cpp is_hidden_frontend), so it is never listed or auto-selected.+// Drop it from that list once this frontend gains file-based loading and passes production review.++struct FrontEnd::Impl {+ std::unordered_map<std::string, CreatorFunction> op_extension_translators;+ std::vector<ConversionExtensionBase::Ptr> conversion_extensions;+ // Transformation extensions run in the normalization stage. A caller uses these to swap the+ // default (stateless) SetRows lowering for an alternative (e.g. a backend stateful lowering).+ std::vector<DecoderTransformationExtension::Ptr> transformation_extensions;+ TelemetryExtension::Ptr telemetry;+};++namespace {++// Merge the built-in op translators with any registered via ConversionExtension+// (extension translators win on name collision).+std::unordered_map<std::string, CreatorFunction> merged_ops(+ const std::unordered_map<std::string, CreatorFunction>& ext_translators) {+ auto ops = get_supported_ops();+ for (const auto& ext : ext_translators) {+ ops[ext.first] = ext.second;+ }+ return ops;+}++} // namespace++FrontEnd::FrontEnd() : m_impl(std::make_shared<Impl>()) {}+FrontEnd::~FrontEnd() = default;++std::shared_ptr<Model> FrontEnd::convert(const InputModel::Ptr& model) const {+ auto gguf_model = std::dynamic_pointer_cast<gguf::InputModel>(model);+ FRONT_END_GENERAL_CHECK(gguf_model, "Invalid input model");+ std::shared_ptr<Model> converted_model;+ {+ auto ops = merged_ops(m_impl->op_extension_translators);+ TranslateSession translate_session(model, ops, m_impl->transformation_extensions);+ converted_model = translate_session.get_converted_model();+ }+ return converted_model;+}++std::string FrontEnd::get_name() const {+ return "gguf";+}++void FrontEnd::add_extension(const std::shared_ptr<ov::Extension>& extension) {+ if (auto conv_ext = ov::as_type_ptr<ov::frontend::ConversionExtension>(extension)) {+ m_impl->conversion_extensions.push_back(conv_ext);+ // Wrap the base CreatorFunction (takes ov::frontend::NodeContext) into a+ // gguf::CreatorFunction (takes gguf::NodeContext). gguf::NodeContext IS an+ // ov::frontend::NodeContext so the call is safe.+ m_impl->op_extension_translators[conv_ext->get_op_type()] = [conv_ext](const NodeContext& ctx) {+ return conv_ext->get_converter()(ctx);+ };+ } else if (const auto& so_ext = std::dynamic_pointer_cast<ov::detail::SOExtension>(extension)) {+ add_extension(so_ext->extension());+ m_extensions.push_back(so_ext);+ } else if (const auto& transformation = std::dynamic_pointer_cast<DecoderTransformationExtension>(extension)) {+ m_impl->transformation_extensions.push_back(transformation);+ } else if (const auto& telemetry = std::dynamic_pointer_cast<TelemetryExtension>(extension)) {+ m_impl->telemetry = telemetry;+ } else if (auto op_base_ext = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension)) {+ for (const auto& attached_ext : op_base_ext->get_attached_extensions()) {+ add_extension(attached_ext);+ }+ }+}++bool FrontEnd::supported_impl(const std::vector<ov::Any>&) const {+ // Always false: this frontend is never selected by FrontEndManager (load_by_model). It is used+ // only via direct linkage -- a caller constructs FrontEnd and calls convert() with an+ // InputModel built from a GgufDecoder -- which does not go through supported(). See the+ // discoverability note at the top of this file.+ return false;+}++InputModel::Ptr FrontEnd::load_impl(const std::vector<ov::Any>& variants) const {+ FRONT_END_GENERAL_CHECK(!variants.empty(),+ "GGUF Frontend requires at least one parameter in model representation.");+ FRONT_END_GENERAL_CHECK(variants[0].is<std::shared_ptr<GgufDecoder>>(),+ "GGUF Frontend supports loading from a GgufDecoder only.");+ auto decoder = variants[0].as<std::shared_ptr<GgufDecoder>>();+ FRONT_END_GENERAL_CHECK(decoder, "Couldn't cast ov::Any to std::shared_ptr<GgufDecoder>");+ return std::make_shared<InputModel>(decoder);+}++} // namespace gguf+} // namespace frontend+} // namespace ov++// Plugin registration. The frontend is installed in the frontend directory, so it must export+// these entry points or FrontEndManager throws while scanning it. It registers as hidden (see the+// discoverability note above): FrontEndManager loads it without error but never lists or+// auto-selects it; only direct linkers use it.+GGUF_FRONTEND_C_API ov::frontend::FrontEndVersion get_api_version() {+ return OV_FRONTEND_API_VERSION;+}++GGUF_FRONTEND_C_API void* get_front_end_data() {+ auto* res = new ov::frontend::FrontEndPluginInfo();+ res->m_name = "gguf";+ res->m_creator = []() {+ return std::make_shared<ov::frontend::gguf::FrontEnd>();+ };+ return res;+}diff --git a/src/frontends/gguf/src/helper_ops/set_rows_op.cpp b/src/frontends/gguf/src/helper_ops/set_rows_op.cppnew file mode 100644index 00000000000..c675c3ed60d--- /dev/null+++ b/src/frontends/gguf/src/helper_ops/set_rows_op.cpp@@ -0,0 +1,31 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/gguf/set_rows_op.hpp"++namespace ov {+namespace frontend {+namespace gguf {++SetRows::SetRows(const ov::Output<ov::Node>& data,+ const ov::Output<ov::Node>& indices,+ const ov::Output<ov::Node>& dst)+ : ov::op::Op({data, indices, dst}) {+ constructor_validate_and_infer_types();+}++void SetRows::validate_and_infer_types() {+ // The updated tensor is read like the destination: same element type and shape. Lowering+ // replaces this op before compile, so this only has to satisfy graph validation meanwhile.+ set_output_type(0, get_input_element_type(2), get_input_partial_shape(2));+}++std::shared_ptr<ov::Node> SetRows::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<SetRows>(new_args[0], new_args[1], new_args[2]);+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/input_model.cpp b/src/frontends/gguf/src/input_model.cppnew file mode 100644index 00000000000..7969bd860dc--- /dev/null+++ b/src/frontends/gguf/src/input_model.cpp@@ -0,0 +1,39 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "input_model.hpp"++#include "openvino/frontend/gguf/decoder.hpp"++namespace ov {+namespace frontend {+namespace gguf {++InputModel::InputModel(const std::shared_ptr<GgufDecoder>& gdecoder) : m_decoder(gdecoder) {}++const std::map<std::string, std::shared_ptr<ov::Node>>& InputModel::get_model_inputs() const {+ return m_decoder->get_model_inputs();+}++std::vector<std::string> InputModel::get_model_output_names() const {+ return m_decoder->get_model_output_names();+}++RopeConfig InputModel::get_rope_config() const {+ // A decoder bound to a full LLM graph exposes "rope_config"; a decoder wrapping a bare op /+ // small cgraph (the former "naive" path) has no such attribute. Return a default config+ // (n_dims == 0, "model uses no RoPE") in that case, so TranslateSession::preprocess builds no+ // shared rope sin/cos table and the ROPE translator -- if one is even present -- falls back to+ // its own per-op sin/cos. This is what makes a separate naive flag unnecessary.+ auto cfg = m_decoder->get_attribute("rope_config");+ return cfg.empty() ? RopeConfig{} : cfg.as<RopeConfig>();+}++void InputModel::visit_subgraph(const std::function<void(std::shared_ptr<GgufDecoder>)>& node_visitor) const {+ m_decoder->visit_subgraph(node_visitor);+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/input_model.hpp b/src/frontends/gguf/src/input_model.hppnew file mode 100644index 00000000000..7a3aec81823--- /dev/null+++ b/src/frontends/gguf/src/input_model.hpp@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <functional>+#include <map>+#include <memory>+#include "openvino/frontend/input_model.hpp"+#include <string>+#include <vector>++#include "openvino/frontend/gguf/decoder.hpp"+#include "openvino/frontend/gguf/visibility.hpp"++namespace ov::frontend::gguf {++class FrontEnd;++// Model-scope view over a GgufDecoder. Following the OpenVINO frontend pattern (cf. the PyTorch+// InputModel over TorchDecoder), the model-level questions -- the graph's Parameter inputs, its+// output names, the shared RoPE config, and iteration over the operation nodes -- are answered+// here, not by treating a decoder instance as a "model decoder". A GgufDecoder is thus purely+// node-scoped from the translators' point of view: TranslateSession asks the InputModel for model+// topology and only ever sees a GgufDecoder bound to a single node (handed out by visit_subgraph).+class GGUF_FRONTEND_API InputModel : public ov::frontend::InputModel {+ friend class ::ov::frontend::gguf::FrontEnd;++public:+ explicit InputModel(const std::shared_ptr<GgufDecoder>& gdecoder);++ // Model-scope topology (forwarded to the underlying decoder's model-scope accessors).+ const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const;+ std::vector<std::string> get_model_output_names() const;+ RopeConfig get_rope_config() const;+ void visit_subgraph(const std::function<void(std::shared_ptr<GgufDecoder>)>& node_visitor) const;++private:+ std::shared_ptr<GgufDecoder> m_decoder;+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/node_context.hpp b/src/frontends/gguf/src/node_context.hppnew file mode 100644index 00000000000..dc15ee70b79--- /dev/null+++ b/src/frontends/gguf/src/node_context.hpp@@ -0,0 +1,76 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include "openvino/frontend/node_context.hpp"+#include <string>++#include "openvino/frontend/gguf/decoder.hpp"++namespace ov::frontend::gguf {++typedef std::map<std::string, Output<Node>> TensorMap;++class NodeContext : public frontend::NodeContext {+public:+ NodeContext(const std::shared_ptr<GgufDecoder>& decoder, std::shared_ptr<TensorMap>& tensor_map)+ : ov::frontend::NodeContext(decoder->get_op_type()),+ m_decoder(decoder),+ m_tensor_map(tensor_map) {+ m_input_names = decoder->get_input_names();+ m_output_names = decoder->get_output_names();+ }++ size_t get_input_size() const override {+ return m_decoder->get_input_size();+ }++ int64_t get_input_view_element_offset(size_t index) const {+ return m_decoder->get_input_view_element_offset(m_input_names[index]);+ }++ PartialShape get_input_shape(size_t input_index) const {+ return m_decoder->get_input_shape(m_input_names[input_index]);+ }++ PartialShape get_output_shape() const {+ return m_decoder->get_output_shape();+ }++ Output<Node> get_input(int idx) const override {+ return m_tensor_map->at(m_input_names[idx]);+ }++ Output<Node> get_input(const std::string& name) const override {+ auto it = m_tensor_map->find(name);+ if (it == m_tensor_map->end()) {+ throw std::runtime_error("'" + name + "' not found in tensor map.");+ }+ return it->second;+ }++ bool has_input(const std::string& name) const {+ return m_tensor_map->find(name) != m_tensor_map->end();+ }++ const std::string& get_name() const override {+ return m_decoder->get_op_name();+ }++ ov::Any get_attribute_as_any(const std::string& name) const override {+ return m_decoder->get_attribute(name);+ }++private:+ std::shared_ptr<GgufDecoder> m_decoder;+ std::shared_ptr<TensorMap>& m_tensor_map;+ std::vector<std::string> m_input_names;+ std::vector<std::string> m_output_names;+};++using CreatorFunction = std::function<ov::OutputVector(const ov::frontend::gguf::NodeContext&)>;++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/op/add_id.cpp b/src/frontends/gguf/src/op/add_id.cppnew file mode 100644index 00000000000..88a230de081--- /dev/null+++ b/src/frontends/gguf/src/op/add_id.cpp@@ -0,0 +1,82 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++namespace {+// Collapse a 4D [1, 1, a, b] input to 2D [a, b] when it isn't already 2D. Bias/id constants may+// already be stored 2D, hence the early-outs.+ov::Output<ov::Node> reshape_add_id_input_to_2d(const ov::Output<ov::Node>& input,+ const ov::PartialShape& input_shape,+ const std::vector<int>& dims) {+ const auto actual_shape = input.get_partial_shape();+ if (actual_shape.rank().is_static() && actual_shape.rank().get_length() == 2) {+ return input;+ }+ if (input_shape.rank().is_static() && input_shape.rank().get_length() == 2) {+ return input;+ }+ auto shape = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);+ return std::make_shared<ov::op::v1::Reshape>(input, get_dimensions(shape, dims), false);+}+} // namespace++// GGML_OP_ADD_ID: gather per-token bias rows selected by ids and add to the input (MoE bias).+OutputVector translate_add_id(const NodeContext& context) {+ num_inputs_check(context, 3, 3);++ auto input = context.get_input(0);+ auto bias = context.get_input(1);+ auto ids = context.get_input(2);++ // OpenVINO uses reversed GGML dimensions:+ // input: [1, n_token, n_used, n_embd]+ // bias: [1, 1, n_expert, n_embd]+ // ids: [1, 1, n_token, n_used]+ bias = reshape_add_id_input_to_2d(bias, context.get_input_shape(1), {2, 3});+ ids = reshape_add_id_input_to_2d(ids, context.get_input_shape(2), {2, 3});++ if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {+ ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);+ }++ auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ ov::Output<ov::Node> selected_bias = std::make_shared<ov::op::v8::Gather>(bias, ids, gather_axis);+ selected_bias = std::make_shared<ov::op::v1::Reshape>(+ selected_bias, std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64), false);++ if (selected_bias.get_element_type() != input.get_element_type()) {+ selected_bias = std::make_shared<ov::op::v0::Convert>(selected_bias, input.get_element_type());+ }++ ov::Output<ov::Node> res = std::make_shared<ov::op::v1::Add>(input, selected_bias);+ const auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (res.get_element_type() != output_type) {+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);+ }++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/argsort.cpp b/src/frontends/gguf/src/op/argsort.cppnew file mode 100644index 00000000000..79d57d4bc4d--- /dev/null+++ b/src/frontends/gguf/src/op/argsort.cpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/frontend/exception.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/topk.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_ARGSORT: return the indices that sort the last dimension. The decoder maps ggml's+// GGML_SORT_ORDER_ASC/DESC enum to a plain int "sort_order" (0 = ascending, 1 = descending), so+// the translator needs no ggml headers. Implemented via TopK over the full last dim (k == dim).+OutputVector translate_argsort(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ const int sort_order = context.get_attribute<int>("sort_order");++ ov::op::v11::TopK::Mode mode;+ switch (sort_order) {+ case 0:+ mode = ov::op::v11::TopK::Mode::MIN;+ break;+ case 1:+ mode = ov::op::v11::TopK::Mode::MAX;+ break;+ default:+ FRONT_END_OP_CONVERSION_CHECK(false, "Unsupported ARGSORT order: ", sort_order);+ }++ auto index_type = context.get_attribute<ov::element::Type>("output_type");+ // ggml ARGSORT sorts ne[0] == the OV last axis; derive it from the rank (rank-4 keeps axis 3).+ const auto& in_ps = input.get_partial_shape();+ const int64_t axis = in_ps.rank().is_static() ? in_ps.rank().get_length() - 1 : 3;+ auto k = std::make_shared<ov::op::v0::Squeeze>(get_dimensions(input.get_node_shared_ptr(), {(int)axis}),+ ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));+ auto topk = std::make_shared<ov::op::v11::TopK>(input,+ k,+ axis,+ mode,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ index_type,+ false);++ return rename_outputs_with_suffix({topk->output(1)}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/clamp.cpp b/src/frontends/gguf/src/op/clamp.cppnew file mode 100644index 00000000000..58b6472a6dc--- /dev/null+++ b/src/frontends/gguf/src/op/clamp.cpp@@ -0,0 +1,33 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/op/clamp.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_CLAMP: elementwise clamp to [min, max]. The decoder exposes the bounds as typed+// float attributes ("clamp_min"/"clamp_max"), so the translator never reads ggml op_params.+OutputVector translate_clamp(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ float min = context.get_attribute<float>("clamp_min");+ float max = context.get_attribute<float>("clamp_max");++ auto res = std::make_shared<ov::op::v0::Clamp>(input, min, max);+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/concat.cpp b/src/frontends/gguf/src/op/concat.cppnew file mode 100644index 00000000000..a52edaa7b32--- /dev/null+++ b/src/frontends/gguf/src/op/concat.cpp@@ -0,0 +1,51 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/frontend/exception.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_CONCAT: concatenate two inputs along a ggml axis. The decoder exposes the raw ggml+// dimension index as "concat_axis"; here it is converted to the reversed OV axis order.+OutputVector translate_concat(const NodeContext& context) {+ num_inputs_check(context, 2, 2);++ const auto output_shape = context.get_output_shape();+ FRONT_END_OP_CONVERSION_CHECK(output_shape.rank().is_static(), "CONCAT requires static output rank");+ const auto rank = output_shape.rank().get_length();++ const int ggml_dim = context.get_attribute<int>("concat_axis");+ FRONT_END_OP_CONVERSION_CHECK(ggml_dim >= 0 && ggml_dim < rank, "CONCAT axis is out of range");++ auto input_0 = context.get_input(0);+ auto input_1 = context.get_input(1);+ const auto output_type = context.get_attribute<ov::element::Type>("output_type");++ if (input_0.get_element_type() != output_type) {+ input_0 = std::make_shared<ov::op::v0::Convert>(input_0, output_type);+ }+ if (input_1.get_element_type() != output_type) {+ input_1 = std::make_shared<ov::op::v0::Convert>(input_1, output_type);+ }++ const auto axis = static_cast<int64_t>(rank - 1 - ggml_dim);+ auto res = std::make_shared<ov::op::v0::Concat>(OutputVector{input_0, input_1}, axis);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/cont.cpp b/src/frontends/gguf/src/op/cont.cppnew file mode 100644index 00000000000..1a167b12b2e--- /dev/null+++ b/src/frontends/gguf/src/op/cont.cpp@@ -0,0 +1,42 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include <memory>++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_cont(const NodeContext & context) {+ num_inputs_check(context, 1, 1);++ int op_case = context.get_attribute<int>("op_case", 0);+ FRONT_END_CHECK_IMPLEMENTED(op_case == 1 || op_case == 2 || op_case == 3, "Unsupported CONT case");++ ov::Output<Node> res;++ if (op_case == 1) {+ // Input from PERMUTE: translate_permute already emitted a real Transpose, so the OV tensor+ // is logically contiguous -- CONT (a ggml memory-contiguity op) is a no-op for us.+ return {context.get_input(0)};+ } else if (op_case == 2) {+ // The input comes from a TRANSPOSE+ return {context.get_input(0)};+ } else {+ // The input comes from a VIEW+ res = process_view_input(context, 0);+ }++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/cpy.cpp b/src/frontends/gguf/src/op/cpy.cppnew file mode 100644index 00000000000..a2fefcfb2a7--- /dev/null+++ b/src/frontends/gguf/src/op/cpy.cpp@@ -0,0 +1,25 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include <memory>+#include "openvino/op/convert.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_cpy(const NodeContext & context) {+ auto res = std::make_shared<ov::op::v0::Convert>(context.get_input(0), context.get_attribute<ov::element::Type>("output_type"));+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/flash_attn_ext.cpp b/src/frontends/gguf/src/op/flash_attn_ext.cppnew file mode 100644index 00000000000..2cd6d8a60c4--- /dev/null+++ b/src/frontends/gguf/src/op/flash_attn_ext.cpp@@ -0,0 +1,99 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <memory>+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/convert_like.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include <string>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_flash_attn_ext(const NodeContext& context) {+ num_inputs_check(context, 4, 4);+ auto q_f32 = context.get_input(0);+ auto k = context.get_input(1);+ auto v = context.get_input(2);+ auto mask = context.get_input(3);++ float scale = context.get_attribute<float>("scale");++ auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);+ auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f16, ov::Shape{}, std::vector<float>{scale});++ ov::Output<ov::Node> mask_sliced, res;+ const std::string mask_name = context.get_attribute<bool>("is_swa", false) ? "KQ_mask_swa_sliced" : "KQ_mask_sliced";+ if (context.has_input(mask_name)) {+ mask_sliced = context.get_input(mask_name);+ } else {+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto two = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});+ auto token_len = get_dimensions(q, {2});+ mask_sliced = std::make_shared<ov::op::v8::Slice>(mask, zero, token_len, one, two);+ }++ if (mask_sliced.get_element_type() != ov::element::f16) {+ mask_sliced = std::make_shared<ov::op::v0::Convert>(mask_sliced, ov::element::f16);+ }++ auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {+ int64_t factor = num_heads / num_heads_kv;+ if (factor > 1 && num_heads_kv > 1) {+ ov::Output<ov::Node> kv_broadcast_shape, kv_unsqueezed, new_kv_shape;+ auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, Shape{}, {2});+ kv_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(kv, unsqueeze_axes);++ kv_broadcast_shape = ov::op::v0::Constant::create(ov::element::i64,+ {5},+ {(int64_t)1, (int64_t)1, factor, (int64_t)1, (int64_t)1});+ new_kv_shape =+ ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t)0, num_heads, (int64_t)-1, head_size});++ kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed,+ kv_broadcast_shape,+ ov::op::BroadcastType::BIDIRECTIONAL);+ kv = std::make_shared<ov::op::v1::Reshape>(kv, new_kv_shape, true);+ }+ return kv;+ };++ // Use the static ggml input shapes (get_input_shape), not the live OV node shapes: on the+ // stateful KV-cache path the OV node's batch/seq dims are dynamic (K/V are fed by the cache+ // concat), but the head-count / head-size dims are static ggml facts the decoder knows.+ auto q_shape = context.get_input_shape(0).to_shape();+ auto k_shape = context.get_input_shape(1).to_shape();+ k = tile_kv(q_shape[1], k_shape[1], q_shape[3], k);+ v = tile_kv(q_shape[1], k_shape[1], q_shape[3], v);++ // SDPA requires q/k/v to share an element type; match k/v to q (ConvertConvertLike lowers these).+ k = std::make_shared<ov::op::v1::ConvertLike>(k, q);+ v = std::make_shared<ov::op::v1::ConvertLike>(v, q);++ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask_sliced, scale_node, false);+ res = std::make_shared<ov::op::v1::Transpose>(sdpa,+ ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3}));+ res = std::make_shared<ov::op::v0::Convert>(res, ov::element::f32);+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/gated_delta_net.cpp b/src/frontends/gguf/src/op/gated_delta_net.cppnew file mode 100644index 00000000000..1bc89390a88--- /dev/null+++ b/src/frontends/gguf/src/op/gated_delta_net.cpp@@ -0,0 +1,192 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cmath>+#include <cstdint>+#include <memory>+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/exp.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/loop.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_GATED_DELTA_NET (qwen3next linear-attention block). Implemented as a recurrent OV Loop+// scan over the sequence, matching ggml's per-token gated delta update. This is the portable+// reference path; the OV core also ships an ov::op::internal::GatedDeltaNet fused op, but it is+// left for a hardware-side optimization once validated against a model (the frontend stays+// conversion-only and device-agnostic).+OutputVector translate_gated_delta_net(const NodeContext& context) {+ num_inputs_check(context, 6, 6);++ auto q = context.get_input(0);+ auto k = context.get_input(1);+ auto v = context.get_input(2);+ auto g = context.get_input(3);+ auto beta = context.get_input(4);+ auto state = context.get_input(5);++ auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]+ auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]+ auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]++ const int64_t B = v_shape[0];+ const int64_t T = v_shape[1];+ const int64_t H_v = v_shape[2];+ const int64_t S_v = v_shape[3];+ const int64_t H_k = q_shape[2];+ const bool kda = (g_shape[3] == (size_t)S_v);++ const int64_t rq1 = H_v / H_k; // GQA head repeat factor+ const float scale = 1.0f / std::sqrt((float)S_v);++ auto axis_1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto axis_2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});++ // [B, T, H, S] -> [B, H, T, S]+ auto perm_0213 = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 2, 1, 3});+ auto q_t = std::make_shared<ov::op::v1::Transpose>(q, perm_0213);+ auto k_t = std::make_shared<ov::op::v1::Transpose>(k, perm_0213);+ auto v_t = std::make_shared<ov::op::v1::Transpose>(v, perm_0213);+ auto g_t = std::make_shared<ov::op::v1::Transpose>(g, perm_0213);+ auto beta_t = std::make_shared<ov::op::v1::Transpose>(beta, perm_0213);++ // Broadcast Q/K heads to V heads (GQA) if needed.+ ov::Output<ov::Node> q_bh = q_t;+ ov::Output<ov::Node> k_bh = k_t;+ if (rq1 > 1) {+ auto q_unsq = std::make_shared<ov::op::v0::Unsqueeze>(q_t, axis_2);+ auto k_unsq = std::make_shared<ov::op::v0::Unsqueeze>(k_t, axis_2);+ auto bcast_shape = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{1, 1, rq1, 1, 1});+ auto q_bcast = std::make_shared<ov::op::v3::Broadcast>(q_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);+ auto k_bcast = std::make_shared<ov::op::v3::Broadcast>(k_unsq, bcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);+ auto perm_5d = ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{0, 2, 1, 3, 4});+ auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);+ auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);+ auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});+ q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);+ k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);+ }++ // Merge batch and head: [B*H_v, T, last]+ auto merge_bh = [&](ov::Output<ov::Node> x, int64_t last_dim) {+ auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, T, last_dim});+ return std::make_shared<ov::op::v1::Reshape>(x, shape, false);+ };+ auto q_m = merge_bh(q_bh, S_v);+ auto k_m = merge_bh(k_bh, S_v);+ auto v_m = merge_bh(v_t, S_v);+ auto g_m = merge_bh(g_t, kda ? S_v : 1);+ auto beta_m = merge_bh(beta_t, 1);++ auto state_shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, S_v, S_v});+ auto state_m = std::make_shared<ov::op::v1::Reshape>(state, state_shape, false);++ auto scale_const = ov::op::v0::Constant::create(ov::element::f32, {}, std::vector<float>{scale});++ // --- Loop body ---+ auto body_state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_q = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_k = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_v = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_g = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_beta = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic());+ auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});++ auto body_cond_out = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});++ auto q_t_cur = std::make_shared<ov::op::v8::Gather>(body_q, body_iter, axis_1);+ auto k_t_cur = std::make_shared<ov::op::v8::Gather>(body_k, body_iter, axis_1);+ auto v_t_cur = std::make_shared<ov::op::v8::Gather>(body_v, body_iter, axis_1);+ auto g_t_cur = std::make_shared<ov::op::v8::Gather>(body_g, body_iter, axis_1);+ auto b_t_cur = std::make_shared<ov::op::v8::Gather>(body_beta, body_iter, axis_1);++ auto q_cur = std::make_shared<ov::op::v0::Squeeze>(q_t_cur, axis_1);+ auto k_cur = std::make_shared<ov::op::v0::Squeeze>(k_t_cur, axis_1);+ auto v_cur = std::make_shared<ov::op::v0::Squeeze>(v_t_cur, axis_1);+ auto g_cur = std::make_shared<ov::op::v0::Squeeze>(g_t_cur, axis_1);+ auto b_cur = std::make_shared<ov::op::v0::Squeeze>(b_t_cur, axis_1);++ auto exp_g = std::make_shared<ov::op::v0::Exp>(g_cur);+ auto exp_g_unsq = std::make_shared<ov::op::v0::Unsqueeze>(exp_g, axis_1);+ auto state_decayed = std::make_shared<ov::op::v1::Multiply>(body_state, exp_g_unsq);++ auto k_col = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_2);+ auto sk = std::make_shared<ov::op::v0::MatMul>(state_decayed, k_col, false, false);+ auto sk_sq = std::make_shared<ov::op::v0::Squeeze>(sk, axis_2);+ auto v_minus_sk = std::make_shared<ov::op::v1::Subtract>(v_cur, sk_sq);+ auto delta = std::make_shared<ov::op::v1::Multiply>(v_minus_sk, b_cur);++ auto delta_col = std::make_shared<ov::op::v0::Unsqueeze>(delta, axis_2);+ auto k_row = std::make_shared<ov::op::v0::Unsqueeze>(k_cur, axis_1);+ auto outer_prod = std::make_shared<ov::op::v0::MatMul>(delta_col, k_row, false, false);+ auto state_updated = std::make_shared<ov::op::v1::Add>(state_decayed, outer_prod);++ auto q_col = std::make_shared<ov::op::v0::Unsqueeze>(q_cur, axis_2);+ auto sq = std::make_shared<ov::op::v0::MatMul>(state_updated, q_col, false, false);+ auto sq_squeezed = std::make_shared<ov::op::v0::Squeeze>(sq, axis_2);+ auto attn_out = std::make_shared<ov::op::v1::Multiply>(sq_squeezed, scale_const);+ auto attn_out_unsq = std::make_shared<ov::op::v0::Unsqueeze>(attn_out, axis_1);++ auto body = std::make_shared<ov::Model>(+ ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},+ ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});++ auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{T});+ auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});++ auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);+ loop->set_function(body);+ loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});+ loop->set_merged_input(body_state, state_m, state_updated);+ loop->set_invariant_input(body_q, q_m);+ loop->set_invariant_input(body_k, k_m);+ loop->set_invariant_input(body_v, v_m);+ loop->set_invariant_input(body_g, g_m);+ loop->set_invariant_input(body_beta, beta_m);++ auto final_state_out = loop->get_iter_value(state_updated, -1);+ auto attn_concat_out = loop->get_concatenated_slices(attn_out_unsq, 0, 1, 1, -1, 1);++ // Pack [attn | state] into ggml's output layout: OV [1, 1, T*B + S_v*B, S_v*H_v].+ auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});+ auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);+ auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213);+ auto flat_shape_1d = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{-1});+ auto attn_1d = std::make_shared<ov::op::v1::Reshape>(attn_perm, flat_shape_1d, false);++ auto state_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, S_v, S_v});+ auto state_4d = std::make_shared<ov::op::v1::Reshape>(final_state_out, state_4d_shape, false);+ auto state_1d = std::make_shared<ov::op::v1::Reshape>(state_4d, flat_shape_1d, false);++ auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);+ auto out_shape =+ ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, T * B + S_v * B, S_v * H_v});+ auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cppnew file mode 100644index 00000000000..13b00eb84f5--- /dev/null+++ b/src/frontends/gguf/src/op/get_rows.cpp@@ -0,0 +1,69 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/unsqueeze.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_get_rows(const NodeContext & context) {+ num_inputs_check(context, 2, 2);++ int op_case = context.get_attribute<int>("op_case", 0);++ Output<Node> res;+ auto data = context.get_input(0);+ auto indices = context.get_input(1);++ if (op_case == 2) {+ // The input comes from a VIEW+ indices = process_view_input(context, 1);+ }++ // data[1,b,x,y] ind[1,1,b,x'] test-backend-ops case+ // data[x,y] ind[1,1,1,x'] normal case+ indices =+ std::make_shared<ov::op::v0::Squeeze>(indices, ov::op::v0::Constant::create(ov::element::i64, {2}, {0, 1}));+ if (data.get_partial_shape().rank() == 4) {+ if (!(data.get_partial_shape()[1].is_dynamic()) && data.get_partial_shape()[1].get_length() == 1) {+ // Work-around for a bug in ov cpu plugin for test-backend-ops+ data = std::make_shared<ov::op::v0::Squeeze>(data,+ ov::op::v0::Constant::create(ov::element::i64, {2}, {0, 1}));+ auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ res = std::make_shared<ov::op::v8::Gather>(data, indices, axis);+ } else {+ auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});+ data =+ std::make_shared<ov::op::v0::Squeeze>(data, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));+ res = std::make_shared<ov::op::v8::Gather>(data, indices, axis, 1);+ }+ } else {+ auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ res = std::make_shared<ov::op::v8::Gather>(data, indices, axis);+ }++ auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (res.get_element_type() != output_type) {+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);+ }+ res = std::make_shared<ov::op::v0::Unsqueeze>(res, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/glu_geglu.cpp b/src/frontends/gguf/src/op/glu_geglu.cppnew file mode 100644index 00000000000..c4868a2cbf6--- /dev/null+++ b/src/frontends/gguf/src/op/glu_geglu.cpp@@ -0,0 +1,64 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/core/node_output.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gelu.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/sigmoid.hpp"+#include "openvino/op/slice.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_glu_geglu(const NodeContext& context) {+ num_inputs_check(context, 1, 2);++ ov::Output<ov::Node> src0;+ ov::Output<ov::Node> src1;+ if (context.get_input_size() == 2) {+ src0 = context.get_input(0);+ src1 = context.get_input(1);+ } else {+ // GGML splits along ne[0] (OV last axis) using floor division: nc = ne[0] / 2.+ // Both halves are nc elements; if the dimension is odd, the last element is dropped.+ // Use Slice instead of Split to handle odd dimensions correctly.+ auto combined = context.get_input(0);+ auto combined_shape = combined.get_partial_shape();+ int64_t last_dim_val = combined_shape[combined_shape.rank().get_length() - 1].get_length();+ int64_t nc = last_dim_val / 2;++ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});+ auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto start0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto stop0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {nc});+ auto start1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {nc});+ auto stop1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2 * nc});++ src0 = std::make_shared<ov::op::v8::Slice>(combined, start0, stop0, step, axis);+ src1 = std::make_shared<ov::op::v8::Slice>(combined, start1, stop1, step, axis);+ }++ if (context.get_attribute<bool>("swapped")) {+ std::swap(src0, src1);+ }++ // ggml's GEGLU uses the tanh GELU approximation (ggml_gelu_f32); v7::Gelu defaults to ERF.+ auto gelu = std::make_shared<ov::op::v7::Gelu>(src0, ov::op::GeluApproximationMode::TANH);+ auto res = std::make_shared<ov::op::v1::Multiply>(gelu, src1);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/glu_swiglu.cpp b/src/frontends/gguf/src/op/glu_swiglu.cppnew file mode 100644index 00000000000..b0c53eab889--- /dev/null+++ b/src/frontends/gguf/src/op/glu_swiglu.cpp@@ -0,0 +1,100 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <limits>+#include <memory>+#include "openvino/core/node_output.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/sigmoid.hpp"+#include "openvino/op/slice.hpp"+#include <utility>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++namespace {+// Resolve the two GLU halves: either two explicit inputs, or one combined tensor split along the+// last axis (floor division; an odd trailing element is dropped). Applies the "swapped" flag.+std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> get_glu_inputs(const NodeContext& context) {+ num_inputs_check(context, 1, 2);++ ov::Output<ov::Node> src0;+ ov::Output<ov::Node> src1;+ if (context.get_input_size() == 2) {+ src0 = context.get_input(0);+ src1 = context.get_input(1);+ } else {+ auto combined = context.get_input(0);+ auto combined_shape = combined.get_partial_shape();+ int64_t last_dim_val = combined_shape[combined_shape.rank().get_length() - 1].get_length();+ int64_t nc = last_dim_val / 2;++ auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});+ auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto start0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto stop0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {nc});+ auto start1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {nc});+ auto stop1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {2 * nc});++ src0 = std::make_shared<ov::op::v8::Slice>(combined, start0, stop0, step, axis);+ src1 = std::make_shared<ov::op::v8::Slice>(combined, start1, stop1, step, axis);+ }++ if (context.get_attribute<bool>("swapped")) {+ std::swap(src0, src1);+ }+ return {src0, src1};+}+} // namespace++OutputVector translate_glu_swiglu(const NodeContext& context) {+ auto inputs = get_glu_inputs(context);+ auto src0 = inputs.first;+ auto src1 = inputs.second;++ auto sigmoid = std::make_shared<ov::op::v0::Sigmoid>(src0);+ auto silu = std::make_shared<ov::op::v1::Multiply>(src0, sigmoid);+ auto res = std::make_shared<ov::op::v1::Multiply>(silu, src1);++ return rename_outputs_with_suffix({res}, context.get_name());+}++// gpt-oss gated SiLU: clamp gate to (-inf, limit], scale by alpha, sigmoid-gate, then multiply by+// (clamp(up, -limit, limit) + 1). alpha/limit come from the decoder as typed float attributes.+OutputVector translate_glu_swiglu_oai(const NodeContext& context) {+ auto inputs = get_glu_inputs(context);+ auto src0 = inputs.first;+ auto src1 = inputs.second;++ const float alpha = context.get_attribute<float>("glu_alpha");+ const float limit = context.get_attribute<float>("glu_limit");++ auto gate = std::make_shared<ov::op::v0::Clamp>(src0, -std::numeric_limits<float>::infinity(), limit);+ auto alpha_const = ov::op::v0::Constant::create(ov::element::f32, {}, {alpha});+ auto scaled_gate = std::make_shared<ov::op::v1::Multiply>(gate, alpha_const);+ auto sigmoid = std::make_shared<ov::op::v0::Sigmoid>(scaled_gate);+ auto out_glu = std::make_shared<ov::op::v1::Multiply>(gate, sigmoid);++ auto up = std::make_shared<ov::op::v0::Clamp>(src1, -limit, limit);+ auto one = ov::op::v0::Constant::create(ov::element::f32, {}, {1.0f});+ auto up_plus_one = std::make_shared<ov::op::v1::Add>(up, one);+ auto res = std::make_shared<ov::op::v1::Multiply>(out_glu, up_plus_one);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/im2col.cpp b/src/frontends/gguf/src/op/im2col.cppnew file mode 100644index 00000000000..1e799186df6--- /dev/null+++ b/src/frontends/gguf/src/op/im2col.cpp@@ -0,0 +1,121 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstddef>+#include <cstdint>+#include <memory>+#include "openvino/core/shape.hpp"+#include "openvino/core/strides.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/extractimagepatches.hpp"+#include "openvino/op/pad.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/util/attr_types.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_IM2COL: unfold a 1D/2D convolution input into column patches (conv / vision models).+// The decoder exposes the conv params (strides/pads/dilations + is_2D) as a typed int vector.+OutputVector translate_im2col(const NodeContext& context) {+ num_inputs_check(context, 2, 2);++ auto params = context.get_attribute<std::vector<int32_t>>("im2col_params");+ FRONT_END_OP_CONVERSION_CHECK(params.size() >= 7, "IM2COL requires 7 params");+ int32_t s0 = params[0];+ int32_t s1 = params[1];+ int32_t p0 = params[2];+ int32_t p1 = params[3];+ int32_t d0 = params[4];+ int32_t d1 = params[5];+ bool is_2D = params[6] == 1;+ ov::Output<Node> res;++ ov::Output<Node> image = context.get_input(1);+ const ov::Shape kernel_shape = context.get_input(0).get_shape();++ const size_t IC = is_2D ? kernel_shape[1] : kernel_shape[2];+ const size_t KH = is_2D ? kernel_shape[2] : 1;+ const size_t KW = kernel_shape[3];++ int32_t stride_w = s0;+ int32_t stride_h = is_2D ? s1 : 1;+ int32_t pad_w = p0;+ int32_t pad_h = is_2D ? p1 : 0;+ int32_t dil_w = d0;+ int32_t dil_h = is_2D ? d1 : 1;++ if (!is_2D) {+ const ov::Shape image_shape = image.get_shape();+ const size_t N = image_shape[1];+ const size_t IW = image_shape[3];+ auto image_reshape_shape = ov::op::v0::Constant::create(+ ov::element::i64, ov::Shape{4},+ std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(IC), 1, static_cast<int64_t>(IW)});+ image = std::make_shared<ov::op::v1::Reshape>(image, image_reshape_shape, false);+ }++ const ov::Shape patch_sizes = {KH, KW};+ const ov::Strides strides = {static_cast<size_t>(stride_h), static_cast<size_t>(stride_w)};+ const ov::Shape rates = {static_cast<size_t>(dil_h), static_cast<size_t>(dil_w)};++ auto pads_begin =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, pad_h, pad_w});+ auto pads_end =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 0, pad_h, pad_w});++ auto pad = std::make_shared<ov::op::v1::Pad>(image, pads_begin, pads_end, ov::op::PadMode::CONSTANT);+ auto patches =+ std::make_shared<ov::op::v3::ExtractImagePatches>(pad, patch_sizes, strides, rates, ov::op::PadType::VALID);++ auto perm1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 2, 3, 1});+ auto t1 = std::make_shared<ov::op::v1::Transpose>(patches, perm1);++ const ov::Shape out_shape = t1->get_output_shape(0);+ const size_t N = out_shape[0];+ const size_t OH = out_shape[1];+ const size_t OW = out_shape[2];+ auto reshape1_shape = ov::op::v0::Constant::create(+ ov::element::i64, ov::Shape{5},+ std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(OH), static_cast<int64_t>(OW),+ static_cast<int64_t>(KH * KW), static_cast<int64_t>(IC)});+ auto r1 = std::make_shared<ov::op::v1::Reshape>(t1, reshape1_shape, false);++ auto perm2 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});+ auto t2 = std::make_shared<ov::op::v1::Transpose>(r1, perm2);++ auto r2_shape = ov::op::v0::Constant::create(+ ov::element::i64, ov::Shape{4},+ std::vector<int64_t>{static_cast<int64_t>(N), static_cast<int64_t>(OH), static_cast<int64_t>(OW),+ static_cast<int64_t>(IC * KH * KW)});+ res = std::make_shared<ov::op::v1::Reshape>(t2, r2_shape, false);++ if (!is_2D) {+ auto final_reshape_shape = ov::op::v0::Constant::create(+ ov::element::i64, ov::Shape{4},+ std::vector<int64_t>{1, static_cast<int64_t>(N), static_cast<int64_t>(OW), static_cast<int64_t>(IC * KW)});+ res = std::make_shared<ov::op::v1::Reshape>(res, final_reshape_shape, false);+ }++ auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (res.get_element_type() != output_type) {+ res = std::make_shared<ov::op::v0::Convert>(res, output_type);+ }++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/l2_norm.cpp b/src/frontends/gguf/src/op/l2_norm.cppnew file mode 100644index 00000000000..e7596996b74--- /dev/null+++ b/src/frontends/gguf/src/op/l2_norm.cpp@@ -0,0 +1,43 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/op/constant.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/maximum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/sqrt.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// L2 normalization over the last dimension: x / max(sqrt(sum(x^2)), eps).+OutputVector translate_l2_norm(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input_node = context.get_input(0);+ float eps = context.get_attribute<float>("eps");++ auto squared = std::make_shared<ov::op::v1::Multiply>(input_node, input_node);+ auto sum_squared = std::make_shared<ov::op::v1::ReduceSum>(+ squared, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1}), true);+ auto l2_norm = std::make_shared<ov::op::v0::Sqrt>(sum_squared);+ auto eps_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {eps});+ auto clamped_norm = std::make_shared<ov::op::v1::Maximum>(l2_norm, eps_const);+ auto res = std::make_shared<ov::op::v1::Divide>(input_node, clamped_norm);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cppnew file mode 100644index 00000000000..e5584b10af0--- /dev/null+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp@@ -0,0 +1,236 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <cstring>+#include <limits>+#include <memory>+#include "openvino/op/bitwise_and.hpp"+#include "openvino/op/bitwise_right_shift.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/unsqueeze.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++namespace {++std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t>& values) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);+}++ov::Output<ov::Node> slice_axis(const ov::Output<ov::Node>& input, int64_t axis, int64_t begin, int64_t end) {+ return std::make_shared<ov::op::v8::Slice>(input, const_i64({begin}), const_i64({end}), const_i64({1}),+ const_i64({axis}));+}++// Packed-MXFP4 MoE path: expert weights arrive as raw u8 blocks of shape+// [1, n_expert, m, k_blocks, 17] (1 e8m0 scale byte + 16 nibble-packed f4e2m1 quants per 32-block).+// The dequant (nibble unpack + LUT + scale) is done on-graph, per selected expert.+ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext& context,+ ov::Output<ov::Node> expert_weights,+ ov::Output<ov::Node> activations,+ ov::Output<ov::Node> ids) {+ auto packed_shape = expert_weights.get_partial_shape().to_shape();+ FRONT_END_OP_CONVERSION_CHECK(packed_shape.size() == 5 && packed_shape[4] == 17,+ "Expected packed MXFP4 expert weights with shape [1, n_expert, m, k_blocks, 17]");++ const int64_t n_expert = static_cast<int64_t>(packed_shape[1]);+ const int64_t rows = static_cast<int64_t>(packed_shape[2]);+ const int64_t k_blocks = static_cast<int64_t>(packed_shape[3]);+ const int64_t qk = 32;+ const int64_t cols = k_blocks * qk;++ auto packed_shape_4d = const_i64({n_expert, rows, k_blocks, 17});+ expert_weights = std::make_shared<ov::op::v1::Reshape>(expert_weights, packed_shape_4d, false);++ auto activations_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);+ auto ids_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);+ auto activations_shape_3d = get_dimensions(activations_shape_4d, {1, 2, 3});+ auto ids_shape_2d = get_dimensions(ids_shape_4d, {2, 3});++ activations = std::make_shared<ov::op::v1::Reshape>(activations, activations_shape_3d, false);+ ids = std::make_shared<ov::op::v1::Reshape>(ids, ids_shape_2d, false);+ if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {+ ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);+ }++ auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});++ static const std::vector<float> f4e2m1_lut = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,+ -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f};+ // Input-independent e8m0 exponent table; build once (was rebuilt per invocation).+ static const std::vector<float> e8m0_lut = [] {+ std::vector<float> lut(256);+ for (size_t i = 0; i < lut.size(); ++i) {+ uint32_t bits = static_cast<uint32_t>(i) << 23;+ memcpy(&lut[i], &bits, sizeof(float));+ }+ lut[0] = std::numeric_limits<float>::min() / 2.0f;+ lut[255] = std::numeric_limits<float>::quiet_NaN();+ return lut;+ }();++ auto f4_lut = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{f4e2m1_lut.size()}, f4e2m1_lut);+ auto scale_lut = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{e8m0_lut.size()}, e8m0_lut);++ auto selected_packed_weights = std::make_shared<ov::op::v8::Gather>(expert_weights, ids, gather_axis);+ auto scale_byte = slice_axis(selected_packed_weights, 4, 0, 1);+ auto qs = slice_axis(selected_packed_weights, 4, 1, 17);+ auto low = std::make_shared<ov::op::v13::BitwiseAnd>(+ qs, ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {0x0F}), ov::op::AutoBroadcastType::NUMPY);+ auto high_shift = std::make_shared<ov::op::v15::BitwiseRightShift>(+ qs, ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {4}), ov::op::AutoBroadcastType::NUMPY);+ auto nibbles = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{low, high_shift}, 4);+ auto nibble_indices = std::make_shared<ov::op::v0::Convert>(nibbles, ov::element::i32);+ auto weights_f32 = std::make_shared<ov::op::v8::Gather>(f4_lut, nibble_indices, gather_axis);++ auto scale_indices = std::make_shared<ov::op::v0::Convert>(scale_byte, ov::element::i32);+ auto scales_f32 = std::make_shared<ov::op::v8::Gather>(scale_lut, scale_indices, gather_axis);+ ov::Output<ov::Node> selected_weights =+ std::make_shared<ov::op::v1::Multiply>(weights_f32, scales_f32, ov::op::AutoBroadcastType::NUMPY);++ auto ids_shape = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);+ auto selected_weights_target_dims = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{get_dimensions(ids_shape, {0, 1}), const_i64({rows, cols})}, 0);+ selected_weights = std::make_shared<ov::op::v1::Reshape>(selected_weights, selected_weights_target_dims, false);++ auto activations_shape = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);+ ov::Output<ov::Node> acts_target_dims = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{+ get_dimensions(activations_shape, {0}),+ get_dimensions(ids_shape, {1}),+ get_dimensions(activations_shape, {2}),+ },+ 0);+ ov::Output<ov::Node> acts_broadcasted =+ std::make_shared<ov::op::v3::Broadcast>(activations, acts_target_dims, ov::op::BroadcastType::BIDIRECTIONAL);++ auto activations_expanded = std::make_shared<ov::op::v0::Unsqueeze>(acts_broadcasted, const_i64({2}));+ ov::Output<ov::Node> result =+ std::make_shared<ov::op::v0::MatMul>(activations_expanded, selected_weights, false, true);++ auto batch_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {rows});+ auto result_target_dims = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim}, 0);+ result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);++ const auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (result.get_element_type() != output_type) {+ result = std::make_shared<ov::op::v0::Convert>(result, output_type);+ }+ return result;+}++} // namespace++// GGML_OP_MUL_MAT_ID: per-token MoE expert matmul. ids select which expert row of the weight+// tensor each token uses; activations are gathered/broadcast accordingly and matmul'd.+OutputVector translate_mul_mat_id(const NodeContext& context) {+ num_inputs_check(context, 3, 3);++ auto expert_weights = context.get_input(0);+ auto activations = context.get_input(1);+ auto ids = context.get_input(2);++ if (expert_weights.get_element_type() == ov::element::u8 && expert_weights.get_partial_shape().rank().is_static() &&+ expert_weights.get_partial_shape().rank().get_length() == 5) {+ return rename_outputs_with_suffix({translate_mul_mat_id_mxfp4_packed(context, expert_weights, activations, ids)},+ context.get_name());+ }++ // OpenVINO sees GGML tensors in reversed dimension order:+ // weights: [1, n_expert, m, k]+ // activations: [1, n_tokens, n_used_or_1, k]+ // ids: [1, 1, n_tokens, n_used]+ auto expert_weights_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(expert_weights, ov::element::i64);+ auto activations_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);+ auto ids_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);++ auto expert_weights_shape_3d = get_dimensions(expert_weights_shape_4d, {1, 2, 3});+ auto activations_shape_3d = get_dimensions(activations_shape_4d, {1, 2, 3});+ auto ids_shape_2d = get_dimensions(ids_shape_4d, {2, 3});++ expert_weights = std::make_shared<ov::op::v1::Reshape>(expert_weights, expert_weights_shape_3d, false);+ activations = std::make_shared<ov::op::v1::Reshape>(activations, activations_shape_3d, false);+ ids = std::make_shared<ov::op::v1::Reshape>(ids, ids_shape_2d, false);++ if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {+ ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);+ }++ auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ ov::Output<ov::Node> selected_weights = std::make_shared<ov::op::v8::Gather>(expert_weights, ids, gather_axis);++ const auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (selected_weights.get_element_type() != ov::element::f32) {+ selected_weights = std::make_shared<ov::op::v0::Convert>(selected_weights, ov::element::f32);+ }+ if (activations.get_element_type() != ov::element::f32) {+ activations = std::make_shared<ov::op::v0::Convert>(activations, ov::element::f32);+ }++ auto activations_shape = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);+ auto ids_shape = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);+ ov::Output<ov::Node> acts_target_dims = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{+ get_dimensions(activations_shape, {0}),+ get_dimensions(ids_shape, {1}),+ get_dimensions(activations_shape, {2}),+ },+ 0);+ ov::Output<ov::Node> acts_broadcasted =+ std::make_shared<ov::op::v3::Broadcast>(activations, acts_target_dims, ov::op::BroadcastType::BIDIRECTIONAL);++ auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});+ auto activations_expanded = std::make_shared<ov::op::v0::Unsqueeze>(acts_broadcasted, unsqueeze_axes);++ auto batch_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto output_shape = context.get_output_shape();+ FRONT_END_OP_CONVERSION_CHECK(output_shape.rank().is_static() && output_shape.rank().get_length() == 4,+ "Unexpected MUL_MAT_ID output rank");+ FRONT_END_OP_CONVERSION_CHECK(output_shape[3].is_static(), "Expected static row dimension for MUL_MAT_ID output");+ const auto row_dim_value = output_shape[3].get_length();+ auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {row_dim_value});++ ov::Output<ov::Node> result =+ std::make_shared<ov::op::v0::MatMul>(activations_expanded, selected_weights, false, true);++ auto result_target_dims = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{+ batch_dim,+ get_dimensions(ids_shape, {0, 1}),+ row_dim,+ },+ 0);+ result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);++ if (result.get_element_type() != output_type) {+ result = std::make_shared<ov::op::v0::Convert>(result, output_type);+ }++ return rename_outputs_with_suffix({result}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cppnew file mode 100644index 00000000000..a84de78fe12--- /dev/null+++ b/src/frontends/gguf/src/op/mulmat.cpp@@ -0,0 +1,98 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include <climits>+#include <cstdint>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/util/op_types.hpp"+#include <vector>++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_mulmat(const NodeContext & context) {+ num_inputs_check(context, 2, 2);++ int op_case = context.get_attribute<int>("op_case", 0);++ ov::Output<Node> res;+ ov::Output<ov::Node> B = context.get_input(0);+ ov::Output<ov::Node> A = context.get_input(1);++ bool transpose_b = true;+ if (op_case == 2) {+ B = B.get_node_shared_ptr()->input_value(0);+ transpose_b = false;+ } else if (op_case == 3) {+ B = process_view_input(context, 0);+ A = process_view_input(context, 1);+ }+ if (A.get_element_type() != B.get_element_type()) {+ // Convert the reprocessed B, not input(0), to preserve the op_case 2/3 rebinding.+ B = std::make_shared<ov::op::v0::Convert>(B, A.get_element_type());+ }++ // Use the static ggml input shapes (get_input_shape), not the live OV node shapes: on the+ // stateful KV-cache path the OV node's batch/seq dims are dynamic, but the batch/head/feature+ // dims MUL_MAT needs are static ggml facts the decoder knows by construction.+ auto B_shape = context.get_input_shape(0).to_shape();+ auto A_shape = context.get_input_shape(1).to_shape();+ int64_t A_batch = A_shape[1];+ int64_t B_batch = B_shape[1];++ auto A_batch_larger = A_batch > B_batch;+ auto batch_large = A_batch_larger ? A_batch : B_batch;+ auto batch_small = A_batch_larger ? B_batch : A_batch;++ Output<Node> Z = A_batch_larger ? B : A;+ int64_t factor = batch_large / batch_small;+ if (factor > 1 && batch_small > 1) {+ auto batch_large_node = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{batch_large});+ auto batch_small_node = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{batch_small});+ auto factor_node = ov::op::v0::Constant::create(ov::element::i64, {1}, std::vector<int64_t>{factor});++ auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, Shape{}, {2});+ auto Z_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(Z, unsqueeze_axes);++ auto broadcast_shape = ov::op::v0::Constant::create(+ ov::element::i64, {5}, {(int64_t) 1, (int64_t) 1, factor, (int64_t) 1, (int64_t) 1});+ auto new_Z_shape = ov::op::v0::Constant::create(ov::element::i64, {4},+ {(int64_t) 0, batch_large, (int64_t) -1, (int64_t) A_shape[3]});++ auto Z_broadcasted = std::make_shared<ov::op::v3::Broadcast>(Z_unsqueezed, broadcast_shape,+ ov::op::BroadcastType::BIDIRECTIONAL);+ Z = std::make_shared<ov::op::v1::Reshape>(Z_broadcasted, new_Z_shape, true);+ }+ if (A_batch_larger) {+ B = Z;+ } else {+ A = Z;+ }++ res = std::make_shared<ov::op::v0::MatMul>(A, B, false, transpose_b);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/norm.cpp b/src/frontends/gguf/src/op/norm.cppnew file mode 100644index 00000000000..8f5d484fa84--- /dev/null+++ b/src/frontends/gguf/src/op/norm.cpp@@ -0,0 +1,45 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/subtract.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// LayerNorm over the last dimension: (x - mean) / sqrt(var + eps).+OutputVector translate_norm(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input_node = context.get_input(0);+ float eps = context.get_attribute<float>("eps");++ auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});+ auto mean = std::make_shared<ov::op::v1::ReduceMean>(input_node, axis, true);+ auto centered = std::make_shared<ov::op::v1::Subtract>(input_node, mean);+ auto squared = std::make_shared<ov::op::v1::Multiply>(centered, centered);+ auto variance = std::make_shared<ov::op::v1::ReduceMean>(squared, axis, true);+ auto std_dev = std::make_shared<ov::op::v0::Sqrt>(std::make_shared<ov::op::v1::Add>(+ variance, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {eps})));+ auto res = std::make_shared<ov::op::v1::Divide>(centered, std_dev);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/pad.cpp b/src/frontends/gguf/src/op/pad.cppnew file mode 100644index 00000000000..7b0b02cee41--- /dev/null+++ b/src/frontends/gguf/src/op/pad.cpp@@ -0,0 +1,94 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <array>+#include <cstdint>+#include "openvino/frontend/exception.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/pad.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++namespace {+ov::Output<ov::Node> translate_circular_pad(ov::Output<ov::Node> input,+ const std::array<int32_t, 8>& pads,+ const ov::Shape& input_shape) {+ ov::Output<ov::Node> result = input;+ const std::array<int32_t, 4> pads_begin = {pads[6], pads[4], pads[2], pads[0]};+ const std::array<int32_t, 4> pads_end = {pads[7], pads[5], pads[3], pads[1]};++ for (size_t axis = 0; axis < input_shape.size(); ++axis) {+ const int64_t input_dim = static_cast<int64_t>(input_shape[axis]);+ const int64_t pad_begin = pads_begin[axis];+ const int64_t pad_end = pads_end[axis];+ if (pad_begin == 0 && pad_end == 0) {+ continue;+ }+ FRONT_END_CHECK_IMPLEMENTED(input_dim > 0, "Circular PAD requires static non-zero input dimensions");++ std::vector<int64_t> indices(static_cast<size_t>(input_dim + pad_begin + pad_end));+ for (int64_t index = 0; index < static_cast<int64_t>(indices.size()); ++index) {+ int64_t wrapped = (index - pad_begin) % input_dim;+ if (wrapped < 0) {+ wrapped += input_dim;+ }+ indices[static_cast<size_t>(index)] = wrapped;+ }+ auto gather_indices = ov::op::v0::Constant::create(ov::element::i64, {indices.size()}, indices);+ auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {axis});+ result = std::make_shared<ov::op::v8::Gather>(result, gather_indices, gather_axis);+ }+ return result;+}+} // namespace++// GGML_OP_PAD: constant (zero) pad, or circular pad. The 8 per-edge pad extents and the circular+// flag are exposed by the decoder as typed attributes ("pad_params" / "pad_circular").+OutputVector translate_pad(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ if (context.get_input_shape(0) == context.get_output_shape()) {+ auto input_shape = std::make_shared<ov::op::v3::ShapeOf>(input);+ auto res = std::make_shared<ov::op::v1::Reshape>(input, input_shape, false);+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ auto pad_params = context.get_attribute<std::vector<int32_t>>("pad_params");+ FRONT_END_CHECK_IMPLEMENTED(pad_params.size() >= 8, "PAD requires 8 pad extents");+ const std::array<int32_t, 8> pads = {pad_params[0], pad_params[1], pad_params[2], pad_params[3],+ pad_params[4], pad_params[5], pad_params[6], pad_params[7]};+ const bool circular = context.get_attribute<bool>("pad_circular", false);++ if (circular) {+ auto res = translate_circular_pad(input, pads, context.get_input_shape(0).to_shape());+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ const std::vector<int64_t> pads_begin = {pads[6], pads[4], pads[2], pads[0]};+ const std::vector<int64_t> pads_end = {pads[7], pads[5], pads[3], pads[1]};+ auto pads_begin_node = ov::op::v0::Constant::create(ov::element::i64, {pads_begin.size()}, pads_begin);+ auto pads_end_node = ov::op::v0::Constant::create(ov::element::i64, {pads_end.size()}, pads_end);+ auto pad_value = ov::op::v0::Constant::create(input.get_element_type(), ov::Shape{}, {0});+ auto res =+ std::make_shared<ov::op::v1::Pad>(input, pads_begin_node, pads_end_node, pad_value, ov::op::PadMode::CONSTANT);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/permute.cpp b/src/frontends/gguf/src/op/permute.cppnew file mode 100644index 00000000000..e55506025aa--- /dev/null+++ b/src/frontends/gguf/src/op/permute.cpp@@ -0,0 +1,103 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <climits>+#include <cstdint>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_permute(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ int op_case = context.get_attribute<int>("op_case", 0);+ FRONT_END_CHECK_IMPLEMENTED(op_case == 1 || op_case == 2 || op_case == 3 || op_case == 4,+ "Unsupported PERMUTE case");++ ov::Output<Node> res;+ auto src = context.get_input(0);+ auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});++ if (op_case == 1) {+ res = std::make_shared<ov::op::v1::Transpose>(src, perm);+ } else if (op_case == 4) {+ auto output_shape = context.get_output_shape().to_shape();+ auto n_heads = ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[1]});+ auto head_size = ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[3]});+ auto n_seq_active = context.has_input("n_seq_active")+ ? context.get_input("n_seq_active")+ : ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[0]});+ auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});++ auto new_shape =+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, n_heads, head_size}, 0);++ auto reshaped = std::make_shared<ov::op::v1::Reshape>(src, new_shape, true);+ res = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);+ } else {+ auto cache_shape = src.get_partial_shape();+ auto output_shape = context.get_output_shape().to_shape();+ int64_t head_size = output_shape[3];+ int64_t n_heads = output_shape[1];+ int64_t ctx_per_seq = cache_shape[2].is_static() ? cache_shape[2].get_length() : -1;+ int64_t n_seq = cache_shape[1].get_length();++ Output<Node> attention_size;+ if (!context.has_input("attention_size")) {+ attention_size = ov::op::v0::Constant::create(ov::element::i64, {1}, {output_shape[2]});+ } else if (op_case == 2) {+ attention_size = context.get_input("attention_size");+ } else {+ attention_size = context.get_input("attention_size_swa");+ }++ Output<Node> seq_active_start;+ Output<Node> seq_active_end;+ if (context.has_input("seq_active_start")) {+ seq_active_start = context.get_input("seq_active_start");+ seq_active_end = context.get_input("seq_active_end");+ } else {+ int64_t n_seq_active = output_shape[0];+ int64_t seq_active_start_val = context.get_attribute<int64_t>("view_seq_offset", 0);+ int64_t seq_active_end_val = seq_active_start_val + n_seq_active;+ seq_active_start = ov::op::v0::Constant::create(ov::element::i64, {1}, {seq_active_start_val});+ seq_active_end = ov::op::v0::Constant::create(ov::element::i64, {1}, {seq_active_end_val});+ }++ // 1. reshape to [n_seq, ctx_per_seq, n_heads, head_size]+ // 2. slice out the active sequences+ // 3. slice out the attention part in each sequence+ // 4. permute+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});++ auto src_reshaped = std::make_shared<ov::op::v1::Reshape>(+ src,+ ov::op::v0::Constant::create(ov::element::i64, {4}, {n_seq, ctx_per_seq, n_heads, head_size}),+ false);+ auto slice1 = std::make_shared<ov::op::v8::Slice>(src_reshaped, seq_active_start, seq_active_end, one, zero);+ auto slice2 = std::make_shared<ov::op::v8::Slice>(slice1, zero, attention_size, one, one);+ res = std::make_shared<ov::op::v1::Transpose>(slice2, perm);+ }+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/repeat.cpp b/src/frontends/gguf/src/op/repeat.cppnew file mode 100644index 00000000000..a395d2b8c9f--- /dev/null+++ b/src/frontends/gguf/src/op/repeat.cpp@@ -0,0 +1,73 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/frontend/exception.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/tile.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_REPEAT tiles src[0] to fill the destination shape; every destination dimension is an+// integer multiple of the corresponding source dimension.+OutputVector translate_repeat(const NodeContext& context) {+ num_inputs_check(context, 1, 2);++ auto input = context.get_input(0);+ const auto input_shape = context.get_input_shape(0);+ const auto output_shape = context.get_output_shape();++ if (input_shape.rank().is_static() && output_shape.rank().is_static() &&+ input_shape.rank() == output_shape.rank()) {+ const auto rank = static_cast<size_t>(input_shape.rank().get_length());+ std::vector<int64_t> repeats(rank, 1);+ bool all_static = true;++ for (size_t axis = 0; axis < rank; ++axis) {+ if (!input_shape[axis].is_static() || !output_shape[axis].is_static()) {+ all_static = false;+ break;+ }+ const int64_t input_dim = input_shape[axis].get_length();+ const int64_t output_dim = output_shape[axis].get_length();+ FRONT_END_OP_CONVERSION_CHECK(input_dim > 0 && output_dim > 0 && output_dim % input_dim == 0,+ "REPEAT input shape ", input_shape, " cannot tile to match ", output_shape);+ repeats[axis] = output_dim / input_dim;+ }++ if (all_static) {+ auto repeats_node = ov::op::v0::Constant::create(ov::element::i64, {repeats.size()}, repeats);+ ov::Output<ov::Node> res = std::make_shared<ov::op::v0::Tile>(input, repeats_node);+ return rename_outputs_with_suffix({res}, context.get_name());+ }+ }++ // Dynamic fallback: tile by the ratio of output to input shape.+ auto input_shape_node = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);+ std::shared_ptr<ov::Node> target_shape_node;+ if (output_shape.rank().is_static() && output_shape.is_static()) {+ target_shape_node =+ ov::op::v0::Constant::create(ov::element::i64, {output_shape.to_shape().size()}, output_shape.to_shape());+ } else {+ target_shape_node = std::make_shared<ov::op::v3::ShapeOf>(context.get_input(1), ov::element::i64);+ }+ auto repeats_node = std::make_shared<ov::op::v1::Divide>(target_shape_node, input_shape_node);+ ov::Output<ov::Node> res = std::make_shared<ov::op::v0::Tile>(input, repeats_node);+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/reshape.cpp b/src/frontends/gguf/src/op/reshape.cppnew file mode 100644index 00000000000..5af5beb59b9--- /dev/null+++ b/src/frontends/gguf/src/op/reshape.cpp@@ -0,0 +1,70 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include <cstdint>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/frontend/exception.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/reshape.hpp"+#include <stdexcept>+#include <vector>++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_reshape(const NodeContext & context) {+ num_inputs_check(context, 1, 1);+ if (context.get_input(0).get_partial_shape() == context.get_output_shape()) {+ return {context.get_input(0)};+ }++ int op_case = context.get_attribute<int>("op_case", 0);+ FRONT_END_CHECK_IMPLEMENTED(+ op_case == 1 || op_case == 2 || op_case == 3 || op_case == 4 || op_case == 5 || op_case == 6,+ "Unsupported RESHAPE case");++ auto output_shape = context.get_output_shape().to_shape();+ std::shared_ptr<ov::Node> new_shape_node;+ if (op_case == 1) {+ new_shape_node = ov::op::v0::Constant::create(+ ov::element::i64, {4},+ std::vector<int64_t>{(int64_t) output_shape[0], -1, (int64_t) output_shape[2], (int64_t) output_shape[3]});+ } else if (op_case == 2) {+ new_shape_node = ov::op::v0::Constant::create(+ ov::element::i64, {4},+ std::vector<int64_t>{(int64_t) output_shape[0], (int64_t) output_shape[1], -1, (int64_t) output_shape[3]});++ } else if (op_case == 3) {+ // Flatten-for-SET_ROWS: [F, tok, 1, 1] -> [1, F*tok, -1, 1] (the KV-cache write path, e.g.+ // gpt-oss cache_v). Token count stays on the dynamic axis via -1.+ new_shape_node = ov::op::v0::Constant::create(+ ov::element::i64, {4}, std::vector<int64_t>{(int64_t) output_shape[0], (int64_t) output_shape[1], -1, 1});++ } else if (op_case == 4) {+ return {context.get_input(0).get_node_shared_ptr()->input_value(0)};++ } else if (op_case == 5) {+ std::vector<int64_t> shape_vec = {1, 1, -1, (int64_t) output_shape[3]};+ new_shape_node = ov::op::v0::Constant::create(ov::element::i64, {4}, shape_vec);++ } else if (op_case == 6) {+ new_shape_node = ov::op::v0::Constant::create(ov::element::i64, {4}, output_shape);+ }+ auto res = std::make_shared<ov::op::v1::Reshape>(context.get_input(0), new_shape_node, false);+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/rms_norm.cpp b/src/frontends/gguf/src/op/rms_norm.cppnew file mode 100644index 00000000000..9cfbdefe502--- /dev/null+++ b/src/frontends/gguf/src/op/rms_norm.cpp@@ -0,0 +1,40 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>++#include "openvino/core/node_output.hpp"+#include "openvino/decompositions/rms_norm.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/pass/node_registry.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_rms_norm(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ // ggml RMS_NORM is norm-only (the weight/gamma multiply is a separate ggml MUL op), so no scale+ // is passed. The shared helper emits the canonical form ov::pass::RMSFusion folds into+ // ov::op::internal::RMS.+ auto input_node = context.get_input(0);+ auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});+ auto eps = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {context.get_attribute<float>("eps")});++ ov::pass::NodeRegistry reg;+ auto res = ov::decomposition::rms_norm(reg, input_node, axes, eps);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/rope.cpp b/src/frontends/gguf/src/op/rope.cppnew file mode 100644index 00000000000..c3e9f9ea1df--- /dev/null+++ b/src/frontends/gguf/src/op/rope.cpp@@ -0,0 +1,193 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <memory>+#include <vector>++#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/decompositions/rope.hpp"+#include "openvino/frontend/exception.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/cos.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/sin.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/split.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/unsqueeze.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_rope(const NodeContext& context) {+ num_inputs_check(context, 2, 3);++ int op_case = context.get_attribute<int>("op_case", 0);++ ov::Output<Node> res;++ auto data_node = context.get_input(0).get_node_shared_ptr();+ auto output_shape = context.get_output_shape().to_shape();+ auto rope_config = context.get_attribute<RopeConfig>("rope_config");+ const int mode = (op_case & 0xFFFF0000) >> 16;+ op_case = (op_case & 0x0000FFFF);++ constexpr int TYPE_NORMAL = 0;+ constexpr int TYPE_NEOX = 1;+ constexpr int TYPE_IMROPE = 2;++ Output<Node> cos_theta_node;+ Output<Node> sin_theta_node;+ if (context.has_input("rope_cos")) {+ cos_theta_node = context.get_input("rope_cos");+ sin_theta_node = context.get_input("rope_sin");+ } else {+ auto inp_pos = context.get_input(1).get_node_shared_ptr();+ std::shared_ptr<ov::Node> rope_freqs_weight;+ if (context.get_input_size() == 3) {+ rope_freqs_weight = context.get_input(2).get_node_shared_ptr();+ }+ auto sin_cos = make_sin_cos(rope_config, inp_pos, rope_freqs_weight, mode == TYPE_IMROPE);+ sin_theta_node = sin_cos.first;+ cos_theta_node = sin_cos.second;+ }++ // The canonical [1, -1, n_head, head_size] reshape target (token count on the dynamic axis),+ // used by the VIEW prologue and the TYPE_NORMAL stack below.+ auto make_bhsd_shape = [&]() {+ return ov::op::v0::Constant::create(+ ov::element::i64,+ {4},+ std::vector<int64_t>{1, -1, (int64_t)output_shape[2], (int64_t)output_shape[3]});+ };++ if (op_case == 2) {+ // The input comes from a VIEW+ int slice_len = static_cast<int>(output_shape[2] * output_shape[3]);+ data_node = process_view_input(context, 0, slice_len).get_node_shared_ptr();+ data_node = std::make_shared<ov::op::v1::Reshape>(data_node, make_bhsd_shape(), false);+ }++ if (mode == TYPE_NORMAL) {+ // Emit the Flux-style interleaved RoPE pattern so ov::pass::RoPEFusionFlux+ // folds this subgraph into ov::op::internal::RoPE → GPU ocl::rope::opt kernel.+ // RoPEFusionFlux requires rank-4 x with static last two dims [n_heads, head_size].+ // After the VIEW prologue the data is already [1,L,n_heads,head_size] (non-stateful)+ // or [L,n_heads,head_size] (stateful, lifted to rank-4 below).+ const int64_t n_heads = static_cast<int64_t>(output_shape[2]);+ const int64_t head_size = static_cast<int64_t>(output_shape[3]);+ const int64_t half = head_size / 2;++ // Reshape to [1, L, n_heads, half, 2] to expose interleaved pairs (reinterprets any+ // incoming rank in element order, so no separate rank lift is needed).+ auto paired_shape = ov::op::v0::Constant::create(+ ov::element::i64, {5}, std::vector<int64_t>{1, -1, n_heads, half, 2});+ auto x_paired = std::make_shared<ov::op::v1::Reshape>(data_node, paired_shape, false);++ auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {-1LL});+ auto data_split = std::make_shared<ov::op::v1::Split>(x_paired, split_axis, 2);+ auto x0 = data_split->output(0);+ auto x1 = data_split->output(1);++ auto neg_one_f = ov::op::v0::Constant::create(data_node->get_element_type(), ov::Shape{}, {-1.0f});+ auto x1_neg = std::make_shared<ov::op::v1::Multiply>(x1, neg_one_f);++ auto x_rotated_paired = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{x1_neg, x0}, -1);+ auto x_rotated = std::make_shared<ov::op::v1::Reshape>(x_rotated_paired, make_bhsd_shape(), false);++ // Expand cos/sin from [B, L, 1, half] to [B, L, 1, head_size].+ auto expand_cos_sin = [&](ov::Output<ov::Node> cs) -> ov::Output<ov::Node> {+ auto cs_unsq = std::make_shared<ov::op::v0::Unsqueeze>(+ cs, ov::op::v0::Constant::create(ov::element::i64, {1}, {-1LL}));+ auto bcast_target = ov::op::v0::Constant::create(+ ov::element::i64, {5}, std::vector<int64_t>{1, 1, 1, half, 2});+ auto bcast = std::make_shared<ov::op::v3::Broadcast>(+ cs_unsq, bcast_target, ov::op::BroadcastType::BIDIRECTIONAL);+ auto flat = ov::op::v0::Constant::create(+ ov::element::i64, {4}, std::vector<int64_t>{0, 0, 0, head_size});+ return std::make_shared<ov::op::v1::Reshape>(bcast, flat, /*special_zero=*/true);+ };+ auto cos_full = expand_cos_sin(cos_theta_node);+ auto sin_full = expand_cos_sin(sin_theta_node);++ auto y1 = std::make_shared<ov::op::v1::Multiply>(data_node, cos_full);+ auto y2 = std::make_shared<ov::op::v1::Multiply>(x_rotated, sin_full);+ res = std::make_shared<ov::op::v1::Add>(y1, y2);+ } else if (mode == TYPE_NEOX) {+ // Partial rotary (ggml n_dims < head_dim): only the first n_dims of every head are+ // rotated; the remaining tail is passed through unchanged. cos/sin have width n_dims/2,+ // so the rotated block must be exactly n_dims wide.+ const int64_t head_dim = static_cast<int64_t>(output_shape[3]);+ const int64_t n_rot = rope_config.n_dims > 0 ? rope_config.n_dims : head_dim;++ // Rotate only the first n_rot elements of every head and concatenate the untouched tail.+ Output<Node> rotary_in = data_node;+ Output<Node> pass_through;+ if (n_rot < head_dim) {+ auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto n_rot_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {n_rot});+ auto head_c = ov::op::v0::Constant::create(ov::element::i64, {1}, {head_dim});+ rotary_in = std::make_shared<ov::op::v8::Slice>(data_node, zero, n_rot_c, one, neg_one);+ pass_through = std::make_shared<ov::op::v8::Slice>(data_node, n_rot_c, head_c, one, neg_one);+ }++ // Core split-halves RoPE via the shared decomposition helper: it emits the exact+ // split + Multiply(-1)+Add + Concat pattern that ov::pass::RoPEFusion folds into+ // ov::op::internal::RoPE (the previous hand-built Subtract form did not match and so+ // was never fused). cos/sin already carry the n_rot/2 width.+ ov::pass::NodeRegistry reg;+ Output<Node> rotated = ov::decomposition::rope(reg, rotary_in, cos_theta_node, sin_theta_node, n_rot / 2);+ res = (n_rot < head_dim) ? std::make_shared<ov::op::v0::Concat>(ov::OutputVector{rotated, pass_through}, -1)+ : rotated;+ } else if (mode == TYPE_IMROPE) {+ // Use output_shape, not data_node->get_shape() which throws on a dynamic dim.+ int64_t n_dims = output_shape[3];+ auto cos_sin_shape = std::make_shared<ov::op::v0::Constant>(ov::element::i64,+ ov::Shape{4},+ std::vector<int64_t>{1, -1, 1, (n_dims >> 1)});+ auto cos_reshaped = std::make_shared<ov::op::v1::Reshape>(cos_theta_node, cos_sin_shape, true);+ auto sin_reshaped = std::make_shared<ov::op::v1::Reshape>(sin_theta_node, cos_sin_shape, true);++ auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {3});+ auto split_a = std::make_shared<ov::op::v1::Split>(data_node, split_axis, 2);+ auto x0 = split_a->output(0);+ auto x1 = split_a->output(1);+ auto mul_a = std::make_shared<ov::op::v1::Multiply>(x0, cos_reshaped);+ auto mul_b = std::make_shared<ov::op::v1::Multiply>(x1, sin_reshaped);+ auto sub = std::make_shared<ov::op::v1::Subtract>(mul_a, mul_b);++ auto mul_c = std::make_shared<ov::op::v1::Multiply>(x0, sin_reshaped);+ auto mul_d = std::make_shared<ov::op::v1::Multiply>(x1, cos_reshaped);+ auto add = std::make_shared<ov::op::v1::Add>(mul_c, mul_d);++ res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{sub, add}, 3);+ }++ // Fail cleanly on an unmapped mode rather than dereferencing a null res downstream.+ FRONT_END_CHECK_IMPLEMENTED(res.get_node_shared_ptr() != nullptr, "Unsupported ROPE mode");++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/scale.cpp b/src/frontends/gguf/src/op/scale.cppnew file mode 100644index 00000000000..8dfaf2c41b8--- /dev/null+++ b/src/frontends/gguf/src/op/scale.cpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/multiply.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_scale(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ // bias is optional in ggml SCALE; default it so a missing op-param does not abort conversion.+ float scale = context.get_attribute<float>("scale", 1.0f);+ float bias = context.get_attribute<float>("bias", 0.0f);++ auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale});+ auto scaled = std::make_shared<ov::op::v1::Multiply>(context.get_input(0), scale_node);++ std::shared_ptr<ov::Node> res;+ if (bias != 0.0f) {+ auto bias_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{bias});+ res = std::make_shared<ov::op::v1::Add>(scaled, bias_node);+ } else {+ res = scaled;+ }++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/set_rows.cpp b/src/frontends/gguf/src/op/set_rows.cppnew file mode 100644index 00000000000..cbb92052c92--- /dev/null+++ b/src/frontends/gguf/src/op/set_rows.cpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "openvino/frontend/gguf/set_rows_op.hpp"+#include "utils.hpp"++#include <cstdint>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/frontend/exception.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/squeeze.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// Always emit the internal SetRows placeholder op (never a device-specific ScatterUpdate). A+// normalization-stage lowering replaces it: the built-in LowerSetRows rebuilds the stateless+// ScatterUpdate form; a caller-registered stateful lowering may instead turn the SetRows that+// feeds attention into a stateful KV-cache subgraph. This keeps conversion identical regardless+// of execution mode and needs no KV-vs-non-KV classification at translate time.+OutputVector translate_set_rows(const NodeContext & context) {+ num_inputs_check(context, 3, 3);++ auto data = context.get_input(0);+ auto indices = context.get_input(1);+ auto dst = context.get_input(2);++ data = std::make_shared<ov::op::v0::Convert>(data, context.get_attribute<ov::element::Type>("output_type"));++ // Row size = the destination cache's innermost dim. Using the dst input (not the SET_ROWS+ // output shape) matters for the flattened KV-cache write (gpt-oss cache_v is stored as+ // [1,1,ctx,1], row_size 1); the output layout can report a different last dim, which would+ // reshape the update to a width the ScatterUpdate dst cannot match.+ const auto dst_ps = context.get_input_shape(2);+ FRONT_END_OP_CONVERSION_CHECK(dst_ps.rank().is_static() && dst_ps[dst_ps.rank().get_length() - 1].is_static(),+ "SET_ROWS requires a static destination row size");+ const int64_t row_size = dst_ps[dst_ps.rank().get_length() - 1].get_length();++ auto ind_squeezed =+ std::make_shared<ov::op::v0::Squeeze>(indices, ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}));+ auto data_reshaped = std::make_shared<ov::op::v1::Reshape>(+ data,+ ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 1, (int64_t) 1, (int64_t) -1, row_size}),+ false);++ auto set_rows = std::make_shared<SetRows>(data_reshaped, ind_squeezed, dst);+ return rename_outputs_with_suffix({set_rows}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/softmax.cpp b/src/frontends/gguf/src/op/softmax.cppnew file mode 100644index 00000000000..5eba537072f--- /dev/null+++ b/src/frontends/gguf/src/op/softmax.cpp@@ -0,0 +1,168 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cmath>+#include <cstdint>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/frontend/exception.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/softmax.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++static bool is_static_one(const ov::Dimension& dim) {+ return dim.is_static() && dim.get_length() == 1;+}++static bool same_static_dim(const ov::Dimension& lhs, const ov::Dimension& rhs) {+ return lhs.is_static() && rhs.is_static() && lhs.get_length() == rhs.get_length();+}++// Attention sinks (gpt-oss): a per-head learned bias appended as one hidden logit column before the+// softmax and dropped afterwards. The sinks tensor is [1,1,1,n_head] (matches the logits' head dim).+static bool is_attention_sinks_input_shape(const ov::PartialShape& candidate, const ov::PartialShape& logits_shape) {+ if (candidate.rank().is_dynamic() || logits_shape.rank().is_dynamic() || candidate.rank().get_length() != 4 ||+ logits_shape.rank().get_length() != 4) {+ return false;+ }+ return is_static_one(candidate[0]) && is_static_one(candidate[1]) && is_static_one(candidate[2]) &&+ same_static_dim(candidate[3], logits_shape[1]);+}++// Append attention sinks as one hidden logit column, softmax over the last axis, then drop it.+static ov::Output<ov::Node> apply_sinks(const NodeContext& context,+ const ov::Output<ov::Node>& logits,+ const ov::Output<ov::Node>& sinks_in) {+ ov::Output<ov::Node> sinks = sinks_in;+ if (sinks.get_element_type() != logits.get_element_type()) {+ sinks = std::make_shared<ov::op::v0::Convert>(sinks, logits.get_element_type());+ }+ auto sink_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, {1, -1, 1, 1});+ auto sinks_4d = std::make_shared<ov::op::v1::Reshape>(sinks, sink_shape, false);++ auto logits_shape = std::make_shared<ov::op::v3::ShapeOf>(logits, ov::element::i64);+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto three = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});+ auto four = ov::op::v0::Constant::create(ov::element::i64, {1}, {4});+ auto shape_axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});++ auto sink_prefix_shape = std::make_shared<ov::op::v8::Slice>(logits_shape, zero, three, one, shape_axis);+ auto sink_last_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto sink_broadcast_shape =+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{sink_prefix_shape, sink_last_dim}, 0);+ auto sink_column =+ std::make_shared<ov::op::v3::Broadcast>(sinks_4d, sink_broadcast_shape, ov::op::BroadcastType::BIDIRECTIONAL);+ auto softmax_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{logits, sink_column}, 3);+ auto softmax_with_sink = std::make_shared<ov::op::v8::Softmax>(softmax_input, -1);+ auto original_last_dim = std::make_shared<ov::op::v8::Slice>(logits_shape, three, four, one, shape_axis);+ return std::make_shared<ov::op::v8::Slice>(softmax_with_sink, zero, original_last_dim, one, three);+}++OutputVector translate_soft_max(const NodeContext& context) {+ num_inputs_check(context, 1, 3);++ auto input0 = context.get_input(0);+ auto input_node = input0.get_node_shared_ptr();+ ov::Output<Node> res;++ // ggml SOFT_MAX reduces ne[0] == the OV last axis (rank-3 attention -> 2, rank-4 router -> 3);+ // derive it from the rank instead of hardcoding 2. Reused by both Softmax paths below.+ const auto& in_ps = input0.get_partial_shape();+ const int64_t softmax_axis = in_ps.rank().is_static() ? in_ps.rank().get_length() - 1 : 2;++ float scale = context.get_attribute<float>("scale", 1.0f);+ float max_bias = context.get_attribute<float>("max_bias", 0.0f);++ auto scale_node = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale});+ ov::Output<ov::Node> scaled_input = std::make_shared<ov::op::v1::Multiply>(input_node, scale_node);++ // Disambiguate a 2nd input: it is either the additive mask or (gpt-oss) the attention sinks.+ const bool second_input_is_sinks =+ context.get_input_size() == 2 &&+ is_attention_sinks_input_shape(context.get_input_shape(1), context.get_output_shape());+ const bool has_mask = context.get_input_size() > 1 && !second_input_is_sinks;+ const bool has_sinks = second_input_is_sinks || context.get_input_size() > 2;+ const int sinks_input_idx = second_input_is_sinks ? 1 : 2;++ if (!has_mask) {+ if (has_sinks) {+ res = apply_sinks(context, scaled_input, context.get_input(sinks_input_idx));+ return rename_outputs_with_suffix({res}, context.get_name());+ }+ res = std::make_shared<ov::op::v8::Softmax>(scaled_input, softmax_axis);+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ ov::Output<ov::Node> mask_node_sliced;+ if (context.has_input("KQ_mask_sliced")) {+ mask_node_sliced = context.get_input("KQ_mask_sliced");+ } else {+ auto token_len = get_dimensions(input_node, {1});+ auto mask_node = context.get_input(1);+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ mask_node_sliced = std::make_shared<ov::op::v8::Slice>(mask_node, zero, token_len, one, one);+ }++ auto output_type = context.get_attribute<ov::element::Type>("output_type");+ if (mask_node_sliced.get_element_type() != output_type) {+ mask_node_sliced = std::make_shared<ov::op::v0::Convert>(mask_node_sliced, output_type);+ }++ ov::Output<ov::Node> biased_input = scaled_input;+ if (max_bias > 0.0f) {+ // ALiBi: per-head slope[h] applied to the mask (ggml ggml_compute_forward_soft_max_f32).+ // n_head is dim 0 (head count) -- read only that dim, since the token dim may be dynamic.+ FRONT_END_OP_CONVERSION_CHECK(in_ps.rank().is_static() && in_ps[0].is_static(),+ "SOFT_MAX ALiBi requires a static head-count dimension");+ const uint32_t n_head = static_cast<uint32_t>(in_ps[0].get_length());+ const uint32_t n_head_log2 = 1u << static_cast<uint32_t>(std::floor(std::log2(n_head)));+ const float m0 = std::pow(2.0f, -max_bias / static_cast<float>(n_head_log2));+ const float m1 = std::pow(2.0f, -(max_bias / 2.0f) / static_cast<float>(n_head_log2));+ std::vector<float> slopes(n_head);+ for (uint32_t h = 0; h < n_head; ++h) {+ slopes[h] = h < n_head_log2 ? std::pow(m0, static_cast<float>(h + 1)) : std::pow(m1, static_cast<float>(2 * (h - n_head_log2) + 1));+ }+ auto slope_node = std::make_shared<ov::op::v0::Constant>(output_type,+ ov::Shape{n_head, 1, 1},+ slopes);+ auto slope_mask = std::make_shared<ov::op::v1::Multiply>(mask_node_sliced, slope_node);+ biased_input = std::make_shared<ov::op::v1::Add>(scaled_input, slope_mask);+ } else {+ biased_input = std::make_shared<ov::op::v1::Add>(scaled_input, mask_node_sliced);+ }++ if (has_sinks) {+ res = apply_sinks(context, biased_input, context.get_input(sinks_input_idx));+ return rename_outputs_with_suffix({res}, context.get_name());+ }++ res = std::make_shared<ov::op::v8::Softmax>(biased_input, softmax_axis);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/ssm_conv.cpp b/src/frontends/gguf/src/op/ssm_conv.cppnew file mode 100644index 00000000000..c39b1706fa1--- /dev/null+++ b/src/frontends/gguf/src/op/ssm_conv.cpp@@ -0,0 +1,61 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/constant.hpp"+#include "openvino/op/group_conv.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_SSM_CONV: depthwise 1D causal convolution over the conv-state window (SSM / Mamba-style+// models, e.g. qwen3next). Implemented as a GroupConvolution with groups == channels.+OutputVector translate_ssm_conv(const NodeContext& context) {+ num_inputs_check(context, 2, 2);++ auto sx = context.get_input(0); // conv state + input: OV [1, n_s, d_inner, ncs]+ auto c = context.get_input(1); // conv1d weight: OV [1, 1, d_inner, d_conv]++ auto sx_shape = context.get_input_shape(0).to_shape();+ auto c_shape = context.get_input_shape(1).to_shape();++ int64_t n_s = sx_shape[1];+ int64_t d_inner = sx_shape[2];+ int64_t ncs = sx_shape[3];+ int64_t d_conv = c_shape[3];+ int64_t n_t = ncs - d_conv + 1;++ // [1, n_s, d_inner, ncs] -> [n_s, d_inner, ncs] for 1D GroupConvolution.+ auto sx_new_shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{n_s, d_inner, ncs});+ auto sx_reshaped = std::make_shared<ov::op::v1::Reshape>(sx, sx_new_shape, false);++ // Filter [groups, out/groups, in/groups, kernel] = [d_inner, 1, 1, d_conv].+ auto c_new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{d_inner, 1, 1, d_conv});+ auto c_reshaped = std::make_shared<ov::op::v1::Reshape>(c, c_new_shape, false);++ auto conv = std::make_shared<ov::op::v1::GroupConvolution>(+ sx_reshaped, c_reshaped, ov::Strides{1}, ov::CoordinateDiff{0}, ov::CoordinateDiff{0}, ov::Strides{1});++ // [n_s, d_inner, n_t] -> [n_s, n_t, d_inner]+ auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});+ auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);++ auto out_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, n_s, n_t, d_inner});+ auto res = std::make_shared<ov::op::v1::Reshape>(transposed, out_shape, false);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/sum_rows.cpp b/src/frontends/gguf/src/op/sum_rows.cppnew file mode 100644index 00000000000..be880181c61--- /dev/null+++ b/src/frontends/gguf/src/op/sum_rows.cpp@@ -0,0 +1,32 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <memory>+#include "openvino/op/constant.hpp"+#include "openvino/op/reduce_sum.hpp"++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// GGML_OP_SUM_ROWS: sum along the last (row) dimension, keeping rank.+OutputVector translate_sum_rows(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ auto res = std::make_shared<ov::op::v1::ReduceSum>(+ input, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1}), true);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/transpose.cpp b/src/frontends/gguf/src/op/transpose.cppnew file mode 100644index 00000000000..0933b986a8f--- /dev/null+++ b/src/frontends/gguf/src/op/transpose.cpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/transpose.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_transpose(const NodeContext& context) {+ num_inputs_check(context, 1, 1);++ // The permutation is a static ggml layout fact (derived from input/output strides). The decoder+ // computes it and exposes it as the typed "perm" attribute, so the translator never inspects+ // ggml strides. Fall back to the classic swap-last-two-dims order when the attribute is absent+ // (e.g. single-op tests), matching ggml's plain GGML_OP_TRANSPOSE.+ auto perm = context.get_attribute<std::vector<int64_t>>("perm", {0, 1, 3, 2});++ auto res = std::make_shared<ov::op::v1::Transpose>(+ context.get_input(0),+ ov::op::v0::Constant::create(ov::element::i64, {perm.size()}, perm));+ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/unary_gelu.cpp b/src/frontends/gguf/src/op/unary_gelu.cppnew file mode 100644index 00000000000..70ba83b0ba0--- /dev/null+++ b/src/frontends/gguf/src/op/unary_gelu.cpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include "openvino/core/node_output.hpp"+#include "openvino/op/gelu.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_unary_gelu(const NodeContext & context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ // ggml GELU is the tanh approximation; v7::Gelu defaults to ERF.+ auto res = std::make_shared<ov::op::v7::Gelu>(input, ov::op::GeluApproximationMode::TANH);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/unary_silu.cpp b/src/frontends/gguf/src/op/unary_silu.cppnew file mode 100644index 00000000000..0744e234b71--- /dev/null+++ b/src/frontends/gguf/src/op/unary_silu.cpp@@ -0,0 +1,31 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node_context.hpp"+#include "op_table.hpp"+#include "utils.hpp"++#include "openvino/core/node_output.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/sigmoid.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_unary_silu(const NodeContext & context) {+ num_inputs_check(context, 1, 1);++ auto input = context.get_input(0);+ auto sigmoid = std::make_shared<ov::op::v0::Sigmoid>(input);+ auto res = std::make_shared<ov::op::v1::Multiply>(input, sigmoid);++ return rename_outputs_with_suffix({res}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cppnew file mode 100644index 00000000000..562a84ce0ee--- /dev/null+++ b/src/frontends/gguf/src/op/view.cpp@@ -0,0 +1,109 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "op_table.hpp"+#include "utils.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/slice.hpp"+#include <vector>+namespace ov {+namespace frontend {+namespace gguf {+namespace op {++OutputVector translate_view(const NodeContext & context) {+ num_inputs_check(context, 1, 1);++ if (context.get_attribute<int>("op_case", 0) == 2) {+ auto dst_shape = context.get_output_shape().to_shape();+ return rename_outputs_with_suffix(+ {process_view_input(context, 0, static_cast<int>(dst_shape[2] * dst_shape[3]))},+ context.get_name());+ }+ if (context.get_attribute<int>("op_case", 0) == 3) {+ auto input = context.get_input(0);+ auto input_ov_shape = input.get_partial_shape();+ auto input_ggml_shape = context.get_attribute<ov::Shape>("input_ggml_shape");++ // Input already reshaped: restore the original ggml (base) shape before slicing.+ if (input_ov_shape.rank().is_static() &&+ static_cast<size_t>(input_ov_shape.rank().get_length()) != input_ggml_shape.size()) {+ input = std::make_shared<ov::op::v1::Reshape>(+ input,+ ov::op::v0::Constant::create(ov::element::i64, {input_ggml_shape.size()}, input_ggml_shape),+ false);+ }++ // The decoder computes the slice as {ov_axis, start, len} from ggml's ne/nb/offset -- this+ // handles both a shrunk dim (topk 64->8, start 0) and an offset-selected sub-block+ // (per-expert ffn_moe_weighted, start selects the expert). The frontend never inspects+ // ggml strides.+ auto slice = context.get_attribute<std::vector<int64_t>>("view_slice", {});+ ov::Output<ov::Node> result = input;+ if (slice.size() == 3) {+ const int64_t axis = slice[0], start = slice[1], len = slice[2];+ auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {start});+ auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {start + len});+ auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});+ result = std::make_shared<ov::op::v8::Slice>(input, begin, end, step, axes);+ }++ // Reshape the sliced result to the view's own (output) shape: ggml views rearrange/drop+ // singleton dims (e.g. select-expert slice yields [1,tok,1,2048] but the view's layout is+ // [1,1,tok,2048], token on axis 2). Skipping this leaves the dynamic token axis in the wrong+ // position, which later broadcasts incorrectly against the residual stream. The decoder+ // supplies the reshape target as "view_reshape" -- the output dims with -1 at the (dynamic)+ // token axis -- so the token dim stays dynamic and lands where the consumer expects it.+ auto tgt = context.get_attribute<std::vector<int64_t>>("view_reshape", {});+ if (!tgt.empty()) {+ // The decoder gives the (static) output layout. The sliced result carries the token+ // count on one dynamic axis; keep it dynamic by placing a single -1 on the output axis+ // that absorbs it. Determine that axis by conservation of element count: the product of+ // the sliced result's static dims must equal the product of the output's non--1 dims,+ // so the -1 axis is the one whose value equals (token count) = slice_static_product /+ // (output_static_product_without_that_axis). Concretely, if the sliced result has a+ // dynamic axis, exactly one output axis must be -1; pick the output axis whose value is+ // not needed to match the sliced result's static dims.+ const auto& res_ps = result.get_partial_shape();+ bool res_has_dyn = res_ps.rank().is_static() && [&] {+ for (int64_t i = 0; i < res_ps.rank().get_length(); ++i)+ if (res_ps[i].is_dynamic())+ return true;+ return false;+ }();+ if (res_has_dyn) {+ // product of static dims in the sliced result (excludes the single dynamic axis)+ int64_t slice_static = 1;+ for (int64_t i = 0; i < res_ps.rank().get_length(); ++i)+ if (res_ps[i].is_static())+ slice_static *= res_ps[i].get_length();+ // product of all output dims+ int64_t out_prod = 1;+ for (auto d : tgt)+ out_prod *= d;+ // token count = out_prod / slice_static ; mark the axis holding it as -1+ if (slice_static != 0 && out_prod % slice_static == 0) {+ int64_t token_len = out_prod / slice_static;+ for (auto& d : tgt) {+ if (d == token_len) {+ d = -1;+ break;+ }+ }+ }+ }+ result = std::make_shared<ov::op::v1::Reshape>(+ result, ov::op::v0::Constant::create(ov::element::i64, {tgt.size()}, tgt), false);+ }+ return {result};+ }+ return {context.get_input(0)};+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op/weight.cpp b/src/frontends/gguf/src/op/weight.cppnew file mode 100644index 00000000000..a1106c7ef6b--- /dev/null+++ b/src/frontends/gguf/src/op/weight.cpp@@ -0,0 +1,71 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <functional>+#include <memory>+#include <numeric>+#include "openvino/op/constant.hpp"+#include "openvino/op/reshape.hpp"+#include <vector>++#include "node_context.hpp"+#include "op_table.hpp"+#include "quant/weights.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace op {++// A GGUF weight surfaced as a node. A weight is a ggml leaf (op type "GGML_OP_NONE") that the+// decoder marks by exposing a "data" attribute (the raw weight bytes), alongside the ggml quant+// type name and the logical shape. The frontend does all dequant / repacking here, so the+// decoder never builds OV nodes itself. (Model-input leaves are also GGML_OP_NONE, but they are+// resolved to Parameters before the graph walk and never reach this translator.)+OutputVector translate_weight(const NodeContext& context) {+ auto data = context.get_attribute<ov::Tensor>("data");+ FRONT_END_OP_CONVERSION_CHECK(data, "GGML_OP_NONE node has no 'data' attribute; not a weight");+ auto quant_type = context.get_attribute<std::string>("quant_type");+ auto shape = context.get_output_shape().to_shape();++ // MoE MXFP4 expert weights stay PACKED: MUL_MAT_ID gathers the selected expert and dequantizes+ // on-graph, so materializing all experts to f32 here would waste memory. Surface the raw bytes+ // as a rank-5 u8 constant [1, n_expert, m, k_blocks, 17] (17 = 1 e8m0 scale byte + 16 nibble+ // bytes per 32-element block), which the mul_mat_id MXFP4 path recognizes.+ if (shape.size() > 2 && quant_type == "MXFP4") {+ constexpr size_t kQk = 32, kBlockBytes = 17;+ const size_t n_expert = shape[shape.size() - 3];+ const size_t m = shape[shape.size() - 2];+ const size_t k = shape.back();+ FRONT_END_OP_CONVERSION_CHECK(k % kQk == 0, "MXFP4 MoE expert cols must be a multiple of 32");+ const size_t k_blocks = k / kQk;+ ov::Shape packed_shape{1, n_expert, m, k_blocks, kBlockBytes};+ FRONT_END_OP_CONVERSION_CHECK(data.get_byte_size() == n_expert * m * k_blocks * kBlockBytes,+ "MXFP4 MoE packed byte size mismatch");+ auto packed = std::make_shared<ov::op::v0::Constant>(ov::element::u8, packed_shape, data.data());+ return rename_outputs_with_suffix({packed}, context.get_name());+ }++ // MoE expert weights are rank > 2 ([1, n_expert, m, k]). The dequant path works on a 2D+ // [rows, cols] tensor, so flatten the leading dims to rows, dequantize, then reshape the f32+ // result back to the full expert shape for MUL_MAT_ID. (Regular weights are already 2D.)+ if (shape.size() > 2) {+ const size_t cols = shape.back();+ const size_t rows = std::accumulate(shape.begin(), shape.end() - 1, size_t{1}, std::multiplies<size_t>());+ auto node = make_weight_node(data, quant_type, ov::Shape{rows, cols}, context.get_name());+ std::vector<int64_t> full(shape.begin(), shape.end());+ auto target = ov::op::v0::Constant::create(ov::element::i64, {full.size()}, full);+ auto reshaped = std::make_shared<ov::op::v1::Reshape>(node, target, false);+ return rename_outputs_with_suffix({reshaped}, context.get_name());+ }++ auto node = make_weight_node(data, quant_type, shape, context.get_name());+ return rename_outputs_with_suffix({node}, context.get_name());+}++} // namespace op+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op_table.cpp b/src/frontends/gguf/src/op_table.cppnew file mode 100644index 00000000000..ea449add92c--- /dev/null+++ b/src/frontends/gguf/src/op_table.cpp@@ -0,0 +1,71 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "op_table.hpp"++#include "openvino/op/add.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/softplus.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/tanh.hpp"++#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {++std::unordered_map<std::string, CreatorFunction> get_supported_ops() {+ using namespace ov::op;+ return {+ {"GGML_GLU_OP_GEGLU", op::translate_glu_geglu},+ {"GGML_GLU_OP_SWIGLU", op::translate_glu_swiglu},+ {"GGML_GLU_OP_SWIGLU_OAI", op::translate_glu_swiglu_oai},+ {"GGML_OP_ADD", op::translate_1to1_match_2_inputs<v1::Add>},+ {"GGML_OP_ADD1", op::translate_1to1_match_2_inputs<v1::Add>},+ {"GGML_OP_ADD_ID", op::translate_add_id},+ {"GGML_OP_ARGSORT", op::translate_argsort},+ {"GGML_OP_CLAMP", op::translate_clamp},+ {"GGML_OP_CONCAT", op::translate_concat},+ {"GGML_OP_CONT", op::translate_cont},+ {"GGML_OP_CPY", op::translate_cpy},+ {"GGML_OP_DIV", op::translate_1to1_match_2_inputs<v1::Divide>},+ {"GGML_OP_FLASH_ATTN_EXT", op::translate_flash_attn_ext},+ {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net},+ {"GGML_OP_GET_ROWS", op::translate_get_rows},+ {"GGML_OP_IM2COL", op::translate_im2col},+ {"GGML_OP_L2_NORM", op::translate_l2_norm},+ {"GGML_OP_MUL", op::translate_1to1_match_2_inputs<v1::Multiply>},+ {"GGML_OP_MUL_MAT", op::translate_mulmat},+ {"GGML_OP_MUL_MAT_ID", op::translate_mul_mat_id},+ // A GGML_OP_NONE leaf carrying a "data" attribute is a weight (see translate_weight).+ {"GGML_OP_NONE", op::translate_weight},+ {"GGML_OP_NORM", op::translate_norm},+ {"GGML_OP_PAD", op::translate_pad},+ {"GGML_OP_PERMUTE", op::translate_permute},+ {"GGML_OP_RESHAPE", op::translate_reshape},+ {"GGML_OP_REPEAT", op::translate_repeat},+ {"GGML_OP_RMS_NORM", op::translate_rms_norm},+ {"GGML_OP_ROPE", op::translate_rope},+ {"GGML_OP_SCALE", op::translate_scale},+ {"GGML_OP_SET_ROWS", op::translate_set_rows},+ {"GGML_OP_SOFT_MAX", op::translate_soft_max},+ {"GGML_OP_SSM_CONV", op::translate_ssm_conv},+ {"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},+ {"GGML_OP_SUM_ROWS", op::translate_sum_rows},+ {"GGML_OP_TRANSPOSE", op::translate_transpose},+ {"GGML_OP_VIEW", op::translate_view},+ {"GGML_UNARY_OP_GELU", op::translate_unary_gelu},+ {"GGML_UNARY_OP_SILU", op::translate_unary_silu},+ {"GGML_UNARY_OP_SOFTPLUS", op::translate_1to1_match_1_input<v4::SoftPlus>},+ {"GGML_UNARY_OP_TANH", op::translate_1to1_match_1_input<v0::Tanh>},+ };+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/op_table.hpp b/src/frontends/gguf/src/op_table.hppnew file mode 100644index 00000000000..9a6b5d26380--- /dev/null+++ b/src/frontends/gguf/src/op_table.hpp@@ -0,0 +1,57 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "node_context.hpp"++namespace ov {+namespace frontend {+namespace gguf {++namespace op {++#define GGUF_OP_CONVERTER(op) OutputVector op(const NodeContext& context)++GGUF_OP_CONVERTER(translate_add_id);+GGUF_OP_CONVERTER(translate_argsort);+GGUF_OP_CONVERTER(translate_clamp);+GGUF_OP_CONVERTER(translate_concat);+GGUF_OP_CONVERTER(translate_cont);+GGUF_OP_CONVERTER(translate_gated_delta_net);+GGUF_OP_CONVERTER(translate_get_rows);+GGUF_OP_CONVERTER(translate_im2col);+GGUF_OP_CONVERTER(translate_l2_norm);+GGUF_OP_CONVERTER(translate_norm);+GGUF_OP_CONVERTER(translate_pad);+GGUF_OP_CONVERTER(translate_repeat);+GGUF_OP_CONVERTER(translate_ssm_conv);+GGUF_OP_CONVERTER(translate_mulmat);+GGUF_OP_CONVERTER(translate_mul_mat_id);+GGUF_OP_CONVERTER(translate_permute);+GGUF_OP_CONVERTER(translate_reshape);+GGUF_OP_CONVERTER(translate_rms_norm);+GGUF_OP_CONVERTER(translate_rope);+GGUF_OP_CONVERTER(translate_scale);+GGUF_OP_CONVERTER(translate_sum_rows);+GGUF_OP_CONVERTER(translate_unary_silu);+GGUF_OP_CONVERTER(translate_unary_gelu);+GGUF_OP_CONVERTER(translate_soft_max);+GGUF_OP_CONVERTER(translate_transpose);+GGUF_OP_CONVERTER(translate_view);+GGUF_OP_CONVERTER(translate_glu_swiglu);+GGUF_OP_CONVERTER(translate_glu_swiglu_oai);+GGUF_OP_CONVERTER(translate_glu_geglu);+GGUF_OP_CONVERTER(translate_set_rows);+GGUF_OP_CONVERTER(translate_cpy);+GGUF_OP_CONVERTER(translate_flash_attn_ext);+GGUF_OP_CONVERTER(translate_weight);++} // namespace op++std::unordered_map<std::string, CreatorFunction> get_supported_ops();++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cppnew file mode 100644index 00000000000..3c92155f45c--- /dev/null+++ b/src/frontends/gguf/src/pass/lower_set_rows_stateless.cpp@@ -0,0 +1,63 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "pass/lower_set_rows_stateless.hpp"++#include <memory>++#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/frontend/gguf/set_rows_op.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scatter_update.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"++namespace ov {+namespace frontend {+namespace gguf {+namespace pass {++LowerSetRowsStateless::LowerSetRowsStateless() {+ auto set_rows_pattern = ov::pass::pattern::wrap_type<SetRows>();++ const auto callback = [](ov::pass::pattern::Matcher& m) {+ auto set_rows = ov::as_type_ptr<SetRows>(m.get_match_root());+ if (!set_rows) {+ return false;+ }+ auto data = set_rows->input_value(0); // reshaped to [1, 1, seq, emb]+ auto indices = set_rows->input_value(1); // squeezed row indices+ auto dst = set_rows->input_value(2); // destination tensor (Parameter for a KV cache)++ auto axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {2});+ std::shared_ptr<ov::Node> res = std::make_shared<ov::op::v3::ScatterUpdate>(dst, indices, data, axes);++ // Multi-sequence: if the destination is a Reshape, reshape the scatter result back to the+ // original [1, n_seq, ctx_per_seq, emb] layout (ctx_per_seq stays dynamic for llama-bench).+ if (auto dst_reshape = ov::as_type_ptr<ov::op::v1::Reshape>(dst.get_node_shared_ptr())) {+ auto dst_ps = dst_reshape->get_input_partial_shape(0);+ // -1 for any dynamic dim; get_length() throws on dynamic.+ auto dim_or_dynamic = [&](size_t i) -> int64_t {+ return dst_ps[i].is_static() ? dst_ps[i].get_length() : -1;+ };+ std::vector<int64_t> shape = {dim_or_dynamic(0), dim_or_dynamic(1), dim_or_dynamic(2), dim_or_dynamic(3)};+ res = std::make_shared<ov::op::v1::Reshape>(+ res, ov::op::v0::Constant::create(ov::element::i64, {4}, shape), false);+ }++ res->set_friendly_name(set_rows->get_friendly_name());+ ov::copy_runtime_info(set_rows, res);+ ov::replace_node(set_rows, res);+ return true;+ };++ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(set_rows_pattern, "gguf::LowerSetRowsStateless"),+ callback);+}++} // namespace pass+} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp b/src/frontends/gguf/src/pass/lower_set_rows_stateless.hppnew file mode 100644index 00000000000..03b85b6b06c--- /dev/null+++ b/src/frontends/gguf/src/pass/lower_set_rows_stateless.hpp@@ -0,0 +1,26 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/matcher_pass.hpp"++namespace ov::frontend::gguf {+namespace pass {++// Default lowering of the internal SetRows op into the stateless (llama.cpp-faithful) form:+// SetRows(data, indices, dst) -> ScatterUpdate(dst, indices, data)+// i.e. the rows are scattered into the passed-in destination tensor, which stays a graph+// input/output. Applies to every SetRows (KV cache, MoE routing, etc.) identically. Runs in the+// frontend's normalization stage so a plain convert() yields a runnable stateless model. A caller+// wanting stateful execution registers an alternative lowering via DecoderTransformationExtension+// (which runs first and consumes the KV-cache SetRows ops before this pass sees them).+class LowerSetRowsStateless : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ov::frontend::gguf::pass::LowerSetRowsStateless")+ LowerSetRowsStateless();+};++} // namespace pass+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hppnew file mode 100644index 00000000000..234deebbd4a--- /dev/null+++ b/src/frontends/gguf/src/quant/gguf.hpp@@ -0,0 +1,141 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <map>+#include <string>+#include <unordered_map>+#include <variant>+#include <vector>++#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/tensor.hpp"+#include "openvino/util/mmap_object.hpp"++namespace ov::frontend::gguf {++// GGUF tensor (quantization) type ids, matching the on-disk GGUF format numbering.+// Only the subset the frontend handles is enumerated explicitly; others are accepted+// numerically but rejected at dequant time.+enum gguf_tensor_type {+ GGUF_TYPE_F32 = 0,+ GGUF_TYPE_F16 = 1,+ GGUF_TYPE_Q4_0 = 2,+ GGUF_TYPE_Q4_1 = 3,+ GGUF_TYPE_Q5_0 = 6,+ GGUF_TYPE_Q5_1 = 7,+ GGUF_TYPE_Q8_0 = 8,+ GGUF_TYPE_Q8_1 = 9,+ GGUF_TYPE_Q2_K = 10,+ GGUF_TYPE_Q3_K = 11,+ GGUF_TYPE_Q4_K = 12,+ GGUF_TYPE_Q5_K = 13,+ GGUF_TYPE_Q6_K = 14,+ GGUF_TYPE_Q8_K = 15,+ GGUF_TYPE_I8 = 24,+ GGUF_TYPE_I16 = 25,+ GGUF_TYPE_I32 = 26,+ GGUF_TYPE_I64 = 27,+ GGUF_TYPE_F64 = 28,+ GGUF_TYPE_BF16 = 30,+ GGUF_TYPE_MXFP4 = 39, // 4-bit microscaling (gpt-oss): 1-byte E8M0 scale + 32x E2M1+ GGUF_TYPE_COUNT,+};++// GGUF metadata value type ids (the kv-pair value encoding).+enum gguf_value_type {+ GGUF_VALUE_TYPE_UINT8 = 0,+ GGUF_VALUE_TYPE_INT8 = 1,+ GGUF_VALUE_TYPE_UINT16 = 2,+ GGUF_VALUE_TYPE_INT16 = 3,+ GGUF_VALUE_TYPE_UINT32 = 4,+ GGUF_VALUE_TYPE_INT32 = 5,+ GGUF_VALUE_TYPE_FLOAT32 = 6,+ GGUF_VALUE_TYPE_BOOL = 7,+ GGUF_VALUE_TYPE_STRING = 8,+ GGUF_VALUE_TYPE_ARRAY = 9,+ GGUF_VALUE_TYPE_UINT64 = 10,+ GGUF_VALUE_TYPE_INT64 = 11,+ GGUF_VALUE_TYPE_FLOAT64 = 12,+};++// A single tensor descriptor parsed from the GGUF file. `weights_data` points directly+// into the memory-mapped file (zero-copy); the owning reader keeps the mapping alive.+// Field names mirror the classic gguf-tools layout so the dequant code in+// gguf_quants.cpp reads them unchanged.+struct gguf_tensor {+ const char* name = nullptr; // points into the mmap (not null-terminated)+ size_t namelen = 0;+ uint32_t type = 0; // gguf_tensor_type+ uint32_t ndim = 0;+ uint64_t dim[4] = {1, 1, 1, 1};+ uint64_t offset = 0; // offset from the start of the tensor-data section+ uint64_t bsize = 0; // total size in bytes+ uint64_t num_weights = 0; // total number of elements+ const uint8_t* weights_data = nullptr;+};++// A metadata value: scalars are stored as an ov::Tensor of shape {} (so that numeric+// metadata round-trips through ov::element types), strings as std::string, and arrays as+// an ov::Tensor of shape {n} or a vector<std::string>.+using GGUFMetaData =+ std::variant<std::monostate, float, int, ov::Tensor, std::string, std::vector<std::string>, std::vector<int32_t>>;++// GGUFLoad result: (metadata, tensor arrays, qtype map, mmap, quant_buf).+// - mmap: must stay alive while arrays tensors are used (non-quantized tensors are mmap views).+// - quant_buf: single AlignedBuffer holding all repacked quantized weight/scale/bias data;+// tensors in `arrays` for quantized weights are SharedBuffer slices into this buffer.+using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,+ std::unordered_map<std::string, ov::Tensor>,+ std::unordered_map<std::string, gguf_tensor_type>,+ std::shared_ptr<ov::MappedMemory>,+ std::shared_ptr<ov::AlignedBuffer>>;++// Fill pre-allocated i4 weights (u32-packed, XORed for i4 sign) and f16 scales from a+// Q4_0 tensor. No bias: Q4_0 is symmetric (zp = -8*scale is implicit, not stored).+void gguf_fill_q4_0(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales);++// Fill pre-allocated weights and f16 scales from a symmetric GGUF tensor+// (Q8_0/Q5_0/Q6_K: i8 weights; Q3_K: i4 weights packed as u8).+// No zero-point: the center value is subtracted during unpacking so weights are centered at 0.+void gguf_fill_sym(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales);++// Fill pre-allocated weights, f16 scales, and integer zero-points from an asymmetric GGUF+// tensor (Q4_1: u4 zp; Q4_K: u4 zp; Q5_K/Q5_1: u8 zp; Q2_K: u8 zp).+// Tensor shapes must match quant_sizes.+void gguf_fill_asym(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp);++// Fill pre-allocated f4e2m1 weights and f8e8m0 scales from an MXFP4 GGUF tensor.+void gguf_fill_mxfp4(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales);++// Fused bit-exact ggml dequant + channel-wise Q8_0_C requant for the token_embd/output/Q6_K/Q5_K+// requant path. Streams one row at a time (never materializes the full f32 weight). Fills i8+// weights [rows,cols] + f16 scales [rows,1]; matches upstream's to_float->quantize_q8_0 exactly so+// those tensors are bit-identical to the vendored backend. Returns false for unsupported qtypes.+bool requantize_q8_0_channelwise_faithful(const gguf_tensor& tensor,+ size_t rows,+ size_t cols,+ gguf_tensor_type qtype,+ int8_t* out_weights,+ ov::float16* out_scales);++// Test-only accessors for the per-row faithful K-quant dequant (see test_dequant_vs_ggml.cpp).+void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y);+void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y);+void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y);++// Parse a GGUF file: returns (metadata, tensors-by-ggml-name, qtype map, mmap, quant_buf).+// Non-quantized tensors are zero-copy views into the mmap (mmap must outlive arrays use).+// Quantized tensors are SharedBuffer slices of a single AlignedBuffer (quant_buf) so all+// repacked weight/scale/bias data lives in one allocation (IR-frontend pattern).+GGUFLoad get_gguf_data(const std::string& file);++// Extract the architecture config (architecture, layer_num, head_num, head_size,+// head_num_kv, hidden_size, max_position_embeddings, rms_norm_eps, rope_freq_base,+// file_type) from parsed metadata.+std::map<std::string, GGUFMetaData> config_from_meta(const std::unordered_map<std::string, GGUFMetaData>& metadata);++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cppnew file mode 100644index 00000000000..17edd3b24c7--- /dev/null+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp@@ -0,0 +1,680 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <cmath>+#include <cstdint>+#include <cstring>+#include <memory>+#include <numeric>+#include "openvino/core/parallel.hpp"+#include <sstream>++#include "gguf.hpp"+#include "openvino/core/type/element_type_traits.hpp"++namespace ov {+namespace frontend {+namespace gguf {++using namespace std;++// K-quant 256-element super-block byte sizes (ggml layout), used by fill_* / dequant_row_* / requant.+static constexpr uint64_t kQ4K_BLOCK_BYTES = 2 + 2 + 12 + 128; // d + dmin + 12 scales + 128 ql+static constexpr uint64_t kQ5K_BLOCK_BYTES = 2 + 2 + 12 + 32 + 128; // Q4_K + 32 qh+static constexpr uint64_t kQ6K_BLOCK_BYTES = 128 + 64 + 16 + 2; // ql + qh + 16 scales + d++// Round a fractional zero-point to u8, clamping to avoid a modulo-256 wrap when min/scale > 255.+static inline uint8_t quantize_zp_u8(float zpval) {+ long r = std::lround(zpval);+ return static_cast<uint8_t>(std::min<long>(255, std::max<long>(0, r)));+}++void unpack_32_4(const uint8_t* data, uint8_t* dst) {+ std::fill_n(dst, 16, 0);+ for (int j = 0; j < 16; ++j) {+ uint8_t x = (data[j] & 0x0F);+ uint8_t y = (data[j] >> 4);+ if (j % 2 != 0) {+ x <<= 4;+ y <<= 4;+ }+ dst[j / 2] |= x;+ dst[8 + j / 2] |= y; // Last 16 weights are in the higher bits+ }+}++// Q4_1 asymmetric: block = |f16 scale|f16 min|32x4bit weights|.+// Dequant w = sc*q + mn = sc*(q - zp), zp = -mn/sc.+// The zp element type selects the representation (see fill_q4_k for the rationale):+// - u8 -> INTEGER zp = round(-mn/sc): keeps the dequant in the low-precision form the CPU+// plugin fuses into the MatMul (matches the original ggml-openvino backend).+// - f16 -> FRACTIONAL zp = -mn/sc: numerically faithful, used on the requant path where the+// dequant is consumed by channel-wise Q8_0_C rather than fed to the compressed MatMul.+// Outputs u32-packed u4 weights + f16 scales + zero-points (one per block).+void fill_q4_1(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {+ const uint64_t bytes_per_block = 20; // 2 bytes scale, 2 bytes min, 32x0.5 byte weights+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<uint8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);+ auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;+ const size_t n = scales_arr.get_size();+ ov::parallel_for(n, [&](size_t i) {+ const float sc = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block))));+ const float mn = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block + 2))));+ scales[i] = ov::float16(sc);+ const float zpval = (sc != 0.f) ? (-mn / sc) : 0.f;+ if (int_zp)+ zp_u8[i] = quantize_zp_u8(zpval);+ else+ zp_f16[i] = ov::float16(zpval);+ unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);+ });+}++// Q8_0 symmetric: block = |f16 scale|32x i8 weights|. Weights are stored as i8 on disk.+// No zero-point. Output: i8 weights (direct copy) + f16 scales.+void fill_q8_0(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t weights_per_block = 32;+ const uint64_t bytes_per_block = 34; // 2 bytes scale, 32x1 byte weights (i8)+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ const uint8_t* block_data = data + i * bytes_per_block;+ scales[i] = ov::float16::from_bits(*(uint16_t*)block_data);+ std::memcpy(weights + i * weights_per_block, block_data + 2, weights_per_block);+ });+}++// Q5_0 symmetric: block = |f16 scale d|32-bit qh|16 bytes ql (32x4bit low)|.+// weight = lo|(hi<<4) in [0..31]; dequant = d*(w - 16). Output: i8 weights [-16..15].+void fill_q5_0(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t weights_per_block = 32;+ const uint64_t bytes_per_block = 2 + 4 + 16;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ const uint8_t* block_data = data + i * bytes_per_block;+ scales[i] = ov::float16::from_bits(*(uint16_t*)block_data);+ uint32_t qh;+ std::memcpy(&qh, block_data + 2, sizeof(qh));+ const uint8_t* ql = block_data + 6;+ for (uint64_t j = 0; j < weights_per_block; ++j) {+ const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);+ const uint8_t hi = (qh >> j) & 1;+ weights[i * weights_per_block + j] = static_cast<int8_t>((lo | (hi << 4)) - 16);+ }+ });+}++void unpack_256_4(const uint8_t* data, uint8_t* dst) {+ // Initialize the output array with zeros+ std::fill_n(dst, 128, 0);++ for (size_t i = 0; i < 4; ++i) {+ for (int j = 0; j < 32; ++j) {+ uint8_t x = (data[i * 32 + j] & 0x0F);+ uint8_t y = (data[i * 32 + j] >> 4);+ if (j % 2 != 0) {+ x <<= 4;+ y <<= 4;+ }+ dst[i * 32 + j / 2] |= x;+ dst[i * 32 + 16 + j / 2] |= y; // Last 16 weights are in the higher bits+ }+ }+}++// Q4_K asymmetric: super-block = |f16 d|f16 dmin|12 bytes scales/mins|128 bytes ql|.+// 8 sub-blocks of 32 with 6-bit scale and 6-bit min each.+// Outputs: u32-packed u4 weights + f16 scales + zp (one per sub-block).+// Dequant is w = scale*q - min, scale = d*sc_raw, min = dmin*m_raw, expressed as scale*(q - zp).+// The zp element type selects the representation:+// - u8 -> INTEGER zp = round(min/scale): forces min to a multiple of scale (injects a small+// per-weight rounding error) but keeps the low-precision form the CPU plugin fuses+// into the MatMul -- this is what the original ggml-openvino backend does.+// - f16 -> FRACTIONAL zp = min/scale: faithful, used on the requant path (token_embd/output)+// where the dequant is re-quantized channel-wise rather than fed to the MatMul.+void fill_q4_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {+ const uint64_t bytes_per_block = kQ4K_BLOCK_BYTES;+ const uint64_t n_super_block = tensor.bsize / bytes_per_block;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<uint8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);+ auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;++ ov::parallel_for(n_super_block, [&](size_t i) {+ const uint8_t* block_data = data + i * bytes_per_block;+ const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data)));+ const float dmin = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 1)));+ const uint8_t* qs1 = block_data + 4;++ // 8 sub-blocks: 6-bit scale and 6-bit min packed in 12 bytes.+ uint8_t sc_raw[8], m_raw[8];+ for (int j = 0; j < 4; ++j) {+ sc_raw[j] = qs1[j] & 0x3F;+ m_raw[j] = qs1[j + 4] & 0x3F;+ sc_raw[j + 4] = (qs1[j + 8] & 0x0F) | ((qs1[j] >> 6) << 4);+ m_raw[j + 4] = (qs1[j + 8] >> 4) | ((qs1[j + 4] >> 6) << 4);+ }++ for (int j = 0; j < 8; ++j) {+ const float sc = d * sc_raw[j];+ const float mn = dmin * m_raw[j];+ scales[i * 8 + j] = ov::float16(sc);+ const float zpval = (sc != 0.f) ? (mn / sc) : 0.f;+ if (int_zp)+ zp_u8[i * 8 + j] = quantize_zp_u8(zpval);+ else+ zp_f16[i * 8 + j] = ov::float16(zpval);+ }+ unpack_256_4(block_data + 16, weights + i * 128);+ });+}++// 6-bit packed sub-scale/min extraction for K-quants (Q4_K/Q5_K 12-byte scale block).+static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t* m) {+ if (j < 4) {+ *d = q[j] & 63;+ *m = q[j + 4] & 63;+ } else {+ *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);+ *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);+ }+}++// ---------------------------------------------------------------------------------------------+// Bit-exact per-row K-quant dequant used ONLY as the source for the Q8_0_C requant of the+// token_embd/output/Q6_K/Q5_K tensors (see requantize_q8_0_channelwise_faithful). These are verbatim+// ports of ggml's dequantize_row_q{4,5,6}_K: they compute w = (d*sc)*q - (dmin*m) with the products+// kept in f32 (d/dmin are the f16 super-block scales widened to f32), matching what the upstream+// backend feeds into its Q8_0_C requant. This is NOT the general dequant path -- the compressed+// matmul weights still go through fill_*/make_int4 (f16 scales, integer zp) unchanged. Each function+// fills ONE row (`cols` floats) so the caller never materializes the whole f32 weight.+static void dequant_row_q4_k_f32(const uint8_t* row, size_t cols, float* y) {+ const uint64_t bpb = kQ4K_BLOCK_BYTES;+ for (size_t b = 0; b < cols / 256; ++b, y += 256) {+ const uint8_t* blk = row + b * bpb;+ const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk)));+ const float dmin = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk + 1)));+ const uint8_t* sc = blk + 4;+ const uint8_t* q = blk + 16;+ int is = 0;+ float* yy = y;+ for (int j = 0; j < 256; j += 64) {+ uint8_t s1, m1, s2, m2;+ get_scale_min_k4(is + 0, sc, &s1, &m1);+ get_scale_min_k4(is + 1, sc, &s2, &m2);+ const float d1 = d * s1, mn1 = dmin * m1, d2 = d * s2, mn2 = dmin * m2;+ for (int l = 0; l < 32; ++l) {+ yy[l] = d1 * (q[l] & 0xF) - mn1;+ }+ for (int l = 0; l < 32; ++l) {+ yy[32 + l] = d2 * (q[l] >> 4) - mn2;+ }+ q += 32;+ is += 2;+ yy += 64;+ }+ }+}++static void dequant_row_q5_k_f32(const uint8_t* row, size_t cols, float* y) {+ const uint64_t bpb = kQ5K_BLOCK_BYTES;+ for (size_t b = 0; b < cols / 256; ++b, y += 256) {+ const uint8_t* blk = row + b * bpb;+ const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk)));+ const float dmin = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk + 1)));+ const uint8_t* sc = blk + 4;+ const uint8_t* qh = blk + 16;+ const uint8_t* ql = blk + 48;+ int is = 0;+ uint8_t u1 = 1, u2 = 2;+ float* yy = y;+ for (int j = 0; j < 256; j += 64) {+ uint8_t s1, m1, s2, m2;+ get_scale_min_k4(is + 0, sc, &s1, &m1);+ get_scale_min_k4(is + 1, sc, &s2, &m2);+ const float d1 = d * s1, mn1 = dmin * m1, d2 = d * s2, mn2 = dmin * m2;+ for (int l = 0; l < 32; ++l) {+ yy[l] = d1 * static_cast<float>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0)) - mn1;+ }+ for (int l = 0; l < 32; ++l) {+ yy[32 + l] = d2 * static_cast<float>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - mn2;+ }+ ql += 32;+ is += 2;+ u1 <<= 2;+ u2 <<= 2;+ yy += 64;+ }+ }+}++static void dequant_row_q6_k_f32(const uint8_t* row, size_t cols, float* y) {+ const uint64_t bpb = kQ6K_BLOCK_BYTES; // ql(128) + qh(64) + scales(16) + d(2)+ for (size_t b = 0; b < cols / 256; ++b, y += 256) {+ const uint8_t* blk = row + b * bpb;+ const uint8_t* ql = blk;+ const uint8_t* qh = blk + 128;+ const int8_t* sc = reinterpret_cast<const int8_t*>(blk + 192);+ const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)(blk + 208))));+ float* yy = y;+ for (int n = 0; n < 256; n += 128) {+ for (int l = 0; l < 32; ++l) {+ const int is = l / 16;+ const int8_t q1 = (int8_t)((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32;+ const int8_t q2 = (int8_t)((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32;+ const int8_t q3 = (int8_t)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;+ const int8_t q4 = (int8_t)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;+ yy[l + 0] = d * sc[is + 0] * q1;+ yy[l + 32] = d * sc[is + 2] * q2;+ yy[l + 64] = d * sc[is + 4] * q3;+ yy[l + 96] = d * sc[is + 6] * q4;+ }+ yy += 128;+ ql += 64;+ qh += 32;+ sc += 8;+ }+ }+}++// Fused faithful dequant + channel-wise Q8_0_C requant, streaming one row at a time so the full f32+// weight is never materialized (holds only `cols` floats). Fills i8 weights [rows,cols] + f16 scales+// [rows,1], matching the upstream Q8_0_C path (amax/127 per row, roundf). qtype selects the exact+// ggml row dequant. Returns false if qtype is not a supported requant source.+bool requantize_q8_0_channelwise_faithful(const gguf_tensor& tensor,+ size_t rows,+ size_t cols,+ gguf_tensor_type qtype,+ int8_t* out_weights,+ ov::float16* out_scales) {+ void (*dq)(const uint8_t*, size_t, float*) = nullptr;+ uint64_t bytes_per_row = 0;+ switch (qtype) {+ case GGUF_TYPE_Q4_K: dq = dequant_row_q4_k_f32; bytes_per_row = (cols / 256) * kQ4K_BLOCK_BYTES; break;+ case GGUF_TYPE_Q5_K: dq = dequant_row_q5_k_f32; bytes_per_row = (cols / 256) * kQ5K_BLOCK_BYTES; break;+ case GGUF_TYPE_Q6_K: dq = dequant_row_q6_k_f32; bytes_per_row = (cols / 256) * kQ6K_BLOCK_BYTES; break;+ default: return false;+ }+ const uint8_t* data = static_cast<const uint8_t*>(tensor.weights_data);+ ov::parallel_for(rows, [&](size_t r) {+ // Per-thread scratch reused across rows (dq() overwrites all cols); avoids per-row malloc.+ thread_local std::vector<float> rowf;+ rowf.resize(cols);+ dq(data + r * bytes_per_row, cols, rowf.data());+ float amax = 0.0f;+ for (size_t c = 0; c < cols; ++c) {+ amax = std::max(amax, std::fabs(rowf[c]));+ }+ const float d = amax / 127.0f;+ const float id = d ? 1.0f / d : 0.0f;+ out_scales[r] = ov::float16(d);+ for (size_t c = 0; c < cols; ++c) {+ out_weights[r * cols + c] = static_cast<int8_t>(std::lround(rowf[c] * id));+ }+ });+ return true;+}++// Test-only thin wrappers exposing the file-static per-row dequant to the unit tests.+void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y) { dequant_row_q4_k_f32(row, cols, y); }+void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y) { dequant_row_q5_k_f32(row, cols, y); }+void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y) { dequant_row_q6_k_f32(row, cols, y); }++// Q5_K asymmetric: super-block = 2(d) + 2(dmin) + 12(scales) + 32(qh) + 128(ql).+// 8 sub-blocks of 32 with 6-bit scale and 6-bit min. Output: i8 weights + f16 scales + zp.+// Like Q4_K, dequant is w = scale*q - dmin*m; zp = dmin*m/scale. The zp element type selects+// integer (u8, fuses) vs fractional (f16, faithful) -- see fill_q4_k.+void fill_q5_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {+ const uint64_t bytes_per_block = kQ5K_BLOCK_BYTES;+ const uint64_t n_super_block = tensor.bsize / bytes_per_block;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);+ auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;+ const auto store_zp = [&](size_t idx, float scale, float mn) {+ const float zpval = (scale != 0.f) ? (mn / scale) : 0.f;+ if (int_zp)+ zp_u8[idx] = quantize_zp_u8(zpval);+ else+ zp_f16[idx] = ov::float16(zpval);+ };++ ov::parallel_for(n_super_block, [&](size_t i) {+ const uint8_t* block_data = data + i * bytes_per_block;+ const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data)));+ const float dmin = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 1)));+ const uint8_t* scales_data = block_data + 4;+ const uint8_t* qh = block_data + 16; // 32 bytes high bits+ const uint8_t* ql = block_data + 48; // 128 bytes low bits++ int is = 0;+ uint8_t u1 = 1, u2 = 2;+ for (int j = 0; j < 256; j += 64) {+ uint8_t sc, m;+ get_scale_min_k4(is + 0, scales_data, &sc, &m);+ const float d1 = d * sc, m1 = dmin * m;+ get_scale_min_k4(is + 1, scales_data, &sc, &m);+ const float d2 = d * sc, m2 = dmin * m;+ scales[i * 8 + is] = ov::float16(d1);+ scales[i * 8 + is + 1] = ov::float16(d2);+ store_zp(i * 8 + is, d1, m1);+ store_zp(i * 8 + is + 1, d2, m2);+ for (int l = 0; l < 32; ++l) {+ weights[i * 256 + j + l] = static_cast<int8_t>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0));+ weights[i * 256 + j + l + 32] = static_cast<int8_t>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0));+ }+ ql += 32;+ is += 2;+ u1 <<= 2;+ u2 <<= 2;+ }+ });+}++// Q5_1 asymmetric: block = |f16 d|f16 m|32-bit qh|16 bytes ql (32x4bit low)|.+// weight = lo|(hi<<4) in [0..31]; dequant = d*w + m = d*(w - zp), zp = -m/d.+// Output: i8 weights [0..31] (raw, not centered) + f16 scales + zp (u8 integer or f16+// fractional per element type -- see fill_q4_k).+void fill_q5_1(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {+ const uint64_t weights_per_block = 32;+ const uint64_t bytes_per_block = 2 + 2 + 4 + 16; // d, m, qh, ql+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);+ auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ const uint8_t* block = data + i * bytes_per_block;+ const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)block));+ const float m = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 2)));+ scales[i] = ov::float16(d);+ const float zpval = (d != 0.f) ? (-m / d) : 0.f;+ if (int_zp)+ zp_u8[i] = quantize_zp_u8(zpval);+ else+ zp_f16[i] = ov::float16(zpval);+ uint32_t qh;+ std::memcpy(&qh, block + 4, sizeof(qh));+ const uint8_t* ql = block + 8;+ for (uint64_t j = 0; j < weights_per_block; ++j) {+ const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);+ const uint8_t hi = (qh >> j) & 1;+ weights[i * weights_per_block + j] = static_cast<int8_t>(lo | (hi << 4));+ }+ });+}++// Q3_K symmetric: super-block = 32(hmask) + 64(qs) + 12(scales 6-bit) + 2(f16 d) = 110 bytes.+// 16 sub-blocks of 16; 3-bit values (2 low bits from qs, 1 inverted high bit from hmask) centered+// to [-4..3]. Mirrors ggml dequantize_row_q3_K: kmask1/kmask2 scale interleave + strided qs order.+// Output: i4 weights (2 per byte, low nibble first) + f16 scales (d * (scale6 - 32)). No zp.+void fill_q3_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t bytes_per_block = 32 + 64 + 12 + 2; // 110+ const uint64_t n_super_block = tensor.bsize / bytes_per_block;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<uint8_t*>(weights_arr.data()); // packed i4 nibbles+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ ov::parallel_for(n_super_block, [&](size_t i) {+ const uint8_t* block = data + i * bytes_per_block;+ const uint8_t* hmask = block; // 32 bytes: 1 high bit per weight+ const uint8_t* qs = block + 32; // 64 bytes: 2 low bits per weight+ const uint8_t* sc = block + 32 + 64; // 12 bytes: 16 x 6-bit sub-scales+ const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 32 + 64 + 12)));++ // 16 signed 6-bit sub-scales, interleaved as in ggml dequantize_row_q3_K.+ constexpr uint32_t kmask1 = 0x03030303, kmask2 = 0x0f0f0f0f;+ uint32_t aux[4];+ std::memcpy(aux, sc, 12);+ const uint32_t tmp = aux[2];+ aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);+ aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);+ aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);+ aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);+ const int8_t* isc = reinterpret_cast<const int8_t*>(aux);+ for (int j = 0; j < 16; ++j) {+ scales[i * 16 + j] = ov::float16(d * static_cast<float>(isc[j] - 32));+ }++ // Unpack in ggml element order; the hmask bit is inverted (set means high bit 0).+ uint8_t* wdst = weights + i * 128;+ std::fill_n(wdst, 128, 0);+ size_t out = 0;+ const auto put = [&](int8_t c) {+ wdst[out / 2] |= static_cast<uint8_t>((static_cast<uint8_t>(c) & 0xF) << ((out % 2) * 4));+ ++out;+ };+ uint8_t m = 1;+ for (int n = 0; n < 2; ++n) {+ const uint8_t* q = qs + n * 32;+ for (int shift = 0; shift < 8; shift += 2) {+ for (int l = 0; l < 16; ++l)+ put(static_cast<int8_t>(((q[l] >> shift) & 3) - ((hmask[l] & m) ? 0 : 4)));+ for (int l = 0; l < 16; ++l)+ put(static_cast<int8_t>(((q[l + 16] >> shift) & 3) - ((hmask[l + 16] & m) ? 0 : 4)));+ m <<= 1;+ }+ }+ });+}++// Q2_K asymmetric: super-block = 16(scales 4+4 bit) + 64(qs) + 2(f16 d) + 2(f16 dmin) = 84 bytes,+// matching ggml block_q2_K (scales first, then qs). 16 sub-blocks of 16; 2-bit values [0..3],+// scales[j] lower nibble = sub-scale, upper nibble = sub-min. qs is not in element order, so unpack+// per element into element-order u2 (4 per byte, LSB-first) like ggml dequantize_row_q2_K.+// Output: u2 weights + f16 scales (d * sub_scale) + zp = ml/dl per sub-block (see fill_q4_k).+void fill_q2_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {+ const uint64_t bytes_per_block = 16 + 64 + 2 + 2; // 84+ const uint64_t n_super_block = tensor.bsize / bytes_per_block;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<uint8_t*>(weights_arr.data()); // packed u2 (4 per byte, LSB-first)+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);+ auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;+ ov::parallel_for(n_super_block, [&](size_t i) {+ const uint8_t* block = data + i * bytes_per_block;+ const uint8_t* sc = block; // 16 bytes: per-sub-block scale+min nibbles+ const uint8_t* qs = block + 16; // 64 bytes: 4 weights per byte, 2 bits each+ const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 80)));+ const float dmin = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 82)));+ for (int j = 0; j < 16; ++j) {+ const float dl = d * static_cast<float>(sc[j] & 0xF);+ const float ml = dmin * static_cast<float>(sc[j] >> 4);+ scales[i * 16 + j] = ov::float16(dl);+ const float zpval = (dl != 0.f) ? (ml / dl) : 0.f;+ if (int_zp)+ zp_u8[i * 16 + j] = quantize_zp_u8(zpval);+ else+ zp_f16[i * 16 + j] = ov::float16(zpval);+ }+ // Unpack in ggml element order (see dequantize_row_q2_K).+ uint8_t* wdst = weights + i * 64;+ std::fill_n(wdst, 64, 0);+ size_t out = 0;+ const auto put = [&](uint8_t q2) {+ wdst[out / 4] |= static_cast<uint8_t>((q2 & 3) << ((out % 4) * 2));+ ++out;+ };+ for (int n = 0; n < 2; ++n) {+ const uint8_t* q = qs + n * 32;+ for (int shift = 0; shift < 8; shift += 2) {+ for (int l = 0; l < 16; ++l)+ put((q[l] >> shift) & 3);+ for (int l = 0; l < 16; ++l)+ put((q[l + 16] >> shift) & 3);+ }+ }+ });+}++// Q6_K symmetric: super-block = 128(ql) + 64(qh) + 16(scales i8) + 2(f16 d).+// 16 sub-blocks of 16 with i8 scale each. Values in [0..63]; center = 32 → i8 [-32..31].+// Output: i8 weights (value - 32) + f16 scales. No zero-point.+void fill_q6_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t bytes_per_block = kQ6K_BLOCK_BYTES;+ const uint64_t n_super_block = tensor.bsize / bytes_per_block;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();+ // Each super-block writes a disjoint 256-element region, so parallelize like the other fill_*+ // functions (Q6_K is used for the largest tensors -- output/embed -- so the serial loop left+ // most cores idle on the biggest weight in the model).+ ov::parallel_for(n_super_block, [&](size_t i) {+ const uint8_t* block_data = data + i * bytes_per_block;+ const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t*)block_data + 104))); // (128+64+16)/2+ for (size_t j = 0; j < 16; j++) {+ scales[j + i * 16] = ov::float16(d * static_cast<float>(*((int8_t*)(block_data + 128 + 64 + j))));+ }+ const uint8_t* ql = block_data;+ const uint8_t* qh = block_data + 128;+ for (int64_t j = 0; j < 32; ++j) {+ weights[i * 256 + j] = static_cast<int8_t>(((ql[j] & 0xF) | (((qh[j] >> 0) & 3) << 4)) - 32);+ weights[i * 256 + j + 32] = static_cast<int8_t>(((ql[32 + j] & 0xF) | (((qh[j] >> 2) & 3) << 4)) - 32);+ weights[i * 256 + j + 64] = static_cast<int8_t>(((ql[j] >> 4) | (((qh[j] >> 4) & 3) << 4)) - 32);+ weights[i * 256 + j + 96] = static_cast<int8_t>(((ql[32 + j] >> 4) | (((qh[j] >> 6) & 3) << 4)) - 32);+ weights[i * 256 + j + 128] =+ static_cast<int8_t>(((ql[64 + j] & 0xF) | (((qh[32 + j] >> 0) & 3) << 4)) - 32);+ weights[i * 256 + j + 160] =+ static_cast<int8_t>(((ql[96 + j] & 0xF) | (((qh[32 + j] >> 2) & 3) << 4)) - 32);+ weights[i * 256 + j + 192] = static_cast<int8_t>(((ql[64 + j] >> 4) | (((qh[32 + j] >> 4) & 3) << 4)) - 32);+ weights[i * 256 + j + 224] = static_cast<int8_t>(((ql[96 + j] >> 4) | (((qh[32 + j] >> 6) & 3) << 4)) - 32);+ }+ });+}++// MXFP4 (gpt-oss): per-32 block = 1-byte E8M0 scale + 16 bytes of 4-bit E2M1 indices.+// On disk, within a block the low nibble of qs[j] is element j and the high nibble is+// element j+16. We deinterleave into NATURAL element order and store as two compressed+// OpenVINO Constants the CPU plugin handles natively: a f4e2m1 weight tensor [rows, cols]+// and an f8e8m0 scale tensor [rows, cols/32]. (No host dequant.)+//+// Value equivalence: gguf MXFP4 value = kvalues_mxfp4[idx] * 2^(e-128); OpenVINO's+// f4e2m1 LUT equals kvalues_mxfp4/2 and f8e8m0->f32 = 2^(e-127), so+// f4e2m1[idx] * f8e8m0(e) = (kvalues/2) * 2^(e-127) = kvalues * 2^(e-128) -- exact.+void gguf_fill_mxfp4(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {+ const uint64_t bytes_per_block = 17;+ const uint64_t qk = 32;+ // GGUF stores dims fastest-first: dim[0] is the innermost (cols); the remaining dims fold+ // into rows. (Equivalent to the OV-order shape [.., cols] the caller sets.)+ const uint64_t cols = tensor.dim[0];+ uint64_t rows = 1;+ for (uint32_t i = 1; i < tensor.ndim; ++i) {+ rows *= tensor.dim[i];+ }+ const uint64_t groups = cols / qk;++ auto* wdst = static_cast<uint8_t*>(weights.data());+ auto* sdst = static_cast<uint8_t*>(scales.data());+ const auto* data = static_cast<const uint8_t*>(tensor.weights_data);++ ov::parallel_for(rows, [&](size_t r) {+ for (uint64_t g = 0; g < groups; ++g) {+ const uint8_t* block = data + (r * groups + g) * bytes_per_block;+ sdst[r * groups + g] = block[0];+ const uint8_t* qs = block + 1;+ const uint64_t base = r * cols + g * qk;+ for (uint64_t j = 0; j < qk / 2; ++j) {+ const uint8_t lo = qs[j] & 0x0F;+ const uint8_t hi = qs[j] >> 4;+ auto put = [&](uint64_t elem, uint8_t nib) {+ uint64_t idx = base + elem;+ uint8_t& byte = wdst[idx / 2];+ if (idx & 1) {+ byte = (byte & 0x0F) | (nib << 4);+ } else {+ byte = (byte & 0xF0) | nib;+ }+ };+ put(j, lo);+ put(j + qk / 2, hi);+ }+ }+ });+}++// Q4_0 symmetric: same block layout as Q4_0 but XORs each packed byte with 0x88 to+// flip the MSB of every nibble, converting u4 [0..15] to i4 [-8..7] in-place. No bias+// tensor is produced (zp is exactly -8 * scale = a fixed shift, not per-element).+void gguf_fill_q4_0(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t bytes_per_block = 18;+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<uint8_t*>(weights_arr.data());+ auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();++ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ scales[i] = ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block)));+ unpack_32_4(data + i * bytes_per_block + 2, weights + i * 16);+ for (int b = 0; b < 16; ++b)+ weights[i * 16 + b] ^= 0x88; // u4→i4: flip MSB of both nibbles per byte+ });+}++// Q8_K symmetric: block = |f32 d|i8 qs[256]|i16 bsums[16]| (292 bytes/block).+// bsums are partial sums for dot-product acceleration; unused in dequant-then-multiply.+void fill_q8_k(const gguf_tensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr) {+ const uint64_t weights_per_block = 256;+ const uint64_t bytes_per_block = 292; // 4(f32 d) + 256(i8) + 32(i16 bsums)+ auto data = static_cast<const uint8_t*>(tensor.weights_data);+ auto weights = static_cast<int8_t*>(weights_arr.data());+ auto scales = static_cast<float*>(scales_arr.data());+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {+ const uint8_t* block = data + i * bytes_per_block;+ float d;+ std::memcpy(&d, block, sizeof(d)); // f32 scale+ scales[i] = d;+ std::memcpy(weights + i * weights_per_block, block + 4, weights_per_block); // i8 qs+ // bsums at block+260 are ignored+ });+}++// Symmetric types (Q8_0, Q5_0, Q6_K, Q3_K): fill weights + scales (f16), no zero-point.+// Q8_K uses f32 scales and is handled by a separate overload dispatched on tensor.type.+void gguf_fill_sym(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {+ if (tensor.type == GGUF_TYPE_Q8_0) {+ fill_q8_0(tensor, weights, scales);+ } else if (tensor.type == GGUF_TYPE_Q5_0) {+ fill_q5_0(tensor, weights, scales);+ } else if (tensor.type == GGUF_TYPE_Q6_K) {+ fill_q6_k(tensor, weights, scales);+ } else if (tensor.type == GGUF_TYPE_Q3_K) {+ fill_q3_k(tensor, weights, scales);+ } else if (tensor.type == GGUF_TYPE_Q8_K) {+ fill_q8_k(tensor, weights, scales);+ } else {+ OPENVINO_ASSERT(false, "Unsupported tensor type in 'gguf_fill_sym'");+ }+}++// Asymmetric types (Q4_1, Q4_K, Q5_K, Q5_1, Q2_K): fill weights + scales + integer zero-points.+void gguf_fill_asym(const gguf_tensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp) {+ if (tensor.type == GGUF_TYPE_Q4_1) {+ fill_q4_1(tensor, weights, scales, zp);+ } else if (tensor.type == GGUF_TYPE_Q4_K) {+ fill_q4_k(tensor, weights, scales, zp);+ } else if (tensor.type == GGUF_TYPE_Q5_K) {+ fill_q5_k(tensor, weights, scales, zp);+ } else if (tensor.type == GGUF_TYPE_Q5_1) {+ fill_q5_1(tensor, weights, scales, zp);+ } else if (tensor.type == GGUF_TYPE_Q2_K) {+ fill_q2_k(tensor, weights, scales, zp);+ } else {+ OPENVINO_ASSERT(false, "Unsupported tensor type in 'gguf_fill_asym'");+ }+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppnew file mode 100644index 00000000000..613aa7c8a57--- /dev/null+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -0,0 +1,642 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Weight node construction for the native GGUF path. Quantized weights become a+// low-bitness compressed decompression subgraph (u4 for 4-bit, u8 for 8-bit; OpenVINO+// supports every GGUF bitness used here except 3-bit). Adapted from the genai gguf_utils+// make_int4/int8_weights helpers, working from the parser's compressed tensors+// (.weight u32-packed + .scales f16 + .biases f16).++#include "weights.hpp"++#include <cctype>+#include <cmath>+#include <cstdlib>+#include <cstring>+#include <vector>++#include "openvino/core/except.hpp"+#include "openvino/core/type/float16.hpp"+#include "openvino/decompositions/low_precision_dequantize.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/pass/constant_folding.hpp"+#include "openvino/pass/manager.hpp"++namespace ov {+namespace frontend {+namespace gguf {++namespace {++const ov::Tensor& get(const std::unordered_map<std::string, ov::Tensor>& weights, const std::string& key) {+ auto it = weights.find(key);+ OPENVINO_ASSERT(it != weights.end(), "[ggml] missing weight tensor: ", key);+ return it->second;+}+++// Shared shape helpers for grouped weight layouts. See make_int8 comment for why we keep+// all leading dims separate rather than flattening: the trailing Reshape must be+// (orig_rank+1)D -> orig_rank for the CompressedWeightsBlock matcher to fire.+ov::Shape grouped_weight_shape(const ov::Shape& orig, size_t num_groups, size_t group_size) {+ ov::Shape s(orig.begin(), orig.end() - 1);+ s.push_back(num_groups);+ s.push_back(group_size);+ return s;+}+ov::Shape per_group_shape(const ov::Shape& orig, size_t num_groups) {+ ov::Shape s(orig.begin(), orig.end() - 1);+ s.push_back(num_groups);+ s.push_back(1);+ return s;+}++// Build a low-bit weight Constant wrapping `weight`'s bytes (no copy: the ov::Tensor is held+// alive by the Constant's shared buffer).+std::shared_ptr<ov::op::v0::Constant> make_compressed_weight_constant(ov::element::Type et,+ const ov::Shape& shape,+ const ov::Tensor& weight) {+ // Shared-buffer ctor: the Constant wraps the bytes without copying and keeps the Tensor alive.+ return std::make_shared<ov::op::v0::Constant>(et,+ shape,+ static_cast<const void*>(weight.data()),+ std::make_shared<ov::Tensor>(weight));+}++// Q4_0 symmetric: i4 weights (XOR-converted from u4) + f16 scale, no zero-point.+// Emits: Multiply(Convert(i4_const, f16), scale) [-> Reshape] via low_precision_dequantize.+std::shared_ptr<ov::Node> make_q4_0(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // u32-packed i4 nibbles+ ov::Tensor scales = get(weights, name + ".scales");++ ov::Shape orig_shape = weight.get_shape();+ orig_shape.back() *= sizeof(uint32_t) / sizeof(uint8_t) * 2; // u32 packs 8 i4+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::i4, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ {},+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// Symmetric 8-bit (Q8_0, Q5_0, Q6_K): i8 weights (pre-centered) + per-group f16 scale.+// No zero-point. Emits: Multiply(Convert(i8_const, f16), scale) [-> Reshape].+std::shared_ptr<ov::Node> make_sym_int8(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // i8 byte per element+ ov::Tensor scales = get(weights, name + ".scales");++ const ov::Shape& orig_shape = weight.get_shape();+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::i8, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ {},+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// 4-bit asymmetric (Q4_1/Q4_K): u4 weights + per-group f16 scale + u8 integer zero-points.+// Emits: Multiply(Subtract(Convert(u4_const, f16), zp_u8), scale) [-> Reshape].+std::shared_ptr<ov::Node> make_int4(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // u32-packed u4+ ov::Tensor scales = get(weights, name + ".scales");+ ov::Tensor zp_t = get(weights, name + ".zp"); // u8 integer zero-points++ ov::Shape orig_shape = weight.get_shape();+ orig_shape.back() *= sizeof(uint32_t) / sizeof(uint8_t) * 2; // u32 packs 8 u4+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);+ zp_t.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::u4, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ zp_node->output(0),+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// Symmetric 4-bit (Q3_K): i4 weights (centered [-4..3]) + per-group f16 scale. No zero-point.+// Emits: Multiply(Convert(i4_const, f16), scale) [-> Reshape].+std::shared_ptr<ov::Node> make_sym_int4(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // i4 packed, 2 per byte+ ov::Tensor scales = get(weights, name + ".scales");++ const ov::Shape& orig_shape = weight.get_shape();+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::i4, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ {},+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// Asymmetric 2-bit (Q2_K): u2 weights (raw [0..3]) + per-group f16 scale + u8 zp.+// Emits: Multiply(Subtract(Convert(u2_const, f16), zp_u8), scale) [-> Reshape].+std::shared_ptr<ov::Node> make_int2(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // u2 packed, 4 per byte+ ov::Tensor scales = get(weights, name + ".scales");+ ov::Tensor zp_t = get(weights, name + ".zp"); // u8 integer zero-points++ const ov::Shape& orig_shape = weight.get_shape();+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);+ zp_t.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::u2, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ zp_node->output(0),+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// Asymmetric 8-bit (Q5_K): i8 weights (raw 5-bit value, not centered) + f16 scales + u8 zp.+// Emits: Multiply(Subtract(Convert(i8_const, f16), zp_u8), scale) [-> Reshape].+std::shared_ptr<ov::Node> make_asym_int8(const std::string& name,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, name + ".weight"); // i8 byte per element+ ov::Tensor scales = get(weights, name + ".scales");+ ov::Tensor zp_t = get(weights, name + ".zp"); // u8 integer zero-points++ const ov::Shape& orig_shape = weight.get_shape();+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);+ auto scale_shape = per_group_shape(orig_shape, num_groups);+ scales.set_shape(scale_shape);+ zp_t.set_shape(scale_shape);++ auto weights_node =+ make_compressed_weight_constant(ov::element::i8, grouped_shape, weight);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);+ auto final_shape_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);++ auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),+ scales_node->output(0),+ zp_node->output(0),+ final_shape_node->output(0));+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+}++// MXFP4 (gpt-oss): native compressed weights = f4e2m1 weight * f8e8m0 per-32 scale, both+// kept compressed so the CPU plugin decompresses on the fly (no host f16 expansion). The+// parser already deinterleaved into natural order; here we just build the subgraph.+std::shared_ptr<ov::Node> make_mxfp4(const std::string& base,+ const std::unordered_map<std::string, ov::Tensor>& weights) {+ ov::Tensor weight = get(weights, base + ".weight"); // f4e2m1 [.., cols]+ ov::Tensor scales = get(weights, base + ".scales"); // f8e8m0 [.., groups]++ ov::Shape orig_shape = weight.get_shape();+ size_t rows = 1;+ for (size_t i = 0; i + 1 < orig_shape.size(); ++i) {+ rows *= orig_shape[i];+ }+ const size_t num_groups = scales.get_shape().back();+ const size_t group_size = orig_shape.back() / num_groups;++ auto w_node = std::make_shared<ov::op::v0::Constant>(weight);+ auto w_grp = std::make_shared<ov::op::v1::Reshape>(+ w_node,+ ov::op::v0::Constant::create(ov::element::i64,+ {3},+ std::vector<int64_t>{(int64_t)rows, (int64_t)num_groups, (int64_t)group_size}),+ false);+ auto w_f16 = std::make_shared<ov::op::v0::Convert>(w_grp, ov::element::f16);++ scales.set_shape(ov::Shape{rows, num_groups, 1});+ auto s_node = std::make_shared<ov::op::v0::Constant>(scales);+ auto s_f16 = std::make_shared<ov::op::v0::Convert>(s_node, ov::element::f16);++ auto scaled = std::make_shared<ov::op::v1::Multiply>(w_f16, s_f16, ov::op::AutoBroadcastType::NUMPY);+ auto final_shape =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);+ auto reshaped = std::make_shared<ov::op::v1::Reshape>(scaled, final_shape, false);+ return std::make_shared<ov::op::v0::Convert>(reshaped, ov::element::f32);+}++// Channel-wise requantization to Q8_0_C, matching the llama.cpp ggml-openvino backend's+// CPU/GPU weight pipeline (ggml_openvino_get_requant_type -> Q8_0_C for embed/output/Q6_K/+// Q5_K). `x` is the row-major f32 weight (rows*cols); one f16 scale per row (channel-wise);+// signed int8 weights. ggml-free (the f32 input is produced by the frontend's own faithful+// dequant, which the unit tests prove matches ggml to_float).+// Build the Q8_0_C compressed-weights OV subgraph from pre-filled i8 weights [rows,cols] ++// f16 scales [rows,1]. Shared by the (legacy) f32-vector requant and the fused faithful requant.+static std::shared_ptr<ov::Node> build_q8_0_c_node(ov::Tensor weights, ov::Tensor scales, size_t rows, size_t cols) {+ // Build the channel-wise compressed-weights subgraph exactly as the llama.cpp+ // ggml-openvino backend does for Q8_0_C: a 2D i8 Constant (rows x cols) + 2D f16 scale+ // (rows x 1), Convert(i8)->Multiply(scale), with NO Reshape and NO low_precision_dequantize.+ // The 2D form (group == cols, a single group per row) is what the CPU/GPU plugin fuses+ // into an int8 MatMul; routing it through the grouped low_precision_dequantize path+ // (3D weight + Reshape) defeats that fusion and roughly halves prefill throughput.+ auto weights_node =+ std::make_shared<ov::op::v0::Constant>(ov::element::i8,+ ov::Shape{rows, cols},+ static_cast<const void*>(weights.data()),+ std::shared_ptr<void>(new ov::Tensor(weights), [](ov::Tensor* p) {+ delete p;+ }));+ auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);+ auto scales_node = std::make_shared<ov::op::v0::Constant>(scales); // {rows, 1}+ auto scaled =+ std::make_shared<ov::op::v1::Multiply>(weights_f16, scales_node, ov::op::AutoBroadcastType::NUMPY);+ return std::make_shared<ov::op::v0::Convert>(scaled, ov::element::f32);+}++// Legacy path: requant from an already-materialized f32 weight vector (used for token_embd/output+// when the type has no faithful per-row dequant, and for any non-K requant source).+std::shared_ptr<ov::Node> requantize_q8_0_channelwise(const std::vector<float>& x, size_t rows, size_t cols) {+ ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, 1});+ auto* w = weights.data<int8_t>();+ auto* s = scales.data<ov::float16>();+ for (size_t r = 0; r < rows; ++r) {+ float amax = 0.0f;+ for (size_t c = 0; c < cols; ++c) {+ amax = std::max(amax, std::fabs(x[r * cols + c]));+ }+ const float d = amax / 127.0f;+ const float id = d ? 1.0f / d : 0.0f;+ s[r] = ov::float16(d);+ for (size_t c = 0; c < cols; ++c) {+ w[r * cols + c] = static_cast<int8_t>(std::lround(x[r * cols + c] * id));+ }+ }+ return build_q8_0_c_node(weights, scales, rows, cols);+}++// Dequantize the gguf_fill_* output (i8, i4, u2, or u32-packed u4 weights + per-group f16 scale+// and optional f16 zero-point) to row-major f32: f32 = (w - zp) * scale, grouped along cols.+std::vector<float> dequant_extracted_to_f32(const std::unordered_map<std::string, ov::Tensor>& w,+ const std::string& base,+ size_t rows,+ size_t cols) {+ const ov::Tensor& weight = get(w, base + ".weight");+ const ov::Tensor& scales = get(w, base + ".scales");+ const size_t num_groups = scales.get_shape().back();+ const size_t group = cols / num_groups;+ const auto* s = scales.data<ov::float16>();++ auto zp_it = w.find(base + ".zp");+ const bool has_zp = zp_it != w.end();+ const ov::float16* z = has_zp ? zp_it->second.data<ov::float16>() : nullptr;++ const auto et = weight.get_element_type();+ std::vector<float> out(rows * cols);+ const auto emit = [&](size_t r, size_t c, float qval) {+ size_t g = r * num_groups + c / group;+ float zpf = z ? static_cast<float>(z[g]) : 0.0f;+ out[r * cols + c] = (qval - zpf) * static_cast<float>(s[g]);+ };+ if (et == ov::element::i8) {+ const auto* q = weight.data<int8_t>();+ for (size_t r = 0; r < rows; ++r)+ for (size_t c = 0; c < cols; ++c)+ emit(r, c, static_cast<float>(q[r * cols + c]));+ } else if (et == ov::element::u2) {+ // Q2_K: u2 weights, 4 per byte LSB-first, raw [0..3] with a zero-point.+ const auto* bytes = static_cast<const uint8_t*>(weight.data());+ const size_t per_row_bytes = cols / 4;+ for (size_t r = 0; r < rows; ++r)+ for (size_t c = 0; c < cols; ++c) {+ uint8_t v = (bytes[r * per_row_bytes + c / 4] >> ((c % 4) * 2)) & 0x3;+ emit(r, c, static_cast<float>(v));+ }+ } else {+ // u32-packed 4-bit, 8 nibbles per u32. With a zero-point (Q4_1/Q4_K) the nibbles are+ // unsigned u4; without one (Q4_0 XOR-encoded, Q3_K centered) they are signed i4.+ const bool signed_u4 = !has_zp;+ const auto* packed = static_cast<const uint32_t*>(weight.data());+ const size_t per_row_u32 = cols / 8;+ for (size_t r = 0; r < rows; ++r)+ for (size_t c = 0; c < cols; ++c) {+ uint32_t word = packed[r * per_row_u32 + c / 8];+ uint8_t nib = (word >> ((c % 8) * 4)) & 0xF;+ float qval = signed_u4 ? static_cast<float>(nib < 8 ? static_cast<int>(nib) : static_cast<int>(nib) - 16)+ : static_cast<float>(nib);+ emit(r, c, qval);+ }+ }+ return out;+}++// Decide whether a weight is requantized to Q8_0_C, mirroring llama.cpp's+// ggml_openvino_get_requant_type for the CPU/GPU (non-NPU) path.+bool needs_q8_0_c_requant(const std::string& name, gguf_tensor_type qtype) {+ // The env var does not change during a conversion; read it once.+ static const bool no_requant = std::getenv("GGUF_FE_NO_REQUANT") != nullptr;+ if (no_requant) {+ return false; // diagnostic: faithful dequant only+ }+ if (name.rfind("token_embd.weight", 0) == 0 || name.rfind("output.weight", 0) == 0) {+ return true;+ }+ return qtype == GGUF_TYPE_Q6_K || qtype == GGUF_TYPE_Q5_K;+}++} // namespace++std::shared_ptr<ov::Node> make_weight_node(const std::string& base,+ const std::unordered_map<std::string, ov::Tensor>& weights,+ const std::unordered_map<std::string, gguf_tensor_type>& qtypes) {+ gguf_tensor_type qtype = GGUF_TYPE_F16;+ if (auto it = qtypes.find(base + ".qtype"); it != qtypes.end()) {+ qtype = it->second;+ }++ std::shared_ptr<ov::Node> node;+ switch (qtype) {+ case GGUF_TYPE_MXFP4:+ node = make_mxfp4(base, weights);+ break;+ case GGUF_TYPE_Q4_0:+ node = make_q4_0(base, weights);+ break;+ case GGUF_TYPE_Q4_1:+ case GGUF_TYPE_Q4_K:+ node = make_int4(base, weights);+ break;+ case GGUF_TYPE_Q2_K:+ node = make_int2(base, weights);+ break;+ case GGUF_TYPE_Q5_K:+ case GGUF_TYPE_Q5_1:+ node = make_asym_int8(base, weights);+ break;+ case GGUF_TYPE_Q3_K:+ node = make_sym_int4(base, weights);+ break;+ case GGUF_TYPE_Q5_0:+ case GGUF_TYPE_Q8_0:+ case GGUF_TYPE_Q6_K:+ case GGUF_TYPE_Q8_K:+ node = make_sym_int8(base, weights);+ break;+ case GGUF_TYPE_F16:+ case GGUF_TYPE_F32:+ case GGUF_TYPE_BF16:+ default: {+ // Non-quantized weight: a plain Constant (converted to f32 for the translators).+ ov::Tensor w = get(weights, base + ".weight");+ auto cnst = std::make_shared<ov::op::v0::Constant>(w);+ node = (w.get_element_type() == ov::element::f32)+ ? std::static_pointer_cast<ov::Node>(cnst)+ : std::make_shared<ov::op::v0::Convert>(cnst, ov::element::f32);+ break;+ }+ }+ node->set_friendly_name(base + ".weight");+ return node;+}+++gguf_tensor_type gguf_type_from_name(const std::string& quant_type) {+ static const std::unordered_map<std::string, gguf_tensor_type> names = {{"F32", GGUF_TYPE_F32},+ {"F16", GGUF_TYPE_F16},+ {"BF16", GGUF_TYPE_BF16},+ {"Q4_0", GGUF_TYPE_Q4_0},+ {"Q4_1", GGUF_TYPE_Q4_1},+ {"Q5_0", GGUF_TYPE_Q5_0},+ {"Q5_1", GGUF_TYPE_Q5_1},+ {"Q8_0", GGUF_TYPE_Q8_0},+ {"Q2_K", GGUF_TYPE_Q2_K},+ {"Q3_K", GGUF_TYPE_Q3_K},+ {"Q4_K", GGUF_TYPE_Q4_K},+ {"Q5_K", GGUF_TYPE_Q5_K},+ {"Q6_K", GGUF_TYPE_Q6_K},+ {"Q8_K", GGUF_TYPE_Q8_K},+ {"MXFP4", GGUF_TYPE_MXFP4}};+ // Accept ggml's lowercase type names ("q4_0", "q6_K", "f16", ...) as well as the+ // canonical uppercase form by upper-casing the prefix before the "_K"/"_0" suffix.+ std::string key = quant_type;+ for (auto& ch : key) {+ ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));+ }+ auto it = names.find(key);+ OPENVINO_ASSERT(it != names.end(), "[ggml] unsupported weight quant type: ", quant_type);+ return it->second;+}++std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,+ const std::string& quant_type,+ const ov::Shape& logical_shape,+ const std::string& name) {+ OPENVINO_ASSERT(logical_shape.size() == 2,+ "[ggml] weight logical shape must be 2D [rows, cols], got rank ",+ logical_shape.size());+ const uint64_t rows = logical_shape[0];+ const uint64_t cols = logical_shape[1];+ const gguf_tensor_type qtype = gguf_type_from_name(quant_type);++ const std::string base = "weight";++ // Non-quantized weights: wrap the bytes directly as a Constant of the matching type.+ if (qtype == GGUF_TYPE_F32 || qtype == GGUF_TYPE_F16 || qtype == GGUF_TYPE_BF16) {+ ov::element::Type et = qtype == GGUF_TYPE_F32 ? ov::element::f32+ : qtype == GGUF_TYPE_F16 ? ov::element::f16+ : ov::element::bf16;+ ov::Tensor typed(et, logical_shape, data.data());+ std::unordered_map<std::string, ov::Tensor> w{{base + ".weight", typed}};+ std::unordered_map<std::string, gguf_tensor_type> q{{base + ".qtype", qtype}};+ return make_weight_node(base, w, q);+ }++ // Quantized weights: run the matching fill function to extract weights/scales/zp into+ // OpenVINO-native tensors, then build the decompression subgraph via make_weight_node.+ gguf_tensor tensor{};+ tensor.type = static_cast<uint32_t>(qtype);+ tensor.ndim = 2;+ tensor.dim[0] = cols; // GGUF stores dims fastest-first+ tensor.dim[1] = rows;+ tensor.num_weights = rows * cols;+ tensor.bsize = data.get_byte_size();+ tensor.weights_data = static_cast<const uint8_t*>(data.data());++ const auto sub_blocks_per_row = [&](uint64_t block) {+ return cols / block;+ };++ std::unordered_map<std::string, ov::Tensor> w;+ std::unordered_map<std::string, gguf_tensor_type> q{{base + ".qtype", qtype}};++ // Asymmetric zero-points. The CPU plugin only folds the dequant into the MatMul when the+ // zp is an INTEGER (u8) low-precision constant; a fractional f16 zp leaves a standalone+ // dequant MatMul (~2x slower prefill). Q4_K is the asymmetric type that appears as MatMul+ // weights in modern models (Q4_K_M = Q4_K + symmetric Q6_K), so it uses integer zp to match+ // the original ggml-openvino backend. The legacy Q4_1/Q5_1/Q2_K types keep a faithful f16 zp:+ // they are not perf-critical here, and their zp = -min/scale can fall outside u8 range. The+ // requant path (token_embd/output) also keeps f16 -- its dequant feeds channel-wise Q8_0_C.+ const bool requant = needs_q8_0_c_requant(name, qtype);+ const ov::element::Type zp_type =+ (!requant && qtype == GGUF_TYPE_Q4_K) ? ov::element::u8 : ov::element::f16;++ // K-quant requant sources: the fused dequant -> Q8_0_C streams from the raw bytes, so skip the+ // full-tensor gguf_fill_* extraction below (it would be discarded) and return before the switch.+ if (requant && (qtype == GGUF_TYPE_Q4_K || qtype == GGUF_TYPE_Q5_K || qtype == GGUF_TYPE_Q6_K)) {+ ov::Tensor rq_weights(ov::element::i8, ov::Shape{rows, cols});+ ov::Tensor rq_scales(ov::element::f16, ov::Shape{rows, 1});+ bool ok = requantize_q8_0_channelwise_faithful(tensor, rows, cols, qtype, rq_weights.data<int8_t>(),+ rq_scales.data<ov::float16>());+ OPENVINO_ASSERT(ok, "[ggml] faithful K-quant requant failed for ", base);+ return build_q8_0_c_node(rq_weights, rq_scales, rows, cols);+ }++ switch (qtype) {+ case GGUF_TYPE_Q4_0: {+ ov::Tensor weights(ov::element::u32, ov::Shape{rows, cols / 8});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(32)});+ gguf_fill_q4_0(tensor, weights, scales);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ break;+ }+ case GGUF_TYPE_Q5_0:+ case GGUF_TYPE_Q8_0: {+ // Symmetric, i8 weights + f16 scales (group 32).+ ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(32)});+ gguf_fill_sym(tensor, weights, scales);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ break;+ }+ case GGUF_TYPE_Q6_K: {+ // Symmetric, i8 weights + f16 scales (group 16).+ ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(16)});+ gguf_fill_sym(tensor, weights, scales);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ break;+ }+ case GGUF_TYPE_Q3_K: {+ // Symmetric, i4 weights (2/byte) + f16 scales (group 16).+ ov::Tensor weights(ov::element::i4, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(16)});+ gguf_fill_sym(tensor, weights, scales);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ break;+ }+ case GGUF_TYPE_Q4_1:+ case GGUF_TYPE_Q4_K: {+ // Asymmetric 4-bit: u32-packed u4 weights + f16 scales + zp (group 32).+ ov::Tensor weights(ov::element::u32, ov::Shape{rows, cols / 8});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(32)});+ ov::Tensor zp(zp_type, ov::Shape{rows, sub_blocks_per_row(32)});+ gguf_fill_asym(tensor, weights, scales, zp);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ w[base + ".zp"] = zp;+ break;+ }+ case GGUF_TYPE_Q5_1:+ case GGUF_TYPE_Q5_K: {+ // Asymmetric 8-bit weights + f16 scales + zp (group 32).+ ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(32)});+ ov::Tensor zp(zp_type, ov::Shape{rows, sub_blocks_per_row(32)});+ gguf_fill_asym(tensor, weights, scales, zp);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ w[base + ".zp"] = zp;+ break;+ }+ case GGUF_TYPE_Q2_K: {+ // Asymmetric 2-bit weights (u2) + f16 scales + zp (group 16).+ ov::Tensor weights(ov::element::u2, ov::Shape{rows, cols});+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(16)});+ ov::Tensor zp(zp_type, ov::Shape{rows, sub_blocks_per_row(16)});+ gguf_fill_asym(tensor, weights, scales, zp);+ w[base + ".weight"] = weights;+ w[base + ".scales"] = scales;+ w[base + ".zp"] = zp;+ break;+ }+ default:+ OPENVINO_THROW("[ggml] unsupported weight quant type: ", quant_type);+ }++ // Non-K requant sources (e.g. an F16 / Q4_0 / Q8_0 token_embd or output): the K-quant fast path+ // above already handled Q4_K/Q5_K/Q6_K, so here reproduce the backend's channel-wise Q8_0_C by+ // dequantizing to f32 from the extracted tensors, then re-quantizing.+ if (requant) { // computed above; reuse rather than re-running getenv + name scans+ auto f32 = dequant_extracted_to_f32(w, base, rows, cols);+ return requantize_q8_0_channelwise(f32, rows, cols);+ }++ return make_weight_node(base, w, q);+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hppnew file mode 100644index 00000000000..fa7cac374c6--- /dev/null+++ b/src/frontends/gguf/src/quant/weights.hpp@@ -0,0 +1,51 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <string>+#include <unordered_map>++#include "gguf.hpp"++namespace ov {+class Node;+}++namespace ov::frontend::gguf {++// Build the OpenVINO node for a GGUF weight with base name `base` (the tensor name without+// the trailing ".weight", e.g. "blk.0.attn_q" or "token_embd"). Quantized weights become a+// low-bitness compressed subgraph (u4/u8 weights + zero-point + f16 scale, Convert ->+// Subtract -> Multiply -> Reshape), matching what the cgraph path produces; F16/F32 weights+// become a plain Constant. The returned node's output is f32 and feeds the translators.+//+// `weights` holds the parser output (tensors by gguf name; quantized tensors expanded to+// "<base>.weight" + "<base>.scales" + "<base>.biases"). `qtypes` maps "<base>.qtype" ->+// gguf_tensor_type.+std::shared_ptr<ov::Node> make_weight_node(const std::string& base,+ const std::unordered_map<std::string, ov::Tensor>& weights,+ const std::unordered_map<std::string, gguf_tensor_type>& qtypes);++// Build the OpenVINO weight node directly from the raw GGUF weight bytes, as provided by a+// decoder (e.g. wrapping llama.cpp's tensor->data). `data` holds the bytes exactly as ggml+// laid them out; `quant_type` is the ggml type name ("F16", "F32", "BF16", "Q4_0", "Q4_K",+// "Q6_K", ...); `logical_shape` is the {rows, cols} element shape. This is the frontend+// entry point used by translate_weight: it runs the appropriate fill function to extract+// weights/scales/zp and builds the decompression subgraph. Throws on an unsupported quant+// type. The returned node's output is f32.+//+// `name` is the gguf tensor name (e.g. "token_embd.weight", "blk.0.ffn_down.weight"). It is+// used to decide channel-wise requantization to Q8_0_C for the embedding / output / Q6_K /+// Q5_K tensors, matching the llama.cpp ggml-openvino backend's CPU/GPU weight pipeline.+std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,+ const std::string& quant_type,+ const ov::Shape& logical_shape,+ const std::string& name = "");++// Map a ggml quant type name (e.g. "Q4_K") to its gguf_tensor_type id. Throws if unknown.+gguf_tensor_type gguf_type_from_name(const std::string& quant_type);++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cppnew file mode 100644index 00000000000..1e2c2843fb9--- /dev/null+++ b/src/frontends/gguf/src/translate_session.cpp@@ -0,0 +1,252 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "translate_session.hpp"++#include <cstdint>+#include <cstdlib>+#include <map>+#include <memory>+#include "openvino/core/node.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/cos.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/range.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/sin.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/strided_slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/pass/constant_folding.hpp"++#include "input_model.hpp"+#include "node_context.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "pass/lower_set_rows_stateless.hpp"+#include "transformations/fp16_compression/mark_decompression_convert_constant_folding.hpp"+#include "transformations/op_conversions/convert_convertlike.hpp"+#include "utils.hpp"++namespace ov {+namespace frontend {+namespace gguf {++using namespace ov::op;++namespace {++void add_sliced_mask(TensorMap& tensor_map) {+ // Slice the full attention mask down to the current token window for the attention ops.+ // For static (fixed-shape) models the slice bounds are constants, so this folds to a+ // fixed-size slice -- there is no separate static pass-through branch.+ auto create_sliced_mask = [&](const std::string& mask_name, const std::string& sliced_name) {+ if ((tensor_map.find(mask_name) != tensor_map.end()) &&+ (tensor_map.find("token_len_per_seq") != tensor_map.end())) {+ auto token_len_per_seq = tensor_map.at("token_len_per_seq").get_node_shared_ptr();+ auto mask = tensor_map.at(mask_name).get_node_shared_ptr();+ auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});+ auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto two = ov::op::v0::Constant::create(ov::element::i64, {1}, {2});+ std::shared_ptr<ov::Node> mask_sliced =+ std::make_shared<ov::op::v8::Slice>(mask, zero, token_len_per_seq, one, two);+ mask_sliced = std::make_shared<ov::op::v0::Convert>(mask_sliced, ov::element::f16);+ mask_sliced->set_friendly_name(sliced_name);+ tensor_map.insert({sliced_name, mask_sliced->output(0)});+ }+ };++ create_sliced_mask("self_kq_mask", "KQ_mask_sliced");+ create_sliced_mask("self_kq_mask_swa", "KQ_mask_swa_sliced");+}++void add_rope_sin_cos(TensorMap& tensor_map, const RopeConfig& rope_config) {+ // n_dims == 0 means the model uses no RoPE; per_op means each ROPE op builds its own sin/cos+ // (e.g. gemma4 where SWA and global layers differ), so skip the shared table entirely.+ if (tensor_map.find("inp_pos") == tensor_map.end() || rope_config.n_dims == 0 || rope_config.per_op) {+ return;+ }+ auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();+ std::shared_ptr<ov::Node> rope_freqs_weight;+ if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) {+ rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr();+ }++ auto sin_cos = make_sin_cos(rope_config, inp_pos, rope_freqs_weight);+ auto sin_theta = sin_cos.first;+ auto cos_theta = sin_cos.second;++ cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos");+ sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin");+ tensor_map.insert({"rope_cos", cos_theta});+ tensor_map.insert({"rope_sin", sin_theta});+}++// Create common patterns+void preprocess(TensorMap& tensor_map, const RopeConfig& rope_config) {+ add_sliced_mask(tensor_map);+ add_rope_sin_cos(tensor_map, rope_config);+}++} // namespace++TranslateSession::TranslateSession(const frontend::InputModel::Ptr& input_model,+ const std::unordered_map<std::string, CreatorFunction>& translator_map,+ const std::vector<DecoderTransformationExtension::Ptr>& transformation_extensions)+ : m_input_model(input_model),+ m_translator_map(translator_map),+ m_ov_model(nullptr),+ m_transformation_extensions(transformation_extensions) {}++std::shared_ptr<Model> TranslateSession::get_converted_model() {+ if (m_ov_model) {+ return m_ov_model;+ }+ m_ov_model = translate_graph(m_input_model);+ return m_ov_model;+}++std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputModel::Ptr& input_model) {+ ov::ParameterVector params;+ ov::ResultVector results;+ auto tensor_map = std::make_shared<TensorMap>();+ std::shared_ptr<Model> resulting_model;++ const auto& gguf_model = std::dynamic_pointer_cast<InputModel>(input_model);++ for (const auto& it : gguf_model->get_model_inputs()) {+ if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(it.second)) {+ params.push_back(param);+ }+ (*tensor_map)[it.first] = it.second;+ }++ // Weights are not seeded here: a weight is visited as a regular "GGML_OP_NONE" node (a ggml+ // leaf carrying a "data" attribute) in visit_subgraph, and translate_weight writes its+ // dequantized node into the tensor map under the weight name, before the consuming op is+ // visited (the cgraph is topologically ordered).++ auto node_visitor = [&](std::shared_ptr<GgufDecoder> decoder) {+ auto operation_type = decoder->get_op_type();+ if (operation_type == "GGML_OP_NONE") {+ // A GGML_OP_NONE leaf is a weight only if the decoder exposes its raw bytes via the+ // "data" attribute; otherwise it is a model-input leaf (already seeded as a Parameter+ // above) and there is nothing to translate.+ if (!decoder->get_attribute("data").is<ov::Tensor>()) {+ return;+ }+ }++ ov::OutputVector converted_outputs;+ auto it = m_translator_map.find(operation_type);+ FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(),+ "Translation for operation type ",+ operation_type,+ " is not implemented.");+ NodeContext node_context(decoder, tensor_map);+ converted_outputs = it->second(node_context);++ const auto& node_output_names = decoder->get_output_names();+ FRONT_END_OP_CONVERSION_CHECK(node_output_names.size() == converted_outputs.size(),+ "Number of ",+ operation_type,+ " outputs greater than number of converted outputs, which are ",+ node_output_names.size(),+ " and ",+ converted_outputs.size(),+ " respectively.");++ for (size_t i = 0; i < node_output_names.size(); ++i) {+ auto output_name = node_output_names[i];+ if (i < converted_outputs.size() && converted_outputs[i].get_node_shared_ptr() != nullptr) {+ (*tensor_map)[output_name] = converted_outputs[i];+ }+ }+ };++ // Build the shared LLM scaffolding (sliced attention mask + rope sin/cos table) once, so all+ // layers reuse it. Both builders are self-gating: add_sliced_mask only fires when the mask ++ // token_len_per_seq inputs are present, and add_rope_sin_cos only when inp_pos is present and+ // the model uses a shared rope table (n_dims != 0, not per-op). For a bare op / small cgraph+ // (no rope_config -> default n_dims == 0, no mask/pos inputs) both no-op, and the ROPE/attention+ // translators fall back to building their own -- so there is no separate "naive" mode.+ preprocess(*tensor_map, gguf_model->get_rope_config());+ gguf_model->visit_subgraph(node_visitor);++ for (const auto& name : gguf_model->get_model_output_names()) {+ FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(),+ "Output name not found in tensor map: ",+ name);+ auto result = std::make_shared<v0::Result>(tensor_map->at(name));+ result->set_friendly_name(name);+ results.push_back(result);+ }++ ov::ParameterVector used_params;+ for (const auto& param : params) {+ if (!param->output(0).get_target_inputs().empty()) {+ used_params.push_back(param);+ }+ }+ resulting_model = std::make_shared<Model>(results, used_params);++ apply_transformations(resulting_model);++ // Set WeightlessCacheAttribute on large constants to avoid unnecessary memory copies+ // in the NPUW plugin. Without this attribute, NPUW's LazyTensor constructor+ // (lazy_tensor.cpp, op::Const::Const) will memcpy every constant "in case export+ // occurs", doubling memory usage per compile_model call.+ //+ // The bin_offset field serves as a unique key (not a real file offset) — this is+ // the same convention the GPU plugin uses for non-IR models (see+ // Plugin::set_weightless_cache_attributes in intel_gpu/src/plugin/plugin.cpp).+ // Each constant must have a distinct bin_offset, otherwise GPU's weightless cache+ // import will map multiple constants to the same data.+ //+ // Small constants (< 16 elements) are excluded since they may be introduced by+ // optimization patterns and the overhead is negligible.+ size_t offset = 0;+ for (auto& node : resulting_model->get_ordered_ops()) {+ if (auto cnst = ov::as_type_ptr<ov::op::v0::Constant>(node);+ cnst && cnst->get_byte_size() / cnst->get_element_type().size() >= 16) {+ auto& rt_info = cnst->get_rt_info();+ if (rt_info.find(ov::WeightlessCacheAttribute::get_type_info_static()) == rt_info.end()) {+ rt_info[ov::WeightlessCacheAttribute::get_type_info_static()] =+ ov::WeightlessCacheAttribute(cnst->get_byte_size(), offset++, cnst->get_element_type());+ }+ }+ }+ return resulting_model;+}++std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<Model> model) {+ ov::pass::Manager manager;+ manager.set_per_pass_validation(true);+ manager.register_pass<ov::pass::MarkCompressedFloatConstants>();++ // Caller-registered transformation extensions run first. A SetRows-lowering extension (e.g.+ // the backend's stateful lowering) consumes the KV-cache SetRows ops here; the built-in stateless+ // lowering below then only fires on the ops left untouched. With no extension registered, the+ // stateless lowering handles every SetRows op -- so a plain convert() yields the+ // llama.cpp-faithful stateless model.+ for (const auto& ext : m_transformation_extensions) {+ ext->register_pass(manager);+ }+ manager.register_pass<pass::LowerSetRowsStateless>();+ manager.register_pass<ov::pass::ConvertConvertLike>();++ manager.run_passes(model);+ return model;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/translate_session.hpp b/src/frontends/gguf/src/translate_session.hppnew file mode 100644index 00000000000..cb4f60c56f0--- /dev/null+++ b/src/frontends/gguf/src/translate_session.hpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "input_model.hpp"+#include "node_context.hpp"+#include "openvino/frontend/extension/decoder_transformation.hpp"++namespace ov::frontend::gguf {++class TranslateSession {+public:+ TranslateSession(const frontend::InputModel::Ptr& input_model,+ const std::unordered_map<std::string, CreatorFunction>& translator_map,+ const std::vector<DecoderTransformationExtension::Ptr>& transformation_extensions = {});++ std::shared_ptr<Model> get_converted_model();+ std::shared_ptr<Model> translate_graph(const frontend::InputModel::Ptr& input_model);++private:+ std::shared_ptr<Model> apply_transformations(std::shared_ptr<Model> model);+ const frontend::InputModel::Ptr m_input_model;+ const std::unordered_map<std::string, CreatorFunction>& m_translator_map;+ std::shared_ptr<Model> m_ov_model;+ std::vector<DecoderTransformationExtension::Ptr> m_transformation_extensions;+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cppnew file mode 100644index 00000000000..d7d2e97abf0--- /dev/null+++ b/src/frontends/gguf/src/utils.cpp@@ -0,0 +1,219 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "utils.hpp"++#include <cmath>+#include <cstddef>+#include <memory>+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/cos.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/maximum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/sin.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include <string>++namespace ov {+namespace frontend {+namespace gguf {++void num_inputs_check(const NodeContext& context, size_t min_inputs, size_t max_inputs) {+ auto input_size = context.get_input_size();+ FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected");+ FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");+}++std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,+ const std::vector<int>& dims) {+ using namespace ov::op;+ const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);+ return std::make_shared<v8::Gather>(shape, dims_const, zero);+}++std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims) {+ return get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(node), dims);+}++OutputVector rename_outputs_with_suffix(const OutputVector& outputs, const std::string& suffix) {+ for (const auto& output : outputs) {+ auto node = output.get_node_shared_ptr();+ std::string name = node->get_friendly_name();+ name += "_";+ name += suffix;+ node->set_friendly_name(name);+ }+ return outputs;+}++namespace {+ov::Output<ov::Node> rope_yarn_ramp_mix(int n_dims, const float corr_dims[2], float ext_factor) {+ int half_n_dims = n_dims / 2;+ std::vector<float> dim_ids_vec(half_n_dims);+ // Fill 0,1,2,... explicitly (std::iota on a float vector warns on the int->float assignment).+ for (int i = 0; i < half_n_dims; ++i) {+ dim_ids_vec[i] = static_cast<float>(i);+ }+ auto dim_ids = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, (size_t)half_n_dims}, dim_ids_vec);+ auto corr_low = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[0]});+ auto corr_high = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[1]});+ auto denom = std::make_shared<ov::op::v1::Maximum>(+ std::make_shared<ov::op::v1::Subtract>(corr_high, corr_low),+ ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {0.001f}));+ auto ramp_y =+ std::make_shared<ov::op::v1::Divide>(std::make_shared<ov::op::v1::Subtract>(dim_ids, corr_low), denom);+ auto ramp_clamped = std::make_shared<ov::op::v0::Clamp>(ramp_y, 0.0f, 1.0f);+ // rope_yarn_ramp returns (1 - clamp(y)), so invert before scaling+ auto one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});+ auto ramp_inverted = std::make_shared<ov::op::v1::Subtract>(one, ramp_clamped);+ auto ext_factor_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {ext_factor});+ auto ramp_mix = std::make_shared<ov::op::v1::Multiply>(ramp_inverted, ext_factor_node);+ return ramp_mix;+}++float gguf_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {+#ifndef M_PI+# define M_PI 3.14159265358979323846+#endif+ return static_cast<float>(n_dims) * logf(static_cast<float>(n_ctx_orig) / (n_rot * 2 * static_cast<float>(M_PI))) /+ (2 * logf(base));+}++void gguf_rope_yarn_corr_dims(int n_dims,+ int n_ctx_orig,+ float freq_base,+ float beta_fast,+ float beta_slow,+ float dims[2]) {+ float start = floorf(gguf_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));+ float end = ceilf(gguf_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));+ dims[0] = std::max(0.0f, start);+ dims[1] = std::min(static_cast<float>(n_dims - 1), end);+}+} // namespace++std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(const RopeConfig& rope_config,+ std::shared_ptr<ov::Node> inp_pos,+ std::shared_ptr<ov::Node> rope_freqs_weight,+ bool imrope) {+ if (imrope) {+ inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);+ auto pos_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, {0, 0, 0, 4, -1});+ inp_pos = std::make_shared<ov::op::v1::Reshape>(inp_pos, pos_shape, true);+ auto pos_transpose_shape =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});+ inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_transpose_shape);+ } else {+ inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);+ auto pos_perm =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 3, 1, 2});+ inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_perm);+ }++ const float freq_base = rope_config.freq_base;+ const float freq_scale = rope_config.freq_scale;+ const float ext_factor = rope_config.ext_factor;+ const float attn_factor = rope_config.attn_factor;+ const float beta_fast = rope_config.beta_fast;+ const float beta_slow = rope_config.beta_slow;+ const int n_dims = rope_config.n_dims;+ const size_t n_dims_half = n_dims >> 1;+ const int n_ctx_orig = rope_config.n_ctx_orig;++ const float theta_scale = powf(freq_base, -2.0f / static_cast<float>(n_dims));++ std::vector<float> factor(n_dims_half);++ Output<Node> freq_factors;++ Output<Node> theta;+ float mscale = attn_factor;+ if (imrope) {+ std::vector<int64_t> gather_indices(n_dims_half);+ for (size_t j = 0; j < n_dims_half; j++) {+ gather_indices[j] = j % 3;+ factor[j] = static_cast<float>(std::pow(theta_scale, j));+ }+ auto gather_indices_const =+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{n_dims_half}, gather_indices);+ auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {4});+ inp_pos = std::make_shared<ov::op::v8::Gather>(inp_pos, gather_indices_const, gather_axis);+ auto factor_const = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{n_dims_half}, factor);+ theta = std::make_shared<ov::op::v1::Multiply>(inp_pos, factor_const);+ } else {+ float corr_dims[2];+ gguf_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);+ factor[0] = 1.0f;+ for (size_t i = 1; i < factor.size(); i++) {+ factor[i] = theta_scale * factor[i - 1];+ }+ freq_factors =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, 1, 1, factor.size()}, factor);+ if (rope_freqs_weight) {+ freq_factors = std::make_shared<ov::op::v1::Divide>(freq_factors, rope_freqs_weight);+ }++ auto theta_extrap = std::make_shared<ov::op::v1::Multiply>(freq_factors, inp_pos);+ auto theta_interp =+ std::make_shared<ov::op::v1::Multiply>(theta_extrap,+ ov::op::v0::Constant::create(ov::element::f32, {1}, {freq_scale}));++ if (ext_factor == 0.0f) {+ theta = theta_interp;+ } else {+ auto ramp_mix = rope_yarn_ramp_mix(n_dims, corr_dims, ext_factor);+ Output<Node> one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});+ auto one_minus_ramp = std::make_shared<ov::op::v1::Subtract>(one, ramp_mix);++ theta =+ std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(theta_interp, one_minus_ramp),+ std::make_shared<ov::op::v1::Multiply>(theta_extrap, ramp_mix));+ mscale *= (1.0f + 0.1f * std::log(1.0f / freq_scale));+ }+ }++ Output<Node> cos_theta = std::make_shared<ov::op::v0::Cos>(theta);+ Output<Node> sin_theta = std::make_shared<ov::op::v0::Sin>(theta);++ if (!imrope) {+ auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});++ cos_theta = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);+ sin_theta = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);+ }++ return std::make_pair(sin_theta, cos_theta);+}++ov::Output<ov::Node> process_view_input(const NodeContext& context, int input_index, int slice_len) {+ // Only works for VIEW operations that slice at the lowest dimension+ // If the VIEW also reshape the result, `slice_len` should be provided+ auto input = context.get_input(input_index);+ int64_t split_addr = context.get_input_view_element_offset(input_index);+ if (slice_len == 0) {+ slice_len = static_cast<int>(context.get_input(input_index).get_partial_shape()[3].get_length());+ }+ int64_t slice_end = split_addr + slice_len;++ auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {split_addr});+ auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_end});+ auto stride = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});+ auto axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});+ auto sliced = std::make_shared<ov::op::v8::Slice>(input, begin, end, stride, axes);+ return sliced;+}++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hppnew file mode 100644index 00000000000..bd576d726d1--- /dev/null+++ b/src/frontends/gguf/src/utils.hpp@@ -0,0 +1,57 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <utility>++#include "openvino/core/node_vector.hpp"++#include "node_context.hpp"++namespace ov {+namespace op {+namespace v3 {+class ShapeOf;+} // namespace v3+} // namespace op++namespace frontend {+namespace gguf {++void num_inputs_check(const NodeContext& context, size_t min_inputs, size_t max_inputs);++std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,+ const std::vector<int>& dims);+std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims);++OutputVector rename_outputs_with_suffix(const OutputVector& outputs, const std::string& suffix);++std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(const RopeConfig& rope_config,+ std::shared_ptr<ov::Node> inp_pos,+ std::shared_ptr<ov::Node> rope_freqs_weight = nullptr,+ bool imrope = false);++ov::Output<ov::Node> process_view_input(const NodeContext& context, int input_index, int slice_len = 0);++namespace op {+template <typename T>+OutputVector translate_1to1_match_1_input(const NodeContext& context) {+ num_inputs_check(context, 1, 1);+ auto res = std::make_shared<T>(context.get_input(0));+ return rename_outputs_with_suffix({res}, context.get_name());+}++template <typename T>+OutputVector translate_1to1_match_2_inputs(const NodeContext& context) {+ num_inputs_check(context, 2, 2);+ auto res = std::make_shared<T>(context.get_input(0), context.get_input(1));+ return rename_outputs_with_suffix({res}, context.get_name());+}+} // namespace op++} // namespace gguf+} // namespace frontend+} // namespace ovdiff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txtnew file mode 100644index 00000000000..5fcf7885c44--- /dev/null+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -0,0 +1,105 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#++set(TARGET_NAME ov_gguf_frontend_tests)++# Compile the frontend sources directly into the test binary instead of linking the+# installed library. Explicit source lists (no GLOB); keep in sync when adding sources.+set(FE_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")+set(FRONTEND_SRCS+ "${FE_SRC_DIR}/frontend.cpp"+ "${FE_SRC_DIR}/input_model.cpp"+ "${FE_SRC_DIR}/op_table.cpp"+ "${FE_SRC_DIR}/translate_session.cpp"+ "${FE_SRC_DIR}/utils.cpp"+ "${FE_SRC_DIR}/helper_ops/set_rows_op.cpp"+ "${FE_SRC_DIR}/pass/lower_set_rows_stateless.cpp"+ "${FE_SRC_DIR}/quant/gguf_quants.cpp"+ "${FE_SRC_DIR}/quant/weights.cpp"+ "${FE_SRC_DIR}/op/add_id.cpp"+ "${FE_SRC_DIR}/op/argsort.cpp"+ "${FE_SRC_DIR}/op/clamp.cpp"+ "${FE_SRC_DIR}/op/concat.cpp"+ "${FE_SRC_DIR}/op/cont.cpp"+ "${FE_SRC_DIR}/op/cpy.cpp"+ "${FE_SRC_DIR}/op/flash_attn_ext.cpp"+ "${FE_SRC_DIR}/op/gated_delta_net.cpp"+ "${FE_SRC_DIR}/op/get_rows.cpp"+ "${FE_SRC_DIR}/op/glu_geglu.cpp"+ "${FE_SRC_DIR}/op/glu_swiglu.cpp"+ "${FE_SRC_DIR}/op/im2col.cpp"+ "${FE_SRC_DIR}/op/l2_norm.cpp"+ "${FE_SRC_DIR}/op/mul_mat_id.cpp"+ "${FE_SRC_DIR}/op/mulmat.cpp"+ "${FE_SRC_DIR}/op/norm.cpp"+ "${FE_SRC_DIR}/op/pad.cpp"+ "${FE_SRC_DIR}/op/permute.cpp"+ "${FE_SRC_DIR}/op/repeat.cpp"+ "${FE_SRC_DIR}/op/reshape.cpp"+ "${FE_SRC_DIR}/op/rms_norm.cpp"+ "${FE_SRC_DIR}/op/rope.cpp"+ "${FE_SRC_DIR}/op/scale.cpp"+ "${FE_SRC_DIR}/op/set_rows.cpp"+ "${FE_SRC_DIR}/op/softmax.cpp"+ "${FE_SRC_DIR}/op/ssm_conv.cpp"+ "${FE_SRC_DIR}/op/sum_rows.cpp"+ "${FE_SRC_DIR}/op/transpose.cpp"+ "${FE_SRC_DIR}/op/unary_gelu.cpp"+ "${FE_SRC_DIR}/op/unary_silu.cpp"+ "${FE_SRC_DIR}/op/view.cpp"+ "${FE_SRC_DIR}/op/weight.cpp"+)++set(TEST_SRCS+ "${CMAKE_CURRENT_SOURCE_DIR}/test_dequant_vs_ggml.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/test_extensions.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/test_ops.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/test_weights.cpp"+)++set(GGUF_TEST_DATA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/test_data")++ov_add_test_target(+ NAME ${TARGET_NAME}+ SOURCES ${TEST_SRCS} ${FRONTEND_SRCS}+ LINK_LIBRARIES+ gtest+ gtest_main+ common_test_utils+ openvino::runtime+ openvino::runtime::dev+ openvino::offline_transformations+ openvino::cnpy+ INCLUDES+ "${CMAKE_CURRENT_SOURCE_DIR}/../src"+ "${CMAKE_CURRENT_SOURCE_DIR}/../include"+ ADD_CLANG_FORMAT+ LABELS+ OV UNIT GGUF_FE+)++# Install the .npy reference data next to the test binary (found via getExecutableDirectory()).+install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/test_data"+ DESTINATION tests+ COMPONENT tests+ EXCLUDE_FROM_ALL+ FILES_MATCHING PATTERN "*.npy")++# Sources compiled into the binary: resolve the visibility macros to local definitions, not dllimport.+target_compile_definitions(${TARGET_NAME} PRIVATE openvino_gguf_frontend_EXPORTS)++# ov::parallel_for needs the threading (TBB) include directories.+ov_set_threading_interface_for(${TARGET_NAME})++# Frontend sources have file-internal helpers without separate declarations; relax only that warning.+if(CMAKE_COMPILER_IS_GNUCXX OR OV_COMPILER_IS_CLANG)+ set_source_files_properties(${FRONTEND_SRCS} PROPERTIES+ COMPILE_OPTIONS "-Wno-missing-declarations")+endif()++target_compile_definitions(${TARGET_NAME} PRIVATE+ TEST_DATA_DIR="${GGUF_TEST_DATA_DIR}"+)++ov_build_target_faster(${TARGET_NAME} PCH)diff --git a/src/frontends/gguf/tests/op_test_utils.hpp b/src/frontends/gguf/tests/op_test_utils.hppnew file mode 100644index 00000000000..eaa22e97b32--- /dev/null+++ b/src/frontends/gguf/tests/op_test_utils.hpp@@ -0,0 +1,269 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Utilities shared by the GGUF frontend per-op test suite (test_ops.cpp).+//+// The GGUF frontend translation layer operates purely on the abstract GgufDecoder+// interface; it does not read .gguf files. For tests we therefore provide a tiny+// in-memory decoder (SingleOpDecoder) that describes a single ggml op plus its+// input/output tensors, and drive ov::frontend::gguf::FrontEnd::convert on it. This+// keeps the tests free of any llama.cpp / ggml dependency.+//+// Provides:+// - SingleOpDecoder / SingleOpBuilder — describe one op and build an ov::Model.+// - run_on_cpu — compile an ov::Model on CPU and run one inference.+// - expect_near — element-wise |actual-expected| <= atol check via GTest.++#pragma once++#include <cnpy.h>+#include <gtest/gtest.h>++#include <algorithm>+#include <cmath>+#include <cstring>+#include <map>+#include <memory>+#include <string>+#include <vector>++#include "common_test_utils/file_utils.hpp"+#include "op_table.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/frontend/gguf/frontend.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/runtime/core.hpp"+#include "openvino/runtime/tensor.hpp"+#include "openvino/util/file_util.hpp"++// TEST_DATA_DIR is injected by CMakeLists.txt as an absolute path to the source-tree+// test_data/ directory; used as a fallback when running from the build tree.+#ifndef TEST_DATA_DIR+# error "TEST_DATA_DIR must be defined by CMake (add_compile_definitions)"+#endif++namespace ov_gguf_test {++using namespace ov::frontend::gguf;++// Description of one tensor (graph input or op output) in the single-op model.+struct TensorDesc {+ std::string name;+ ov::element::Type type;+ ov::PartialShape shape;+};++// A minimal GgufDecoder that exposes exactly one ggml op. The op has `inputs`+// (all of which become graph Parameters) and a single output. Operation parameters+// are exposed through the typed node-scoped get_attribute(name) accessor, matching the+// decoder API the op translators consume; a real decoder (e.g. the llama.cpp cgraph+// decoder) populates the same attributes from ggml's op_params.+class SingleOpDecoder : public GgufDecoder, public std::enable_shared_from_this<SingleOpDecoder> {+public:+ SingleOpDecoder(std::string op_type,+ std::vector<TensorDesc> inputs,+ TensorDesc output,+ std::map<std::string, ov::Any> attributes)+ : m_op_type(std::move(op_type)),+ m_inputs(std::move(inputs)),+ m_output(std::move(output)),+ m_attributes(std::move(attributes)) {+ for (const auto& in : m_inputs) {+ m_input_names.push_back(in.name);+ auto p = std::make_shared<ov::op::v0::Parameter>(in.type, in.shape);+ p->set_friendly_name(in.name);+ p->output(0).set_names({in.name});+ m_model_inputs[in.name] = p;+ }+ }++ // ── typed node-scoped attribute access (we hold a single op) ────────────────+ ov::Any get_attribute(const std::string& name) const override {+ auto it = m_attributes.find(name);+ return it == m_attributes.end() ? ov::Any{} : it->second;+ }++ // ── per-node metadata ───────────────────────────────────────────────────────+ int64_t get_input_view_element_offset(const std::string&) const override {+ return 0;+ }+ ov::PartialShape get_input_shape(const std::string& name) const override {+ return find_input(name).shape;+ }+ size_t get_input_size() const override {+ return m_inputs.size();+ }++ std::vector<std::string> get_input_names() const override {+ return m_input_names;+ }++ ov::PartialShape get_output_shape() const override {+ return m_output.shape;+ }++ std::vector<std::string> get_output_names() const override {+ return {m_output.name};+ }++ const std::string& get_op_type() const override {+ return m_op_type;+ }+ const std::string& get_op_name() const override {+ return m_output.name;+ }++ void visit_subgraph(std::function<void(std::shared_ptr<GgufDecoder>)> node_visitor) const override {+ node_visitor(std::const_pointer_cast<SingleOpDecoder>(shared_from_this()));+ }++ const std::map<std::string, std::shared_ptr<ov::Node>>& get_model_inputs() const override {+ return m_model_inputs;+ }+ std::vector<std::string> get_model_output_names() const override {+ return {m_output.name};+ }++private:+ const TensorDesc& find_input(const std::string& name) const {+ for (const auto& in : m_inputs) {+ if (in.name == name) {+ return in;+ }+ }+ throw std::runtime_error("SingleOpDecoder: unknown input '" + name + "'");+ }++ std::string m_op_type;+ std::vector<TensorDesc> m_inputs;+ TensorDesc m_output;+ std::map<std::string, ov::Any> m_attributes;+ std::vector<std::string> m_input_names;+ std::map<std::string, std::shared_ptr<ov::Node>> m_model_inputs;+};++// Fluent builder: describe a single op and convert it to an ov::Model.+class SingleOpBuilder {+public:+ SingleOpBuilder& op(const std::string& op_type) {+ m_op_type = op_type;+ return *this;+ }+ SingleOpBuilder& input(const std::string& name, ov::element::Type type, const ov::PartialShape& shape) {+ m_inputs.push_back({name, type, shape});+ return *this;+ }+ SingleOpBuilder& output(const std::string& name, ov::element::Type type, const ov::PartialShape& shape) {+ m_output = {name, type, shape};+ return *this;+ }+ // Set a typed operation attribute (e.g. "scale", "eps", "swapped"), the way a real+ // decoder exposes ggml op_params to the translators.+ template <typename T>+ SingleOpBuilder& attr(const std::string& name, const T& value) {+ m_attributes[name] = ov::Any(value);+ return *this;+ }+ SingleOpBuilder& op_case(int c) {+ m_attributes["op_case"] = ov::Any(c);+ return *this;+ }++ // Build the single-op decoder. A SingleOpDecoder exposes no "rope_config" attribute, so the+ // frontend's InputModel::get_rope_config returns a default (no shared rope table) and the LLM+ // preprocess step no-ops -- exactly what a single-op test wants, with no naive flag.+ std::shared_ptr<GgufDecoder> decoder() const {+ auto attrs = m_attributes;+ attrs.emplace("output_type", ov::Any(m_output.type));+ return std::make_shared<SingleOpDecoder>(m_op_type, m_inputs, m_output, attrs);+ }++ std::shared_ptr<ov::Model> build() const {+ FrontEnd fe;+ return fe.convert(fe.load(decoder()));+ }++ // Convert through a FrontEnd that has the given extensions registered first.+ std::shared_ptr<ov::Model> build_with_extensions(+ const std::vector<std::shared_ptr<ov::Extension>>& extensions) const {+ FrontEnd fe;+ for (const auto& ext : extensions) {+ fe.add_extension(ext);+ }+ return fe.convert(fe.load(decoder()));+ }++private:+ std::string m_op_type;+ std::vector<TensorDesc> m_inputs;+ TensorDesc m_output;+ std::map<std::string, ov::Any> m_attributes;+};++// ── inference / comparison helpers ──────────────────────────────────────────────++inline ov::Tensor make_f32_tensor(const ov::Shape& shape, const std::vector<float>& data) {+ ov::Tensor t(ov::element::f32, shape);+ std::copy(data.begin(), data.end(), t.data<float>());+ return t;+}++// Compile on CPU and run one inference with the given named inputs; return the single output.+inline ov::Tensor run_on_cpu(const std::shared_ptr<ov::Model>& model, const std::map<std::string, ov::Tensor>& inputs) {+ ov::Core core;+ auto compiled = core.compile_model(model, "CPU");+ auto req = compiled.create_infer_request();+ for (const auto& kv : inputs) {+ req.set_tensor(kv.first, kv.second);+ }+ req.infer();+ return req.get_output_tensor(0);+}++// Compare against an fp32 reference with a combined absolute + relative tolerance:+// |actual - expected| <= atol + rtol * |expected|+// The relative term matters on hardware that runs the graph in fp16 (e.g. ARM CPU by default),+// where the rounding error grows with the magnitude of the value; a fixed absolute atol tuned on+// fp32 x86 is too tight there. rtol defaults to ~fp16 precision (2^-9).+inline void expect_near(const ov::Tensor& actual,+ const std::vector<float>& expected,+ float atol = 1e-4f,+ float rtol = 2e-3f) {+ ASSERT_EQ(actual.get_element_type(), ov::element::f32);+ ASSERT_EQ(actual.get_size(), expected.size());+ const float* a = actual.data<float>();+ for (size_t i = 0; i < expected.size(); ++i) {+ const float tol = atol + rtol * std::fabs(expected[i]);+ EXPECT_NEAR(a[i], expected[i], tol) << "mismatch at index " << i;+ }+}++// ── npy helpers (used by the dequant tests) ─────────────────────────────────────++// Locate the test_data directory. When installed (CI), the data lives in a "test_data"+// folder next to the test executable; when running from the build tree it is in the+// source tree at the compile-time TEST_DATA_DIR path.+inline std::string test_data_dir() {+ const std::string installed =+ ov::util::path_join({ov::test::utils::getExecutableDirectory(), "test_data"}).string();+ if (ov::util::directory_exists(installed)) {+ return installed;+ }+ return TEST_DATA_DIR;+}++inline std::string test_data_path(const std::string& stem) {+ return ov::util::path_join({test_data_dir(), stem + ".npy"}).string();+}++// Load a .npy array as a flat vector of T.+template <typename T>+std::vector<T> load_npy(const std::string& stem) {+ cnpy::NpyArray arr = cnpy::npy_load(test_data_path(stem));+ const T* begin = arr.data<T>();+ return std::vector<T>(begin, begin + arr.num_vals);+}++} // namespace ov_gguf_testdiff --git a/src/frontends/gguf/tests/test_data/q2_k_deq.npy b/src/frontends/gguf/tests/test_data/q2_k_deq.npynew file mode 100644index 00000000000..3fa4cbb363bBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q2_k_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q2_k_qbytes.npy b/src/frontends/gguf/tests/test_data/q2_k_qbytes.npynew file mode 100644index 00000000000..b708eebd4eaBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q2_k_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q3_k_deq.npy b/src/frontends/gguf/tests/test_data/q3_k_deq.npynew file mode 100644index 00000000000..c60ad2ee907Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q3_k_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q3_k_qbytes.npy b/src/frontends/gguf/tests/test_data/q3_k_qbytes.npynew file mode 100644index 00000000000..c0b754ed5faBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q3_k_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_0_deq.npy b/src/frontends/gguf/tests/test_data/q4_0_deq.npynew file mode 100644index 00000000000..9ac4464d830Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_0_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_0_qbytes.npy b/src/frontends/gguf/tests/test_data/q4_0_qbytes.npynew file mode 100644index 00000000000..3ae2062db3aBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_0_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_1_deq.npy b/src/frontends/gguf/tests/test_data/q4_1_deq.npynew file mode 100644index 00000000000..dee7a6e75deBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_1_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_1_qbytes.npy b/src/frontends/gguf/tests/test_data/q4_1_qbytes.npynew file mode 100644index 00000000000..e890f3efd52Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_1_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_k_deq.npy b/src/frontends/gguf/tests/test_data/q4_k_deq.npynew file mode 100644index 00000000000..7aa309f4b63Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_k_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q4_k_qbytes.npy b/src/frontends/gguf/tests/test_data/q4_k_qbytes.npynew file mode 100644index 00000000000..56b2703a728Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q4_k_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_0_deq.npy b/src/frontends/gguf/tests/test_data/q5_0_deq.npynew file mode 100644index 00000000000..a6a4576f22eBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_0_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_0_qbytes.npy b/src/frontends/gguf/tests/test_data/q5_0_qbytes.npynew file mode 100644index 00000000000..ddf272c13bfBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_0_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_1_deq.npy b/src/frontends/gguf/tests/test_data/q5_1_deq.npynew file mode 100644index 00000000000..abdcf81465dBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_1_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_1_qbytes.npy b/src/frontends/gguf/tests/test_data/q5_1_qbytes.npynew file mode 100644index 00000000000..8429b839295Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_1_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_k_deq.npy b/src/frontends/gguf/tests/test_data/q5_k_deq.npynew file mode 100644index 00000000000..20f73edd016Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_k_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q5_k_qbytes.npy b/src/frontends/gguf/tests/test_data/q5_k_qbytes.npynew file mode 100644index 00000000000..bffe0b1c9faBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q5_k_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q6_k_deq.npy b/src/frontends/gguf/tests/test_data/q6_k_deq.npynew file mode 100644index 00000000000..31597a8b25eBinary files /dev/null and b/src/frontends/gguf/tests/test_data/q6_k_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q6_k_qbytes.npy b/src/frontends/gguf/tests/test_data/q6_k_qbytes.npynew file mode 100644index 00000000000..609a9930431Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q6_k_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_data/q8_0_deq.npy b/src/frontends/gguf/tests/test_data/q8_0_deq.npynew file mode 100644index 00000000000..52f870d2807Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q8_0_deq.npy differdiff --git a/src/frontends/gguf/tests/test_data/q8_0_qbytes.npy b/src/frontends/gguf/tests/test_data/q8_0_qbytes.npynew file mode 100644index 00000000000..97432173a59Binary files /dev/null and b/src/frontends/gguf/tests/test_data/q8_0_qbytes.npy differdiff --git a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp b/src/frontends/gguf/tests/test_dequant_vs_ggml.cppnew file mode 100644index 00000000000..b949994063e--- /dev/null+++ b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp@@ -0,0 +1,184 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Dequantization correctness tests with REAL ggml as the oracle.+//+// The reference data was produced offline by linking real ggml from llama.cpp+// (see tests/gen_ggml_reference.c): ggml quantizes smooth, asymmetric synthetic+// data into real GGUF-format blocks (_qbytes) and dequantizes those exact bytes+// (_deq). The committed .npy files mean the tests need no ggml / llama.cpp at+// build or run time.+//+// Here we feed the SAME bytes through the frontend's fill + make_weight_node dequant+// subgraph and require it to match ggml's to_float output.+//+// Tolerance: ggml stores K-quant scales as f16 and the dequant subgraph runs in f16,+// so allow ~3e-3 (matching llama.cpp's MAX_QUANTIZATION_TOTAL_ERROR-class thresholds).++#include <gtest/gtest.h>++#include <cmath>+#include <cstdint>+#include <cstring>+#include <string>+#include <vector>++#include "op_test_utils.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/result.hpp"+#include "openvino/pass/constant_folding.hpp"+#include "openvino/pass/manager.hpp"+#include "quant/gguf.hpp"+#include "quant/weights.hpp"++using namespace ov::frontend::gguf;+using ov_gguf_test::load_npy;++namespace {++std::vector<float> eval_as_f32(const std::shared_ptr<ov::Node>& node) {+ auto result = std::make_shared<ov::op::v0::Result>(node);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{});+ ov::pass::Manager pm;+ pm.register_pass<ov::pass::ConstantFolding>();+ pm.run_passes(model);+ auto folded =+ std::dynamic_pointer_cast<ov::op::v0::Constant>(model->get_results()[0]->get_input_node_shared_ptr(0));+ EXPECT_NE(folded, nullptr) << "dequant graph did not constant-fold to a single Constant";+ if (!folded)+ return {};+ const float* d = folded->get_data_ptr<float>();+ return std::vector<float>(d, d + ov::shape_size(folded->get_shape()));+}++// Map the test's ggml type id to the quant-type name string the frontend API expects.+const char* type_name(uint32_t type) {+ switch (type) {+ case GGUF_TYPE_Q4_0:+ return "Q4_0";+ case GGUF_TYPE_Q4_1:+ return "Q4_1";+ case GGUF_TYPE_Q5_0:+ return "Q5_0";+ case GGUF_TYPE_Q5_1:+ return "Q5_1";+ case GGUF_TYPE_Q8_0:+ return "Q8_0";+ case GGUF_TYPE_Q2_K:+ return "Q2_K";+ case GGUF_TYPE_Q3_K:+ return "Q3_K";+ case GGUF_TYPE_Q4_K:+ return "Q4_K";+ case GGUF_TYPE_Q5_K:+ return "Q5_K";+ case GGUF_TYPE_Q6_K:+ return "Q6_K";+ default:+ return "";+ }+}++// Build the frontend dequant of `rows x cols` weights from raw ggml block bytes `qbytes`+// via the public make_weight_node(data, quant_type, shape) entry point, then constant-fold+// it to f32 values (row-major, rows*cols).+std::vector<float> frontend_dequant(uint32_t type, const std::vector<uint8_t>& qbytes, uint64_t rows, uint64_t cols) {+ ov::Tensor data(ov::element::u8, ov::Shape{qbytes.size()});+ std::memcpy(data.data(), qbytes.data(), qbytes.size());+ auto node = make_weight_node(data, type_name(type), ov::Shape{rows, cols});+ return eval_as_f32(node);+}++float max_abs_diff(const std::vector<float>& a, const std::vector<float>& b) {+ EXPECT_EQ(a.size(), b.size());+ float m = 0.f;+ for (size_t i = 0; i < a.size() && i < b.size(); ++i)+ m = std::max(m, std::fabs(a[i] - b[i]));+ return m;+}++// One case: stem (test_data file prefix) + ggml quant enum + tolerance. rows/cols match the+// generator. Q5_K/Q6_K go through the channel-wise Q8_0_C requantization (matching the+// llama.cpp ggml-openvino CPU/GPU backend), so they diverge from ggml's faithful to_float by+// the Q8_0_C round-off (~1e-2) rather than by f16 noise (~3e-3).+struct DeqCase {+ const char* stem;+ uint32_t type;+ float tol;+};++constexpr uint64_t kRows = 4;+constexpr uint64_t kCols = 256;+constexpr float kTolFaithful = 3e-3f; // f16-scale dequant noise+constexpr float kTolRequant = 1.5e-2f; // channel-wise Q8_0_C requant round-off+// Q4_K uses an INTEGER (u8) zero-point so the CPU plugin fuses the dequant into the MatMul+// (matching the original ggml-openvino backend). The integer zp rounds min to a multiple of+// scale, so the dequant diverges from ggml's faithful to_float by up to ~0.045 per weight.+constexpr float kTolIntZp = 5e-2f;++} // namespace++class DequantVsGGML : public ::testing::TestWithParam<DeqCase> {};++TEST_P(DequantVsGGML, MatchesGgmlToFloat) {+ const DeqCase c = GetParam();+ const auto qbytes = load_npy<uint8_t>(std::string(c.stem) + "_qbytes");+ const auto ref = load_npy<float>(std::string(c.stem) + "_deq");+ ASSERT_EQ(ref.size(), kRows * kCols);++ const auto ours = frontend_dequant(c.type, qbytes, kRows, kCols);+ ASSERT_EQ(ours.size(), ref.size());++ EXPECT_LE(max_abs_diff(ours, ref), c.tol)+ << c.stem << ": frontend dequant diverges from ggml to_float beyond tolerance";+}++// The faithful per-row K-quant dequant used as the Q8_0_C requant source must match ggml's+// to_float almost exactly (f16 super-scale widening only): assert tight agreement with the ggml+// reference. A loose result here means a byte-layout/index bug (which would silently corrupt the+// requant of token_embd/output/Q6_K/Q5_K and break swap-vs-master parity).+struct FaithfulCase {+ const char* stem;+ uint32_t type;+ void (*dq)(const uint8_t*, size_t, float*);+};++class FaithfulDequantVsGGML : public ::testing::TestWithParam<FaithfulCase> {};++TEST_P(FaithfulDequantVsGGML, MatchesGgmlToFloat) {+ const FaithfulCase c = GetParam();+ const auto qbytes = load_npy<uint8_t>(std::string(c.stem) + "_qbytes");+ const auto ref = load_npy<float>(std::string(c.stem) + "_deq");+ ASSERT_EQ(ref.size(), kRows * kCols);+ // Reference is row-major [kRows, kCols]; the raw blocks for a row are contiguous.+ const size_t bytes_per_row = qbytes.size() / kRows;+ std::vector<float> ours(kRows * kCols);+ for (size_t r = 0; r < kRows; ++r) {+ c.dq(qbytes.data() + r * bytes_per_row, kCols, ours.data() + r * kCols);+ }+ EXPECT_LE(max_abs_diff(ours, ref), 3e-3f)+ << c.stem << ": faithful per-row dequant diverges from ggml to_float";+}++INSTANTIATE_TEST_SUITE_P(FaithfulKQuant,+ FaithfulDequantVsGGML,+ ::testing::Values(FaithfulCase{"q4_k", GGUF_TYPE_Q4_K, ov::frontend::gguf::dequant_row_q4_k_f32_for_test},+ FaithfulCase{"q5_k", GGUF_TYPE_Q5_K, ov::frontend::gguf::dequant_row_q5_k_f32_for_test},+ FaithfulCase{"q6_k", GGUF_TYPE_Q6_K, ov::frontend::gguf::dequant_row_q6_k_f32_for_test}),+ [](const ::testing::TestParamInfo<FaithfulCase>& i) { return std::string(i.param.stem); });++INSTANTIATE_TEST_SUITE_P(AllQuantTypes,+ DequantVsGGML,+ ::testing::Values(DeqCase{"q4_0", GGUF_TYPE_Q4_0, kTolFaithful},+ DeqCase{"q4_1", GGUF_TYPE_Q4_1, kTolFaithful},+ DeqCase{"q5_0", GGUF_TYPE_Q5_0, kTolFaithful},+ DeqCase{"q5_1", GGUF_TYPE_Q5_1, kTolFaithful},+ DeqCase{"q8_0", GGUF_TYPE_Q8_0, kTolFaithful},+ DeqCase{"q2_k", GGUF_TYPE_Q2_K, kTolFaithful},+ DeqCase{"q3_k", GGUF_TYPE_Q3_K, kTolFaithful},+ DeqCase{"q4_k", GGUF_TYPE_Q4_K, kTolIntZp},+ DeqCase{"q5_k", GGUF_TYPE_Q5_K, kTolRequant},+ DeqCase{"q6_k", GGUF_TYPE_Q6_K, kTolRequant}),+ [](const ::testing::TestParamInfo<DeqCase>& i) {+ return std::string(i.param.stem);+ });diff --git a/src/frontends/gguf/tests/test_extensions.cpp b/src/frontends/gguf/tests/test_extensions.cppnew file mode 100644index 00000000000..505311f09a1--- /dev/null+++ b/src/frontends/gguf/tests/test_extensions.cpp@@ -0,0 +1,95 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Tests for FrontEnd::add_extension (the extension-passing path in frontend.cpp).+//+// A ConversionExtension registers a custom translator for a ggml op name; the frontend+// merges it into the op table (overriding a built-in translator on name collision, or+// adding a translator for an otherwise unsupported op). The converter receives an+// ov::frontend::NodeContext, which the gguf NodeContext derives from.++#include <openvino/op/abs.hpp>+#include <openvino/op/multiply.hpp>+#include <openvino/op/negative.hpp>++#include "op_test_utils.hpp"+#include "openvino/frontend/extension/conversion.hpp"++using namespace ov_gguf_test;++namespace {++// A ConversionExtension whose converter emits Negative(in0) for whatever op it is+// registered against.+std::shared_ptr<ov::frontend::ConversionExtension> make_negate_ext(const std::string& op_type) {+ return std::make_shared<ov::frontend::ConversionExtension>(+ op_type,+ [](const ov::frontend::NodeContext& context) -> ov::OutputVector {+ return {std::make_shared<ov::op::v0::Negative>(context.get_input(0))};+ });+}++} // namespace++// A ConversionExtension registered for a built-in op name overrides the built-in+// translator: GGML_OP_SCALE normally does in*scale+bias, but here it must negate.+TEST(GGUFExtensions, ConversionExtensionOverridesBuiltin) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_SCALE")+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .attr<float>("scale", 2.0f)+ .attr<float>("bias", 0.0f)+ .build_with_extensions({make_negate_ext("GGML_OP_SCALE")});++ std::vector<float> x{1, -2, 3, -4, 5, -6, 7, -8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});++ std::vector<float> expected(x.size());+ for (size_t i = 0; i < x.size(); ++i)+ expected[i] = -x[i]; // Negative, not the built-in scale+ expect_near(out, expected);+}++// A ConversionExtension can add a translator for an op the frontend does not support+// out of the box (here a made-up "GGML_OP_CUSTOM_NEGATE").+TEST(GGUFExtensions, ConversionExtensionAddsNewOp) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_CUSTOM_NEGATE")+ .input("x", ov::element::f32, {3})+ .output("out", ov::element::f32, {3})+ .build_with_extensions({make_negate_ext("GGML_OP_CUSTOM_NEGATE")});++ std::vector<float> x{1, -2, 3};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({3}, x)}});+ expect_near(out, {-1, 2, -3});+}++// Two extensions registered together are both applied.+TEST(GGUFExtensions, MultipleConversionExtensions) {+ auto abs_ext = std::make_shared<ov::frontend::ConversionExtension>(+ "GGML_OP_CUSTOM_ABS",+ [](const ov::frontend::NodeContext& context) -> ov::OutputVector {+ return {std::make_shared<ov::op::v0::Abs>(context.get_input(0))};+ });++ auto model = SingleOpBuilder()+ .op("GGML_OP_CUSTOM_ABS")+ .input("x", ov::element::f32, {4})+ .output("out", ov::element::f32, {4})+ .build_with_extensions({make_negate_ext("GGML_OP_CUSTOM_NEGATE"), abs_ext});++ std::vector<float> x{1, -2, 3, -4};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({4}, x)}});+ expect_near(out, {1, 2, 3, 4}); // Abs applied+}++// Without the extension, an unsupported op fails to convert -- confirming the op is not+// already known and that the extension in the test above is what enables it.+TEST(GGUFExtensions, UnsupportedOpWithoutExtensionThrows) {+ auto builder = SingleOpBuilder()+ .op("GGML_OP_CUSTOM_NEGATE")+ .input("x", ov::element::f32, {3})+ .output("out", ov::element::f32, {3});+ EXPECT_ANY_THROW(builder.build());+}diff --git a/src/frontends/gguf/tests/test_ops.cpp b/src/frontends/gguf/tests/test_ops.cppnew file mode 100644index 00000000000..8f07b29855e--- /dev/null+++ b/src/frontends/gguf/tests/test_ops.cpp@@ -0,0 +1,1174 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Per-op conversion tests for the GGUF frontend.+//+// Each test builds a one-op model through SingleOpBuilder (which drives+// ov::frontend::gguf::FrontEnd::convert via an in-memory SingleOpDecoder), runs it on+// CPU and checks the result against a reference computed in plain C++. No .gguf file,+// ggml or llama.cpp is involved.++#include <algorithm>+#include <cmath>+#include <functional>++#include "op_test_utils.hpp"++using namespace ov_gguf_test;++namespace {++// ── Elementwise binary ops (two equally-shaped f32 inputs) ──────────────────────+// add / mul / sub / div share the exact same graph shape and driver, so they are+// parameterized over (op type, reference lambda) rather than duplicated.++struct BinaryCase {+ const char* name;+ const char* op_type;+ std::function<float(float, float)> ref;+};++class GGUFBinaryElementwise : public ::testing::TestWithParam<BinaryCase> {};++TEST_P(GGUFBinaryElementwise, MatchesReference) {+ const BinaryCase c = GetParam();+ auto model = SingleOpBuilder()+ .op(c.op_type)+ .input("a", ov::element::f32, {2, 4})+ .input("b", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .build();++ // Inputs chosen to be valid for every op (non-zero divisor for div).+ std::vector<float> a{10, 20, 30, 40, 50, 60, 70, 80};+ std::vector<float> b{2, 4, 5, 8, 10, 12, 14, 16};+ auto out = run_on_cpu(model, {{"a", make_f32_tensor({2, 4}, a)}, {"b", make_f32_tensor({2, 4}, b)}});++ std::vector<float> expected(a.size());+ for (size_t i = 0; i < a.size(); ++i)+ expected[i] = c.ref(a[i], b[i]);+ expect_near(out, expected);+}++INSTANTIATE_TEST_SUITE_P(GGUFOps,+ GGUFBinaryElementwise,+ ::testing::Values(BinaryCase{"add", "GGML_OP_ADD", [](float x, float y) { return x + y; }},+ BinaryCase{"mul", "GGML_OP_MUL", [](float x, float y) { return x * y; }},+ BinaryCase{"sub", "GGML_OP_SUB", [](float x, float y) { return x - y; }},+ BinaryCase{"div", "GGML_OP_DIV", [](float x, float y) { return x / y; }}),+ [](const ::testing::TestParamInfo<BinaryCase>& i) { return std::string(i.param.name); });++// ── Elementwise unary ops (single f32 input) ────────────────────────────────────+// silu / gelu(tanh) / tanh / softplus share the same one-input graph and driver.++struct UnaryCase {+ const char* name;+ const char* op_type;+ std::function<float(float)> ref;+ float atol;+};++class GGUFUnaryElementwise : public ::testing::TestWithParam<UnaryCase> {};++TEST_P(GGUFUnaryElementwise, MatchesReference) {+ const UnaryCase c = GetParam();+ auto model = SingleOpBuilder()+ .op(c.op_type)+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .build();++ std::vector<float> x{-2, -1, -0.5f, 0, 0.5f, 1, 2, 3};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});++ std::vector<float> expected(x.size());+ for (size_t i = 0; i < x.size(); ++i)+ expected[i] = c.ref(x[i]);+ expect_near(out, expected, c.atol);+}++// ggml GELU is the tanh approximation, but the frontend maps GGML_UNARY_OP_GELU to v7::Gelu(TANH)+// which is close enough to the exact (erf) form to check against it at 1e-3.+// Softplus uses 1e-3 to cover ARM CPU fp16 execution (small outputs where fp16 spacing ~1e-3+// dominates); on x86 fp32 the exact reference still matches comfortably within that bound.+INSTANTIATE_TEST_SUITE_P(+ GGUFOps,+ GGUFUnaryElementwise,+ ::testing::Values(+ UnaryCase{"silu", "GGML_UNARY_OP_SILU", [](float x) { return x / (1.0f + std::exp(-x)); }, 1e-4f},+ UnaryCase{"gelu",+ "GGML_UNARY_OP_GELU",+ [](float x) { return 0.5f * x * (1.0f + std::erf(x / std::sqrt(2.0f))); },+ 1e-3f},+ UnaryCase{"tanh", "GGML_UNARY_OP_TANH", [](float x) { return std::tanh(x); }, 1e-4f},+ UnaryCase{"softplus",+ "GGML_UNARY_OP_SOFTPLUS",+ [](float x) { return std::log1p(std::exp(-std::abs(x))) + std::max(x, 0.0f); },+ 1e-3f}),+ [](const ::testing::TestParamInfo<UnaryCase>& i) { return std::string(i.param.name); });++// Scale: out = in * scale + bias (scale/bias in op-params slots 0,1).+TEST(GGUFOps, Scale) {+ const float scale = 2.5f;+ const float bias = 1.0f;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SCALE")+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .attr<float>("scale", scale)+ .attr<float>("bias", bias)+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});++ std::vector<float> expected(x.size());+ for (size_t i = 0; i < x.size(); ++i)+ expected[i] = x[i] * scale + bias;+ expect_near(out, expected);+}++// RMS norm over the last axis (eps in op-params slot 0).+TEST(GGUFOps, RmsNorm) {+ const float eps = 1e-6f;+ const size_t cols = 4;+ auto model = SingleOpBuilder()+ .op("GGML_OP_RMS_NORM")+ .input("x", ov::element::f32, {2, cols})+ .output("out", ov::element::f32, {2, cols})+ .attr<float>("eps", eps)+ .build();++ std::vector<float> x{1, 2, 3, 4, -1, -2, -3, -4};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, cols}, x)}});++ std::vector<float> expected(x.size());+ for (size_t r = 0; r < 2; ++r) {+ float ss = 0.f;+ for (size_t c = 0; c < cols; ++c)+ ss += x[r * cols + c] * x[r * cols + c];+ float scale = 1.0f / std::sqrt(ss / cols + eps);+ for (size_t c = 0; c < cols; ++c)+ expected[r * cols + c] = x[r * cols + c] * scale;+ }+ expect_near(out, expected, 1e-4f);+}++// RMS norm rank-4 multi-token: each (token) row over the last axis independently. Mirrors OLMoE's+// QK-norm input layout [1,1,tok,width].+TEST(GGUFOps, RmsNormRank4MultiTok) {+ const float eps = 1e-6f;+ const size_t T = 3, W = 8;+ auto model = SingleOpBuilder()+ .op("GGML_OP_RMS_NORM")+ .input("x", ov::element::f32, {1, 1, T, W})+ .output("out", ov::element::f32, {1, 1, T, W})+ .attr<float>("eps", eps)+ .build();++ std::vector<float> x(T * W);+ for (size_t i = 0; i < x.size(); ++i)+ x[i] = 0.3f * static_cast<float>((int)i - 5) + ((i % 2) ? 0.7f : -0.4f);+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, T, W}, x)}});++ std::vector<float> expected(x.size());+ for (size_t t = 0; t < T; ++t) {+ float ss = 0.f;+ for (size_t c = 0; c < W; ++c)+ ss += x[t * W + c] * x[t * W + c];+ float scale = 1.0f / std::sqrt(ss / W + eps);+ for (size_t c = 0; c < W; ++c)+ expected[t * W + c] = x[t * W + c] * scale;+ }+ expect_near(out, expected, 1e-4f);+}++// Softmax along last axis (single-input form; shape rank 3 as the translator expects).+TEST(GGUFOps, SoftMax) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_SOFT_MAX")+ .input("x", ov::element::f32, {1, 2, 4})+ .output("out", ov::element::f32, {1, 2, 4})+ .attr<float>("scale", 1.0f)+ .attr<float>("max_bias", 0.0f)+ .build();++ std::vector<float> x{1, 2, 3, 4, 4, 3, 2, 1};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 2, 4}, x)}});++ std::vector<float> expected(x.size());+ for (size_t r = 0; r < 2; ++r) {+ float mx = -1e30f;+ for (size_t c = 0; c < 4; ++c)+ mx = std::max(mx, x[r * 4 + c]);+ float sum = 0.f;+ for (size_t c = 0; c < 4; ++c)+ sum += std::exp(x[r * 4 + c] - mx);+ for (size_t c = 0; c < 4; ++c)+ expected[r * 4 + c] = std::exp(x[r * 4 + c] - mx) / sum;+ }+ expect_near(out, expected, 1e-5f);+}++// Softmax with ALiBi (max_bias > 0): per-head slope applied to the mask.+TEST(GGUFOps, SoftMaxAlibi) {+ const uint32_t n_head = 6;+ const size_t T = 2, Kd = 4;+ const float scale = 1.0f, max_bias = 8.0f;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SOFT_MAX")+ .input("x", ov::element::f32, {n_head, T, Kd})+ .input("mask", ov::element::f32, {1, T, Kd})+ .output("out", ov::element::f32, {n_head, T, Kd})+ .attr<float>("scale", scale)+ .attr<float>("max_bias", max_bias)+ .build();++ std::vector<float> x(n_head * T * Kd);+ for (size_t i = 0; i < x.size(); ++i)+ x[i] = 0.1f * static_cast<float>(i) - 2.0f;+ std::vector<float> mask{0, 0, -1e9f, -1e9f, 0, 0, 0, -1e9f};+ auto out = run_on_cpu(model,+ {{"x", make_f32_tensor({n_head, T, Kd}, x)}, {"mask", make_f32_tensor({1, T, Kd}, mask)}});++ const uint32_t n_head_log2 = 1u << static_cast<uint32_t>(std::floor(std::log2(n_head)));+ const float m0 = std::pow(2.0f, -max_bias / n_head_log2);+ const float m1 = std::pow(2.0f, -(max_bias / 2.0f) / n_head_log2);+ std::vector<float> expected(x.size());+ for (uint32_t h = 0; h < n_head; ++h) {+ float slope = h < n_head_log2 ? std::pow(m0, static_cast<float>(h + 1)) : std::pow(m1, static_cast<float>(2 * (h - n_head_log2) + 1));+ for (size_t t = 0; t < T; ++t) {+ float mx = -1e30f;+ std::vector<float> z(Kd);+ for (size_t k = 0; k < Kd; ++k) {+ z[k] = scale * x[(h * T + t) * Kd + k] + slope * mask[t * Kd + k];+ mx = std::max(mx, z[k]);+ }+ float sum = 0.f;+ for (size_t k = 0; k < Kd; ++k) {+ z[k] = std::exp(z[k] - mx);+ sum += z[k];+ }+ for (size_t k = 0; k < Kd; ++k)+ expected[(h * T + t) * Kd + k] = z[k] / sum;+ }+ }+ expect_near(out, expected, 1e-4f);+}++// SwiGLU GLU: split last axis in half -> silu(a) * b.+TEST(GGUFOps, SwiGLU) {+ auto model = SingleOpBuilder()+ .op("GGML_GLU_OP_SWIGLU")+ .input("x", ov::element::f32, {2, 8})+ .output("out", ov::element::f32, {2, 4})+ .attr<bool>("swapped", false)+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8, -1, -2, -3, -4, 1, 1, 1, 1};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 8}, x)}});++ std::vector<float> expected(8);+ for (size_t r = 0; r < 2; ++r) {+ for (size_t c = 0; c < 4; ++c) {+ float a = x[r * 8 + c];+ float b = x[r * 8 + 4 + c];+ float silu = a / (1.0f + std::exp(-a));+ expected[r * 4 + c] = silu * b;+ }+ }+ expect_near(out, expected, 1e-4f);+}++// Clamp: elementwise clamp to [min, max] (bounds from typed attributes).+TEST(GGUFOps, Clamp) {+ const float min = -1.0f, max = 2.0f;+ auto model = SingleOpBuilder()+ .op("GGML_OP_CLAMP")+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .attr<float>("clamp_min", min)+ .attr<float>("clamp_max", max)+ .build();++ std::vector<float> x{-3, -1.5f, -0.5f, 0, 0.5f, 1.5f, 2.5f, 5};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});++ std::vector<float> expected(x.size());+ for (size_t i = 0; i < x.size(); ++i)+ expected[i] = std::min(std::max(x[i], min), max);+ expect_near(out, expected);+}++// LayerNorm over the last axis: (x - mean) / sqrt(var + eps).+TEST(GGUFOps, Norm) {+ const float eps = 1e-5f;+ const size_t cols = 4;+ auto model = SingleOpBuilder()+ .op("GGML_OP_NORM")+ .input("x", ov::element::f32, {2, cols})+ .output("out", ov::element::f32, {2, cols})+ .attr<float>("eps", eps)+ .build();++ std::vector<float> x{1, 2, 3, 4, -2, 0, 2, 8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, cols}, x)}});++ std::vector<float> expected(x.size());+ for (size_t r = 0; r < 2; ++r) {+ float mean = 0.f;+ for (size_t c = 0; c < cols; ++c)+ mean += x[r * cols + c];+ mean /= cols;+ float var = 0.f;+ for (size_t c = 0; c < cols; ++c)+ var += (x[r * cols + c] - mean) * (x[r * cols + c] - mean);+ var /= cols;+ float inv = 1.0f / std::sqrt(var + eps);+ for (size_t c = 0; c < cols; ++c)+ expected[r * cols + c] = (x[r * cols + c] - mean) * inv;+ }+ expect_near(out, expected, 1e-4f);+}++// L2 norm over the last axis: x / max(sqrt(sum(x^2)), eps).+TEST(GGUFOps, L2Norm) {+ const float eps = 1e-12f;+ const size_t cols = 4;+ auto model = SingleOpBuilder()+ .op("GGML_OP_L2_NORM")+ .input("x", ov::element::f32, {2, cols})+ .output("out", ov::element::f32, {2, cols})+ .attr<float>("eps", eps)+ .build();++ std::vector<float> x{1, 2, 3, 4, -1, -2, -3, -4};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, cols}, x)}});++ std::vector<float> expected(x.size());+ for (size_t r = 0; r < 2; ++r) {+ float ss = 0.f;+ for (size_t c = 0; c < cols; ++c)+ ss += x[r * cols + c] * x[r * cols + c];+ float denom = std::max(std::sqrt(ss), eps);+ for (size_t c = 0; c < cols; ++c)+ expected[r * cols + c] = x[r * cols + c] / denom;+ }+ expect_near(out, expected, 1e-4f);+}++// SumRows: reduce-sum over the last axis, keeping rank.+TEST(GGUFOps, SumRows) {+ const size_t cols = 4;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SUM_ROWS")+ .input("x", ov::element::f32, {2, cols})+ .output("out", ov::element::f32, {2, 1})+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, cols}, x)}});++ std::vector<float> expected{1 + 2 + 3 + 4, 5 + 6 + 7 + 8};+ expect_near(out, expected);+}++// Concat: join two inputs along a ggml axis (here ggml dim 0 == innermost == OV last axis).+TEST(GGUFOps, Concat) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_CONCAT")+ .input("a", ov::element::f32, {2, 3})+ .input("b", ov::element::f32, {2, 2})+ .output("out", ov::element::f32, {2, 5})+ .attr<int>("concat_axis", 0)+ .build();++ std::vector<float> a{1, 2, 3, 4, 5, 6};+ std::vector<float> b{7, 8, 9, 10};+ auto out = run_on_cpu(model, {{"a", make_f32_tensor({2, 3}, a)}, {"b", make_f32_tensor({2, 2}, b)}});++ // Row-wise concat on the last axis: [1,2,3 | 7,8], [4,5,6 | 9,10].+ std::vector<float> expected{1, 2, 3, 7, 8, 4, 5, 6, 9, 10};+ expect_near(out, expected);+}++// Argsort: indices that sort the last axis; output is integer indices, checked manually.+TEST(GGUFOps, Argsort) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_ARGSORT")+ .input("x", ov::element::f32, {1, 1, 2, 4})+ .output("out", ov::element::i32, {1, 1, 2, 4})+ .attr<int>("sort_order", 0) // ascending+ .build();++ std::vector<float> x{4, 1, 3, 2, 10, 40, 20, 30};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 4}, x)}});++ ASSERT_EQ(out.get_element_type(), ov::element::i32);+ ASSERT_EQ(out.get_size(), 8u);+ const int32_t* a = out.data<int32_t>();+ // Row 0: values 4,1,3,2 -> ascending indices 1,3,2,0. Row 1: 10,40,20,30 -> 0,2,3,1.+ std::vector<int32_t> expected{1, 3, 2, 0, 0, 2, 3, 1};+ for (size_t i = 0; i < expected.size(); ++i)+ EXPECT_EQ(a[i], expected[i]) << "mismatch at index " << i;+}++// Transpose with an explicit decoder-supplied permutation (perm attribute).+TEST(GGUFOps, TransposePerm) {+ // Swap the last two axes of a [1,1,2,3] tensor -> [1,1,3,2].+ auto model = SingleOpBuilder()+ .op("GGML_OP_TRANSPOSE")+ .input("x", ov::element::f32, {1, 1, 2, 3})+ .output("out", ov::element::f32, {1, 1, 3, 2})+ .attr<std::vector<int64_t>>("perm", {0, 1, 3, 2})+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 3}, x)}});++ // [[1,2,3],[4,5,6]] -> [[1,4],[2,5],[3,6]]+ std::vector<float> expected{1, 4, 2, 5, 3, 6};+ expect_near(out, expected);+}++// Repeat: tile src to fill the output shape (integer multiples per axis).+TEST(GGUFOps, Repeat) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_REPEAT")+ .input("x", ov::element::f32, {1, 1, 1, 3})+ .output("out", ov::element::f32, {1, 1, 2, 3})+ .build();++ std::vector<float> x{1, 2, 3};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 1, 3}, x)}});++ std::vector<float> expected{1, 2, 3, 1, 2, 3};+ expect_near(out, expected);+}++// AddId: gather bias rows by ids and add to input (MoE bias).+TEST(GGUFOps, AddId) {+ // input [1, n_token=2, n_used=1, n_embd=3]; bias [1,1,n_expert=3,n_embd=3]; ids [1,1,2,1].+ auto model = SingleOpBuilder()+ .op("GGML_OP_ADD_ID")+ .input("x", ov::element::f32, {1, 2, 1, 3})+ .input("bias", ov::element::f32, {1, 1, 3, 3})+ .input("ids", ov::element::i32, {1, 1, 2, 1})+ .output("out", ov::element::f32, {1, 2, 1, 3})+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6};+ std::vector<float> bias{10, 20, 30, 40, 50, 60, 70, 80, 90}; // experts 0,1,2+ std::vector<int32_t> ids{2, 0}; // token0->expert2, token1->expert0++ ov::Tensor ids_t(ov::element::i32, ov::Shape{1, 1, 2, 1});+ std::copy(ids.begin(), ids.end(), ids_t.data<int32_t>());+ auto out = run_on_cpu(model,+ {{"x", make_f32_tensor({1, 2, 1, 3}, x)},+ {"bias", make_f32_tensor({1, 1, 3, 3}, bias)},+ {"ids", ids_t}});++ // token0 += expert2 (70,80,90); token1 += expert0 (10,20,30)+ std::vector<float> expected{1 + 70, 2 + 80, 3 + 90, 4 + 10, 5 + 20, 6 + 30};+ expect_near(out, expected);+}++// Pad: constant (zero) pad on the last axis.+TEST(GGUFOps, Pad) {+ // Pad last axis by 1 at the end: op_params[0]=begin(dim0), [1]=end(dim0) in ggml order.+ // ggml dim0 is the innermost == OV last axis. pads_begin/end mapping in the op: pad end of last+ // axis is pads[1].+ auto model = SingleOpBuilder()+ .op("GGML_OP_PAD")+ .input("x", ov::element::f32, {1, 1, 2, 2})+ .output("out", ov::element::f32, {1, 1, 2, 3})+ .attr<std::vector<int32_t>>("pad_params", {0, 1, 0, 0, 0, 0, 0, 0})+ .attr<bool>("pad_circular", false)+ .build();++ std::vector<float> x{1, 2, 3, 4};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 2}, x)}});++ // Each row [a,b] -> [a,b,0]+ std::vector<float> expected{1, 2, 0, 3, 4, 0};+ expect_near(out, expected);+}++// SwiGLU-OAI (gpt-oss): clamped, alpha-scaled gated SiLU times (clamped up + 1).+TEST(GGUFOps, SwigluOai) {+ const float alpha = 1.702f, limit = 7.0f;+ auto model = SingleOpBuilder()+ .op("GGML_GLU_OP_SWIGLU_OAI")+ .input("x", ov::element::f32, {2, 8})+ .output("out", ov::element::f32, {2, 4})+ .attr<bool>("swapped", false)+ .attr<float>("glu_alpha", alpha)+ .attr<float>("glu_limit", limit)+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8, -1, -2, -3, -4, 0.5f, 1.5f, 2.5f, 9};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 8}, x)}});++ std::vector<float> expected(8);+ for (size_t r = 0; r < 2; ++r) {+ for (size_t c = 0; c < 4; ++c) {+ float g = x[r * 8 + c];+ float u = x[r * 8 + 4 + c];+ float gate = std::min(g, limit);+ float glu = gate / (1.0f + std::exp(-(gate * alpha)));+ float up = std::min(std::max(u, -limit), limit);+ expected[r * 4 + c] = glu * (up + 1.0f);+ }+ }+ expect_near(out, expected, 1e-4f);+}++// MulMatId (generic dequantized experts): per-token expert matmul.+TEST(GGUFOps, MulMatId) {+ // weights [1, n_expert=2, m=2, k=3]; activations [1, n_tokens=2, 1, k=3];+ // ids [1, 1, n_tokens=2, n_used=1]; output [1, 1, n_tokens=2, m=2] (n_used collapsed).+ const int64_t n_expert = 2, m = 2, k = 3, n_tokens = 2;+ auto model = SingleOpBuilder()+ .op("GGML_OP_MUL_MAT_ID")+ .input("w", ov::element::f32, {1, n_expert, m, k})+ .input("a", ov::element::f32, {1, n_tokens, 1, k})+ .input("ids", ov::element::i32, {1, 1, n_tokens, 1})+ .output("out", ov::element::f32, {1, 1, n_tokens, m})+ .build();++ // expert 0 rows: [1,2,3],[4,5,6]; expert 1 rows: [7,8,9],[10,11,12]+ std::vector<float> w{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};+ std::vector<float> a{1, 0, 1, 0, 1, 0}; // token0 act=[1,0,1], token1 act=[0,1,0]+ std::vector<int32_t> ids{1, 0}; // token0 -> expert1, token1 -> expert0++ ov::Tensor ids_t(ov::element::i32, ov::Shape{1, 1, (size_t)n_tokens, 1});+ std::copy(ids.begin(), ids.end(), ids_t.data<int32_t>());+ auto out = run_on_cpu(model,+ {{"w", make_f32_tensor({1, (size_t)n_expert, (size_t)m, (size_t)k}, w)},+ {"a", make_f32_tensor({1, (size_t)n_tokens, 1, (size_t)k}, a)},+ {"ids", ids_t}});++ // token0 (expert1, act [1,0,1]): row0 dot = 7+9=16, row1 dot = 10+12=22+ // token1 (expert0, act [0,1,0]): row0 dot = 2, row1 dot = 5+ std::vector<float> expected{16, 22, 2, 5};+ expect_near(out, expected, 1e-4f);+}++// MulMatId with n_used=2 (multiple experts per token): output [1, n_tokens, n_used, m].+TEST(GGUFOps, MulMatIdNused2) {+ const int64_t n_expert = 3, m = 2, k = 2, n_tokens = 2, n_used = 2;+ auto model = SingleOpBuilder()+ .op("GGML_OP_MUL_MAT_ID")+ .input("w", ov::element::f32, {1, n_expert, m, k})+ .input("a", ov::element::f32, {1, n_tokens, 1, k})+ .input("ids", ov::element::i32, {1, 1, n_tokens, n_used})+ .output("out", ov::element::f32, {1, n_tokens, n_used, m})+ .build();++ // experts: e0 rows [1,0],[0,1]; e1 rows [2,0],[0,2]; e2 rows [3,0],[0,3]+ std::vector<float> w{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3};+ std::vector<float> a{1, 2, 3, 4}; // token0 act=[1,2], token1 act=[3,4]+ std::vector<int32_t> ids{0, 1, 2, 0}; // tok0 uses experts {0,1}; tok1 uses {2,0}++ ov::Tensor ids_t(ov::element::i32, ov::Shape{1, 1, (size_t)n_tokens, (size_t)n_used});+ std::copy(ids.begin(), ids.end(), ids_t.data<int32_t>());+ auto out = run_on_cpu(model,+ {{"w", make_f32_tensor({1, (size_t)n_expert, (size_t)m, (size_t)k}, w)},+ {"a", make_f32_tensor({1, (size_t)n_tokens, 1, (size_t)k}, a)},+ {"ids", ids_t}});++ // out[token][used][row] = dot(expert(ids[token][used]).row, act[token])+ // tok0 act [1,2]: e0 -> [1*1+0*2, 0*1+1*2]=[1,2]; e1 -> [2,4]+ // tok1 act [3,4]: e2 -> [9,12]; e0 -> [3,4]+ std::vector<float> expected{1, 2, 2, 4, 9, 12, 3, 4};+ expect_near(out, expected, 1e-4f);+}++// GetRows batched gather for MoE routing weights: data [1, n_tok, n_expert, 1], indices+// [1,1,n_tok,n_used] -> per-token gather of n_used of the n_expert probs -> [1, n_tok, n_used, 1].+TEST(GGUFOps, GetRowsMoeWeights) {+ const int64_t n_tok = 2, n_expert = 4, n_used = 2;+ auto model = SingleOpBuilder()+ .op("GGML_OP_GET_ROWS")+ .input("probs", ov::element::f32, {1, n_tok, n_expert, 1})+ .input("ids", ov::element::i32, {1, 1, n_tok, n_used})+ .output("out", ov::element::f32, {1, n_tok, n_used, 1})+ .build();++ // token0 probs [0.1,0.2,0.3,0.4], token1 probs [0.5,0.6,0.7,0.8]+ std::vector<float> probs{0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f};+ std::vector<int32_t> ids{3, 1, 0, 2}; // tok0 picks experts {3,1}; tok1 picks {0,2}++ ov::Tensor ids_t(ov::element::i32, ov::Shape{1, 1, (size_t)n_tok, (size_t)n_used});+ std::copy(ids.begin(), ids.end(), ids_t.data<int32_t>());+ auto out = run_on_cpu(model,+ {{"probs", make_f32_tensor({1, (size_t)n_tok, (size_t)n_expert, 1}, probs)},+ {"ids", ids_t}});++ // tok0: probs[3],probs[1] = 0.4,0.2 ; tok1: probs[0],probs[2] = 0.5,0.7+ std::vector<float> expected{0.4f, 0.2f, 0.5f, 0.7f};+ expect_near(out, expected, 1e-5f);+}++// SsmConv: depthwise causal 1D conv. sx [1, n_s=1, d_inner=2, ncs=4], weight [1,1,2,d_conv=3]+// -> out [1, 1, n_t=2, 2].+TEST(GGUFOps, SsmConv) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_SSM_CONV")+ .input("sx", ov::element::f32, {1, 1, 2, 4})+ .input("c", ov::element::f32, {1, 1, 2, 3})+ .output("out", ov::element::f32, {1, 1, 2, 2})+ .build();++ // channel 0 sx = [1,2,3,4], channel 1 sx = [5,6,7,8]+ std::vector<float> sx{1, 2, 3, 4, 5, 6, 7, 8};+ // channel 0 filter = [1,0,0], channel 1 filter = [0,0,1]+ std::vector<float> c{1, 0, 0, 0, 0, 1};+ auto out = run_on_cpu(model, {{"sx", make_f32_tensor({1, 1, 2, 4}, sx)}, {"c", make_f32_tensor({1, 1, 2, 3}, c)}});++ // Depthwise conv, kernel size 3, 2 output positions:+ // ch0 (filter [1,0,0]): pos0 = 1*1+2*0+3*0 = 1 ; pos1 = 2*1+3*0+4*0 = 2+ // ch1 (filter [0,0,1]): pos0 = 5*0+6*0+7*1 = 7 ; pos1 = 6*0+7*0+8*1 = 8+ // Output layout [1,1,n_t,d_inner]: [[ch0_p0,ch1_p0],[ch0_p1,ch1_p1]] = [1,7, 2,8]+ std::vector<float> expected{1, 7, 2, 8};+ expect_near(out, expected, 1e-4f);+}++// Softmax with attention sinks (gpt-oss): a 2nd input shaped [1,1,1,n_head] is a per-head sink,+// NOT a mask. It is appended as one hidden logit column, softmax runs over the widened last axis,+// and the sink column is dropped -- so each row sums to (1 - sink_weight) instead of 1.+TEST(GGUFOps, SoftMaxSinks) {+ // logits [1, n_head=2, T=1, Kd=3]; sinks [1,1,1,n_head=2].+ const size_t n_head = 2, T = 1, Kd = 3;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SOFT_MAX")+ .input("x", ov::element::f32, {1, n_head, T, Kd})+ .input("sinks", ov::element::f32, {1, 1, 1, n_head})+ .output("out", ov::element::f32, {1, n_head, T, Kd})+ .attr<float>("scale", 1.0f)+ .attr<float>("max_bias", 0.0f)+ .build();++ std::vector<float> x{1, 2, 3, 3, 2, 1}; // head0 row [1,2,3], head1 row [3,2,1]+ std::vector<float> sinks{0.5f, -0.5f}; // one sink logit per head+ ov::Tensor sinks_t(ov::element::f32, ov::Shape{1, 1, 1, n_head});+ std::copy(sinks.begin(), sinks.end(), sinks_t.data<float>());+ auto out =+ run_on_cpu(model, {{"x", make_f32_tensor({1, n_head, T, Kd}, x)}, {"sinks", sinks_t}});++ // Reference: softmax over [logits..., sink] then drop the sink column.+ std::vector<float> expected(n_head * T * Kd);+ for (size_t h = 0; h < n_head; ++h) {+ std::vector<float> z{x[h * Kd + 0], x[h * Kd + 1], x[h * Kd + 2], sinks[h]};+ float mx = *std::max_element(z.begin(), z.end());+ float sum = 0.f;+ for (float& v : z) {+ v = std::exp(v - mx);+ sum += v;+ }+ for (size_t k = 0; k < Kd; ++k)+ expected[h * Kd + k] = z[k] / sum; // sink column (z[3]) dropped+ }+ expect_near(out, expected, 1e-5f);+}++// Softmax with BOTH a mask and attention sinks (3 inputs): mask add, then sink column.+TEST(GGUFOps, SoftMaxMaskAndSinks) {+ const size_t n_head = 2, T = 1, Kd = 3;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SOFT_MAX")+ .input("x", ov::element::f32, {1, n_head, T, Kd})+ .input("mask", ov::element::f32, {1, 1, T, Kd})+ .input("sinks", ov::element::f32, {1, 1, 1, n_head})+ .output("out", ov::element::f32, {1, n_head, T, Kd})+ .attr<float>("scale", 1.0f)+ .attr<float>("max_bias", 0.0f)+ .build();++ std::vector<float> x{1, 2, 3, 3, 2, 1};+ std::vector<float> mask{0, 0, -1e9f}; // last key position masked out+ std::vector<float> sinks{0.5f, -0.5f};+ ov::Tensor sinks_t(ov::element::f32, ov::Shape{1, 1, 1, n_head});+ std::copy(sinks.begin(), sinks.end(), sinks_t.data<float>());+ auto out = run_on_cpu(model,+ {{"x", make_f32_tensor({1, n_head, T, Kd}, x)},+ {"mask", make_f32_tensor({1, 1, T, Kd}, mask)},+ {"sinks", sinks_t}});++ std::vector<float> expected(n_head * T * Kd);+ for (size_t h = 0; h < n_head; ++h) {+ std::vector<float> z{x[h * Kd + 0] + mask[0], x[h * Kd + 1] + mask[1], x[h * Kd + 2] + mask[2], sinks[h]};+ float mx = *std::max_element(z.begin(), z.end());+ float sum = 0.f;+ for (float& v : z) {+ v = std::exp(v - mx);+ sum += v;+ }+ for (size_t k = 0; k < Kd; ++k)+ expected[h * Kd + k] = z[k] / sum;+ }+ expect_near(out, expected, 1e-5f);+}++// RESHAPE op_case 3: flatten-for-SET_ROWS, [F, tok, 1, 1] -> [1, F*tok?, -1, 1] with the token+// count landing on the dynamic axis (constant folds to the static output shape here). Verifies the+// (previously stubbed) case emits a correct reshape rather than throwing.+TEST(GGUFOps, ReshapeCase3) {+ // input [1,1,tok=2,F=4] -> output [1, F=4, tok=2, 1] (op_case 3 places -1 on the token axis).+ auto model = SingleOpBuilder()+ .op("GGML_OP_RESHAPE")+ .input("x", ov::element::f32, {1, 1, 2, 4})+ .output("out", ov::element::f32, {1, 4, 2, 1})+ .op_case(3)+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({1, 1, 2, 4}, x)}});+ // Row-major reshape preserves element order.+ expect_near(out, x, 0.0f);+}++// SET_ROWS into a flattened KV-cache row (row_size taken from the dst input, not the op output):+// dst cache [1,1,ctx=3,row=2], data [1,1,n=2,row=2] written at indices {2,0}.+TEST(GGUFOps, SetRowsFlattenedCache) {+ const size_t ctx = 3, row = 2, n = 2;+ auto model = SingleOpBuilder()+ .op("GGML_OP_SET_ROWS")+ .input("data", ov::element::f32, {1, 1, n, row})+ .input("ind", ov::element::i64, {1, 1, 1, n})+ .input("dst", ov::element::f32, {1, 1, ctx, row})+ .output("out", ov::element::f32, {1, 1, ctx, row})+ .build();++ std::vector<float> data{10, 11, 20, 21}; // row for idx target 2, then idx target 0+ std::vector<int64_t> ind{2, 0};+ std::vector<float> dst(ctx * row, -1.0f);++ ov::Tensor ind_t(ov::element::i64, ov::Shape{1, 1, 1, n});+ std::copy(ind.begin(), ind.end(), ind_t.data<int64_t>());+ auto out = run_on_cpu(model,+ {{"data", make_f32_tensor({1, 1, n, row}, data)},+ {"ind", ind_t},+ {"dst", make_f32_tensor({1, 1, ctx, row}, dst)}});++ // data row0 -> dst[ind[0]=2] = [10,11]; data row1 -> dst[ind[1]=0] = [20,21]; idx1 untouched.+ std::vector<float> expected{20, 21, -1, -1, 10, 11};+ expect_near(out, expected, 0.0f);+}++// Reference for the frontend's make_sin_cos on the NEOX (non-imrope) path: for a single position p,+// theta[j] = p * freq_scale * factor[j], factor[0]=1, factor[j]=theta_scale^j,+// theta_scale = freq_base^(-2/n_dims); cos/sin scaled by attn_factor. ext_factor is 0 here.+static void neox_ref_cos_sin(int n_dims,+ float freq_base,+ float freq_scale,+ float attn_factor,+ int pos,+ std::vector<float>& cos_out,+ std::vector<float>& sin_out) {+ const int half = n_dims / 2;+ const float theta_scale = std::pow(freq_base, -2.0f / n_dims);+ cos_out.resize(half);+ sin_out.resize(half);+ float factor = 1.0f;+ for (int j = 0; j < half; ++j) {+ const float theta = pos * freq_scale * factor;+ cos_out[j] = std::cos(theta) * attn_factor;+ sin_out[j] = std::sin(theta) * attn_factor;+ factor *= theta_scale;+ }+}++// RoPE NEOX partial rotary (gemma4 MatFormer): head_dim=6 but only the first n_dims=4 are rotated;+// elements [4,6) pass through unchanged. Drives the real make_sin_cos path (data + pos), so the fix+// (Slice rot-block / pass-through remainder) is exercised end-to-end through the op.+TEST(GGUFOps, RopeNeoxPartialRotary) {+ const int64_t head_dim = 6, n_rot = 4, T = 1, n_head = 1, pos = 2;+ RopeConfig cfg;+ cfg.n_dims = static_cast<int>(n_rot);+ cfg.freq_base = 10000.0f;+ cfg.freq_scale = 1.0f;+ cfg.ext_factor = 0.0f;+ cfg.attn_factor = 1.0f;+ cfg.n_ctx_orig = 4096;+ const int op_case = (1 << 16); // NEOX mode lives in the op_case high 16 bits.++ auto model = SingleOpBuilder()+ .op("GGML_OP_ROPE")+ .input("data", ov::element::f32, {1, T, n_head, head_dim})+ .input("pos", ov::element::i32, {1, 1, 1, T})+ .output("out", ov::element::f32, {1, T, n_head, head_dim})+ .op_case(op_case)+ .attr<RopeConfig>("rope_config", cfg)+ .build();++ std::vector<float> data{1, 2, 3, 4, 100, 200}; // [d0,d1, d2,d3, p0,p1]; only d0..d3 rotate.+ ov::Tensor pos_t(ov::element::i32, ov::Shape{1, 1, 1, (size_t)T});+ pos_t.data<int32_t>()[0] = pos;+ auto out = run_on_cpu(model,+ {{"data", make_f32_tensor({1, (size_t)T, (size_t)n_head, (size_t)head_dim}, data)},+ {"pos", pos_t}});++ std::vector<float> cos_v, sin_v;+ neox_ref_cos_sin(static_cast<int>(n_rot), cfg.freq_base, cfg.freq_scale, cfg.attn_factor, pos, cos_v, sin_v);+ // NEOX split of the rotary block [d0,d1,d2,d3]: x0=[d0,d1], x1=[d2,d3].+ // first = x0*cos - x1*sin ; second = x0*sin + x1*cos ; then pass-through [100,200].+ std::vector<float> expected(head_dim);+ for (int j = 0; j < 2; ++j) {+ expected[j] = data[j] * cos_v[j] - data[j + 2] * sin_v[j];+ expected[j + 2] = data[j] * sin_v[j] + data[j + 2] * cos_v[j];+ }+ expected[4] = 100; // pass-through remainder unchanged+ expected[5] = 200;+ expect_near(out, expected, 1e-4f);+}++// RoPE NEOX full rotary (n_dims == head_dim): no pass-through remainder (regression guard that the+// partial-rotary change did not alter the common full-head path).+TEST(GGUFOps, RopeNeoxFullRotary) {+ const int64_t head_dim = 4, T = 1, n_head = 1, pos = 3;+ RopeConfig cfg;+ cfg.n_dims = static_cast<int>(head_dim);+ cfg.freq_base = 10000.0f;+ cfg.freq_scale = 1.0f;+ cfg.ext_factor = 0.0f;+ cfg.attn_factor = 1.0f;+ cfg.n_ctx_orig = 4096;+ const int op_case = (1 << 16);++ auto model = SingleOpBuilder()+ .op("GGML_OP_ROPE")+ .input("data", ov::element::f32, {1, T, n_head, head_dim})+ .input("pos", ov::element::i32, {1, 1, 1, T})+ .output("out", ov::element::f32, {1, T, n_head, head_dim})+ .op_case(op_case)+ .attr<RopeConfig>("rope_config", cfg)+ .build();++ std::vector<float> data{1, 2, 3, 4};+ ov::Tensor pos_t(ov::element::i32, ov::Shape{1, 1, 1, (size_t)T});+ pos_t.data<int32_t>()[0] = pos;+ auto out = run_on_cpu(model,+ {{"data", make_f32_tensor({1, (size_t)T, (size_t)n_head, (size_t)head_dim}, data)},+ {"pos", pos_t}});++ std::vector<float> cos_v, sin_v;+ neox_ref_cos_sin(static_cast<int>(head_dim), cfg.freq_base, cfg.freq_scale, cfg.attn_factor, pos, cos_v, sin_v);+ std::vector<float> expected(head_dim);+ for (int j = 0; j < 2; ++j) {+ expected[j] = data[j] * cos_v[j] - data[j + 2] * sin_v[j];+ expected[j + 2] = data[j] * sin_v[j] + data[j + 2] * cos_v[j];+ }+ expect_near(out, expected, 1e-4f);+}++// The f4e2m1 nibble -> value lookup used by the packed MXFP4 dequant (mirrors mul_mat_id.cpp).+static const float kF4E2M1[16] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,+ -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f};++// MUL_MAT_ID over PACKED MXFP4 experts (gpt-oss MoE): expert weights are raw u8 rank-5 blocks+// [1, n_expert, m, k_blocks, 17] (byte0 = e8m0 scale exponent, bytes1..16 = 32 nibble-packed+// f4e2m1 quants). The dequant (nibble unpack + LUT + 2^(exp-127) scale) runs on-graph. This test+// builds real MXFP4 block bytes and checks the per-token expert matmul against a plain reference.+TEST(GGUFOps, MulMatIdMxfp4Packed) {+ const int64_t n_expert = 2, m = 2, k_blocks = 1, qk = 32, cols = k_blocks * qk, n_tokens = 2;+ const uint8_t scale_exp = 127; // e8m0 127 -> 2^(127-127) = 1.0+ const float scale = 1.0f;++ // Choose nibble codes per (expert,row,element). Keep it simple: each row's first element is a+ // distinct nonzero code, the rest zero, so the matmul isolates one activation lane.+ // codes[e][row][col] in [0,15].+ auto code = [&](int e, int row, int col) -> uint8_t {+ if (col != 0) {+ return 0; // f4 value 0.0+ }+ // expert0 row0 -> 2 (=1.0), row1 -> 4 (=2.0); expert1 row0 -> 5 (=3.0), row1 -> 6 (=4.0)+ static const uint8_t tbl[2][2] = {{2, 4}, {5, 6}};+ return tbl[e][row];+ };++ // Pack into [n_expert, m, k_blocks, 17] u8 (rank-5 with leading 1).+ const size_t block_bytes = 17;+ std::vector<uint8_t> packed(n_expert * m * k_blocks * block_bytes, 0);+ for (int e = 0; e < n_expert; ++e) {+ for (int row = 0; row < m; ++row) {+ size_t base = ((e * m + row) * k_blocks + 0) * block_bytes;+ packed[base + 0] = scale_exp;+ // 16 quant bytes, each low nibble = element 2*b, high nibble = element 2*b+1.+ for (int b = 0; b < 16; ++b) {+ uint8_t lo = code(e, row, 2 * b);+ uint8_t hi = code(e, row, 2 * b + 1);+ packed[base + 1 + b] = static_cast<uint8_t>((hi << 4) | (lo & 0x0F));+ }+ }+ }++ auto model = SingleOpBuilder()+ .op("GGML_OP_MUL_MAT_ID")+ .input("w", ov::element::u8, {1, n_expert, m, k_blocks, block_bytes})+ .input("a", ov::element::f32, {1, n_tokens, 1, cols})+ .input("ids", ov::element::i32, {1, 1, n_tokens, 1})+ .output("out", ov::element::f32, {1, 1, n_tokens, m})+ .build();++ // activations: token0 = e0 pattern, token1 = e1 pattern; only lane 0 is nonzero.+ std::vector<float> a(n_tokens * cols, 0.0f);+ a[0 * cols + 0] = 1.0f; // token0 act lane0 = 1+ a[1 * cols + 0] = 1.0f; // token1 act lane0 = 1+ std::vector<int32_t> ids{1, 0}; // token0 -> expert1, token1 -> expert0++ ov::Tensor w_t(ov::element::u8, ov::Shape{1, (size_t)n_expert, (size_t)m, (size_t)k_blocks, block_bytes});+ std::memcpy(w_t.data<uint8_t>(), packed.data(), packed.size());+ ov::Tensor ids_t(ov::element::i32, ov::Shape{1, 1, (size_t)n_tokens, 1});+ std::copy(ids.begin(), ids.end(), ids_t.data<int32_t>());+ auto out = run_on_cpu(model,+ {{"w", w_t},+ {"a", make_f32_tensor({1, (size_t)n_tokens, 1, (size_t)cols}, a)},+ {"ids", ids_t}});++ // Reference: out[token][row] = sum_col dequant(expert=ids[token], row, col) * act[token][col].+ auto dequant = [&](int e, int row, int col) -> float {+ return kF4E2M1[code(e, row, col)] * scale;+ };+ std::vector<float> expected(n_tokens * m);+ for (int t = 0; t < n_tokens; ++t) {+ int e = ids[t];+ for (int row = 0; row < m; ++row) {+ float acc = 0.f;+ for (int col = 0; col < cols; ++col)+ acc += dequant(e, row, col) * a[t * cols + col];+ expected[t * m + row] = acc;+ }+ }+ // token0 (expert1): row0=3.0*1=3, row1=4.0*1=4 ; token1 (expert0): row0=1.0, row1=2.0+ expect_near(out, expected, 1e-4f);+}++// MulMat: batched matmul A @ B^T. The translator binds B=input(0), A=input(1) and emits+// MatMul(A, B, transpose_b=true), so out[t][n] = sum_k a[t][k] * b[n][k].+TEST(GGUFOps, MulMat) {+ // b (weight) [1,1,N=2,K=3]; a (activation) [1,1,T=2,K=3]; out [1,1,T=2,N=2].+ auto model = SingleOpBuilder()+ .op("GGML_OP_MUL_MAT")+ .input("b", ov::element::f32, {1, 1, 2, 3})+ .input("a", ov::element::f32, {1, 1, 2, 3})+ .output("out", ov::element::f32, {1, 1, 2, 2})+ .build();++ std::vector<float> b{1, 2, 3, 4, 5, 6}; // rows n0=[1,2,3], n1=[4,5,6]+ std::vector<float> a{1, 0, 1, 0, 1, 0}; // tokens t0=[1,0,1], t1=[0,1,0]+ auto out = run_on_cpu(model, {{"b", make_f32_tensor({1, 1, 2, 3}, b)}, {"a", make_f32_tensor({1, 1, 2, 3}, a)}});++ // t0=[1,0,1]: n0=1+3=4, n1=4+6=10 ; t1=[0,1,0]: n0=2, n1=5+ std::vector<float> expected{4, 10, 2, 5};+ expect_near(out, expected, 1e-4f);+}++// FlashAttnExt: scaled-dot-product attention. Inputs q,k,v,mask; output softmax(q@k^T*scale + mask)@v+// transposed to [1,T,H,D]. The op runs the SDPA in fp16 internally, so the tolerance is fp16-scale.+TEST(GGUFOps, FlashAttnExt) {+ // q [1,H=1,T=2,D=2]; k,v [1,H=1,Tk=2,D=2]; mask [1,1,T=2,Tk=2]. scale = 1.0.+ const float scale = 1.0f;+ auto model = SingleOpBuilder()+ .op("GGML_OP_FLASH_ATTN_EXT")+ .input("q", ov::element::f32, {1, 1, 2, 2})+ .input("k", ov::element::f32, {1, 1, 2, 2})+ .input("v", ov::element::f32, {1, 1, 2, 2})+ .input("mask", ov::element::f32, {1, 1, 2, 2})+ .output("out", ov::element::f32, {1, 2, 1, 2})+ .attr<float>("scale", scale)+ .build();++ std::vector<float> q{1, 0, 0, 1};+ std::vector<float> k{1, 0, 0, 1};+ std::vector<float> v{1, 2, 3, 4};+ std::vector<float> mask{0, 0, 0, 0};+ auto out = run_on_cpu(model,+ {{"q", make_f32_tensor({1, 1, 2, 2}, q)},+ {"k", make_f32_tensor({1, 1, 2, 2}, k)},+ {"v", make_f32_tensor({1, 1, 2, 2}, v)},+ {"mask", make_f32_tensor({1, 1, 2, 2}, mask)}});++ // Reference SDPA (H=1). scores[t][s] = scale * dot(q[t], k[s]) + mask[t][s]; softmax over s;+ // out[t][d] = sum_s p[t][s] * v[s][d]. Output layout [1,T,1,D] == flat over (t,d).+ const int T = 2, Tk = 2, D = 2;+ std::vector<float> expected(T * D);+ for (int t = 0; t < T; ++t) {+ std::vector<float> z(Tk);+ float mx = -1e30f;+ for (int s = 0; s < Tk; ++s) {+ float dot = 0.f;+ for (int d = 0; d < D; ++d)+ dot += q[t * D + d] * k[s * D + d];+ z[s] = scale * dot + mask[t * Tk + s];+ mx = std::max(mx, z[s]);+ }+ float sum = 0.f;+ for (int s = 0; s < Tk; ++s) {+ z[s] = std::exp(z[s] - mx);+ sum += z[s];+ }+ for (int d = 0; d < D; ++d) {+ float acc = 0.f;+ for (int s = 0; s < Tk; ++s)+ acc += (z[s] / sum) * v[s * D + d];+ expected[t * D + d] = acc;+ }+ }+ expect_near(out, expected, 2e-2f); // fp16 SDPA+}++// GatedDeltaNet (qwen3next linear attention) as a recurrent scan. Minimal scalar case+// B=H=S=1, T=2 exercises the full per-token gated delta update + output packing+// [attn_t0, attn_t1, final_state].+TEST(GGUFOps, GatedDeltaNet) {+ const int64_t B = 1, T = 2, H = 1, S = 1;+ auto shp = ov::PartialShape{B, T, H, S};+ auto model = SingleOpBuilder()+ .op("GGML_OP_GATED_DELTA_NET")+ .input("q", ov::element::f32, shp)+ .input("k", ov::element::f32, shp)+ .input("v", ov::element::f32, shp)+ .input("g", ov::element::f32, shp)+ .input("beta", ov::element::f32, shp)+ .input("state", ov::element::f32, {1, 1, 1, 1})+ .output("out", ov::element::f32, {1, 1, T * B + S * B, S * H})+ .build();++ // Per-token scalars (see reference math below). g2 = ln(2) so exp(g)=2.+ const float ln2 = std::log(2.0f);+ std::vector<float> q{2, 1}, k{1, 2}, v{3, 1}, g{0, ln2}, beta{0.5f, 1};+ std::vector<float> state0{0};+ auto out = run_on_cpu(model,+ {{"q", make_f32_tensor({1, (size_t)T, 1, 1}, q)},+ {"k", make_f32_tensor({1, (size_t)T, 1, 1}, k)},+ {"v", make_f32_tensor({1, (size_t)T, 1, 1}, v)},+ {"g", make_f32_tensor({1, (size_t)T, 1, 1}, g)},+ {"beta", make_f32_tensor({1, (size_t)T, 1, 1}, beta)},+ {"state", make_f32_tensor({1, 1, 1, 1}, state0)}});++ // Scalar recurrence (scale = 1/sqrt(S) = 1):+ // decayed = state * exp(g); delta = (v - decayed*k) * beta;+ // state' = decayed + delta*k; attn = state' * q.+ float state = state0[0];+ std::vector<float> expected;+ for (int t = 0; t < T; ++t) {+ float decayed = state * std::exp(g[t]);+ float delta = (v[t] - decayed * k[t]) * beta[t];+ state = decayed + delta * k[t];+ expected.push_back(state * q[t]); // attn_t+ }+ expected.push_back(state); // final state, packed after the attn outputs+ expect_near(out, expected, 1e-4f);+}++// Im2col 1D: unfold a width-KW sliding window over the innermost image axis. For IC=1, stride=1,+// no pad/dilation, image [1,2,3] with KW=2 yields the two windows [1,2] and [2,3].+TEST(GGUFOps, Im2col1D) {+ // kernel [1,1,IC=1,KW=2] (only its shape is read); image [1,N=1,1,IW=3]; out [1,1,OW=2,IC*KW=2].+ auto model = SingleOpBuilder()+ .op("GGML_OP_IM2COL")+ .input("kernel", ov::element::f32, {1, 1, 1, 2})+ .input("image", ov::element::f32, {1, 1, 1, 3})+ .output("out", ov::element::f32, {1, 1, 2, 2})+ // {s0,s1,p0,p1,d0,d1,is_2D}: stride 1, no pad, no dilation, 1D.+ .attr<std::vector<int32_t>>("im2col_params", {1, 0, 0, 0, 1, 0, 0})+ .build();++ // The kernel is only read for its shape, so its Parameter is pruned during conversion and has no+ // runtime port -- feed only the image.+ std::vector<float> image{1, 2, 3};+ auto out = run_on_cpu(model, {{"image", make_f32_tensor({1, 1, 1, 3}, image)}});++ // window at ow=0 -> [img0,img1]=[1,2]; ow=1 -> [img1,img2]=[2,3].+ std::vector<float> expected{1, 2, 2, 3};+ expect_near(out, expected, 1e-4f);+}++// Cpy: a ggml copy is a dtype convert to the destination type. i32 -> f32 upcast round-trips+// the integer values exactly.+TEST(GGUFOps, Cpy) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_CPY")+ .input("x", ov::element::i32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .build();++ std::vector<int32_t> x{1, 2, 3, 4, 5, 6, 7, 8};+ ov::Tensor x_t(ov::element::i32, ov::Shape{2, 4});+ std::copy(x.begin(), x.end(), x_t.data<int32_t>());+ auto out = run_on_cpu(model, {{"x", x_t}});++ std::vector<float> expected;+ expected.reserve(x.size());+ for (int32_t v : x) {+ expected.push_back(static_cast<float>(v));+ }+ expect_near(out, expected, 0.0f);+}++// Cont (op_case 1/2): after a PERMUTE/TRANSPOSE the OV tensor is already logically contiguous, so+// CONT is an identity passthrough of its input.+TEST(GGUFOps, Cont) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_CONT")+ .input("x", ov::element::f32, {2, 4})+ .output("out", ov::element::f32, {2, 4})+ .op_case(1) // input from PERMUTE+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 4}, x)}});+ expect_near(out, x, 0.0f);+}++// GeGLU: split the last axis in half -> gelu(a) * b, where gelu is ggml's tanh approximation.+TEST(GGUFOps, GeGLU) {+ auto model = SingleOpBuilder()+ .op("GGML_GLU_OP_GEGLU")+ .input("x", ov::element::f32, {2, 8})+ .output("out", ov::element::f32, {2, 4})+ .attr<bool>("swapped", false)+ .build();++ std::vector<float> x{1, 2, 3, 4, 5, 6, 7, 8, -1, -2, -3, -4, 1, 1, 1, 1};+ auto out = run_on_cpu(model, {{"x", make_f32_tensor({2, 8}, x)}});++ // gelu_tanh(a) = 0.5*a*(1 + tanh(sqrt(2/pi)*(a + 0.044715*a^3)))+ auto gelu_tanh = [](float a) {+ const float pi = 3.14159265358979323846f;+ const float k = std::sqrt(2.0f / pi);+ return 0.5f * a * (1.0f + std::tanh(k * (a + 0.044715f * a * a * a)));+ };+ std::vector<float> expected(8);+ for (size_t r = 0; r < 2; ++r) {+ for (size_t c = 0; c < 4; ++c) {+ float a = x[r * 8 + c];+ float b = x[r * 8 + 4 + c];+ expected[r * 4 + c] = gelu_tanh(a) * b;+ }+ }+ expect_near(out, expected, 1e-3f);+}++// Add1: ggml adds a (broadcast) scalar to the input. The translator is the generic 2-input Add,+// which broadcasts the [1,1] operand across the [2,4] input.+TEST(GGUFOps, Add1) {+ auto model = SingleOpBuilder()+ .op("GGML_OP_ADD1")+ .input("a", ov::element::f32, {2, 4})+ .input("b", ov::element::f32, {1, 1})+ .output("out", ov::element::f32, {2, 4})+ .build();++ std::vector<float> a{1, 2, 3, 4, 5, 6, 7, 8};+ std::vector<float> b{5};+ auto out = run_on_cpu(model, {{"a", make_f32_tensor({2, 4}, a)}, {"b", make_f32_tensor({1, 1}, b)}});++ std::vector<float> expected(a.size());+ for (size_t i = 0; i < a.size(); ++i)+ expected[i] = a[i] + b[0];+ expect_near(out, expected);+}++} // namespacediff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppnew file mode 100644index 00000000000..d7b48316fc0--- /dev/null+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -0,0 +1,192 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// End-to-end tests for weights surfaced as GGML_OP_NONE (leaf) nodes.+//+// A weight is a regular node in the gguf frontend: a ggml leaf (op type "GGML_OP_NONE") that+// the decoder marks as a weight by providing the raw GGUF bytes (get_attribute<ov::Tensor>+// ("data")), the ggml quant type name (get_attribute<std::string>("quant_type")) and the+// logical [rows, cols] shape (get_output_shape()); the frontend's translate_weight does the+// dequant. These tests build a single GGML_OP_NONE model -- exactly like the single-op tests in+// test_ops.cpp -- run it on CPU and compare against the same real-ggml reference data used by+// test_dequant_vs_ggml.cpp.++#include <cmath>+#include <cstring>++#include "op_test_utils.hpp"++using namespace ov_gguf_test;++namespace {++// rows/cols and tolerance match the reference generator (see test_dequant_vs_ggml.cpp).+// Q5_K/Q6_K requantize to channel-wise Q8_0_C (matching the llama.cpp ggml-openvino CPU/GPU+// backend), so they diverge from ggml's faithful to_float by the Q8_0_C round-off rather+// than f16 noise.+constexpr size_t kRows = 4;+constexpr size_t kCols = 256;+constexpr float kTolFaithful = 3e-3f;+constexpr float kTolRequant = 1.5e-2f;+// Q4_K uses an INTEGER (u8) zero-point so the CPU plugin fuses the dequant into the MatMul+// (matching the original ggml-openvino backend); the integer zp diverges from ggml's faithful+// to_float by up to ~0.045 per weight.+constexpr float kTolIntZp = 5e-2f;++struct WeightCase {+ const char* stem; // test_data prefix+ const char* quant_type; // name passed to the frontend+ float tol;+};++ov::Tensor bytes_to_u8_tensor(const std::vector<uint8_t>& bytes) {+ ov::Tensor t(ov::element::u8, ov::Shape{bytes.size()});+ std::memcpy(t.data(), bytes.data(), bytes.size());+ return t;+}++} // namespace++class GGUFWeight : public ::testing::TestWithParam<WeightCase> {};++// Convert a GGML_OP_NONE weight node and check the produced (constant-foldable) dequant against+// ggml's to_float reference.+TEST_P(GGUFWeight, MatchesGgmlToFloat) {+ const WeightCase c = GetParam();+ const auto qbytes = load_npy<uint8_t>(std::string(c.stem) + "_qbytes");+ const auto ref = load_npy<float>(std::string(c.stem) + "_deq");+ ASSERT_EQ(ref.size(), kRows * kCols);++ auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {kRows, kCols})+ .attr<ov::Tensor>("data", bytes_to_u8_tensor(qbytes))+ .attr<std::string>("quant_type", c.quant_type)+ .build();++ // The weight node has no graph inputs; it folds to a constant. Run it to read the values.+ auto out = run_on_cpu(model, {});+ ASSERT_EQ(out.get_size(), ref.size());++ const float* a = out.data<float>();+ float max_diff = 0.f;+ for (size_t i = 0; i < ref.size(); ++i)+ max_diff = std::max(max_diff, std::fabs(a[i] - ref[i]));+ EXPECT_LE(max_diff, c.tol) << c.stem << ": frontend weight dequant diverges from ggml to_float";+}++INSTANTIATE_TEST_SUITE_P(AllQuantTypes,+ GGUFWeight,+ ::testing::Values(WeightCase{"q4_0", "Q4_0", kTolFaithful},+ WeightCase{"q4_1", "Q4_1", kTolFaithful},+ WeightCase{"q5_0", "Q5_0", kTolFaithful},+ WeightCase{"q5_1", "Q5_1", kTolFaithful},+ WeightCase{"q8_0", "Q8_0", kTolFaithful},+ WeightCase{"q2_k", "Q2_K", kTolFaithful},+ WeightCase{"q3_k", "Q3_K", kTolFaithful},+ WeightCase{"q4_k", "Q4_K", kTolIntZp},+ WeightCase{"q5_k", "Q5_K", kTolRequant},+ WeightCase{"q6_k", "Q6_K", kTolRequant}),+ [](const ::testing::TestParamInfo<WeightCase>& i) {+ return std::string(i.param.stem);+ });++// An F16 weight is wrapped directly as a constant (no dequant); round-trips the raw bytes.+TEST(GGUFWeightPlain, F16) {+ std::vector<ov::float16> vals{1.0f, -2.0f, 3.5f, -4.25f, 0.0f, 7.0f};+ ov::Tensor data(ov::element::u8, ov::Shape{vals.size() * sizeof(ov::float16)});+ std::memcpy(data.data(), vals.data(), data.get_byte_size());++ auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {2, 3})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "F16")+ .build();++ auto out = run_on_cpu(model, {});+ ASSERT_EQ(out.get_size(), vals.size());+ const float* a = out.data<float>();+ for (size_t i = 0; i < vals.size(); ++i)+ EXPECT_NEAR(a[i], static_cast<float>(vals[i]), 1e-6f);+}++// An F32 weight is wrapped directly as a Constant (no dequant, no Convert); round-trips exactly.+TEST(GGUFWeightPlain, F32) {+ std::vector<float> vals{1.0f, -2.0f, 3.5f, -4.25f, 0.0f, 7.0f};+ ov::Tensor data(ov::element::u8, ov::Shape{vals.size() * sizeof(float)});+ std::memcpy(data.data(), vals.data(), data.get_byte_size());++ auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {2, 3})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "F32")+ .build();++ auto out = run_on_cpu(model, {});+ ASSERT_EQ(out.get_size(), vals.size());+ const float* a = out.data<float>();+ for (size_t i = 0; i < vals.size(); ++i)+ EXPECT_EQ(a[i], vals[i]);+}++// A BF16 weight is wrapped as a bf16 Constant then Convert'ed to f32 for the translators.+TEST(GGUFWeightPlain, BF16) {+ std::vector<ov::bfloat16> vals{1.0f, -2.0f, 3.5f, -4.25f, 0.0f, 7.0f};+ ov::Tensor data(ov::element::u8, ov::Shape{vals.size() * sizeof(ov::bfloat16)});+ std::memcpy(data.data(), vals.data(), data.get_byte_size());++ auto model = SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {2, 3})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "BF16")+ .build();++ auto out = run_on_cpu(model, {});+ ASSERT_EQ(out.get_size(), vals.size());+ const float* a = out.data<float>();+ for (size_t i = 0; i < vals.size(); ++i)+ EXPECT_NEAR(a[i], static_cast<float>(vals[i]), 1e-6f);+}++// Contract tests for the two ggml types that are NOT supported as stored GGUF *weights*.+//+// Q8_K is a ggml intermediate activation-quantization type: it only ever appears as the+// on-the-fly quantized activation in a dot product, never as a weight tensor stored in a .gguf.+// The frontend therefore does not accept it as a weight -- gguf_type_from_name knows the name+// (so a stray reference is a clear error, not a silent misparse), but make_weight_node has no+// Q8_K path and rejects it. If a future model ever stores Q8_K weights, wire it into the+// make_weight_node switch and turn this into a value test.+TEST(GGUFWeightUnsupported, Q8KIsNotAStoredWeight) {+ // One Q8_K block = 292 bytes covers 256 weights.+ ov::Tensor data(ov::element::u8, ov::Shape{292});+ std::memset(data.data(), 0, data.get_byte_size());+ EXPECT_ANY_THROW({+ SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {1, 256})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "Q8_K")+ .build();+ });+}++// MXFP4 is supported ONLY as rank-5 MoE-packed expert weights ([1,n_expert,m,k_blocks,17]),+// which MUL_MAT_ID dequantizes on-graph (see GGUFOps.MulMatIdMxfp4Packed). A plain 2D MXFP4+// weight is not a shape the frontend produces, so make_weight_node rejects it. This pins that+// the standalone-dequant path is intentionally absent (the packed path is the supported one).+TEST(GGUFWeightUnsupported, Mxfp4TwoDimIsNotAStoredWeight) {+ // 1 block (17 bytes) covers 32 weights.+ ov::Tensor data(ov::element::u8, ov::Shape{17});+ std::memset(data.data(), 0, data.get_byte_size());+ EXPECT_ANY_THROW({+ SingleOpBuilder()+ .op("GGML_OP_NONE")+ .output("w", ov::element::f32, {1, 32})+ .attr<ov::Tensor>("data", data)+ .attr<std::string>("quant_type", "MXFP4")+ .build();+ });+}