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
Normalize raw GGUF weight graphs before repacking (#39428)
Maxim Vafin3276aec72d73
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.mdindex 8f4833fb8b3..6cef246c113 100644--- a/src/frontends/gguf/docs/quantization.md+++ b/src/frontends/gguf/docs/quantization.md@@ -11,6 +11,21 @@ The implementation is in [`gguf.cpp`](../src/quant/gguf.cpp),## Storage and graph conventions+The loader retains one raw descriptor per original tensor, including its logical shape,+GGUF format and mapped payload. Builders emit frontend-only `GGUFConstant` leaves and ordinary+`Concat`, `Slice` and `Gather` operations; they do not unpack or concatenate packed components.+Normalization folds compatible weight-only row concatenations, slices and gathers before+repacking directly into the final code, scale and zero-point buffers. It also combines+compatible two-bit projections sharing an activation. No `GGUFConstant` survives conversion.++Compatible matrix row patterns use the existing native unpacker for each format; plain+row patterns also fold.+Inputs must share their format and conversion policy. Aligned column permutations move complete+quantization groups and may use packed intermediate buffers. Unsupported views, including+unaligned column gathers, retain ordinary graph operations after leaf materialization.+Supplied-decoder weights materialize individually using their existing conversion policy.+Embedding/output policies, quantization groups and zero points are preserved.+The tables below describe the **native `.gguf` input path before device compilation**. The[supplied-decoder path](#supplied-decoder-and-raw-byte-differences) has additional conversions.Mixed checkpoint labels such as `Q4_K_M` select different formats for different tensors; they@@ -358,9 +373,10 @@ For `N` weights of a uniform block format, multiply its OpenVINO bytes per block`N / weights_per_block`. Sum over tensor formats for a mixed checkpoint. This estimatesfrontend payload storage, including per-group metadata.-Native quantized loading allocates independent buffers while reading the memory-mapped-source. Source pages and output buffers can coexist during import; the loader requests-eviction of processed source ranges, but this is not a guarantee about peak resident memory.+Native quantized weights allocate independent buffers when normalization materializes their+memory-mapped source (or when a caller explicitly invokes the unpacking helper). Source pages and output buffers can coexist+during import; the loader requests eviction of processed source ranges, but this is not a+guarantee about peak resident memory.Splitting or reordering projections can also require copies. Constants built from theextracted buffers share those buffers rather than copying each one again.diff --git a/src/frontends/gguf/src/builder/api/graph_context_impl.hpp b/src/frontends/gguf/src/builder/api/graph_context_impl.hppindex 4310fe3ed95..a3620635114 100644--- a/src/frontends/gguf/src/builder/api/graph_context_impl.hpp+++ b/src/frontends/gguf/src/builder/api/graph_context_impl.hpp@@ -18,7 +18,7 @@ namespace ov::frontend::gguf {struct GgufGraphContext::Impl {explicit Impl(const BuildContext& ctx): build_ctx(ctx),- emitter(ctx.weights->weights, ctx.weights->qtypes, ctx.arch, ctx.weights->translators) {}+ emitter(ctx.weights->weights, ctx.arch, ctx.weights->translators) {}BuildContext build_ctx;std::unique_ptr<DecoderConfig> decoder;diff --git a/src/frontends/gguf/src/builder/api/metadata_store.hpp b/src/frontends/gguf/src/builder/api/metadata_store.hppindex 33a3a0686df..3bd864df74c 100644--- a/src/frontends/gguf/src/builder/api/metadata_store.hpp+++ b/src/frontends/gguf/src/builder/api/metadata_store.hpp@@ -31,10 +31,9 @@ struct MetadataAccess {}};-// Borrowed parser weight and quantization tables.+// Borrowed parser weight table.struct WeightStore {- std::unordered_map<std::string, ov::Tensor>& weights;- std::unordered_map<std::string, GgufTensorType>& qtypes;+ const GgufWeightTable& weights;const std::unordered_map<std::string, CreatorFunction>* translators = nullptr;};diff --git a/src/frontends/gguf/src/builder/api/tensor_table.cpp b/src/frontends/gguf/src/builder/api/tensor_table.cppindex 96309b2f32f..edc9a081c5d 100644--- a/src/frontends/gguf/src/builder/api/tensor_table.cpp+++ b/src/frontends/gguf/src/builder/api/tensor_table.cpp@@ -42,7 +42,7 @@ GgufValue GgufTensors::operator()(const std::string& gguf_name) const {if (ov::util::ends_with(gguf_name, ".weight")) {e.add_weight(gguf_name);} else {- e.add_named_weight(gguf_name);+ e.add_weight(gguf_name);}}return GgufValue(gguf_name, e.value(gguf_name));diff --git a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp b/src/frontends/gguf/src/builder/arch/decoder_builder.cppindex feefae6c101..e3897f73516 100644--- a/src/frontends/gguf/src/builder/arch/decoder_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/decoder_builder.cpp@@ -42,7 +42,7 @@ constexpr int64_t D = -1;DecoderBuilder::DecoderBuilder(const BuildContext& context, const DecoderParameters& parameters): m_cfg(parameters, context.weights->weights),- m_emit(context.weights->weights, context.weights->qtypes, context.arch, context.weights->translators),+ m_emit(context.weights->weights, context.arch, context.weights->translators),m_kv(blocks::KvCachePlan::build(m_cfg)) {m_cfg.configure_graph(m_emit, context.metadata);}@@ -252,7 +252,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {auto ffn_norm_r = norm(m_emit, ffn_inp_r, p + m_cfg.ffn_norm_key, p + "ffn_norm", m_cfg.rms_eps);// Mirror the non-recurrent FFN dispatch below: Qwen3-Next is MoE for every trunk layer// (llama.cpp routes both the GDN and full-attention layers through build_moe_ffn), so a- // real model has no per-layer dense FFN tensors here and dense_ffn's weight_tensor lookup+ // real model has no per-layer dense FFN tensors here and dense_ffn's weight lookup// would assert.const bool is_moe_layer_r = m_cfg.layer_is_moe(il);auto down_r = is_moe_layer_r ? blocks::moe_ffn(m_emit, m_cfg, p, ffn_norm_r)@@ -312,7 +312,7 @@ std::string DecoderBuilder::build_layer(int il, const std::string& layer_in) {// Gemma4: per-layer output scale (layer_output_scale.weight is a scalar [1]).if (m_emit.has_weight(p + "layer_output_scale.weight")) {- m_emit.add_named_weight(p + "layer_output_scale.weight");+ m_emit.add_weight(p + "layer_output_scale.weight");cur = m_emit.add_op("GGML_OP_MUL", p + "scaled_out", {cur, p + "layer_output_scale.weight"});}return cur;diff --git a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp b/src/frontends/gguf/src/builder/arch/dspark_builder.cppindex d63b14be17a..12cf895ac00 100644--- a/src/frontends/gguf/src/builder/arch/dspark_builder.cpp+++ b/src/frontends/gguf/src/builder/arch/dspark_builder.cpp@@ -21,7 +21,7 @@ public:explicit DSparkBuilder(const BuildContext& context): m_metadata(context.metadata),m_config(resolve_decoder_parameters(context.metadata, RopeMode::Neox), context.weights->weights),- m_emitter(context.weights->weights, context.weights->qtypes, context.arch, context.weights->translators) {}+ m_emitter(context.weights->weights, context.arch, context.weights->translators) {}std::shared_ptr<GgufGraph> build() override {using ov::element::f32;@@ -75,8 +75,7 @@ public:features.data<float>()[pos * feature_width + feature_width / 2 + i] = std::cos(angle);}}- e.weights()["dspark.log_snr_features"] = features;- e.add_named_weight("dspark.log_snr_features");+ e.add_generated_weight("dspark.log_snr_features", features);auto snr = std::string("dspark.log_snr_features");for (int layer = 1; layer <= 2; ++layer) {const auto name = "dspark.log_snr_fc" + std::to_string(layer);diff --git a/src/frontends/gguf/src/builder/blocks/attention.cpp b/src/frontends/gguf/src/builder/blocks/attention.cppindex acdd69d257f..714abd37c62 100644--- a/src/frontends/gguf/src/builder/blocks/attention.cpp+++ b/src/frontends/gguf/src/builder/blocks/attention.cpp@@ -226,7 +226,7 @@ std::string attention(GraphEmitter& e,if (!cfg.embedding_model || cfg.causal_attention)attn_in.emplace_back(is_swa_layer ? "self_kq_mask_swa" : "self_kq_mask");if (cfg.has_sinks) {- e.add_named_weight(p + "attn_sinks.weight");+ e.add_weight(p + "attn_sinks.weight");attn_in.push_back(p + "attn_sinks.weight");}std::map<std::string, ov::Any> attn_attrs = {{"scale", kq_scale}};@@ -244,11 +244,12 @@ std::string attention(GraphEmitter& e,auto attn_2d = reshape(e, attn, merged_shape, p + "kqv_merged");if (cfg.has_attn_gate) {- const auto& gate_weight = e.weight_tensor(p + (joint_q_gate ? "attn_q.weight" : "attn_gate.weight"));- const bool rank3_gate = gate_weight.get_element_type() != ov::element::u2;+ const auto gate_name = p + (joint_q_gate ? "attn_q.weight" : "attn_gate.weight");+ const auto qtype = e.weight_qtype(gate_name);+ const bool rank3_gate = !gguf_has_u2_weights(qtype);auto gate_width = static_cast<size_t>(q_width);if (!joint_q_gate) {- const auto& gate_shape = gate_weight.get_shape();+ const auto& gate_shape = e.weight_shape(gate_name);OPENVINO_ASSERT(gate_shape.size() == 2 && (gate_shape[0] == static_cast<size_t>(n_head_l) ||gate_shape[0] == static_cast<size_t>(q_width)),"[GGUF] attention gate must have one value per head or per channel");diff --git a/src/frontends/gguf/src/builder/blocks/common.cpp b/src/frontends/gguf/src/builder/blocks/common.cppindex bd89900ae34..29ff485d23e 100644--- a/src/frontends/gguf/src/builder/blocks/common.cpp+++ b/src/frontends/gguf/src/builder/blocks/common.cpp@@ -4,11 +4,11 @@#include "builder/blocks/common.hpp"-#include <cstring>-#include <tuple>#include <utility>#include <vector>+#include "openvino/core/except.hpp"+namespace ov::frontend::gguf::blocks {std::string rms_norm(GraphEmitter& e,@@ -16,10 +16,7 @@ std::string rms_norm(GraphEmitter& e,const std::string& weight,const std::string& out_prefix,float eps) {- if (strip_weight_suffix(weight) == weight)- e.add_named_weight(weight);- else- e.add_weight(weight);+ e.add_weight(weight);auto norm = e.add_op("GGML_OP_RMS_NORM", out_prefix + ".rms", {in}, 0, {{"eps", eps}});return e.add_op("GGML_OP_MUL", out_prefix, {norm, weight});}@@ -48,7 +45,7 @@ std::string reshape(GraphEmitter& e, const std::string& x, std::vector<int64_t>}std::string add_bias(GraphEmitter& e, const std::string& x, const std::string& bias_weight, const std::string& name) {- e.add_named_weight(bias_weight);+ e.add_weight(bias_weight);return e.add_op("GGML_OP_ADD", name, {x, bias_weight});}@@ -84,49 +81,21 @@ std::array<std::string, 2> split_interleaved_projection(GraphEmitter& e,return outputs;}-void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype) {- auto& w = e.weights();- w[base + ".weight"] = t.weight;- if (t.scales) {- w[base + ".scales"] = t.scales;- }- if (t.zero_point) {- w[base + ".zp"] = t.zero_point;- }- e.qtypes()[base + ".qtype"] = qtype;-}--// Concatenate the rows of two weights with the same quantization layout into one; empty on mismatch.-std::optional<WeightTensors> concat_rows(const WeightTensors& a,- const WeightTensors& b,- GgufTensorType qa,- GgufTensorType qb) {- if (qa != qb || !a.weight || !b.weight) {- return std::nullopt;- }- WeightTensors out;- const std::vector<std::tuple<const ov::Tensor*, const ov::Tensor*, ov::Tensor*>> parts{- {&a.weight, &b.weight, &out.weight},- {&a.scales, &b.scales, &out.scales},- {&a.zero_point, &b.zero_point, &out.zero_point}};- for (const auto& [x, y, dst] : parts) {- if (static_cast<bool>(*x) != static_cast<bool>(*y)) {- return std::nullopt;- }- if (!*x) {- continue;- }- auto sx = x->get_shape(), sy = y->get_shape();- if (x->get_element_type() != y->get_element_type() || sx.empty() || sx.size() != sy.size() ||- !std::equal(sx.begin() + 1, sx.end(), sy.begin() + 1)) {- return std::nullopt;- }- sx[0] += sy[0];- *dst = ov::Tensor(x->get_element_type(), sx);- std::memcpy(dst->data(), x->data(), x->get_byte_size());- std::memcpy(static_cast<uint8_t*>(dst->data()) + x->get_byte_size(), y->data(), y->get_byte_size());+std::string concat_weight_rows(GraphEmitter& e, const std::string& name, const std::vector<std::string>& weights) {+ OPENVINO_ASSERT(!weights.empty(), "[GGUF] weight concatenation requires inputs");+ const auto rank = e.weight_shape(weights.front()).size();+ OPENVINO_ASSERT(rank > 0 && weights.size() > 1, "[GGUF] weight concatenation requires nonscalar inputs");+ auto input = weights.front();+ for (size_t i = 1; i < weights.size(); ++i) {+ const auto output = i + 1 == weights.size() ? name : name + ".concat" + std::to_string(i);+ e.derive_weight(output,+ "GGML_OP_CONCAT",+ {input, weights[i]},+ 0,+ {{"concat_axis", static_cast<int>(rank - 1)}});+ input = output;}- return out;+ return name;}} // namespace ov::frontend::gguf::blocksdiff --git a/src/frontends/gguf/src/builder/blocks/common.hpp b/src/frontends/gguf/src/builder/blocks/common.hppindex ff40d454e78..648c5fdf8d7 100644--- a/src/frontends/gguf/src/builder/blocks/common.hpp+++ b/src/frontends/gguf/src/builder/blocks/common.hpp@@ -5,7 +5,6 @@#pragma once#include <array>-#include <optional>#include <string>#include <utility>#include <vector>@@ -54,13 +53,6 @@ std::array<std::string, 2> split_interleaved_projection(GraphEmitter& e,int64_t groups,int64_t width);-// Register the tensors of a derived weight `base` with quant type `qtype`.-void store_parts(GraphEmitter& e, const std::string& base, const WeightTensors& t, GgufTensorType qtype);--// Concatenate the rows of two weights with the same quantization layout into one; empty on mismatch.-std::optional<WeightTensors> concat_rows(const WeightTensors& a,- const WeightTensors& b,- GgufTensorType qa,- GgufTensorType qb);+std::string concat_weight_rows(GraphEmitter& e, const std::string& name, const std::vector<std::string>& weights);} // namespace ov::frontend::gguf::blocksdiff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cppindex 3944397e6a6..3be441eaf7e 100644--- a/src/frontends/gguf/src/builder/blocks/ffn.cpp+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp@@ -216,9 +216,9 @@ std::string moe_ffn(GraphEmitter& e,up = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_up", {p + "ffn_up_exps.weight", ffn_norm, selected});}if (eb) {- e.add_named_weight(p + "ffn_up_exps.bias");+ e.add_weight(p + "ffn_up_exps.bias");up = e.add_op("GGML_OP_ADD_ID", p + "moe_up_b", {up, p + "ffn_up_exps.bias", selected});- e.add_named_weight(p + "ffn_gate_exps.bias");+ e.add_weight(p + "ffn_gate_exps.bias");gate = e.add_op("GGML_OP_ADD_ID", p + "moe_gate_b", {gate, p + "ffn_gate_exps.bias", selected});}std::string act;@@ -238,12 +238,12 @@ std::string moe_ffn(GraphEmitter& e,}auto experts = e.add_op("GGML_OP_MUL_MAT_ID", p + "moe_down", {p + "ffn_down_exps.weight", act, selected});if (eb) {- e.add_named_weight(p + "ffn_down_exps.bias");+ e.add_weight(p + "ffn_down_exps.bias");experts = e.add_op("GGML_OP_ADD_ID", p + "moe_down_b", {experts, p + "ffn_down_exps.bias", selected});}if (e.has_weight(p + "ffn_down_exps.scale")) {- e.add_named_weight(p + "ffn_down_exps.scale");+ e.add_weight(p + "ffn_down_exps.scale");auto scales =e.add_op("GGML_OP_RESHAPE",p + "moe_scale_row",@@ -312,7 +312,7 @@ std::string gemma4_moe_ffn(GraphEmitter& e,auto routed_input = rms_norm(e, input, p + "pre_ffw_norm_2.weight", p + "expert_pre_norm", cfg.rms_eps);auto router = e.add_op("GGML_OP_RMS_NORM", p + "router_norm", {input}, 0, {{"eps", cfg.rms_eps}});router = scale(e, router, 1.f / std::sqrt(float(cfg.n_embd)), p + "router_scale");- e.add_named_weight(p + "ffn_gate_inp.scale");+ e.add_weight(p + "ffn_gate_inp.scale");router = e.add_op("GGML_OP_MUL", p + "router_weighted", {router, p + "ffn_gate_inp.scale"});auto routed = moe_ffn(e, cfg, p, routed_input, router);routed = rms_norm(e, routed, p + "post_ffw_norm_2.weight", p + "expert_post_norm", cfg.rms_eps);diff --git a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cppindex 62ab88d2ed0..e75d9d81f28 100644--- a/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp+++ b/src/frontends/gguf/src/builder/blocks/gated_delta_net.cpp@@ -6,9 +6,7 @@#include <algorithm>#include <array>-#include <cstring>-#include <functional>-#include <optional>+#include <numeric>#include <vector>#include "builder/blocks/common.hpp"@@ -18,88 +16,29 @@ namespace ov::frontend::gguf::blocks {namespace {-// Copy of `t` viewed as `outer` rows of bytes, where the chunks [first, first + src.size())-// of `chunk_bytes` in every row are reordered so that new chunk n holds old chunk src[n].-// Returns an empty tensor when the byte layout does not split evenly.-ov::Tensor permute_chunks(const ov::Tensor& t,- size_t outer,- size_t chunk_bytes,- size_t first,- const std::vector<int64_t>& src) {- const size_t bytes = t.get_byte_size();- if (outer == 0 || bytes % outer != 0 || chunk_bytes == 0 || (first + src.size()) * chunk_bytes > bytes / outer) {+std::vector<int64_t> row_permutation(const ov::Shape& shape,+ int64_t first,+ int64_t rows_per_block,+ const std::vector<int64_t>& source) {+ if (shape.empty() || shape[0] == 0 || rows_per_block <= 0 || first < 0 ||+ static_cast<size_t>(first + rows_per_block * source.size()) > shape[0]) {return {};}- const size_t row_bytes = bytes / outer;- ov::Tensor out(t.get_element_type(), t.get_shape());- const auto* in_data = static_cast<const uint8_t*>(t.data());- auto* out_data = static_cast<uint8_t*>(out.data());- const size_t head = first * chunk_bytes, tail = (first + src.size()) * chunk_bytes;- for (size_t r = 0; r < outer; ++r) {- const auto* in_row = in_data + r * row_bytes;- auto* out_row = out_data + r * row_bytes;- std::memcpy(out_row, in_row, head);- std::memcpy(out_row + tail, in_row + tail, row_bytes - tail);- for (size_t n = 0; n < src.size(); ++n) {- std::memcpy(out_row + (first + n) * chunk_bytes,- in_row + (first + static_cast<size_t>(src[n])) * chunk_bytes,- chunk_bytes);+ std::vector<int64_t> indices(shape[0]);+ std::iota(indices.begin(), indices.end(), 0);+ for (size_t block = 0; block < source.size(); ++block) {+ for (int64_t row = 0; row < rows_per_block; ++row) {+ indices[first + block * rows_per_block + row] = first + source[block] * rows_per_block + row;}}- return out;+ return indices;}-// Reorder `src.size()` blocks of `rows_per_block` rows (dim 0) starting at row `first_row`.-ov::Tensor permute_row_blocks(const ov::Tensor& t,- size_t first_row,- size_t rows_per_block,- const std::vector<int64_t>& src) {- const auto& shape = t.get_shape();- if (shape.empty() || shape[0] == 0 || rows_per_block == 0 || t.get_byte_size() % shape[0] != 0) {- return {};- }- const size_t chunk = t.get_byte_size() / shape[0] * rows_per_block;- if (first_row % rows_per_block != 0) {- return {};- }- return permute_chunks(t, 1, chunk, first_row / rows_per_block, src);-}--// Reorder `src.size()` column blocks of `block_cols` of a [rows, logical_cols] weight part.-// Per-row tensors with a single column (channel-wise scales) are left as they are.-ov::Tensor permute_col_blocks(const ov::Tensor& t,- size_t logical_cols,- size_t block_cols,- const std::vector<int64_t>& src) {- const auto& shape = t.get_shape();- if (shape.size() == 2 && shape[1] == 1) {- return t;- }- if (shape.size() != 2 || shape[0] == 0 || logical_cols == 0 || t.get_byte_size() % shape[0] != 0) {- return {};- }- const size_t row_bytes = t.get_byte_size() / shape[0];- if ((row_bytes * block_cols) % logical_cols != 0) {- return {};- }- return permute_chunks(t, shape[0], row_bytes * block_cols / logical_cols, 0, src);-}--// Apply `fn` to every present part; fails (returns false) if any present part cannot be transformed.-template <typename Fn>-bool transform_parts(const WeightTensors& in, WeightTensors& out, Fn&& fn) {- const std::vector<std::pair<const ov::Tensor*, ov::Tensor*>> parts{{&in.weight, &out.weight},- {&in.scales, &out.scales},- {&in.zero_point, &out.zero_point}};- for (const auto& [src, dst] : parts) {- if (*src) {- *dst = fn(*src);- if (!*dst) {- return false;- }- }- }- return true;+bool concatenable_rows(GraphEmitter& e, const std::string& lhs, const std::string& rhs) {+ const auto& a = e.weight_shape(lhs + ".weight");+ const auto& b = e.weight_shape(rhs + ".weight");+ return !a.empty() && a.size() == b.size() && std::equal(a.begin() + 1, a.end(), b.begin() + 1) &&+ e.weight_qtype(lhs) == e.weight_qtype(rhs);}} // namespace@@ -130,7 +69,7 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c// per-V-head weight lets the op run without a runtime Tile of q and k.std::string qkv_base = p + "attn_qkv", gate_base = p + "attn_gate", out_base = p + "ssm_out";std::string alpha_base = p + "ssm_alpha", beta_base = p + "ssm_beta";- std::string conv_w = p + "ssm_conv1d.weight", a_w = p + "ssm_a", dt_w = p + "ssm_dt.bias";+ std::string conv_base = p + "ssm_conv1d", a_base = p + "ssm_a", dt_base = p + "ssm_dt";bool gqa_grouped = false;const bool grouped_hadamard = e.has_grouped_hadamard_gdn();if ((!e.has_hadamard() || grouped_hadamard) && H_v != H_k && H_v % H_k == 0) {@@ -139,49 +78,45 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, cfor (int64_t n = 0; n < H_v; ++n) {src[n] = (n % rep) * H_k + n / rep;}- const auto rows = [&](size_t first, size_t per_block) {- return [&, first, per_block](const ov::Tensor& t) {- return permute_row_blocks(t, first, per_block, src);- };- };- const auto cols = [&](const ov::Tensor& t) {- if (grouped_hadamard)- return t;- return permute_col_blocks(t, value_dim, head_v, src);- };struct Grouped {- std::string& base;- std::function<ov::Tensor(const ov::Tensor&)> permute;- WeightTensors parts;+ std::string* base;+ std::string suffix;+ int64_t axis;+ std::vector<int64_t> indices;+ };+ std::vector<Grouped> grouped;+ const auto rows = [&](std::string& base, const std::string& suffix, int64_t first, int64_t per_block) {+ const auto& shape = e.weight_shape(base + suffix);+ grouped.push_back({&base, suffix, 0, row_permutation(shape, first, per_block, src)});};- std::array<Grouped, 5> grouped{{{qkv_base, rows(2 * key_dim, head_v), {}},- {gate_base, rows(0, head_v), {}},- {alpha_base, rows(0, 1), {}},- {beta_base, rows(0, 1), {}},- {out_base, cols, {}}}};- bool ok = std::all_of(grouped.begin(), grouped.end(), [&](Grouped& w) {- return transform_parts(e.weight_parts(w.base), w.parts, w.permute);- });- ov::Tensor conv, a, dt;- if (ok) {- conv = permute_row_blocks(e.weight_tensor(conv_w), 2 * key_dim, head_v, src);- a = permute_row_blocks(e.weight_tensor(a_w), 0, 1, src);- dt = permute_row_blocks(e.weight_tensor(dt_w), 0, 1, src);- ok = conv && a && dt;+ rows(qkv_base, ".weight", 2 * key_dim, head_v);+ rows(gate_base, ".weight", 0, head_v);+ rows(alpha_base, ".weight", 0, 1);+ rows(beta_base, ".weight", 0, 1);+ rows(conv_base, ".weight", 2 * key_dim, head_v);+ rows(a_base, "", 0, 1);+ rows(dt_base, ".bias", 0, 1);+ if (!grouped_hadamard) {+ const auto& shape = e.weight_shape(out_base + ".weight");+ auto indices = shape.size() == 2 && shape[1] == static_cast<size_t>(value_dim)+ ? row_permutation({shape[1]}, 0, head_v, src)+ : std::vector<int64_t>{};+ if (!e.column_groups_aligned(out_base + ".weight", indices))+ indices.clear();+ grouped.push_back({&out_base, ".weight", 1, std::move(indices)});}- if (ok) {- const std::string g = "_grouped";- for (auto& w : grouped) {- if (grouped_hadamard && &w.base == &out_base)- continue;- store_parts(e, w.base + g, w.parts, e.weight_qtype(w.base));- e.inherit_hadamard(w.base + g + ".weight", w.base + ".weight");- w.base += g;+ if (std::all_of(grouped.begin(), grouped.end(), [](const Grouped& weight) {+ return !weight.indices.empty();+ })) {+ for (auto& weight : grouped) {+ const auto source = *weight.base + weight.suffix;+ *weight.base += "_grouped";+ e.derive_weight(*weight.base + weight.suffix,+ "GGML_OP_VIEW",+ {source},+ 105,+ {{"gather_axis", weight.axis}, {"gather_indices", weight.indices}});}- conv_w = p + "ssm_conv1d" + g + ".weight", a_w = p + "ssm_a" + g, dt_w = p + "ssm_dt" + g + ".bias";- e.weights()[conv_w] = conv;- e.weights()[a_w] = a;- e.weights()[dt_w] = dt;gqa_grouped = true;}}@@ -194,17 +129,13 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c// remain separate so their bias and activations can fuse into FCs.std::string z, beta, alpha;const bool dense_gates = e.weight_qtype(beta_base) == GGUF_TYPE_F32 && e.weight_qtype(alpha_base) == GGUF_TYPE_F32;- auto ba = !dense_gates || !e.has_hadamard() ? concat_rows(e.weight_parts(beta_base),- e.weight_parts(alpha_base),- e.weight_qtype(beta_base),- e.weight_qtype(alpha_base))- : std::nullopt;- auto zba = ba && !e.has_hadamard()- ? concat_rows(e.weight_parts(gate_base), *ba, e.weight_qtype(gate_base), e.weight_qtype(beta_base))- : std::nullopt;+ const bool ba = (!dense_gates || !e.has_hadamard()) && concatenable_rows(e, beta_base, alpha_base);+ const bool zba = ba && !e.has_hadamard() && (!dense_gates || e.weight_qtype(gate_base) == GGUF_TYPE_F32) &&+ concatenable_rows(e, gate_base, beta_base);if (zba) {- store_parts(e, p + "ssm_z_beta_alpha", *zba, e.weight_qtype(gate_base));- e.add_weight(p + "ssm_z_beta_alpha.weight");+ concat_weight_rows(e,+ p + "ssm_z_beta_alpha.weight",+ {gate_base + ".weight", beta_base + ".weight", alpha_base + ".weight"});auto zba_out = e.add_op("GGML_OP_MUL_MAT", p + "z_beta_alpha", {p + "ssm_z_beta_alpha.weight", attn_norm});z = e.add_op("GGML_OP_VIEW", p + "z", {zba_out}, 3, {{"view_slice", std::vector<int64_t>{3, 0, value_dim}}});beta = e.add_op("GGML_OP_VIEW",@@ -220,8 +151,7 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c} else if (ba && !dense_gates) {e.add_weight(gate_base + ".weight");z = e.add_op("GGML_OP_MUL_MAT", p + "z", {gate_base + ".weight", attn_norm});- store_parts(e, p + "ssm_beta_alpha", *ba, e.weight_qtype(beta_base));- e.add_weight(p + "ssm_beta_alpha.weight");+ concat_weight_rows(e, p + "ssm_beta_alpha.weight", {beta_base + ".weight", alpha_base + ".weight"});auto ba_out = e.add_op("GGML_OP_MUL_MAT", p + "beta_alpha", {p + "ssm_beta_alpha.weight", attn_norm});beta = e.add_op("GGML_OP_VIEW", p + "beta", {ba_out}, 3, {{"view_slice", std::vector<int64_t>{3, 0, H_v}}});alpha = e.add_op("GGML_OP_VIEW", p + "alpha", {ba_out}, 3, {{"view_slice", std::vector<int64_t>{3, H_v, H_v}}});@@ -244,11 +174,12 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, c{{"reshape_target", std::vector<int64_t>{0, -1, H_v, 1}}, {"special_zero", true}});// g = softplus(ssm_alpha @ x + ssm_dt.bias) * ssm_a (ggml: -A_log.exp() * softplus)- e.add_named_weight(dt_w);+ const auto dt_w = dt_base + ".bias";+ e.add_weight(dt_w);alpha = e.add_op("GGML_OP_ADD", p + "alpha_biased", {alpha, dt_w});alpha = e.add_op("GGML_UNARY_OP_SOFTPLUS", p + "alpha_sp", {alpha});- e.add_named_weight(a_w);- auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, a_w});+ e.add_weight(a_base);+ auto g = e.add_op("GGML_OP_MUL", p + "gate", {alpha, a_base});g = e.add_op("GGML_OP_RESHAPE",p + "gate_4d",{g},@@ -272,7 +203,8 @@ std::string gated_delta_net(GraphEmitter& e, const DecoderConfig& cfg, int il, cgraph.model_output_names.push_back(cs_out);graph.recurrent_states.emplace_back(cs, cs_out);- e.add_named_weight(conv_w);+ const auto conv_w = conv_base + ".weight";+ e.add_weight(conv_w);auto conv = e.add_op("GGML_OP_SSM_CONV",p + "conv_silu",{conv_in, conv_w},diff --git a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp b/src/frontends/gguf/src/builder/blocks/qkv_repack.cppindex 4dc7f837c42..3740516c865 100644--- a/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp+++ b/src/frontends/gguf/src/builder/blocks/qkv_repack.cpp@@ -6,7 +6,7 @@#include <array>-#include "quant/weights.hpp"+#include "openvino/core/except.hpp"namespace ov::frontend::gguf::blocks {@@ -14,28 +14,38 @@ void register_fused_qkv(GraphEmitter& e, const DecoderConfig& cfg, int il) {const std::string p = "blk." + std::to_string(il) + ".";const size_t n_q = static_cast<size_t>(cfg.layer_n_head(il)) * cfg.layer_head_size(il);const size_t n_kv = static_cast<size_t>(cfg.layer_n_head_kv(il)) * cfg.layer_head_size(il);- auto parts = split_fused_qkv_extracted(p + "attn_qkv", e.weights(), e.qtypes(), n_q, n_kv, n_kv);- const std::array<std::string, 3> names = {p + "attn_q.weight", p + "attn_k.weight", p + "attn_v.weight"};- for (size_t i = 0; i < 3; ++i) {- e.inherit_hadamard(names[i], p + "attn_qkv.weight");- e.emit_weight_op(names[i], parts[i].tensors, parts[i].qtype);- }-- // Some fused-QKV archs (e.g. phi-3) also carry a single attn_qkv.bias; split it into- // attn_{q,k,v}.bias the same way so attention()'s plain add_bias lookup finds them. Not every- // fused-QKV arch has a bias, so only split when the fused tensor is actually present.- if (e.weights().count(p + "attn_qkv.bias")) {- auto bias_parts = split_fused_qkv_bias(p + "attn_qkv", e.weights(), n_q, n_kv, n_kv);- const std::array<std::string, 3> bias_names = {p + "attn_q.bias", p + "attn_k.bias", p + "attn_v.bias"};- for (size_t i = 0; i < 3; ++i) {- e.weights()[bias_names[i]] = bias_parts[i];+ const std::string source = p + "attn_qkv.weight";+ OPENVINO_ASSERT(e.weight_rows(source) == static_cast<int64_t>(n_q + 2 * n_kv),+ "[GGUF] fused qkv row mismatch for ",+ source);+ const std::array<size_t, 3> starts = {0, n_q, n_q + n_kv};+ const std::array<size_t, 3> lengths = {n_q, n_kv, n_kv};+ const auto split = [&](const std::string& fused, const std::string& suffix) {+ const std::array<std::string, 3> names = {p + "attn_q" + suffix, p + "attn_k" + suffix, p + "attn_v" + suffix};+ for (size_t i = 0; i < names.size(); ++i) {+ e.derive_weight(+ names[i],+ "GGML_OP_VIEW",+ {fused},+ 3,+ {{"view_slice",+ std::vector<int64_t>{0, static_cast<int64_t>(starts[i]), static_cast<int64_t>(lengths[i])}}});}+ };+ split(source, ".weight");++ const std::string bias_source = p + "attn_qkv.bias";+ if (e.has_weight(bias_source)) {+ const auto& shape = e.weight_shape(bias_source);+ OPENVINO_ASSERT(shape.size() == 1 && shape[0] == n_q + 2 * n_kv,+ "[GGUF] fused qkv bias row mismatch for ",+ bias_source);+ split(bias_source, ".bias");}}void register_interleaved_q_gate(GraphEmitter& e, const DecoderConfig& cfg, int il) {const std::string p = "blk." + std::to_string(il) + ".";- e.inherit_hadamard(p + "attn_q_gate.weight", p + "attn_q.weight");e.add_weight_from(p + "attn_q_gate.weight", p + "attn_q");}diff --git a/src/frontends/gguf/src/builder/decoder_config.cpp b/src/frontends/gguf/src/builder/decoder_config.cppindex 731badae4af..f165d05e6ae 100644--- a/src/frontends/gguf/src/builder/decoder_config.cpp+++ b/src/frontends/gguf/src/builder/decoder_config.cpp@@ -31,7 +31,7 @@ void validate_rope(const RopeConfig& rope, int head_size) {}} // namespace-DecoderConfig::DecoderConfig(const DecoderParameters& p, const std::unordered_map<std::string, ov::Tensor>& weights) {+DecoderConfig::DecoderConfig(const DecoderParameters& p, const GgufWeightTable& weights) {const auto has = [&weights](const std::string& name) {return weights.count(name) > 0;};@@ -206,7 +206,7 @@ DecoderConfig::DecoderConfig(const DecoderParameters& p, const std::unordered_ma}has_qk_norm = p.normalization.qk_norm.value_or(has(attention_probe + "attn_q_norm.weight"));if (has_qk_norm && has(attention_probe + "attn_q_norm.weight")) {- const auto& shape = weights.at(attention_probe + "attn_q_norm.weight").get_shape();+ const auto& shape = weights.at(attention_probe + "attn_q_norm.weight").shape;OPENVINO_ASSERT(!shape.empty(), "[GGUF] empty Q normalization weight");qk_norm_full = shape[0] != static_cast<size_t>(layer_head_size(attention_layer));}diff --git a/src/frontends/gguf/src/builder/decoder_config.hpp b/src/frontends/gguf/src/builder/decoder_config.hppindex c0a8abf6578..1eb114bbbc3 100644--- a/src/frontends/gguf/src/builder/decoder_config.hpp+++ b/src/frontends/gguf/src/builder/decoder_config.hpp@@ -20,7 +20,7 @@ class GraphEmitter;// Internal configuration resolved from metadata, tensor shapes and architecture semantics.// Extensions override ambiguous semantics through DecoderOptions before dependent plans are built.struct DecoderConfig {- DecoderConfig(const DecoderParameters& parameters, const std::unordered_map<std::string, ov::Tensor>& weights);+ DecoderConfig(const DecoderParameters& parameters, const GgufWeightTable& weights);// Sets the graph's RoPE, SWA and model-contract state and configures the weight transforms.void configure_graph(GraphEmitter& emitter, const GgufMetadata& metadata) const;diff --git a/src/frontends/gguf/src/builder/gguf_builder.cpp b/src/frontends/gguf/src/builder/gguf_builder.cppindex 08ac115a677..eaa9817f3d3 100644--- a/src/frontends/gguf/src/builder/gguf_builder.cpp+++ b/src/frontends/gguf/src/builder/gguf_builder.cpp@@ -50,7 +50,7 @@ ov::AnyMap extract_tokenizer_config(const std::unordered_map<std::string, GGUFMeGraphBuilder make_gguf_builder(GGUFLoad loaded, const ArchRegistry& registry) {auto data = std::make_shared<GGUFLoad>(std::move(loaded));- auto& [metadata, weights, qtypes, mmap] = *data;+ auto& metadata = std::get<0>(*data);const detail::MetadataStore meta_store{metadata};const GgufMetadata meta_view(meta_store);@@ -75,12 +75,10 @@ GraphBuilder make_gguf_builder(GGUFLoad loaded, const ArchRegistry& registry) {}return [data, definition = *definition, projectors = registry.projectors()](const std::unordered_map<std::string, CreatorFunction>& translators) {- const auto& [metadata, source_weights, source_qtypes, mmap] = *data;- auto weights = source_weights;- auto qtypes = source_qtypes;+ const auto& [metadata, weights, mmap] = *data;const detail::MetadataStore meta_store{metadata};const GgufMetadata meta_view(meta_store);- detail::WeightStore weight_store{weights, qtypes, &translators};+ detail::WeightStore weight_store{weights, &translators};BuildContext ctx{meta_view, meta_view.architecture(), &weight_store, &projectors};auto builder = definition.factory(ctx);OPENVINO_ASSERT(builder, "[GGUF] architecture handler '", definition.id, "' returned no builder");diff --git a/src/frontends/gguf/src/builder/gguf_graph.hpp b/src/frontends/gguf/src/builder/gguf_graph.hppindex 9c430184317..ddffe0cbbe2 100644--- a/src/frontends/gguf/src/builder/gguf_graph.hpp+++ b/src/frontends/gguf/src/builder/gguf_graph.hpp@@ -48,7 +48,7 @@ struct GgufGraph {// Model inputs (Parameters) and extra inputs (e.g. attention_size; Parameter or Constant).// Same semantics as the corresponding GgufDecoder getters. Weights are not here: they are- // emitted into `nodes` as GGML_OP_NONE leaves (see emit_weight_op).+ // emitted into `nodes` as GGML_OP_NONE leaves (see add_weight).std::map<std::string, std::shared_ptr<ov::Node>> model_inputs;std::map<std::string, std::shared_ptr<ov::Node>> model_extra_inputs;std::vector<std::string> model_output_names;diff --git a/src/frontends/gguf/src/builder/graph_emitter.cpp b/src/frontends/gguf/src/builder/graph_emitter.cppindex 90cf0f3ce22..610fa63e62b 100644--- a/src/frontends/gguf/src/builder/graph_emitter.cpp+++ b/src/frontends/gguf/src/builder/graph_emitter.cpp@@ -25,20 +25,6 @@ const T& required_metadata(const std::map<std::string, GGUFMetaData>& config, coreturn *value;}-WeightTensors find_weight_tensors(const std::unordered_map<std::string, ov::Tensor>& weights, const std::string& base) {- WeightTensors tensors;- if (auto it = weights.find(base + ".weight"); it != weights.end()) {- tensors.weight = it->second;- }- if (auto it = weights.find(base + ".scales"); it != weights.end()) {- tensors.scales = it->second;- }- if (auto it = weights.find(base + ".zp"); it != weights.end()) {- tensors.zero_point = it->second;- }- return tensors;-}-} // namespacestd::string strip_weight_suffix(const std::string& name) {@@ -48,34 +34,48 @@ std::string strip_weight_suffix(const std::string& name) {return ends_with_weight ? name.substr(0, name.size() - suffix.size()) : name;}-GraphEmitter::GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,- std::unordered_map<std::string, GgufTensorType>& qtypes,+GraphEmitter::GraphEmitter(const GgufWeightTable& weights,std::string arch,const std::unordered_map<std::string, CreatorFunction>* translators): m_weights(weights),- m_qtypes(qtypes),m_arch(std::move(arch)),m_graph(std::make_shared<GgufGraph>()),m_translators(translators ? *translators : get_supported_ops()) {}-const ov::Tensor& GraphEmitter::weight_tensor(const std::string& name) const {- auto it = m_weights.find(name);+const ov::Shape& GraphEmitter::weight_shape(const std::string& name) const {+ if (const auto it = m_graph_weights.find(name); it != m_graph_weights.end()) {+ return it->second.shape;+ }+ const auto it = m_weights.find(name);OPENVINO_ASSERT(it != m_weights.end(),"[GGUF] model is missing expected weight tensor '",name,"' for architecture '",m_arch,"'");- return it->second;+ return it->second.shape;}int64_t GraphEmitter::weight_rows(const std::string& name) const {- auto it = m_weights.find(name);- if (it == m_weights.end()) {+ if (!has_weight(name)) {return 1;}- const auto& s = it->second.get_shape();- return s.empty() ? 1 : static_cast<int64_t>(s[0]);+ const auto& shape = weight_shape(name);+ return shape.empty() ? 1 : static_cast<int64_t>(shape[0]);+}++void GraphEmitter::register_graph_weight(const std::string& name, GgufTensorType qtype) {+ const auto& shape = value(name).get_partial_shape();+ OPENVINO_ASSERT(shape.is_static(), "[GGUF] derived weight must have a static shape: ", name);+ m_graph_weights[name] = {shape.to_shape(), qtype};+ m_emitted_weights.insert(name);+}++void GraphEmitter::add_generated_weight(const std::string& name, const ov::Tensor& tensor) {+ GgufWeight source(tensor);+ source.source_name = name;+ emit_weight(name, source);+ register_graph_weight(name, source.qtype);}const ov::Output<ov::Node>& GraphEmitter::value(const std::string& name) const {@@ -127,13 +127,6 @@ std::string GraphEmitter::add_op(const std::string& op_type,return name;}-void GraphEmitter::inherit_hadamard(const std::string& name, const std::string& source) {- if (m_hadamard_weights.count(source)) {- m_hadamard_weights.insert(name);- m_hadamard_consumed.insert(source);- }-}-void GraphEmitter::validate_hadamard() const {for (const auto& names : {m_hadamard_weights, m_hadamard_inverse_weights})for (const auto& name : names)@@ -226,7 +219,7 @@ void GraphEmitter::configure_hadamard(const std::map<std::string, GGUFMetaData>&}for (const auto& names : {m_hadamard_weights, m_hadamard_inverse_weights})for (const auto& name : names) {- const auto& shape = weight_tensor(name).get_shape();+ const auto& shape = weight_shape(name);OPENVINO_ASSERT(shape.size() == 2, "[GGUF] Hadamard requires matrix weights: ", name);const auto width = shape.back();OPENVINO_ASSERT(width > 0 && width % m_hadamard_block == 0 &&@@ -266,60 +259,68 @@ void GraphEmitter::add_extra_input_node(const std::string& name, const std::shar(*m_graph->values)[name] = node;}-void GraphEmitter::emit_weight_op(const std::string& node_name, const WeightTensors& tensors, GgufTensorType qtype) {- if (m_emitted_weights.count(node_name)) {+void GraphEmitter::emit_weight(const std::string& name, const GgufWeight& source) {+ if (m_emitted_weights.count(name)) {return;}- m_emitted_weights.insert(node_name);-- std::map<std::string, ov::Any> attrs{{"gguf_weight", true},- {"gguf_qtype", static_cast<int>(qtype)},- {"gguf.blob.weight", tensors.weight}};- if (tensors.scales) {- attrs["gguf.blob.scales"] = tensors.scales;- }- if (tensors.zero_point) {- attrs["gguf.blob.zp"] = tensors.zero_point;- }- add_op("GGML_OP_NONE", node_name, {}, 0, std::move(attrs));+ add_op("GGML_OP_NONE", name, {}, 0, {{"gguf_source", source}});+ m_emitted_weights.insert(name);}-WeightTensors GraphEmitter::weight_parts(const std::string& base) const {- return find_weight_tensors(m_weights, base);+bool GraphEmitter::column_groups_aligned(const std::string& name, const std::vector<int64_t>& columns) const {+ const auto it = m_weights.find(name);+ return it == m_weights.end() || gguf_column_groups_are_aligned(it->second, columns);}GgufTensorType GraphEmitter::weight_qtype(const std::string& base) const {- return lookup_qtype(base, m_qtypes);+ const auto name = strip_weight_suffix(base) + ".weight";+ const auto find = [&](const auto& table) {+ const auto it = table.find(name);+ return it != table.end() ? it : table.find(base);+ };+ if (const auto it = find(m_graph_weights); it != m_graph_weights.end())+ return it->second.qtype;+ if (const auto it = find(m_weights); it != m_weights.end())+ return it->second.qtype;+ return GGUF_TYPE_F16;}-void GraphEmitter::add_weight(const std::string& ggml_name) {- if (m_emitted_weights.count(ggml_name)) {+void GraphEmitter::add_weight_from(const std::string& node_name, const std::string& src_base) {+ if (m_emitted_weights.count(node_name)) {return;}- const std::string base = strip_weight_suffix(ggml_name);- emit_weight_op(ggml_name, weight_parts(base), weight_qtype(base));+ derive_weight(node_name, "GGML_OP_VIEW", {src_base + ".weight"}, 3);}-void GraphEmitter::add_weight_from(const std::string& node_name, const std::string& src_base) {- if (m_emitted_weights.count(node_name)) {- return;+std::string GraphEmitter::derive_weight(const std::string& name,+ const std::string& op_type,+ const std::vector<std::string>& sources,+ int op_case,+ std::map<std::string, ov::Any> attrs) {+ OPENVINO_ASSERT(!sources.empty(), "[GGUF] derived weight requires sources: ", name);+ const bool rotated = m_hadamard_weights.count(sources.front()) > 0;+ for (const auto& source : sources) {+ add_weight(source);+ OPENVINO_ASSERT((m_hadamard_weights.count(source) != 0) == rotated,+ "[GGUF] derived weight mixes Hadamard-rotated and plain sources: ",+ name);}- emit_weight_op(node_name, weight_parts(src_base), weight_qtype(src_base));+ add_op(op_type, name, sources, op_case, std::move(attrs));+ register_graph_weight(name, weight_qtype(sources.front()));+ if (rotated) {+ m_hadamard_weights.insert(name);+ m_hadamard_consumed.insert(sources.begin(), sources.end());+ }+ return name;}-void GraphEmitter::add_named_weight(const std::string& ggml_name) {+void GraphEmitter::add_weight(const std::string& ggml_name) {if (m_emitted_weights.count(ggml_name)) {return;}- auto it = m_weights.find(ggml_name);+ const auto it = m_weights.find(ggml_name);OPENVINO_ASSERT(it != m_weights.end(), "[GGUF] weight not found in gguf: ", ggml_name);- const ov::Tensor& w = it->second;- // Map the OV element type back to the ggml float qtype so translate_weight rebuilds a plain- // Constant of the right precision.- GgufTensorType qtype = w.get_element_type() == ov::element::f32 ? GGUF_TYPE_F32- : w.get_element_type() == ov::element::bf16 ? GGUF_TYPE_BF16- : GGUF_TYPE_F16;- emit_weight_op(ggml_name, {w, {}, {}}, qtype);+ emit_weight(ggml_name, it->second);}} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/builder/graph_emitter.hpp b/src/frontends/gguf/src/builder/graph_emitter.hppindex ecf4fdbaf1f..7016cd7403c 100644--- a/src/frontends/gguf/src/builder/graph_emitter.hpp+++ b/src/frontends/gguf/src/builder/graph_emitter.hpp@@ -18,7 +18,6 @@#include "openvino/op/parameter.hpp"#include "openvino/runtime/tensor.hpp"#include "quant/gguf.hpp"-#include "quant/weights.hpp"namespace ov::frontend::gguf {@@ -29,10 +28,8 @@ std::string strip_weight_suffix(const std::string& name);// Builds OpenVINO values through the shared GGML converters.class GraphEmitter {public:- // `weights` / `qtypes` are the parser's tensor tables; they are referenced, not copied, and- // must outlive the emitter.- GraphEmitter(std::unordered_map<std::string, ov::Tensor>& weights,- std::unordered_map<std::string, GgufTensorType>& qtypes,+ // `weights` is the parser's tensor table; it is referenced, not copied, and must outlive the emitter.+ GraphEmitter(const GgufWeightTable& weights,std::string arch,const std::unordered_map<std::string, CreatorFunction>* translators = nullptr);@@ -41,31 +38,16 @@ public:return m_graph;}- // ---- weight-table queries ----bool has_weight(const std::string& name) const {- return m_weights.count(name) > 0;+ return m_weights.count(name) > 0 || m_graph_weights.count(name) > 0;}- // Look up a weight tensor by GGUF name, failing with the tensor NAME if the GGUF is missing it- // (a bare .at(name) throws std::out_of_range with no context). Used wherever a builder reads a- // weight's shape to size an op; a missing expected tensor means the file does not match the- // detected architecture.- const ov::Tensor& weight_tensor(const std::string& name) const;-- // First extent of a weight's OV shape (its row count), 1 when the weight is absent/scalar.+ const ov::Shape& weight_shape(const std::string& name) const;int64_t weight_rows(const std::string& name) const;-- // The "<base>.weight" / ".scales" / ".zp" tensors present for a weight, and its quant type- // ("<base>.qtype", F16 when absent).- WeightTensors weight_parts(const std::string& base) const;GgufTensorType weight_qtype(const std::string& base) const;-- std::unordered_map<std::string, ov::Tensor>& weights() {- return m_weights;- }- std::unordered_map<std::string, GgufTensorType>& qtypes() {- return m_qtypes;- }+ // Whether selecting `columns` of a parser weight keeps its quantization groups whole.+ bool column_groups_aligned(const std::string& name, const std::vector<int64_t>& columns) const;+ void add_generated_weight(const std::string& name, const ov::Tensor& tensor);const ov::Output<ov::Node>& value(const std::string& name) const;@@ -92,22 +74,15 @@ public:void add_extra_input_node(const std::string& name, const std::shared_ptr<ov::Node>& node);- // The shared weight converter constructs the compressed OpenVINO subgraph from parsed tensors.- void emit_weight_op(const std::string& node_name, const WeightTensors& tensors, GgufTensorType qtype);-- // `ggml_name` is the full tensor name ending in ".weight" (the name translators reference).void add_weight(const std::string& ggml_name);-- // Emit a weight node `node_name` (ends in ".weight") reusing the parser's extracted tensors of- // another weight `src_base` (base without ".weight"). Used for MQA tie-V, where V shares K's- // weight tensor; the two GGML_OP_NONE leaves reference the same underlying ov::Tensor blobs- // (cheap: SharedBuffer views into the parser's single quant buffer).void add_weight_from(const std::string& node_name, const std::string& src_base);-- // Emit a plain (non-quantized) weight stored under its full GGUF name, e.g. a bias tensor- // "blk.N.attn_q.bias" (no ".weight" suffix). It flows through the same GGML_OP_NONE +- // translate_weight path; make_weight_node treats an F16/F32/BF16 blob as a plain Constant.- void add_named_weight(const std::string& ggml_name);+ // Emit weight `name` computed by `op_type` from weights `sources`. It takes the first source's+ // qtype and Hadamard rotation; all sources must agree on the rotation.+ std::string derive_weight(const std::string& name,+ const std::string& op_type,+ const std::vector<std::string>& sources,+ int op_case,+ std::map<std::string, ov::Any> attrs = {});bool weight_emitted(const std::string& name) const {return m_emitted_weights.count(name) > 0;@@ -121,11 +96,17 @@ public:bool has_grouped_hadamard_gdn() const {return m_hadamard_v_heads > 0;}- void inherit_hadamard(const std::string& name, const std::string& source);private:- std::unordered_map<std::string, ov::Tensor>& m_weights;- std::unordered_map<std::string, GgufTensorType>& m_qtypes;+ void register_graph_weight(const std::string& name, GgufTensorType qtype);+ struct GraphWeight {+ ov::Shape shape;+ GgufTensorType qtype;+ };+ void emit_weight(const std::string& name, const GgufWeight& source);++ const GgufWeightTable& m_weights;+ std::unordered_map<std::string, GraphWeight> m_graph_weights;// Architecture name, used only to make a missing-tensor diagnostic actionable.std::string m_arch;diff --git a/src/frontends/gguf/src/helper_ops/gguf_constant.cpp b/src/frontends/gguf/src/helper_ops/gguf_constant.cppnew file mode 100644index 00000000000..99a9736952c--- /dev/null+++ b/src/frontends/gguf/src/helper_ops/gguf_constant.cpp@@ -0,0 +1,48 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gguf_constant.hpp"++#include "openvino/core/except.hpp"+#include "quant/weights.hpp"++namespace ov::frontend::gguf {++GGUFConstant::GGUFConstant(const GgufWeight& source) : ov::op::util::FrameworkNode({}, 1), m_source(source) {+ OPENVINO_ASSERT(source.data, "GGUF weight has no source storage");+ ov::op::util::FrameworkNodeAttrs attrs;+ attrs.set_type_name("GGUFConstant");+ attrs.set_opset_name("gguf");+ set_attrs(attrs);+ constructor_validate_and_infer_types();+}++void GGUFConstant::validate_and_infer_types() {+ auto shape = m_source.shape;+ auto type = ov::element::f32;+ if (!m_source.native && m_source.qtype == GGUF_TYPE_MXFP4 && shape.size() > 2) {+ shape = mxfp4_packed_shape(shape);+ type = ov::element::u8;+ }+ set_output_type(0, type, shape);+}++std::shared_ptr<ov::Node> GGUFConstant::clone_with_new_inputs(const ov::OutputVector& inputs) const {+ OPENVINO_ASSERT(inputs.empty(), "GGUFConstant has no inputs");+ auto clone = std::make_shared<GGUFConstant>(m_source);+ clone->set_attrs(get_attrs());+ return clone;+}++std::shared_ptr<ov::Node> GGUFConstant::materialize() const {+ return make_weight_node(m_source);+}+GgufTensorType GGUFConstant::qtype() const {+ return m_source.qtype;+}+const GgufWeight& GGUFConstant::source() const {+ return m_source;+}++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/helper_ops/gguf_constant.hpp b/src/frontends/gguf/src/helper_ops/gguf_constant.hppnew file mode 100644index 00000000000..64cb7cef662--- /dev/null+++ b/src/frontends/gguf/src/helper_ops/gguf_constant.hpp@@ -0,0 +1,26 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/op/util/framework_node.hpp"+#include "quant/gguf.hpp"++namespace ov::frontend::gguf {++class GGUFConstant : public ov::op::util::FrameworkNode {+public:+ OPENVINO_OP("GGUFConstant", "gguf", ov::op::util::FrameworkNode);+ explicit GGUFConstant(const GgufWeight& source);+ void validate_and_infer_types() override;+ std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& inputs) const override;+ std::shared_ptr<ov::Node> materialize() const;+ GgufTensorType qtype() const;+ const GgufWeight& source() const;++private:+ GgufWeight m_source;+};++} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/op/get_rows.cpp b/src/frontends/gguf/src/op/get_rows.cppindex 9105502193e..de1aa0d8898 100644--- a/src/frontends/gguf/src/op/get_rows.cpp+++ b/src/frontends/gguf/src/op/get_rows.cpp@@ -18,7 +18,6 @@#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/unsqueeze.hpp"-#include "quant/weights.hpp"#include "utils.hpp"namespace ov::frontend::gguf::op {@@ -134,7 +133,9 @@ OutputVector translate_get_rows(const NodeContext& context) {res = std::make_shared<ov::op::v8::Gather>(data, indices, axis, 1);}} else {- res = gather_weight_rows(data, indices);+ res = std::make_shared<ov::op::v8::Gather>(data,+ indices,+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}));}// The two Squeezes above dropped the leading axes; restore ggml's rank-4 form.diff --git a/src/frontends/gguf/src/op/mul_mat_id.cpp b/src/frontends/gguf/src/op/mul_mat_id.cppindex 716ac332336..742285391bc 100644--- a/src/frontends/gguf/src/op/mul_mat_id.cpp+++ b/src/frontends/gguf/src/op/mul_mat_id.cpp@@ -8,6 +8,7 @@#include <memory>#include <vector>+#include "helper_ops/gguf_constant.hpp"#include "node_context.hpp"#include "op_table.hpp"#include "openvino/op/bitwise_and.hpp"@@ -357,7 +358,7 @@ OutputVector translate_mul_mat_id(const NodeContext& context) {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) {result = translate_mul_mat_id_mxfp4_packed(expert_weights, activations, safe_ids);- } else if (ov::op::util::is_on_path<ov::op::v0::Constant>(expert_weights)) {+ } else if (ov::op::util::is_on_path<ov::op::v0::Constant, GGUFConstant>(expert_weights)) {result = translate_mul_mat_id_gathermatmul(expert_weights, activations, safe_ids);} else {result = translate_mul_mat_id_generic(expert_weights, activations, safe_ids);diff --git a/src/frontends/gguf/src/op/mulmat.cpp b/src/frontends/gguf/src/op/mulmat.cppindex 93307aec82e..b87322f9b5c 100644--- a/src/frontends/gguf/src/op/mulmat.cpp+++ b/src/frontends/gguf/src/op/mulmat.cpp@@ -7,6 +7,7 @@#include <memory>#include <vector>+#include "helper_ops/gguf_constant.hpp"#include "node_context.hpp"#include "op_table.hpp"#include "openvino/core/node.hpp"@@ -37,8 +38,10 @@ OutputVector translate_mulmat(const NodeContext& context) {auto weight = B.get_node_shared_ptr();while (weight->get_input_size() > 0)weight = weight->get_input_node_shared_ptr(0);+ const auto deferred = ov::as_type_ptr<GGUFConstant>(weight);const bool u2_weights =- ov::is_type<ov::op::v0::Constant>(weight) && weight->get_output_element_type(0) == ov::element::u2;+ (ov::is_type<ov::op::v0::Constant>(weight) && weight->get_output_element_type(0) == ov::element::u2) ||+ (deferred && gguf_has_u2_weights(deferred->qtype()));const auto& shape = A.get_partial_shape();const bool rank3_output = context.get_attribute<int>("activation_rank", 4) == 3;const bool rank3_projection = u2_weights && shape.rank() == 4 && shape[1] == 1 && shape[3].is_static() &&diff --git a/src/frontends/gguf/src/op/view.cpp b/src/frontends/gguf/src/op/view.cppindex 9921939ee3b..227e9bf5e9b 100644--- a/src/frontends/gguf/src/op/view.cpp+++ b/src/frontends/gguf/src/op/view.cpp@@ -70,6 +70,17 @@ void place_dynamic_token_axis(std::vector<int64_t>& tgt, const ov::PartialShape&OutputVector translate_view(const NodeContext& context) {num_inputs_check(context, 1, 2);+ // op_case 105 (builder): constant row or column permutation of a weight.+ if (context.get_op_case() == 105) {+ const auto gather_indices = context.get_attribute<std::vector<int64_t>>("gather_indices");+ const auto axis = context.get_attribute<int64_t>("gather_axis");+ auto indices = ov::op::v0::Constant::create(ov::element::i64, {gather_indices.size()}, gather_indices);+ auto axis_node = ov::op::v0::Constant::create(ov::element::i64, {}, {axis});+ return rename_outputs_with_suffix(+ {std::make_shared<ov::op::v8::Gather>(context.get_input(0), indices, axis_node)},+ context.get_name());+ }+const auto& output_shape = context.get_output_shape();const auto& input_shape = context.get_input_shape(0);if ((output_shape.is_static() && ov::shape_size(output_shape.to_shape()) == 0) ||diff --git a/src/frontends/gguf/src/op/weight.cpp b/src/frontends/gguf/src/op/weight.cppindex 7d0e7c20d1a..4a660db6b7c 100644--- a/src/frontends/gguf/src/op/weight.cpp+++ b/src/frontends/gguf/src/op/weight.cpp@@ -2,90 +2,30 @@// SPDX-License-Identifier: Apache-2.0//-#include <functional>-#include <memory>-#include <numeric>-#include <vector>-+#include "helper_ops/gguf_constant.hpp"#include "node_context.hpp"#include "op_table.hpp"-#include "openvino/op/constant.hpp"-#include "openvino/op/reshape.hpp"-#include "openvino/op/unsqueeze.hpp"#include "quant/weights.hpp"#include "utils.hpp"namespace ov::frontend::gguf::op {-// A GGUF weight surfaced as a node. A weight is a ggml leaf (op type "GGML_OP_NONE") that the-// decoder marks as a weight. Two payload shapes are supported, both dequantized here so the-// decoder never builds OV nodes itself:-//-// 1. Native .gguf builder path: the parser already extracted the weight into OpenVINO tensors-// (weight [+ scales [+ zp]]); the node carries them as attributes "gguf.blob.<sub>" plus the-// quant type id "gguf_qtype" (and marker "gguf_weight"). We pass the tensors directly to-// make_weight_node -- the exact dequant path the builder used before, unchanged numerics,-// and it handles fused-QKV parts / MoE experts uniformly.-//-// 2. llama.cpp cgraph path: the node carries the raw ggml bytes in "data" plus the ggml type-// name "quant_type"; make_weight_node(data, quant_type, shape) re-extracts and builds. This-// path also handles the MoE MXFP4 packed / rank>2 expert-weight layouts.-//-// (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) {- // Path 1: pre-extracted tensors from the native builder.- if (context.get_attribute<bool>("gguf_weight", false)) {- WeightTensors tensors{- context.get_attribute<ov::Tensor>("gguf.blob.weight", ov::Tensor()),- context.get_attribute<ov::Tensor>("gguf.blob.scales", ov::Tensor()),- context.get_attribute<ov::Tensor>("gguf.blob.zp", ov::Tensor()),- };- FRONT_END_OP_CONVERSION_CHECK(tensors.weight, "GGML_OP_NONE weight leaf has no 'gguf.blob.weight' attribute");- auto qtype = static_cast<GgufTensorType>(context.get_attribute<int>("gguf_qtype"));- auto node = make_weight_node(tensors, qtype, context.get_name());- return rename_outputs_with_suffix({std::move(node)}, context.get_name());- }-- // Path 2: raw ggml bytes from a live cgraph decoder.- auto data = context.get_attribute<ov::Tensor>("data");- FRONT_END_OP_CONVERSION_CHECK(data, "GGML_OP_NONE node has no weight payload; 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({std::move(packed)}, context.get_name());+ GgufWeight source;+ const auto parsed = context.get_attribute<GgufWeight>("gguf_source", GgufWeight{});+ if (parsed.data) {+ source = parsed;+ } else {+ source.data = context.get_attribute<ov::Tensor>("data");+ FRONT_END_OP_CONVERSION_CHECK(source.data, "GGML_OP_NONE node has no weight payload");+ source.shape = context.get_output_shape().to_shape();+ source.qtype = gguf_type_from_name(context.get_attribute<std::string>("quant_type"));+ source.source_name = context.get_name();+ source.native = false;}-- // 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({std::move(reshaped)}, context.get_name());- }-- auto node = make_weight_node(data, quant_type, shape, context.get_name());- return rename_outputs_with_suffix({std::move(node)}, context.get_name());+ auto node = std::make_shared<GGUFConstant>(source);+ node->set_friendly_name(context.get_name());+ return rename_outputs_with_suffix({node}, context.get_name());}} // namespace ov::frontend::gguf::opdiff --git a/src/frontends/gguf/src/pass/materialize_weights.cpp b/src/frontends/gguf/src/pass/materialize_weights.cppnew file mode 100644index 00000000000..cfc6d2349d5--- /dev/null+++ b/src/frontends/gguf/src/pass/materialize_weights.cpp@@ -0,0 +1,399 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "materialize_weights.hpp"++#include <algorithm>+#include <array>+#include <cstring>+#include <map>+#include <numeric>+#include <optional>++#include "helper_ops/gguf_constant.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/validation_util.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/reshape.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/variadic_split.hpp"+#include "quant/weights.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::frontend::gguf::pass {+namespace {++// Consecutive rows [first, first + count) of one GGUF leaf.+struct RowRun {+ std::shared_ptr<const GGUFConstant> leaf;+ size_t first;+ size_t count;++ const GgufWeight& source() const {+ return leaf->source();+ }+};++struct WeightPlan {+ ov::Shape shape;+ std::vector<RowRun> runs;+ std::vector<int64_t> columns;++ void append(const RowRun& run) {+ if (!runs.empty() && runs.back().leaf == run.leaf && runs.back().first + runs.back().count == run.first)+ runs.back().count += run.count;+ else+ runs.push_back(run);+ }+};++bool compatible(const WeightPlan& lhs, const WeightPlan& rhs) {+ if (lhs.shape.size() != rhs.shape.size() || lhs.shape.empty() || lhs.runs.empty() || rhs.runs.empty() ||+ !std::equal(lhs.shape.begin() + 1, lhs.shape.end(), rhs.shape.begin() + 1) || lhs.columns != rhs.columns)+ return false;+ const auto& a = lhs.runs.front().source();+ const auto& b = rhs.runs.front().source();+ return gguf_same_unpacked_layout(a, b) && same_weight_conversion_policy(a.source_name, b.source_name);+}++using Plans = std::map<ov::Node*, std::optional<WeightPlan>>;++std::optional<std::vector<int64_t>> constant_values(const std::shared_ptr<ov::Node>& node) {+ const auto value = ov::as_type_ptr<ov::op::v0::Constant>(node);+ if (!value || !value->get_element_type().is_integral_number())+ return std::nullopt;+ return value->cast_vector<int64_t>();+}++const std::optional<WeightPlan>& plan_weight(const std::shared_ptr<ov::Node>& node, Plans& plans) {+ if (const auto found = plans.find(node.get()); found != plans.end())+ return found->second;+ std::optional<WeightPlan> result;+ if (const auto leaf = ov::as_type_ptr<GGUFConstant>(node)) {+ const auto& source = leaf->source();+ if (source.native && !source.shape.empty() && source.shape.size() <= 2 && ov::shape_size(source.shape) != 0 &&+ (source.shape.size() == 2 || gguf_weight_group_size(source) == 1)) {+ result = WeightPlan{source.shape, {{leaf, 0, source.shape[0]}}, {}};+ }+ } else if (const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(node)) {+ if (concat->get_axis() == 0 && concat->get_input_size() >= 2) {+ result = plan_weight(concat->get_input_node_shared_ptr(0), plans);+ for (size_t i = 1; result && i < concat->get_input_size(); ++i) {+ const auto& next = plan_weight(concat->get_input_node_shared_ptr(i), plans);+ if (!next || !compatible(*result, *next)) {+ result.reset();+ break;+ }+ for (const auto& run : next->runs)+ result->append(run);+ result->shape[0] += next->shape[0];+ }+ }+ } else if (ov::is_type<ov::op::util::GatherBase>(node) || ov::is_type<ov::op::v8::Slice>(node)) {+ const auto& input = plan_weight(node->get_input_node_shared_ptr(0), plans);+ std::vector<int64_t> selection;+ int64_t axis = -1;+ bool valid = false;+ if (input && ov::is_type<ov::op::v8::Slice>(node) && node->get_input_size() == 5) {+ const auto start = constant_values(node->get_input_node_shared_ptr(1));+ const auto stop = constant_values(node->get_input_node_shared_ptr(2));+ const auto step = constant_values(node->get_input_node_shared_ptr(3));+ const auto axes = constant_values(node->get_input_node_shared_ptr(4));+ if (start && stop && step && axes && start->size() == 1 && stop->size() == 1 && step->size() == 1 &&+ axes->size() == 1 && (*step)[0] > 0) {+ axis = ov::util::normalize((*axes)[0], input->shape.size());+ if (axis >= 0 && static_cast<size_t>(axis) < input->shape.size()) {+ const auto extent = static_cast<int64_t>(input->shape[axis]);+ const auto begin = std::clamp(ov::util::normalize((*start)[0], extent), int64_t{0}, extent);+ const auto end = std::clamp(ov::util::normalize((*stop)[0], extent), int64_t{0}, extent);+ for (auto i = begin; i < end;) {+ selection.push_back(i);+ if ((*step)[0] >= end - i)+ break;+ i += (*step)[0];+ }+ valid = true;+ }+ }+ } else if (input) {+ const auto indices = constant_values(node->get_input_node_shared_ptr(1));+ const auto axes = constant_values(node->get_input_node_shared_ptr(2));+ const auto gather = ov::as_type_ptr<ov::op::util::GatherBase>(node);+ if (indices && axes && axes->size() == 1 && gather && gather->get_batch_dims() == 0 &&+ node->get_input_shape(1).size() == 1) {+ axis = ov::util::normalize((*axes)[0], input->shape.size());+ selection = *indices;+ valid = axis >= 0 && static_cast<size_t>(axis) < input->shape.size();+ if (valid) {+ const auto extent = static_cast<int64_t>(input->shape[axis]);+ for (auto& index : selection) {+ index = ov::util::normalize(index, extent);+ valid &= index >= 0 && index < extent;+ }+ }+ }+ }+ if (valid && !selection.empty()) {+ if (axis == 0) {+ std::vector<size_t> ends;+ for (const auto& run : input->runs)+ ends.push_back((ends.empty() ? 0 : ends.back()) + run.count);+ WeightPlan plan{input->shape, {}, input->columns};+ for (const auto index : selection) {+ const auto run =+ std::upper_bound(ends.begin(), ends.end(), static_cast<size_t>(index)) - ends.begin();+ const auto offset = static_cast<size_t>(index) - (run == 0 ? 0 : ends[run - 1]);+ plan.append({input->runs[run].leaf, input->runs[run].first + offset, 1});+ }+ plan.shape[0] = selection.size();+ result = std::move(plan);+ } else if (axis == 1 && input->shape.size() == 2) {+ WeightPlan plan{input->shape, input->runs, {}};+ for (const auto index : selection)+ plan.columns.push_back(input->columns.empty() ? index : input->columns[index]);+ if (std::all_of(plan.runs.begin(), plan.runs.end(), [&](const auto& run) {+ return gguf_column_groups_are_aligned(run.source(), plan.columns);+ })) {+ plan.shape[1] = selection.size();+ result = std::move(plan);+ }+ }+ }+ } else if (ov::is_type<ov::op::v1::Reshape>(node) || ov::is_type<ov::op::v0::Convert>(node) ||+ ov::is_type<ov::op::v1::Transpose>(node)) {+ const auto& input = plan_weight(node->get_input_node_shared_ptr(0), plans);+ if (input && node->get_output_partial_shape(0).is_static() && node->get_output_shape(0) == input->shape &&+ node->get_output_element_type(0) == ov::element::f32) {+ if (ov::is_type<ov::op::v1::Transpose>(node)) {+ const auto order = constant_values(node->get_input_node_shared_ptr(1));+ bool identity = order && order->size() == input->shape.size();+ for (size_t i = 0; identity && i < order->size(); ++i)+ identity &= (*order)[i] == static_cast<int64_t>(i);+ if (identity)+ result = input;+ } else+ result = input;+ }+ }+ return plans.emplace(node.get(), std::move(result)).first->second;+}++std::array<ov::Tensor*, 3> components(WeightTensors& tensors) {+ return {&tensors.weight, &tensors.scales, &tensors.zero_point};+}++GgufWeight source_rows(const GgufWeight& source, size_t first, size_t count) {+ auto result = source;+ const size_t row_bytes = source.data.get_byte_size() / source.shape[0];+ result.shape[0] = count;+ auto* pointer = const_cast<uint8_t*>(static_cast<const uint8_t*>(source.data.data())) + first * row_bytes;+ const auto data_shape =+ source.data.get_element_type() == ov::element::u8 ? ov::Shape{count * row_bytes} : result.shape;+ auto view = ov::Tensor(source.data.get_element_type(), data_shape, pointer);+ result.data = ov::Tensor(view, std::make_shared<ov::Tensor>(source.data));+ return result;+}++std::shared_ptr<ov::Node> materialize_plan(const WeightPlan& plan) {+ const auto& first_source = plan.runs.front().source();+ auto output = allocate_gguf_weight(first_source, plan.shape);+ const auto outputs = components(output);+ size_t begin = 0;+ for (const auto& run : plan.runs) {+ const size_t end = begin + run.count;+ auto source = source_rows(run.source(), run.first, run.count);+ WeightTensors views;+ const auto destinations = components(views);+ for (size_t i = 0; i < outputs.size(); ++i) {+ if (!*outputs[i])+ continue;+ auto shape = outputs[i]->get_shape();+ const auto row_bytes = outputs[i]->get_byte_size() / shape[0];+ shape[0] = end - begin;+ *destinations[i] = ov::Tensor(outputs[i]->get_element_type(),+ shape,+ static_cast<uint8_t*>(outputs[i]->data()) + begin * row_bytes);+ }+ if (plan.columns.empty()) {+ unpack_gguf_weight_into(source, views);+ evict_gguf_weight(source);+ } else {+ auto unpacked = unpack_gguf_weight(source);+ const auto inputs = components(unpacked);+ const auto group = gguf_weight_group_size(source);+ for (size_t i = 0; i < inputs.size(); ++i) {+ if (!*inputs[i])+ continue;+ const auto input_row_bytes = inputs[i]->get_byte_size() / (end - begin);+ const auto output_row_bytes = destinations[i]->get_byte_size() / (end - begin);+ const auto block_bytes = input_row_bytes / (source.shape.back() / group);+ const auto* in = static_cast<const uint8_t*>(inputs[i]->data());+ auto* out = static_cast<uint8_t*>(destinations[i]->data());+ for (size_t r = 0; r < end - begin; ++r)+ for (size_t col = 0; col < plan.columns.size(); col += group)+ std::memcpy(out + r * output_row_bytes + col / group * block_bytes,+ in + r * input_row_bytes + plan.columns[col] / group * block_bytes,+ block_bytes);+ }+ }+ begin = end;+ }+ return make_weight_node(output, first_source.qtype, first_source.source_name);+}++void fuse_projections(const std::shared_ptr<ov::Model>& model) {+ using MatMul = ov::op::v0::MatMul;+ std::map<std::pair<ov::Node*, size_t>, std::vector<std::shared_ptr<MatMul>>> groups;+ Plans plans;+ for (const auto& node : model->get_ordered_ops()) {+ const auto matmul = ov::as_type_ptr<MatMul>(node);+ if (!matmul || matmul->get_transpose_a() || !matmul->get_transpose_b())+ continue;+ const auto& plan = plan_weight(matmul->get_input_node_shared_ptr(1), plans);+ if (!plan || plan->shape.size() != 2 || !gguf_is_q2_0_family(plan->runs.front().source().qtype))+ continue;+ const auto input = matmul->input_value(0);+ groups[{input.get_node(), input.get_index()}].push_back(matmul);+ }+ for (const auto& [input, candidates] : groups) {+ std::vector<bool> used(candidates.size());+ for (size_t first = 0; first < candidates.size(); ++first) {+ if (used[first])+ continue;+ const auto& first_plan = plan_weight(candidates[first]->get_input_node_shared_ptr(1), plans);+ std::vector<std::shared_ptr<MatMul>> projections{candidates[first]};+ ov::OutputVector weights{candidates[first]->input_value(1)};+ std::vector<int64_t> lengths{static_cast<int64_t>(first_plan->shape[0])};+ for (size_t i = first + 1; i < candidates.size(); ++i) {+ if (used[i])+ continue;+ const auto& plan = plan_weight(candidates[i]->get_input_node_shared_ptr(1), plans);+ if (!compatible(*first_plan, *plan))+ continue;+ projections.push_back(candidates[i]);+ weights.push_back(candidates[i]->input_value(1));+ lengths.push_back(plan->shape[0]);+ used[i] = true;+ }+ if (projections.size() == 1)+ continue;+ auto concat = std::make_shared<ov::op::v0::Concat>(weights, 0);+ auto merged = std::make_shared<MatMul>(projections.front()->input_value(0), concat, false, true);+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {-1});+ auto sizes = ov::op::v0::Constant::create(ov::element::i64, {lengths.size()}, lengths);+ auto split = std::make_shared<ov::op::v1::VariadicSplit>(merged, axis, sizes);+ ov::copy_runtime_info(ov::NodeVector(projections.begin(), projections.end()), {concat, merged, split});+ for (size_t i = 0; i < projections.size(); ++i)+ ov::replace_node(projections[i], ov::OutputVector{split->output(i)});+ }+ }+}++bool collect_projection_weights(const std::shared_ptr<ov::Node>& node, Plans& plans, ov::OutputVector& weights) {+ if (const auto& plan = plan_weight(node, plans)) {+ if (plan->shape.size() != 2)+ return false;+ weights.push_back(node);+ return true;+ }+ const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(node);+ if (!concat || concat->get_axis() != 0)+ return false;+ for (const auto& input : concat->input_values())+ if (!collect_projection_weights(input.get_node_shared_ptr(), plans, weights))+ return false;+ return true;+}++void separate_incompatible_projections(const std::shared_ptr<ov::Model>& model) {+ Plans plans;+ for (const auto& node : model->get_ordered_ops()) {+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node);+ if (!matmul || matmul->get_transpose_a() || !matmul->get_transpose_b())+ continue;+ const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(matmul->get_input_node_shared_ptr(1));+ if (!concat || concat->get_axis() != 0 || plan_weight(concat, plans))+ continue;+ ov::OutputVector weights;+ if (!collect_projection_weights(concat, plans, weights))+ continue;+ ov::OutputVector outputs;+ for (const auto& weight : weights) {+ auto projection = std::make_shared<ov::op::v0::MatMul>(matmul->input_value(0), weight, false, true);+ ov::copy_runtime_info(matmul, projection);+ outputs.push_back(projection);+ }+ auto replacement = std::make_shared<ov::op::v0::Concat>(outputs, -1);+ replacement->set_friendly_name(matmul->get_friendly_name());+ ov::copy_runtime_info(matmul, replacement);+ ov::replace_node(matmul, replacement);+ }+}++// Weights are deferred while GET_ROWS translates, so its packed-row lookup is applied once they exist.+void gather_packed_rows(const std::shared_ptr<ov::Model>& model) {+ for (const auto& node : model->get_ordered_ops()) {+ const auto gather = ov::as_type_ptr<ov::op::v8::Gather>(node);+ if (!gather || gather->get_batch_dims() != 0 ||+ constant_values(gather->get_input_node_shared_ptr(2)) != std::vector<int64_t>{0})+ continue;+ if (const auto packed = gather_packed_u2_rows(gather->input_value(0), gather->input_value(1)))+ ov::replace_node_update_name(gather, packed);+ }+}++} // namespace++bool MaterializeGGUFWeights::run_on_model(const std::shared_ptr<ov::Model>& model) {+ bool changed = false;+ for (const auto& node : model->get_ordered_ops())+ changed |= ov::op::util::process_subgraph(*this, node);+ separate_incompatible_projections(model);+ fuse_projections(model);+ Plans plans;+ const auto nodes = model->get_ordered_ops();+ std::vector<std::pair<std::shared_ptr<ov::Node>, const WeightPlan*>> roots;+ for (const auto& node : nodes) {+ if (ov::is_type<GGUFConstant>(node))+ continue;+ const auto& plan = plan_weight(node, plans);+ if (!plan)+ continue;+ bool root = false;+ for (const auto& consumer : node->output(0).get_target_inputs())+ root |= !plan_weight(consumer.get_node()->shared_from_this(), plans).has_value();+ if (root)+ roots.emplace_back(node, &*plan);+ }+ for (const auto& [node, plan] : roots) {+ auto materialized = materialize_plan(*plan);+ OPENVINO_ASSERT(materialized->get_output_shape(0) == node->get_output_shape(0) &&+ materialized->get_output_element_type(0) == node->get_output_element_type(0),+ "Folded GGUF weight has unexpected shape or type");+ ov::replace_node_update_name(node, materialized);+ changed = true;+ }+ for (const auto& node : model->get_ordered_ops())+ if (const auto weight = ov::as_type_ptr<GGUFConstant>(node)) {+ auto materialized = weight->materialize();+ OPENVINO_ASSERT(materialized->get_output_partial_shape(0) == weight->get_output_partial_shape(0) &&+ materialized->get_output_element_type(0) == weight->get_output_element_type(0),+ "Materialized GGUF weight has unexpected shape or type: ",+ weight->source().source_name);+ ov::replace_node_update_name(weight, materialized);+ changed = true;+ }+ if (changed)+ gather_packed_rows(model);+ return changed;+}++} // namespace ov::frontend::gguf::passdiff --git a/src/frontends/gguf/src/pass/materialize_weights.hpp b/src/frontends/gguf/src/pass/materialize_weights.hppnew file mode 100644index 00000000000..4643149ee01--- /dev/null+++ b/src/frontends/gguf/src/pass/materialize_weights.hpp@@ -0,0 +1,17 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/pass.hpp"++namespace ov::frontend::gguf::pass {++class MaterializeGGUFWeights : public ov::pass::ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::MaterializeGGUFWeights");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::frontend::gguf::passdiff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cppindex 765dc69c40b..bb94608fc21 100644--- a/src/frontends/gguf/src/quant/gguf.cpp+++ b/src/frontends/gguf/src/quant/gguf.cpp@@ -42,7 +42,6 @@ namespace {constexpr uint32_t GGUF_MAGIC = 0x46554747; // "GGUF" little-endianconstexpr uint64_t GGUF_DEFAULT_ALIGNMENT = 32;-constexpr std::string_view WEIGHT_SUFFIX = ".weight";// (items_per_block, bytes_per_block) per GgufTensorType, indexed by the type id.struct TypeTraits {@@ -358,6 +357,133 @@ ov::Shape get_shape(const GgufTensor& tensor) {return shape;}+GgufWeight::GgufWeight(const ov::Tensor& tensor) : data(tensor), shape(tensor.get_shape()) {+ for (const auto type : {GGUF_TYPE_F32,+ GGUF_TYPE_F16,+ GGUF_TYPE_BF16,+ GGUF_TYPE_F64,+ GGUF_TYPE_I8,+ GGUF_TYPE_I16,+ GGUF_TYPE_I32,+ GGUF_TYPE_I64}) {+ if (gguf_type_to_dtype(type) == tensor.get_element_type()) {+ qtype = type;+ return;+ }+ }+ OPENVINO_THROW("Unsupported generated GGUF weight element type ", tensor.get_element_type());+}++WeightTensors allocate_gguf_weight(const GgufWeight& source, const ov::Shape& shape) {+ WeightTensors result;+ const auto layout = quant_layout(source.qtype, source.source_name);+ if (!layout) {+ result.weight = ov::Tensor(source.data.get_element_type(), shape);+ return result;+ }+ OPENVINO_ASSERT(!shape.empty() && shape.back() % layout->group_size == 0 && shape.back() % layout->weight_div == 0,+ "Invalid GGUF weight shape ",+ shape);+ auto weight_shape = shape;+ weight_shape.back() /= layout->weight_div;+ auto scale_shape = shape;+ scale_shape.back() /= layout->group_size;+ result.weight = ov::Tensor(layout->weight_type, weight_shape);+ result.scales = ov::Tensor(layout->scale_type, scale_shape);+ if (layout->asymmetric)+ result.zero_point = ov::Tensor(gguf_zero_point_type(source.source_name, source.qtype), scale_shape);+ return result;+}++void unpack_gguf_weight_into(const GgufWeight& source, WeightTensors& destination) {+ const auto layout = quant_layout(source.qtype, source.source_name);+ if (!layout) {+ OPENVINO_ASSERT(source.data.get_element_type() == destination.weight.get_element_type() &&+ source.data.get_byte_size() == destination.weight.get_byte_size());+ std::memcpy(destination.weight.data(), source.data.data(), source.data.get_byte_size());+ return;+ }+ GgufTensor tensor;+ tensor.type = source.qtype;+ OPENVINO_ASSERT(source.shape.size() <= 4, "Unsupported GGUF weight rank");+ tensor.ndim = static_cast<uint32_t>(source.shape.size());+ tensor.num_weights = ov::shape_size(source.shape);+ for (size_t i = 0; i < source.shape.size(); ++i)+ tensor.dim[i] = source.shape[source.shape.size() - 1 - i];+ tensor.name = source.source_name.data();+ tensor.namelen = source.source_name.size();+ tensor.weights_data = source.data.data<const uint8_t>();+ tensor.bsize = source.data.get_byte_size();+ if (source.qtype == GGUF_TYPE_Q5_K && !layout->asymmetric)+ gguf_fill_q5_k_i8(tensor, destination.weight, destination.scales);+ else if (source.qtype == GGUF_TYPE_MXFP4)+ gguf_fill_mxfp4(tensor, destination.weight, destination.scales);+ else if (gguf_is_q2_0_family(source.qtype))+ gguf_fill_q2_0(tensor, destination.weight, destination.scales, destination.zero_point);+ else if (layout->asymmetric)+ gguf_fill_asym(tensor, destination.weight, destination.scales, destination.zero_point);+ else+ gguf_fill_sym(tensor, destination.weight, destination.scales);+}++WeightTensors unpack_gguf_weight(const GgufWeight& source) {+ if (!quant_layout(source.qtype, source.source_name))+ return {source.data, {}, {}};+ auto result = allocate_gguf_weight(source, source.shape);+ unpack_gguf_weight_into(source, result);+ evict_gguf_weight(source);+ return result;+}++bool gguf_is_q2_0_family(GgufTensorType type) {+ return type == GGUF_TYPE_Q2_0 || type == GGUF_TYPE_PQ2_0 || type == GGUF_TYPE_PTQ1_0;+}++bool gguf_same_unpacked_layout(const GgufWeight& a, const GgufWeight& b) {+ if (a.qtype != b.qtype || a.native != b.native)+ return false;+ const auto lhs = quant_layout(a.qtype, a.source_name);+ const auto rhs = quant_layout(b.qtype, b.source_name);+ if (!lhs || !rhs)+ return !lhs && !rhs && a.data.get_element_type() == b.data.get_element_type();+ return lhs->weight_type == rhs->weight_type && lhs->weight_div == rhs->weight_div &&+ lhs->scale_type == rhs->scale_type && lhs->group_size == rhs->group_size &&+ lhs->asymmetric == rhs->asymmetric &&+ (!lhs->asymmetric ||+ gguf_zero_point_type(a.source_name, a.qtype) == gguf_zero_point_type(b.source_name, b.qtype));+}++void evict_gguf_weight(const GgufWeight& source) {+ if (!source.mapped)+ return;+ const auto* base = reinterpret_cast<const uint8_t*>(source.mapped->data());+ source.mapped->hint_evict(static_cast<const uint8_t*>(source.data.data()) - base, source.data.get_byte_size());+}++bool gguf_has_u2_weights(GgufTensorType type) {+ return gguf_is_q2_0_family(type) || type == GGUF_TYPE_Q2_K;+}++size_t gguf_weight_group_size(const GgufWeight& source) {+ const auto layout = quant_layout(source.qtype, source.source_name);+ return layout ? layout->group_size : 1;+}++bool gguf_column_groups_are_aligned(const GgufWeight& source, const std::vector<int64_t>& columns) {+ const auto group = gguf_weight_group_size(source);+ if (columns.size() % group != 0)+ return false;+ for (size_t i = 0; i < columns.size(); i += group) {+ if (columns[i] < 0 || static_cast<size_t>(columns[i]) % group != 0)+ return false;+ for (size_t j = 0; j < group; ++j)+ if (columns[i + j] != columns[i] + static_cast<int64_t>(j) ||+ static_cast<size_t>(columns[i + j]) >= source.shape.back())+ return false;+ }+ return true;+}+namespace {struct TensorInfo {@@ -503,9 +629,7 @@ void detect_legacy_q2_layout(std::vector<GgufFile>& files) {}}-void load_gguf_tensors(GgufFile& file,- std::unordered_map<std::string, ov::Tensor>& arrays,- std::unordered_map<std::string, GgufTensorType>& qtype) {+void load_gguf_tensors(GgufFile& file, GgufWeightTable& arrays) {auto& [metadata, infos, mapped, alignment, data_off] = file;const auto* base = reinterpret_cast<const uint8_t*>(mapped->data());const uint64_t fsize = mapped->size();@@ -584,55 +708,23 @@ void load_gguf_tensors(GgufFile& file,tensor.weights_data = base + abs_off;const std::string& name = ti.name;- // For tensors ending in ".weight" strip the suffix so make_weight_node keys are- // "blk.N.attn_q" (not "blk.N.attn_q.weight"). For quantized non-weight tensors- // (e.g. gpt-oss "blk.N.attn_k.bias") keep the full name as the prefix; the builder- // looks up scales/qtype as name + ".scales" / name + ".qtype".- const std::string name_prefix =- ov::util::ends_with(name, WEIGHT_SUFFIX) ? name.substr(0, name.length() - WEIGHT_SUFFIX.length()) : name;-- const auto layout = quant_layout(ti.type, ti.name);- if (!layout) {- ov::Tensor loaded = extract_tensor_data(tensor, mapped); // zero-copy mmap view- const bool inserted = arrays.emplace(name, std::move(loaded)).second;- OPENVINO_ASSERT(inserted, "[load_gguf] duplicate tensor name '", name, "'");- qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));- continue;- }-- const auto shape = get_shape(tensor);- ov::Shape weight_shape = shape;- weight_shape.back() /= layout->weight_div;- ov::Shape scale_shape = shape;- scale_shape.back() /= layout->group_size;-- // Independent buffers let replaced weights be freed without retaining the whole model.- ov::Tensor weights(layout->weight_type, weight_shape);- ov::Tensor scales(layout->scale_type, scale_shape);- ov::Tensor zp;- if (layout->asymmetric) {- zp = ov::Tensor(gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type)), scale_shape);- }-- if (ti.type == GGUF_TYPE_Q5_K && !layout->asymmetric) {- gguf_fill_q5_k_i8(tensor, weights, scales);- } else if (ti.type == GGUF_TYPE_MXFP4) {- gguf_fill_mxfp4(tensor, weights, scales);- } else if (ti.type == GGUF_TYPE_Q2_0 || ti.type == GGUF_TYPE_PQ2_0 || ti.type == GGUF_TYPE_PTQ1_0) {- gguf_fill_q2_0(tensor, weights, scales, zp);- } else if (layout->asymmetric) {- gguf_fill_asym(tensor, weights, scales, zp);+ GgufWeight source;+ source.shape = get_shape(tensor);+ source.qtype = static_cast<GgufTensorType>(ti.type);+ source.source_name = name;+ source.mapped = mapped;+ if (quant_layout(ti.type, ti.name)) {+ auto bytes = ov::Tensor(ov::element::u8,+ {static_cast<size_t>(tensor.bsize)},+ const_cast<uint8_t*>(tensor.weights_data));+ source.data = ov::Tensor(bytes, mapped);} else {- gguf_fill_sym(tensor, weights, scales);+ source.data = extract_tensor_data(tensor, mapped);}- mapped->hint_evict(abs_off, tensor.bsize);-- arrays.emplace(name, std::move(weights));- arrays.emplace(name_prefix + ".scales", std::move(scales));- if (zp) {- arrays.emplace(name_prefix + ".zp", std::move(zp));- }- qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));+ OPENVINO_ASSERT(arrays.emplace(name, std::move(source)).second,+ "[load_gguf] duplicate tensor name '",+ name,+ "'");}}@@ -721,16 +813,15 @@ GGUFLoad load_gguf_files(std::vector<GgufFile> files) {}}- std::unordered_map<std::string, ov::Tensor> arrays;- std::unordered_map<std::string, GgufTensorType> qtype;+ GgufWeightTable arrays;std::vector<std::shared_ptr<ov::MappedMemory>> mappings;mappings.reserve(files.size());detect_legacy_q2_layout(files);for (auto& file : files) {- load_gguf_tensors(file, arrays, qtype);+ load_gguf_tensors(file, arrays);mappings.push_back(std::move(file.mapped));}- return {std::move(files.front().metadata), std::move(arrays), std::move(qtype), std::move(mappings)};+ return {std::move(files.front().metadata), std::move(arrays), std::move(mappings)};}} // namespacediff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hppindex f1b664782fa..5c80a59f8d5 100644--- a/src/frontends/gguf/src/quant/gguf.hpp+++ b/src/frontends/gguf/src/quant/gguf.hpp@@ -7,6 +7,7 @@#include <cstdint>#include <filesystem>#include <map>+#include <memory>#include <string>#include <unordered_map>#include <variant>@@ -88,10 +89,23 @@ struct GgufTensor {using GGUFMetaData =std::variant<std::monostate, float, int, ov::Tensor, std::string, std::vector<std::string>, std::vector<int32_t>>;-// Parsed arrays own repacked quantized buffers and keep non-quantized mmap views alive.+struct GgufWeight {+ ov::Tensor data;+ ov::Shape shape;+ GgufTensorType qtype = GGUF_TYPE_F32;+ std::string source_name;+ bool native = true;+ std::shared_ptr<ov::MappedMemory> mapped;++ GgufWeight() = default;+ GgufWeight(const ov::Tensor& tensor);+};++using GgufWeightTable = std::unordered_map<std::string, GgufWeight>;++// Raw weight descriptors retain the source mapping without unpacking quantized tensors.using GGUFLoad = std::tuple<std::unordered_map<std::string, GGUFMetaData>,- std::unordered_map<std::string, ov::Tensor>,- std::unordered_map<std::string, GgufTensorType>,+ GgufWeightTable,std::vector<std::shared_ptr<ov::MappedMemory>>>;// Fill pre-allocated weights and f16 scales from a symmetric GGUF tensor@@ -134,7 +148,23 @@ 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 GGUF metadata and tensors. Each repacked quantized tensor owns its buffer.+struct WeightTensors;++WeightTensors allocate_gguf_weight(const GgufWeight& source, const ov::Shape& shape);+void unpack_gguf_weight_into(const GgufWeight& source, WeightTensors& destination);+WeightTensors unpack_gguf_weight(const GgufWeight& source);+bool gguf_column_groups_are_aligned(const GgufWeight& source, const std::vector<int64_t>& columns);+size_t gguf_weight_group_size(const GgufWeight& source);+// Q2_0, PQ2_0 and PTQ1_0 share the ternary Q2_0 code layout.+bool gguf_is_q2_0_family(GgufTensorType type);+// Whether rows of `a` and `b` unpack into tensors of the same types, so they can share one buffer.+bool gguf_same_unpacked_layout(const GgufWeight& a, const GgufWeight& b);+// Hint the OS to drop the mmap pages backing source.data after it has been unpacked.+void evict_gguf_weight(const GgufWeight& source);+// Types unpacked to u2 weights: the Q2_0 family plus Q2_K.+bool gguf_has_u2_weights(GgufTensorType type);++// Parse GGUF metadata and raw weight descriptors.GGUFLoad get_gguf_data(const std::filesystem::path& file);GGUFLoad get_gguf_data(const std::vector<std::filesystem::path>& files);diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cppindex a52b911e360..d4382e152d2 100644--- a/src/frontends/gguf/src/quant/weights.cpp+++ b/src/frontends/gguf/src/quant/weights.cpp@@ -133,44 +133,6 @@ WeightFormat get_weight_format(GgufTensorType qtype,return et == ov::element::i8 ? WeightFormat{FillKind::SYMMETRIC, 32, ov::element::i8} : format;}-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(), "[GGUF] missing weight tensor: ", key);- return it->second;-}--// Copy the range [r0, r1) along the outermost dimension. Rows are block-independent in every-// GGUF quant layout, so a fused attn_qkv weight can be split by a plain row copy without-// touching the quant blocks; a fused attn_qkv.bias is a plain unquantized 1D array, where the-// same byte-range copy is exact regardless of dtype.-ov::Tensor slice_leading(const ov::Tensor& t, size_t r0, size_t r1) {- ov::Shape out_shape = t.get_shape();- OPENVINO_ASSERT(!out_shape.empty() && r1 <= out_shape[0] && r0 <= r1, "[GGUF] bad slice");- const size_t stride = t.get_byte_size() / out_shape[0];- out_shape[0] = r1 - r0;- ov::Tensor out(t.get_element_type(), out_shape);- std::memcpy(out.data(), static_cast<const uint8_t*>(t.data()) + r0 * stride, (r1 - r0) * stride);- return out;-}--// Gather rows in a repeating per-block pattern: for every `block` consecutive rows, take-// [offset, offset + take) into the result. Used to de-interleave qwen35's attn_q, which packs-// query and gate per head as [q_h0 | gate_h0 | q_h1 | gate_h1 | ...].-ov::Tensor gather_rows_strided(const ov::Tensor& t, size_t block, size_t take, size_t offset) {- const auto& s = t.get_shape();- OPENVINO_ASSERT(s.size() == 2 && block > 0 && offset + take <= block && s[0] % block == 0,- "[GGUF] bad strided row gather");- const size_t n_blocks = s[0] / block;- ov::Tensor out(t.get_element_type(), ov::Shape{n_blocks * take, s[1]});- const size_t row_bytes = t.get_byte_size() / s[0];- const auto* src = static_cast<const uint8_t*>(t.data());- auto* dst = static_cast<uint8_t*>(out.data());- for (size_t b = 0; b < n_blocks; ++b) {- std::memcpy(dst + b * take * row_bytes, src + (b * block + offset) * row_bytes, take * row_bytes);- }- return out;-}-// 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) {@@ -497,29 +459,26 @@ private:} // namespace-ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices) {+std::shared_ptr<ov::Node> gather_packed_u2_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices) {const auto axis = ov::op::v0::Constant::create(ov::element::i32, {}, {0});- const auto gather = [&]() -> ov::Output<ov::Node> {- return std::make_shared<ov::op::v8::Gather>(data, indices, axis);- };const auto output_convert = ov::as_type_ptr<ov::op::v0::Convert>(data.get_node_shared_ptr());if (!output_convert || data.get_element_type() != ov::element::f32 || !data.get_partial_shape().is_static() ||data.get_partial_shape().rank() != 2 || indices.get_partial_shape().rank() != 2)- return gather();+ return nullptr;const auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(output_convert->get_input_node_shared_ptr(0));if (!reshape)- return gather();+ return nullptr;const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(reshape->get_input_node_shared_ptr(0));if (!multiply || multiply->get_element_type() != ov::element::f16)- return gather();+ return nullptr;const auto scales = ov::as_type_ptr<ov::op::v0::Constant>(multiply->get_input_node_shared_ptr(1));const auto subtract = ov::as_type_ptr<ov::op::v1::Subtract>(multiply->get_input_node_shared_ptr(0));if (!scales || scales->get_element_type() != ov::element::f16 || !subtract)- return gather();+ return nullptr;const auto convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(0));const auto zp_convert = ov::as_type_ptr<ov::op::v0::Convert>(subtract->get_input_node_shared_ptr(1));if (!convert || convert->get_element_type() != ov::element::f16)- return gather();+ return nullptr;const auto weights = ov::as_type_ptr<ov::op::v0::Constant>(convert->get_input_node_shared_ptr(0));const auto zp = ov::as_type_ptr<ov::op::v0::Constant>(zp_convert ? zp_convert->get_input_node_shared_ptr(0): subtract->get_input_node_shared_ptr(1));@@ -527,14 +486,14 @@ ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, constweights->get_shape().back() % 4 != 0 || !zp ||(zp->get_element_type() != ov::element::u8 && zp->get_element_type() != ov::element::f16) ||!zp->get_shape().empty() || zp->cast_vector<float>()[0] != 1.f)- return gather();+ return nullptr;const auto shape = data.get_shape();const auto rows = shape[0];const auto cols = shape[1];if (weights->get_shape()[0] != rows || weights->get_shape()[1] * weights->get_shape()[2] != cols ||scales->get_shape() != ov::Shape{rows, weights->get_shape()[1], 1})- return gather();+ return nullptr;const auto& compressed_shape = weights->get_shape();// Gather packed bytes before unpacking, sharing the original two-bit buffer.auto dictionary =@@ -580,6 +539,12 @@ ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, constreturn std::make_shared<ov::op::v0::Convert>(restored, ov::element::f32);}+ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices) {+ if (const auto packed = gather_packed_u2_rows(data, indices))+ return packed;+ return std::make_shared<ov::op::v8::Gather>(data, indices, ov::op::v0::Constant::create(ov::element::i32, {}, {0}));+}+void normalize_u2_zero_points(const std::shared_ptr<ov::Model>& model) {const auto nodes = model->get_ordered_ops();if (std::none_of(nodes.begin(), nodes.end(), [](const std::shared_ptr<ov::Node>& node) {@@ -793,101 +758,19 @@ GgufTensorType gguf_type_from_name(const std::string& quant_type) {return it->second;}-GgufTensorType lookup_qtype(const std::string& base, const std::unordered_map<std::string, GgufTensorType>& qtypes) {- GgufTensorType qtype = GGUF_TYPE_F16;- if (auto it = qtypes.find(base + ".qtype"); it != qtypes.end()) {- qtype = it->second;- }- return qtype;-}--// Build one split-off part by applying `slice` (a row-range or strided-gather extractor) to-// the weight and, if present for this qtype's format, the scales and zero-point.-template <typename SliceFn>-FusedQkvPart make_split_part(GgufTensorType qtype,- const std::unordered_map<std::string, ov::Tensor>& weights,- const std::string& base,- const SliceFn& slice) {- const auto& weight = get(weights, base + ".weight");- const auto zp = weights.find(base + ".zp");- const ov::Tensor zero_point = zp != weights.end() ? zp->second : ov::Tensor{};- const auto format = get_weight_format(qtype, weight, zero_point, base);- FusedQkvPart part;- part.qtype = qtype;- part.tensors.weight = slice(weight);- if (format.has_scales()) {- part.tensors.scales = slice(get(weights, base + ".scales"));- }- if (format.has_zero_point()) {- part.tensors.zero_point = slice(get(weights, base + ".zp"));- }- return part;+bool same_weight_conversion_policy(const std::string& lhs, const std::string& rhs) {+ return is_embedding_or_output(lhs) == is_embedding_or_output(rhs);}-std::array<FusedQkvPart, 3> split_fused_qkv_extracted(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- const std::unordered_map<std::string, GgufTensorType>& qtypes,- size_t n_q,- size_t n_k,- size_t n_v) {- const GgufTensorType qtype = lookup_qtype(base, qtypes);-- const size_t total_rows = get(weights, base + ".weight").get_shape()[0];- OPENVINO_ASSERT(n_q + n_k + n_v == total_rows, "[GGUF] fused qkv row mismatch for ", base);-- const std::array<std::pair<size_t, size_t>, 3> ranges = {std::make_pair(size_t(0), n_q),- std::make_pair(n_q, n_q + n_k),- std::make_pair(n_q + n_k, total_rows)};- std::array<FusedQkvPart, 3> out;- for (size_t i = 0; i < 3; ++i) {- const size_t r0 = ranges[i].first;- const size_t r1 = ranges[i].second;- out[i] = make_split_part(qtype, weights, base, [&](const ov::Tensor& t) {- return slice_leading(t, r0, r1);- });- }- return out;-}--std::array<ov::Tensor, 3> split_fused_qkv_bias(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- size_t n_q,- size_t n_k,- size_t n_v) {- const ov::Tensor& b = get(weights, base + ".bias");- const auto& s = b.get_shape();- OPENVINO_ASSERT(s.size() == 1, "[GGUF] fused qkv bias for ", base, " is not 1D");- OPENVINO_ASSERT(n_q + n_k + n_v == s[0], "[GGUF] fused qkv bias row mismatch for ", base);- return {slice_leading(b, 0, n_q), slice_leading(b, n_q, n_q + n_k), slice_leading(b, n_q + n_k, s[0])};-}--// qwen35: attn_q packs the query and the attention output gate interleaved per head, as-// [q_h0 | gate_h0 | q_h1 | gate_h1 | ...] with a stride of 2*head_dim rows. De-interleave it-// into two plain weights so the graph sees ordinary projections. Returns {query, gate}.-std::array<FusedQkvPart, 2> split_interleaved_q_gate(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- const std::unordered_map<std::string, GgufTensorType>& qtypes,- size_t head_dim) {- const GgufTensorType qtype = lookup_qtype(base, qtypes);-- const size_t block = 2 * head_dim;- OPENVINO_ASSERT(get(weights, base + ".weight").get_shape()[0] % block == 0,- "[GGUF] interleaved q/gate row mismatch for ",- base);-- const std::array<size_t, 2> offsets = {0, head_dim};-- std::array<FusedQkvPart, 2> out;- for (size_t i = 0; i < 2; ++i) {- out[i] = make_split_part(qtype, weights, base, [&](const ov::Tensor& t) {- return gather_rows_strided(t, block, head_dim, offsets[i]);- });- }- return out;+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) {+ return make_weight_node(data, gguf_type_from_name(quant_type), logical_shape, name);}std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,- const std::string& quant_type,+ GgufTensorType qtype,const ov::Shape& logical_shape,const std::string& name) {OPENVINO_ASSERT(logical_shape.size() == 2,@@ -895,7 +778,6 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,logical_shape.size());const size_t rows = logical_shape[0];const size_t cols = logical_shape[1];- const GgufTensorType qtype = gguf_type_from_name(quant_type);if (qtype == GGUF_TYPE_Q8_1) {OPENVINO_ASSERT(cols != 0 && cols % 32 == 0, "[GGUF] Q8_1 columns must be a nonzero multiple of 32");@@ -939,6 +821,7 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,: qtype == GGUF_TYPE_F16 ? ov::element::f16: ov::element::bf16;ov::Tensor typed(et, logical_shape, data.data());+ typed = ov::Tensor(typed, std::make_shared<ov::Tensor>(data));return make_weight_node({typed, {}, {}}, qtype, name);}@@ -1030,7 +913,7 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,break;}case FillKind::NONE:- OPENVINO_THROW("[GGUF] unsupported weight quant type: ", quant_type);+ OPENVINO_THROW("[GGUF] unsupported weight quant type: ", static_cast<int>(qtype));}// Non-K requant sources (e.g. an F16 / Q4_0 / Q8_0 token_embd or output): the K-quant fast path@@ -1043,4 +926,27 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,return make_weight_node(tensors, qtype, name);}+ov::Shape mxfp4_packed_shape(const ov::Shape& shape) {+ OPENVINO_ASSERT(shape.size() > 2 && shape.back() % 32 == 0, "Invalid packed MXFP4 expert shape");+ return {1, shape[shape.size() - 3], shape[shape.size() - 2], shape.back() / 32, 17};+}++std::shared_ptr<ov::Node> make_weight_node(const GgufWeight& source) {+ if (source.native)+ return make_weight_node(unpack_gguf_weight(source), source.qtype, source.source_name);+ const auto& shape = source.shape;+ if (shape.size() > 2 && source.qtype == GGUF_TYPE_MXFP4) {+ const auto packed_shape = mxfp4_packed_shape(shape);+ OPENVINO_ASSERT(source.data.get_byte_size() == ov::shape_size(packed_shape), "MXFP4 packed byte size mismatch");+ return std::make_shared<ov::op::v0::Constant>(ov::element::u8, packed_shape, source.data.data());+ }+ if (shape.size() > 2) {+ const auto rows = std::accumulate(shape.begin(), shape.end() - 1, size_t{1}, std::multiplies<size_t>());+ auto node = make_weight_node(source.data, source.qtype, {rows, shape.back()}, source.source_name);+ auto target = ov::op::v0::Constant::create(ov::element::i64, {shape.size()}, shape);+ return std::make_shared<ov::op::v1::Reshape>(node, target, false);+ }+ return make_weight_node(source.data, source.qtype, shape, source.source_name);+}+} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hppindex fefc2ea40e1..c34fba0197f 100644--- a/src/frontends/gguf/src/quant/weights.hpp+++ b/src/frontends/gguf/src/quant/weights.hpp@@ -21,6 +21,9 @@ namespace ov::frontend::gguf {void normalize_u2_zero_points(const std::shared_ptr<ov::Model>& model);+// Rows of a ternary (Q2_0 family) decompressed weight gathered from its packed bytes before+// unpacking; nullptr when `data` is not such a weight.+std::shared_ptr<ov::Node> gather_packed_u2_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices);ov::Output<ov::Node> gather_weight_rows(const ov::Output<ov::Node>& data, const ov::Output<ov::Node>& indices);// Element type of the zero-point constant for an asymmetric quantized weight.@@ -62,8 +65,7 @@ struct WeightTensors {ov::Tensor zero_point;};-// Quant type recorded for a weight as "<base>.qtype"; F16 when absent.-GgufTensorType lookup_qtype(const std::string& base, const std::unordered_map<std::string, GgufTensorType>& qtypes);+bool same_weight_conversion_policy(const std::string& lhs, const std::string& rhs);// Build the OpenVINO node for one extracted GGUF weight. Quantized weights become a// low-bitness compressed subgraph (u4/u8 weights + zero-point + f16 scale, Convert ->@@ -73,17 +75,24 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,GgufTensorType qtype,const std::string& name = "weight");+std::shared_ptr<ov::Node> make_weight_node(const GgufWeight& source);+// u8 shape {1, E, M, K/32, 17} of a packed MXFP4 expert tensor with ggml shape [..., E, M, K].+ov::Shape mxfp4_packed_shape(const ov::Shape& shape);+// 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.+// laid them out; `qtype` is the ggml tensor type; `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,+ GgufTensorType qtype,+ const ov::Shape& logical_shape,+ const std::string& name = "");+// Same, with `quant_type` given as the ggml type name ("F16", "Q4_0", "q6_K", ...).std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,const std::string& quant_type,const ov::Shape& logical_shape,@@ -92,38 +101,4 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,// Map a ggml quant type name (e.g. "Q4_K") to its GgufTensorType id. Throws if unknown.GgufTensorType gguf_type_from_name(const std::string& quant_type);-// One split part of a fused attn_qkv weight: its extracted tensors and shared quant type.-// Used by the GGUF builder to emit a-// GGML_OP_NONE weight leaf per q/k/v part (routing them through translate_weight like any other-// weight) instead of building the decompression nodes eagerly.-struct FusedQkvPart {- WeightTensors tensors;- GgufTensorType qtype = GGUF_TYPE_F16;-};--// Row-slice a fused `<base>` attn_qkv weight into q/k/v tensor payloads (no OV nodes).-std::array<FusedQkvPart, 3> split_fused_qkv_extracted(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- const std::unordered_map<std::string, GgufTensorType>& qtypes,- size_t n_q,- size_t n_k,- size_t n_v);--// Row-slice a fused `<base>.bias` (plain, unquantized 1D tensor) into q/k/v parts, using the-// same row ranges as split_fused_qkv_extracted. Callers only invoke this when `<base>.bias`-// is present -- not every fused-QKV arch has one.-std::array<ov::Tensor, 3> split_fused_qkv_bias(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- size_t n_q,- size_t n_k,- size_t n_v);--// De-interleave a qwen35 `<base>` attn_q weight, which packs the query and the attention output-// gate per head as [q_h0 | gate_h0 | q_h1 | gate_h1 | ...], into two plain projections.-// Returns {query, gate}.-std::array<FusedQkvPart, 2> split_interleaved_q_gate(const std::string& base,- const std::unordered_map<std::string, ov::Tensor>& weights,- const std::unordered_map<std::string, GgufTensorType>& qtypes,- size_t head_dim);-} // namespace ov::frontend::ggufdiff --git a/src/frontends/gguf/src/translate_session.cpp b/src/frontends/gguf/src/translate_session.cppindex 855f61d2f2b..75fb2747745 100644--- a/src/frontends/gguf/src/translate_session.cpp+++ b/src/frontends/gguf/src/translate_session.cpp@@ -47,6 +47,7 @@#include "openvino/pass/manager.hpp"#include "pass/isolate_precision_sensitive_outputs.hpp"#include "pass/lower_set_rows_stateless.hpp"+#include "pass/materialize_weights.hpp"#include "pass/prune_orphaned_parameters.hpp"#include "quant/weights.hpp"#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"@@ -123,12 +124,7 @@ void translate_node(const std::shared_ptr<GgufDecoder>& decoder,const std::shared_ptr<ConstantCache>& constant_cache) {const auto& operation_type = decoder->get_op_type();if (operation_type == "GGML_OP_NONE") {- // A GGML_OP_NONE leaf is a weight if the decoder marks it as one: either the native- // builder's pre-extracted payload (bool "gguf_weight") or the cgraph decoder's raw- // bytes ("data"). Otherwise it is a model-input leaf (already seeded as a Parameter- // above) and there is nothing to translate.- const bool is_builder_weight =- decoder->get_attribute("gguf_weight").is<bool>() && decoder->get_attribute("gguf_weight").as<bool>();+ const bool is_builder_weight = decoder->get_attribute("gguf_source").is<GgufWeight>();const bool is_cgraph_weight = decoder->get_attribute("data").is<ov::Tensor>();if (!is_builder_weight && !is_cgraph_weight) {return;@@ -374,6 +370,9 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo}std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<Model> model) {+ ov::pass::Manager weight_normalization;+ weight_normalization.register_pass<pass::MaterializeGGUFWeights>();+ weight_normalization.run_passes(model);ov::pass::Manager manager;manager.set_per_pass_validation(true);manager.register_pass<ov::pass::MarkCompressedFloatConstants>();diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txtindex eae75509793..d3607f260f9 100644--- a/src/frontends/gguf/tests/CMakeLists.txt+++ b/src/frontends/gguf/tests/CMakeLists.txt@@ -24,6 +24,7 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/utils.cpp""${FE_SRC_DIR}/hadamard_sign_folding.cpp""${FE_SRC_DIR}/helper_ops/set_rows_op.cpp"+ "${FE_SRC_DIR}/helper_ops/gguf_constant.cpp""${FE_SRC_DIR}/pass/adapt_to_genai.cpp""${FE_SRC_DIR}/pass/adapt_mmproj_to_genai.cpp""${FE_SRC_DIR}/pass/lower_set_rows_stateless.cpp"@@ -31,6 +32,7 @@ set(FRONTEND_SRCS"${FE_SRC_DIR}/pass/make_stateful.cpp""${FE_SRC_DIR}/pass/prune_orphaned_parameters.cpp""${FE_SRC_DIR}/pass/simplify_activation_shapes.cpp"+ "${FE_SRC_DIR}/pass/materialize_weights.cpp""${FE_SRC_DIR}/tokenizer_metadata.cpp""${FE_SRC_DIR}/quant/gguf.cpp""${FE_SRC_DIR}/quant/gguf_quants.cpp"@@ -128,6 +130,7 @@ set(TEST_SRCS"${CMAKE_CURRENT_SOURCE_DIR}/test_gdn_normalization.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_isolate_precision_sensitive_outputs.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_parser.cpp"+ "${CMAKE_CURRENT_SOURCE_DIR}/deferred_weights.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_weights.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_shared_linear_inputs.cpp""${CMAKE_CURRENT_SOURCE_DIR}/test_simplify_activation_shapes.cpp"diff --git a/src/frontends/gguf/tests/deferred_weights.cpp b/src/frontends/gguf/tests/deferred_weights.cppnew file mode 100644index 00000000000..43755b3f185--- /dev/null+++ b/src/frontends/gguf/tests/deferred_weights.cpp@@ -0,0 +1,405 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <algorithm>+#include <cstring>+#include <filesystem>+#include <limits>+#include <numeric>+#include <tuple>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/ov_test_utils.hpp"+#include "gguf_writer.hpp"+#include "gtest/gtest.h"+#include "helper_ops/gguf_constant.hpp"+#include "node_context.hpp"+#include "op_table.hpp"+#include "op_test_utils.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/type/float16.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/subtract.hpp"+#include "pass/materialize_weights.hpp"+#include "quant/weights.hpp"++namespace {+using namespace ov::frontend::gguf;++ov::TensorVector evaluate(const std::shared_ptr<ov::Model>& model, const ov::TensorVector& inputs = {}) {+ ov::TensorVector outputs;+ for (const auto& output : model->outputs())+ outputs.emplace_back(output.get_element_type(), output.get_shape());+ EXPECT_TRUE(model->evaluate(outputs, inputs));+ return outputs;+}++void normalize(const std::shared_ptr<ov::Model>& model) {+ EXPECT_TRUE(pass::MaterializeGGUFWeights().run_on_model(model));+ EXPECT_EQ(count_ops_of_type<GGUFConstant>(model), 0);+ EXPECT_EQ(count_ops_of_type<ov::op::util::FrameworkNode>(model), 0);+ model->validate_nodes_and_infer_types();+}++struct TernarySource {+ GgufWeight source;+ std::vector<float> values;+};++TernarySource ternary(size_t rows, size_t seed, bool code_three = false) {+ constexpr size_t cols = 128;+ TernarySource result;+ result.source.data = ov::Tensor(ov::element::u8, {rows * 36});+ result.source.shape = {rows, cols};+ result.source.qtype = GGUF_TYPE_Q2_0;+ result.source.source_name = "blk.0.attn_" + std::to_string(seed) + ".weight";+ auto* bytes = result.source.data.data<uint8_t>();+ std::memset(bytes, 0, rows * 36);+ for (size_t row = 0; row < rows; ++row) {+ for (size_t group = 0; group < 2; ++group) {+ const ov::float16 scale(static_cast<float>(row + group + seed + 1) * 0.25f);+ const auto bits = scale.to_bits();+ auto* block = bytes + (row * 2 + group) * 18;+ std::memcpy(block, &bits, 2);+ for (size_t col = 0; col < 64; ++col) {+ const uint8_t code = (row * 2 + col + group + seed) % (code_three ? 4 : 3);+ block[2 + col / 4] |= code << (2 * (col % 4));+ result.values.push_back((static_cast<int>(code) - 1) * static_cast<float>(scale));+ }+ }+ }+ return result;+}++void expect_values(const ov::Tensor& output, const std::vector<float>& values) {+ ASSERT_EQ(output.get_element_type(), ov::element::f32);+ ASSERT_EQ(output.get_size(), values.size());+ for (size_t i = 0; i < values.size(); ++i)+ EXPECT_FLOAT_EQ(output.data<const float>()[i], values[i]) << i;+}++std::shared_ptr<ov::Node> row_slice(const ov::Output<ov::Node>& input, int64_t start, int64_t stop, int64_t step = 1) {+ auto constant = [](int64_t value) {+ return ov::op::v0::Constant::create(ov::element::i64, {1}, {value});+ };+ return std::make_shared<ov::op::v8::Slice>(input, constant(start), constant(stop), constant(step), constant(0));+}++TEST(GGUFWeightNormalization, RawMetadataAndClonesRetainSourceStorage) {+ auto source = ternary(2, 0);+ const auto original = std::make_shared<GGUFConstant>(source.source);+ EXPECT_TRUE(ov::is_type<ov::op::util::FrameworkNode>(original));+ auto attrs = original->get_attrs();+ EXPECT_EQ(attrs.get_type_name(), "GGUFConstant");+ EXPECT_EQ(attrs.get_opset_name(), "gguf");+ attrs["diagnostic"] = "raw source";+ original->set_attrs(attrs);+ const auto clone = ov::as_type_ptr<GGUFConstant>(original->clone_with_new_inputs({}));+ ASSERT_TRUE(clone);+ EXPECT_TRUE(ov::is_type<ov::op::util::FrameworkNode>(clone));+ EXPECT_TRUE(clone->get_attrs() == original->get_attrs());+ EXPECT_EQ(clone->source().data.data(), source.source.data.data());+ EXPECT_EQ(clone->source().data.get_byte_size(), 72);+ EXPECT_EQ(clone->get_output_shape(0), (ov::Shape{2, 128}));+ EXPECT_EQ(clone->get_output_element_type(0), ov::element::f32);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{clone}, ov::ParameterVector{});+ source.source = {};+ normalize(model);+ expect_values(evaluate(model)[0], source.values);+ EXPECT_FALSE(pass::MaterializeGGUFWeights().run_on_model(model));+}++TEST(GGUFWeightNormalization, NestedConcatSlicesAndGatherFoldBeforeRepacking) {+ const auto a = ternary(2, 0), b = ternary(3, 1, true);+ const auto concat = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{std::make_shared<GGUFConstant>(a.source), std::make_shared<GGUFConstant>(b.source)},+ 0);+ const auto slice = row_slice(concat, 1, 5);+ const auto indices = ov::op::v0::Constant::create(ov::element::i64, {3}, {3, 0, 3});+ const auto rows =+ std::make_shared<ov::op::v8::Gather>(slice, indices, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));+ std::vector<int64_t> order;+ for (int64_t i = 64; i < 128; ++i)+ order.push_back(i);+ for (int64_t i = 0; i < 64; ++i)+ order.push_back(i);+ const auto columns =+ std::make_shared<ov::op::v8::Gather>(rows,+ ov::op::v0::Constant::create(ov::element::i64, {128}, order),+ ov::op::v0::Constant::create(ov::element::i64, {}, {1}));+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{columns}, ov::ParameterVector{});+ auto values = a.values;+ values.insert(values.end(), b.values.begin(), b.values.end());+ std::vector<float> expected;+ for (size_t row : {4, 1, 4})+ for (const auto column : order)+ expected.push_back(values[row * 128 + column]);+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::Concat>(model), 0);+ EXPECT_EQ(count_ops_of_type<ov::op::v8::Gather>(model), 0);+ EXPECT_EQ(count_ops_of_type<ov::op::v8::Slice>(model), 0);+ expect_values(evaluate(model)[0], expected);+}++TEST(GGUFWeightNormalization, UnalignedColumnGatherPreservesLogicalValues) {+ const auto a = ternary(2, 0);+ std::vector<int64_t> order(128);+ std::iota(order.begin(), order.end(), 0);+ std::rotate(order.begin(), order.begin() + 1, order.end());+ const auto gather =+ std::make_shared<ov::op::v8::Gather>(std::make_shared<GGUFConstant>(a.source),+ ov::op::v0::Constant::create(ov::element::i64, {128}, order),+ ov::op::v0::Constant::create(ov::element::i64, {}, {1}));+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{gather}, ov::ParameterVector{});+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v8::Gather>(model), 1);+ std::vector<float> expected;+ for (size_t row = 0; row < 2; ++row)+ for (auto col : order)+ expected.push_back(a.values[row * 128 + col]);+ expect_values(evaluate(model)[0], expected);+}++TEST(GGUFWeightNormalization, SharedProjectionsPreserveUnequalSizesTiesAndCodeThree) {+ const auto a = ternary(2, 0), b = ternary(3, 1, true), c = ternary(1, 2);+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 128});+ const auto shared = std::make_shared<GGUFConstant>(a.source);+ ov::OutputVector outputs;+ for (const auto& weight : ov::OutputVector{shared,+ std::make_shared<GGUFConstant>(b.source),+ std::make_shared<GGUFConstant>(c.source),+ shared})+ outputs.push_back(std::make_shared<ov::op::v0::MatMul>(input, weight, false, true));+ const auto model = std::make_shared<ov::Model>(outputs, ov::ParameterVector{input});+ normalize(model);+ normalize_u2_zero_points(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::MatMul>(model), 1);+ EXPECT_EQ(count_ops_of_type<ov::op::v1::Subtract>(model), 1);+ ov::Tensor x(ov::element::f32, {2, 128});+ for (size_t i = 0; i < x.get_size(); ++i)+ x.data<float>()[i] = (static_cast<int>(i % 11) - 5) * 0.125f;+ const auto result = evaluate(model, {x});+ std::array<const TernarySource*, 4> sources{&a, &b, &c, &a};+ for (size_t out = 0; out < 4; ++out) {+ std::vector<float> expected;+ for (size_t token = 0; token < 2; ++token)+ for (size_t row = 0; row < sources[out]->source.shape[0]; ++row) {+ float sum = 0;+ for (size_t col = 0; col < 128; ++col)+ sum += x.data<float>()[token * 128 + col] * sources[out]->values[row * 128 + col];+ expected.push_back(sum);+ }+ expect_values(result[out], expected);+ }+}++TEST(GGUFWeightNormalization, MixedWeightTypesKeepSeparateCompressedProjections) {+ const auto a = ternary(2, 0);+ ov::Tensor plain(ov::element::f32, {3, 128});+ std::fill_n(plain.data<float>(), plain.get_size(), 0.5f);+ auto b = GgufWeight(plain);+ b.source_name = "blk.0.attn_b.weight";+ const auto concat = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{std::make_shared<GGUFConstant>(a.source), std::make_shared<GGUFConstant>(b)},+ 0);+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 128});+ const auto mm = std::make_shared<ov::op::v0::MatMul>(input, concat, false, true);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{mm}, ov::ParameterVector{input});+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::MatMul>(model), 2);+ ov::Tensor x(ov::element::f32, {1, 128});+ std::fill_n(x.data<float>(), 128, 1.f);+ const auto result = evaluate(model, {x});+ std::vector<float> expected;+ for (size_t row = 0; row < 2; ++row)+ expected.push_back(std::accumulate(a.values.begin() + row * 128, a.values.begin() + (row + 1) * 128, 0.f));+ expected.insert(expected.end(), 3, 64.f);+ expect_values(result[0], expected);+}++TEST(GGUFWeightNormalization, PlainRowViewsAndConcatsPreserveValues) {+ for (const auto& shape : {ov::Shape{4}, ov::Shape{4, 3}}) {+ ov::Tensor data(ov::element::f32, shape);+ std::iota(data.data<float>(), data.data<float>() + data.get_size(), 1.f);+ auto raw = GgufWeight(data);+ raw.source_name = "blk.0.bias";+ const auto leaf = std::make_shared<GGUFConstant>(raw);+ const auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{leaf, row_slice(leaf, 1, 3)}, 0);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{concat}, ov::ParameterVector{});+ normalize(model);+ const auto row_size = data.get_size() / shape[0];+ std::vector<float> expected(data.data<float>(), data.data<float>() + data.get_size());+ expected.insert(expected.end(), data.data<float>() + row_size, data.data<float>() + 3 * row_size);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::Concat>(model), 0);+ expect_values(evaluate(model)[0], expected);+ }+}++TEST(GGUFWeightNormalization, Q5KWeightAndBiasPoliciesRemainSeparate) {+ GgufWeight source;+ source.qtype = GGUF_TYPE_Q5_K;+ source.shape = {1, 256};+ source.data = ov::Tensor(ov::element::u8, {176});+ std::memset(source.data.data(), 1, 176);+ for (const bool bias_first : {false, true}) {+ source.source_name = "blk.0.ffn_up.weight";+ const auto weight = std::make_shared<GGUFConstant>(source);+ source.source_name = "blk.0.attn_q.bias";+ const auto bias = std::make_shared<GGUFConstant>(source);+ const auto inputs = bias_first ? ov::OutputVector{bias, weight} : ov::OutputVector{weight, bias};+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{std::make_shared<ov::op::v0::Concat>(inputs, 0)},+ ov::ParameterVector{});+ const auto reference =+ std::make_shared<ov::Model>(ov::OutputVector{std::make_shared<ov::op::v0::Concat>(+ bias_first ? ov::OutputVector{bias->materialize(), weight->materialize()}+ : ov::OutputVector{weight->materialize(), bias->materialize()},+ 0)},+ ov::ParameterVector{});+ const auto expected = evaluate(reference)[0];+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::Concat>(model), 1);+ expect_values(+ evaluate(model)[0],+ std::vector<float>(expected.data<const float>(), expected.data<const float>() + expected.get_size()));+ }+}++TEST(GGUFWeightNormalization, LargePositiveSliceStepDoesNotOverflow) {+ const auto raw = ternary(3, 0);+ const auto slice = row_slice(std::make_shared<GGUFConstant>(raw.source), 1, 3, std::numeric_limits<int64_t>::max());+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{slice}, ov::ParameterVector{});+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v8::Slice>(model), 0);+ expect_values(evaluate(model)[0], std::vector<float>(raw.values.begin() + 128, raw.values.begin() + 256));+}++TEST(GGUFWeightNormalization, RankOneQuantizedViewsUseLogicalFallback) {+ auto raw = ternary(1, 0);+ raw.source.shape = {128};+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{row_slice(std::make_shared<GGUFConstant>(raw.source), 1, 4)},+ ov::ParameterVector{});+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v8::Slice>(model), 1);+ expect_values(evaluate(model)[0], std::vector<float>(raw.values.begin() + 1, raw.values.begin() + 4));+}++TEST(GGUFWeightNormalization, DeferredTwoBitProjectionPreservesRankThreeLowering) {+ const ov::PartialShape shape{2, 1, -1, 256};+ for (const auto type : {GGUF_TYPE_Q2_0, GGUF_TYPE_PQ2_0, GGUF_TYPE_PTQ1_0, GGUF_TYPE_Q2_K}) {+ SCOPED_TRACE(type);+ auto source = ternary(3, 0).source;+ source.shape = {3, 256};+ source.qtype = type;+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);+ auto tensors =+ std::make_shared<TensorMap>(TensorMap{{"x", input}, {"w", std::make_shared<GGUFConstant>(source)}});+ const auto decoder = std::make_shared<ov_gguf_test::SingleOpDecoder>(+ "GGML_OP_MUL_MAT",+ std::vector<ov_gguf_test::TensorDesc>{{"w", ov::element::f32, {1, 1, 3, 256}},+ {"x", ov::element::f32, shape}},+ std::vector<ov_gguf_test::TensorDesc>{},+ ov_gguf_test::TensorDesc{"y", ov::element::f32, ov::PartialShape::dynamic()},+ std::map<std::string, ov::Any>{});+ const auto output = op::translate_mulmat(NodeContext(decoder, tensors, std::make_shared<ConstantCache>()))[0];+ EXPECT_EQ(output.get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));+ const auto mm = ov::as_type_ptr<ov::op::v0::MatMul>(output.get_node()->get_input_node_shared_ptr(0));+ ASSERT_TRUE(mm);+ EXPECT_EQ(mm->get_output_partial_shape(0), (ov::PartialShape{2, -1, 3}));+ }+}++using QuantCase = std::tuple<GgufTensorType, size_t, size_t>;+class GGUFWeightFormatNormalization : public testing::TestWithParam<QuantCase> {};+TEST_P(GGUFWeightFormatNormalization, ConcatenatesRawRowsWithoutFloatWeightExpansion) {+ const auto type = std::get<0>(GetParam());+ const auto block = std::get<1>(GetParam());+ const auto bytes = std::get<2>(GetParam());+ auto source = [&](size_t rows, uint8_t seed) {+ GgufWeight weight;+ weight.qtype = type;+ weight.shape = {rows, 256};+ weight.source_name = "blk.0.attn_q.weight";+ weight.data = ov::Tensor(ov::element::u8, {rows * (256 / block) * bytes});+ std::memset(weight.data.data(), seed, weight.data.get_byte_size());+ return weight;+ };+ const auto a = source(2, 1);+ const auto b = source(3, 2);+ const auto concat = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{std::make_shared<GGUFConstant>(a), std::make_shared<GGUFConstant>(b)},+ 0);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{concat}, ov::ParameterVector{});+ const auto reference = std::make_shared<ov::Model>(+ ov::OutputVector{+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{make_weight_node(a), make_weight_node(b)}, 0)},+ ov::ParameterVector{});+ const auto expected = evaluate(reference)[0];+ normalize(model);+ EXPECT_EQ(count_ops_of_type<ov::op::v0::Concat>(model), 0);+ const auto actual = evaluate(model)[0];+ ASSERT_EQ(actual.get_shape(), expected.get_shape());+ for (size_t i = 0; i < expected.get_size(); ++i)+ EXPECT_FLOAT_EQ(actual.data<const float>()[i], expected.data<const float>()[i]) << i;+ bool combined = false;+ for (const auto& node : model->get_ordered_ops())+ if (const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node)) {+ const auto& shape = constant->get_shape();+ combined |= shape.size() >= 2 && shape[0] == 5 && constant->get_element_type() != ov::element::f32;+ }+ EXPECT_TRUE(combined);+}+INSTANTIATE_TEST_SUITE_P(AllNativeQuantFormats,+ GGUFWeightFormatNormalization,+ testing::Values(QuantCase{GGUF_TYPE_Q1_0, 128, 18},+ QuantCase{GGUF_TYPE_Q4_0, 32, 18},+ QuantCase{GGUF_TYPE_Q4_1, 32, 20},+ QuantCase{GGUF_TYPE_Q5_0, 32, 22},+ QuantCase{GGUF_TYPE_Q5_1, 32, 24},+ QuantCase{GGUF_TYPE_Q8_0, 32, 34},+ QuantCase{GGUF_TYPE_Q8_1, 32, 36},+ QuantCase{GGUF_TYPE_Q2_K, 256, 84},+ QuantCase{GGUF_TYPE_Q3_K, 256, 110},+ QuantCase{GGUF_TYPE_Q4_K, 256, 144},+ QuantCase{GGUF_TYPE_Q5_K, 256, 176},+ QuantCase{GGUF_TYPE_Q6_K, 256, 210},+ QuantCase{GGUF_TYPE_Q8_K, 256, 292},+ QuantCase{GGUF_TYPE_MXFP4, 32, 17},+ QuantCase{GGUF_TYPE_Q2_0, 64, 18},+ QuantCase{GGUF_TYPE_PQ2_0, 128, 34},+ QuantCase{GGUF_TYPE_PTQ1_0, 128, 28}));++TEST(GGUFWeightNormalization, RawMappedSourceSurvivesLoaderRelease) {+ const auto generated = ternary(2, 0);+ std::vector<uint8_t> bytes(generated.source.data.get_byte_size());+ std::memcpy(bytes.data(), generated.source.data.data(), bytes.size());+ const auto path = ov::test::utils::generateTestFilePrefix() + ".gguf";+ ov_gguf_test::GgufWriter writer;+ writer.raw_tensor("blk.0.attn_q.weight", {128, 2}, GGUF_TYPE_Q2_0, bytes);+ ASSERT_TRUE(writer.write(path));+ std::shared_ptr<GGUFConstant> node;+ {+ const auto loaded = get_gguf_data(path);+ const auto& weights = std::get<1>(loaded);+ ASSERT_EQ(weights.size(), 1);+ const auto& source = weights.at("blk.0.attn_q.weight");+ EXPECT_EQ(source.shape, (ov::Shape{2, 128}));+ EXPECT_EQ(source.data.get_byte_size(), bytes.size());+ node = std::make_shared<GGUFConstant>(source);+ }+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});+ node.reset();+ normalize(model);+ expect_values(evaluate(model)[0], generated.values);+ ASSERT_TRUE(std::filesystem::is_regular_file(path));+ EXPECT_TRUE(std::filesystem::remove(path));+}++} // namespacediff --git a/src/frontends/gguf/tests/test_arch_accuracy.cpp b/src/frontends/gguf/tests/test_arch_accuracy.cppindex 56ed1ca2faf..de7e7f9bdae 100644--- a/src/frontends/gguf/tests/test_arch_accuracy.cpp+++ b/src/frontends/gguf/tests/test_arch_accuracy.cpp@@ -24,6 +24,7 @@#include "common_test_utils/common_utils.hpp"#include "common_test_utils/test_assertions.hpp"#include "gtest/gtest.h"+#include "helper_ops/gguf_constant.hpp"#include "op_test_utils.hpp"#include "openvino/core/type/float16.hpp"#include "openvino/frontend/extension/decoder_transformation.hpp"@@ -140,7 +141,6 @@ TEST(GGUFDSparkAccuracy, ConfidenceAndMarkovHeadsAreIndependent) {auto loaded = get_gguf_data(temporary.path);auto& metadata = std::get<0>(loaded);auto& weights = std::get<1>(loaded);- auto& qtypes = std::get<2>(loaded);ov::Tensor rank_value(ov::element::u32, {});*rank_value.data<uint32_t>() = static_cast<uint32_t>(rank);metadata["dspark.dspark.markov_rank"] = rank_value;@@ -155,12 +155,12 @@ TEST(GGUFDSparkAccuracy, ConfidenceAndMarkovHeadsAreIndependent) {weights.erase("dspark.markov_head_b.weight");}ov::Tensor projection(ov::element::f32, {1, with_markov ? size_t{72} : size_t{64}});- std::copy_n(weights.at("dspark.confidence_head.weight").data<const float>(),+ std::copy_n(weights.at("dspark.confidence_head.weight").data.data<const float>(),projection.get_size(),projection.data<float>());weights["dspark.confidence_head.weight"] = projection;detail::MetadataStore store{metadata};- detail::WeightStore tensors{weights, qtypes};+ detail::WeightStore tensors{weights};const BuildContext context{GgufMetadata(store), "dspark", &tensors};const auto graph = make_dspark_builder(context)->build();EXPECT_EQ(graph->model_inputs.count("dspark_prev_tokens"), rank > 0 ? 1u : 0u);@@ -199,13 +199,14 @@ TEST(GGUFDSparkAccuracy, ConfidenceAndMarkovHeadsAreIndependent) {const auto score = request.get_tensor("dspark.confidence_score");ASSERT_EQ(score.get_size(), 4u);for (size_t token = 0; token < 4; ++token) {- double expected = weights.at("dspark.confidence_head.bias").data<const float>()[0];+ double expected = weights.at("dspark.confidence_head.bias").data.data<const float>()[0];for (size_t feature = 0; feature < 64; ++feature)expected += hidden.data<const float>()[token * 64 + feature] * projection.data<const float>()[feature];if (with_markov)for (size_t feature = 0; feature < 8; ++feature)- expected += weights.at("dspark.markov_head_a.weight").data<const float>()[token * 8 + feature] *- projection.data<const float>()[64 + feature];+ expected +=+ weights.at("dspark.markov_head_a.weight").data.data<const float>()[token * 8 + feature] *+ projection.data<const float>()[64 + feature];EXPECT_NEAR(score.data<const float>()[token], expected, 1e-6);}}@@ -221,7 +222,7 @@ TEST(GGUFDSparkAccuracy, ConfidenceWithMarkovRequiresPositiveRank) {*rank.data<uint32_t>() = 0;metadata["dspark.dspark.markov_rank"] = rank;detail::MetadataStore store{metadata};- detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ detail::WeightStore tensors{std::get<1>(loaded)};const BuildContext context{GgufMetadata(store), "dspark", &tensors};OV_EXPECT_THROW(make_dspark_builder(context)->build(),ov::Exception,@@ -239,7 +240,7 @@ TEST(GGUFHadamardMetadata, MissingAndMistypedFieldsNameTheInvalidKey) {const auto parameters = resolve_decoder_parameters(view, RopeMode::Normal);const auto config =decoder_weight_transform_metadata(view, parameters.hybrid.time_step_rank, parameters.hybrid.group_count);- GraphEmitter valid(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ GraphEmitter valid(std::get<1>(loaded), "qwen35");EXPECT_NO_THROW(valid.configure_hadamard(config));for (const std::string key : {"prism.hadamard.version","prism.hadamard.block_size",@@ -262,13 +263,13 @@ TEST(GGUFHadamardMetadata, MissingAndMistypedFieldsNameTheInvalidKey) {invalid.erase(key);elseinvalid[key] = std::monostate{};- GraphEmitter emitter(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ GraphEmitter emitter(std::get<1>(loaded), "qwen35");OV_EXPECT_THROW(emitter.configure_hadamard(invalid), ov::Exception, testing::HasSubstr(key));}if (std::holds_alternative<ov::Tensor>(config.at(key))) {auto invalid = config;invalid[key] = ov::Tensor(ov::element::f32, {1});- GraphEmitter emitter(std::get<1>(loaded), std::get<2>(loaded), "qwen35");+ GraphEmitter emitter(std::get<1>(loaded), "qwen35");OV_EXPECT_THROW(emitter.configure_hadamard(invalid), ov::Exception, testing::HasSubstr(key));}}@@ -280,9 +281,8 @@ TEST(GGUFDSparkAccuracy, RejectsOversizedDraftBlocksBeforeBuildingTheGraph) {auto loaded = ov::frontend::gguf::get_gguf_data(temporary.path);auto& metadata = std::get<0>(loaded);auto& weights = std::get<1>(loaded);- auto& qtypes = std::get<2>(loaded);ov::frontend::gguf::detail::MetadataStore store{metadata};- ov::frontend::gguf::detail::WeightStore tensors{weights, qtypes};+ ov::frontend::gguf::detail::WeightStore tensors{weights};const ov::frontend::gguf::BuildContext context{ov::frontend::gguf::GgufMetadata(store), "dspark", &tensors};for (int64_t block : {int64_t{0}, int64_t{4097}, int64_t{UINT32_MAX}, std::numeric_limits<int64_t>::max()}) {SCOPED_TRACE(block);@@ -302,7 +302,11 @@ TEST(GGUFDSparkAccuracy, RejectsOversizedDraftBlocksBeforeBuildingTheGraph) {metadata["dspark.dspark.block_size"] = value;const auto graph = ov::frontend::gguf::make_dspark_builder(context)->build();EXPECT_EQ(graph->model_inputs.at("inp_tokens")->get_output_partial_shape(0), (ov::PartialShape{1, 1, 1, 4096}));- EXPECT_EQ(weights.at("dspark.log_snr_features").get_byte_size(), 4096 * 128 * sizeof(float));+ EXPECT_EQ(weights.count("dspark.log_snr_features"), 0);+ const auto features = ov::as_type_ptr<ov::frontend::gguf::GGUFConstant>(+ graph->values->at("dspark.log_snr_features").get_node_shared_ptr());+ ASSERT_TRUE(features);+ EXPECT_EQ(features->source().data.get_byte_size(), 4096 * 128 * sizeof(float));}TEST(GGUFDSparkAccuracy, LogSnrUsesNormalizedEndpointsAndRequiresValidBounds) {@@ -320,17 +324,19 @@ TEST(GGUFDSparkAccuracy, LogSnrUsesNormalizedEndpointsAndRequiresValidBounds) {metadata[key] = bound;}detail::MetadataStore store{metadata};- detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ detail::WeightStore tensors{std::get<1>(loaded)};const BuildContext context{GgufMetadata(store), "dspark", &tensors};- EXPECT_NO_THROW(make_dspark_builder(context)->build());- const auto& features = tensors.weights.at("dspark.log_snr_features");+ const auto graph = make_dspark_builder(context)->build();+ const auto features =+ ov::as_type_ptr<GGUFConstant>(graph->values->at("dspark.log_snr_features").get_node_shared_ptr());+ ASSERT_TRUE(features);for (size_t pos = 0; pos < 4; ++pos) {const float log_snr = pos == 0 ? high : low;const float time = (log_snr - low) / (high - low) * 1000.f;for (size_t i = 0; i < 64; ++i) {const float angle = time * std::exp(-std::log(10000.f) * i / 64.f);- EXPECT_FLOAT_EQ(features.data<const float>()[pos * 128 + i], std::sin(angle));- EXPECT_FLOAT_EQ(features.data<const float>()[pos * 128 + 64 + i], std::cos(angle));+ EXPECT_FLOAT_EQ(features->source().data.data<const float>()[pos * 128 + i], std::sin(angle));+ EXPECT_FLOAT_EQ(features->source().data.data<const float>()[pos * 128 + 64 + i], std::cos(angle));}}}@@ -351,7 +357,7 @@ TEST(GGUFDSparkAccuracy, LogSnrUsesNormalizedEndpointsAndRequiresValidBounds) {metadata[key] = bound;}detail::MetadataStore store{metadata};- detail::WeightStore tensors{std::get<1>(loaded), std::get<2>(loaded)};+ detail::WeightStore tensors{std::get<1>(loaded)};const BuildContext context{GgufMetadata(store), "dspark", &tensors};OV_EXPECT_THROW(make_dspark_builder(context)->build(), ov::Exception, testing::HasSubstr("log-SNR bounds"));}@@ -761,12 +767,27 @@ TEST(GGUFMultimodalBackboneAdaptation, TernaryAttentionGatesRestoreRankBeforeSigconst ov_gguf_test::TemporaryGguf temporary(ov_gguf_test::npz_array(arrays, "model"));auto loaded = get_gguf_data(temporary.path);auto& weights = std::get<1>(loaded);- auto& gate = weights.at("blk.0.attn_gate.weight");- gate = ov::Tensor(type, gate.get_shape());+ const auto name = "blk.0.attn_gate.weight";+ auto& gate = weights.at(name);+ if (type == ov::element::f32) {+ gate = GgufWeight(ov::Tensor(type, gate.shape));+ gate.source_name = name;+ } else {+ size_t elements = 1;+ for (const auto dim : gate.shape)+ elements *= dim;+ ASSERT_EQ(elements % 64, 0);+ gate.data = ov::Tensor(ov::element::u8, {elements / 64 * 18});+ std::memset(gate.data.data(), 0, gate.data.get_byte_size());+ gate.qtype = GGUF_TYPE_Q2_0;+ gate.source_name = name;+ gate.native = true;+ gate.mapped.reset();+ }const auto& metadata = std::get<0>(loaded);detail::MetadataStore store{metadata};const auto parameters = resolve_decoder_parameters(GgufMetadata(store), RopeMode::Neox);- detail::WeightStore tensors{weights, std::get<2>(loaded)};+ detail::WeightStore tensors{weights};const BuildContext context{GgufMetadata(store), parameters.architecture, &tensors};DecoderBuilder builder(context, parameters);const auto graph = builder.build();diff --git a/src/frontends/gguf/tests/test_architecture_extension.cpp b/src/frontends/gguf/tests/test_architecture_extension.cppindex aaa4666a192..9144b8e8af6 100644--- a/src/frontends/gguf/tests/test_architecture_extension.cpp+++ b/src/frontends/gguf/tests/test_architecture_extension.cpp@@ -612,9 +612,9 @@ TEST(GGUFArchitectureExtension, TypedUnknownLayerNormFactoryControlsScalesAndLayreturn parameters;});auto loaded = get_gguf_data(path);- auto& [metadata, weights, qtypes, mappings] = loaded;+ auto& [metadata, weights, mappings] = loaded;detail::MetadataStore store{metadata};- detail::WeightStore tensors{weights, qtypes};+ detail::WeightStore tensors{weights};const BuildContext context{GgufMetadata(store), "custom-normalization", &tensors};const auto graph = definition.factory(context)->build();EXPECT_TRUE(graph->use_per_op_rope);@@ -641,7 +641,7 @@ TEST(GGUFArchitectureExtension, TypedGatedDeltaNetFactoryScalesBothResidualBrancconst auto path = write_decoder_gguf(scratch.path(), "custom-recurrent");ASSERT_FALSE(path.empty());auto loaded = get_gguf_data(path);- auto& [metadata, weights, qtypes, mappings] = loaded;+ auto& [metadata, weights, mappings] = loaded;for (int layer = 0; layer < 2; ++layer) {const auto prefix = "blk." + std::to_string(layer) + ".";const std::map<std::string, ov::Shape> shapes{{"attn_qkv.weight", {12, 8}},@@ -660,7 +660,7 @@ TEST(GGUFArchitectureExtension, TypedGatedDeltaNetFactoryScalesBothResidualBranc}}detail::MetadataStore store{metadata};- detail::WeightStore tensors{weights, qtypes};+ detail::WeightStore tensors{weights};const BuildContext context{GgufMetadata(store), "custom-recurrent", &tensors};for (float scale : {1.0f, 0.375f}) {const auto definition = make_decoder_architecture("custom-recurrent", [scale](const BuildContext& context) {diff --git a/src/frontends/gguf/tests/test_builder_api.cpp b/src/frontends/gguf/tests/test_builder_api.cppindex 0a5dad92f73..0107698e918 100644--- a/src/frontends/gguf/tests/test_builder_api.cpp+++ b/src/frontends/gguf/tests/test_builder_api.cpp@@ -26,10 +26,9 @@ using namespace ov::frontend::gguf;namespace {struct Environment {std::unordered_map<std::string, GGUFMetaData> metadata;- std::unordered_map<std::string, ov::Tensor> weights;- std::unordered_map<std::string, GgufTensorType> qtypes;+ GgufWeightTable weights;detail::MetadataStore store{metadata};- detail::WeightStore tensors{weights, qtypes};+ detail::WeightStore tensors{weights};BuildContext context{GgufMetadata(store), "test", &tensors};Environment() {diff --git a/src/frontends/gguf/tests/test_parser.cpp b/src/frontends/gguf/tests/test_parser.cppindex 6f2eb8fc681..839c106828d 100644--- a/src/frontends/gguf/tests/test_parser.cpp+++ b/src/frontends/gguf/tests/test_parser.cpp@@ -91,16 +91,17 @@ TEST_F(GGUFParser, Q8_1PreservesCodesScalesAndIgnoresSumForAllWeightNames) {SCOPED_TRACE(name);ASSERT_NO_FATAL_FAILURE(write_tensor(name + ".weight", GGUF_TYPE_Q8_1, 256, 4, bytes));const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- EXPECT_EQ(std::get<2>(loaded).at(name + ".qtype"), GGUF_TYPE_Q8_1);- const auto& weights = arrays.at(name + ".weight");- const auto& scales = arrays.at(name + ".scales");+ const auto& source = std::get<1>(loaded).at(name + ".weight");+ EXPECT_EQ(source.qtype, GGUF_TYPE_Q8_1);+ const auto unpacked = unpack_gguf_weight(source);+ const auto& weights = unpacked.weight;+ const auto& scales = unpacked.scales;ASSERT_EQ(weights.get_element_type(), ov::element::i8);ASSERT_EQ(scales.get_element_type(), ov::element::f16);EXPECT_EQ(weights.get_shape(), (ov::Shape{4, 256}));EXPECT_EQ(scales.get_shape(), (ov::Shape{4, 8}));EXPECT_EQ(weights.get_byte_size() + scales.get_byte_size(), 4 * 256 / 32 * 34);- EXPECT_EQ(arrays.count(name + ".zp"), 0);+ EXPECT_FALSE(unpacked.zero_point);for (size_t group = 0; group < scales.get_size(); ++group) {uint16_t bits;std::memcpy(&bits, bytes.data() + group * 36, sizeof(bits));@@ -116,14 +117,28 @@ TEST_F(GGUFParser, Q8_1PreservesCodesScalesAndIgnoresSumForAllWeightNames) {}}+TEST_F(GGUFParser, QuantizedLoaderKeepsOneRawDescriptorPerTensor) {+ const auto bytes = load_npy<uint8_t>("q8_1_qbytes");+ ASSERT_NO_FATAL_FAILURE(write_tensor("output.weight", GGUF_TYPE_Q8_1, 256, 4, bytes));+ const auto loaded = get_gguf_data(m_path);+ const auto& weights = std::get<1>(loaded);+ ASSERT_EQ(weights.size(), 1);+ const auto& weight = weights.at("output.weight");+ EXPECT_EQ(weight.source_name, "output.weight");+ EXPECT_EQ(weight.qtype, GGUF_TYPE_Q8_1);+ EXPECT_EQ(weight.shape, (ov::Shape{4, 256}));+ EXPECT_TRUE(weight.native);+ ASSERT_EQ(weight.data.get_byte_size(), bytes.size());+ EXPECT_EQ(std::memcmp(weight.data.data<const uint8_t>(), bytes.data(), bytes.size()), 0);+}+TEST_F(GGUFParser, Q8_1KeepsHigherRankGroups) {const auto bytes = load_npy<uint8_t>("q8_1_qbytes");const auto reference = load_npy<float>("q8_1_deq");ASSERT_NO_FATAL_FAILURE(write_tensor("experts.weight", GGUF_TYPE_Q8_1, 256, 2, bytes, {}, {2}));- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- const auto& weights = arrays.at("experts.weight");- const auto& scales = arrays.at("experts.scales");+ const auto unpacked = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at("experts.weight"));+ const auto& weights = unpacked.weight;+ const auto& scales = unpacked.scales;EXPECT_EQ(weights.get_shape(), (ov::Shape{2, 2, 256}));EXPECT_EQ(scales.get_shape(), (ov::Shape{2, 2, 8}));const auto node = make_weight_node({weights, scales, {}}, GGUF_TYPE_Q8_1, "experts.weight");@@ -153,9 +168,7 @@ TEST_F(GGUFParser, Q8_1ExtractedBuffersPreserveFiniteScaleRangeAfterParserReleasASSERT_NO_FATAL_FAILURE(write_tensor("output.weight", GGUF_TYPE_Q8_1, reference.size(), 1, bytes));WeightTensors tensors;{- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- tensors = {arrays.at("output.weight"), arrays.at("output.scales"), {}};+ tensors = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at("output.weight"));ASSERT_EQ(tensors.scales.get_size(), scale_bits.size());for (size_t group = 0; group < scale_bits.size(); ++group)EXPECT_EQ(tensors.scales.data<const ov::float16>()[group].to_bits(), scale_bits[group]);@@ -190,15 +203,14 @@ TEST_F(GGUFParser, Q1_0PreservesBinaryStorageAndScaleValues) {const auto bytes = load_npy<uint8_t>("q1_0_qbytes");const auto reference = load_npy<float>("q1_0_deq");ASSERT_NO_FATAL_FAILURE(write_tensor("token_embd.weight", GGUF_TYPE_Q1_0, 256, 4, bytes));- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- const auto& weights = arrays.at("token_embd.weight");- const auto& scales = arrays.at("token_embd.scales");+ const auto unpacked = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at("token_embd.weight"));+ const auto& weights = unpacked.weight;+ const auto& scales = unpacked.scales;ASSERT_EQ(weights.get_element_type(), ov::element::u1);EXPECT_EQ(weights.get_shape(), (ov::Shape{4, 256}));EXPECT_EQ(weights.get_byte_size(), 128);EXPECT_EQ(scales.get_byte_size(), 16);- EXPECT_EQ(arrays.count("token_embd.zp"), 0);+ EXPECT_FALSE(unpacked.zero_point);for (size_t group = 0; group < scales.get_size(); ++group) {uint16_t bits;std::memcpy(&bits, bytes.data() + group * 18, sizeof(bits));@@ -218,11 +230,10 @@ TEST_F(GGUFParser, Q2_0KeepsIntegerZeroPointsForAllWeightNames) {for (const std::string name : {"blk.0.attn_q", "token_embd", "output"}) {SCOPED_TRACE(name);ASSERT_NO_FATAL_FAILURE(write_tensor(name + ".weight", GGUF_TYPE_Q2_0, 256, 4, bytes));- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- const auto& weights = arrays.at(name + ".weight");- const auto& scales = arrays.at(name + ".scales");- const auto& zp = arrays.at(name + ".zp");+ const auto unpacked = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at(name + ".weight"));+ const auto& weights = unpacked.weight;+ const auto& scales = unpacked.scales;+ const auto& zp = unpacked.zero_point;ASSERT_EQ(zp.get_element_type(), ov::element::u8);ASSERT_EQ(zp.get_shape(), (ov::Shape{4, 4}));for (size_t i = 0; i < zp.get_size(); ++i) {@@ -247,13 +258,11 @@ TEST_F(GGUFParser, PrismTernaryFormatsMatchGgmlIncludingLegacyGroup128) {const auto reference = load_npy<float>(std::string(stem) + "_deq");ASSERT_NO_FATAL_FAILURE(write_tensor("token_embd.weight", file_type, 256, 4, bytes));const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- EXPECT_EQ(std::get<2>(loaded).at("token_embd.qtype"), expected_type);- EXPECT_EQ(arrays.at("token_embd.scales").get_shape(), (ov::Shape{4, 2}));- const auto node = make_weight_node(- {arrays.at("token_embd.weight"), arrays.at("token_embd.scales"), arrays.at("token_embd.zp")},- expected_type,- "token_embd");+ const auto& source = std::get<1>(loaded).at("token_embd.weight");+ EXPECT_EQ(source.qtype, expected_type);+ const auto unpacked = unpack_gguf_weight(source);+ EXPECT_EQ(unpacked.scales.get_shape(), (ov::Shape{4, 2}));+ const auto node = make_weight_node(unpacked, expected_type, "token_embd");const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});const auto output = run_on_cpu(model, {});ASSERT_EQ(output.get_size(), reference.size());@@ -263,9 +272,8 @@ TEST_F(GGUFParser, PrismTernaryFormatsMatchGgmlIncludingLegacyGroup128) {}TEST(GGUFHadamardMetadata, RejectsInvalidBlocksWidthsAndUnusedWeights) {- std::unordered_map<std::string, ov::Tensor> weights{{"output.weight", ov::Tensor(ov::element::f32, {4, 16})},- {"token_embd.weight", ov::Tensor(ov::element::f32, {4, 12})}};- std::unordered_map<std::string, GgufTensorType> qtypes;+ GgufWeightTable weights{{"output.weight", ov::Tensor(ov::element::f32, {4, 16})},+ {"token_embd.weight", ov::Tensor(ov::element::f32, {4, 12})}};const auto scalar = [](uint32_t value) {ov::Tensor tensor(ov::element::u32, {});*tensor.data<uint32_t>() = value;@@ -281,14 +289,14 @@ TEST(GGUFHadamardMetadata, RejectsInvalidBlocksWidthsAndUnusedWeights) {for (uint32_t block : {0, 3, 8192}) {auto invalid = config;invalid[p + "block_size"] = scalar(block);- ov::frontend::gguf::GraphEmitter emitter(weights, qtypes, "qwen35");+ ov::frontend::gguf::GraphEmitter emitter(weights, "qwen35");EXPECT_ANY_THROW(emitter.configure_hadamard(invalid));}auto inverse = config;inverse[p + "inverse_weight_names"] = std::vector<std::string>{"token_embd.weight"};- ov::frontend::gguf::GraphEmitter bad_inverse(weights, qtypes, "qwen35");+ ov::frontend::gguf::GraphEmitter bad_inverse(weights, "qwen35");EXPECT_ANY_THROW(bad_inverse.configure_hadamard(inverse));- ov::frontend::gguf::GraphEmitter unused(weights, qtypes, "qwen35");+ ov::frontend::gguf::GraphEmitter unused(weights, "qwen35");ASSERT_NO_THROW(unused.configure_hadamard(config));EXPECT_ANY_THROW(unused.validate_hadamard());}@@ -304,13 +312,9 @@ TEST_F(GGUFParser, Q4KZeroPointModeAppliesToLanguageAndProjectorModels) {for (const std::string architecture : {"clip", "qwen35", "qwen35moe", "gemma4", "muse-glimmer", ""}) {SCOPED_TRACE(architecture);ASSERT_NO_FATAL_FAILURE(write_tensor("v.blk.0.attn_q.weight", GGUF_TYPE_Q4_K, 256, 4, bytes, architecture));- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- const auto& zp = arrays.at("v.blk.0.attn_q.zp");- ASSERT_EQ(zp.get_element_type(), expected_zp);- const auto node = make_weight_node({arrays.at("v.blk.0.attn_q.weight"), arrays.at("v.blk.0.attn_q.scales"), zp},- GGUF_TYPE_Q4_K,- "v.blk.0.attn_q.weight");+ const auto unpacked = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at("v.blk.0.attn_q.weight"));+ ASSERT_EQ(unpacked.zero_point.get_element_type(), expected_zp);+ const auto node = make_weight_node(unpacked, GGUF_TYPE_Q4_K, "v.blk.0.attn_q.weight");const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});const auto output = run_on_cpu(model, {});ASSERT_EQ(output.get_size(), reference.size());@@ -319,26 +323,6 @@ TEST_F(GGUFParser, Q4KZeroPointModeAppliesToLanguageAndProjectorModels) {}}-TEST_F(GGUFParser, QuantizedBuffersOutliveParserResult) {- const auto bytes = load_npy<uint8_t>("q2_k_qbytes");- const auto reference = load_npy<float>("q2_k_deq");- ASSERT_NO_FATAL_FAILURE(write_tensor("blk.0.attn_q.weight", GGUF_TYPE_Q2_K, 256, 4, bytes));- WeightTensors tensors;- {- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- tensors = {arrays.at("blk.0.attn_q.weight"), arrays.at("blk.0.attn_q.scales"), arrays.at("blk.0.attn_q.zp")};- }- ov::test::utils::removeFile(m_path);- const auto node = make_weight_node(tensors, GGUF_TYPE_Q2_K, "blk.0.attn_q");- tensors = {};- const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});- const auto output = run_on_cpu(model, {});- ASSERT_EQ(output.get_size(), reference.size());- for (size_t i = 0; i < reference.size(); ++i)- EXPECT_NEAR(output.data<const float>()[i], reference[i], 3e-3f);-}-TEST_F(GGUFParser, AcceptsEmptyQuantizedTensors) {constexpr std::array types{std::pair{"Q4_0", GGUF_TYPE_Q4_0},@@ -358,12 +342,13 @@ TEST_F(GGUFParser, AcceptsEmptyQuantizedTensors) {for (const auto& [name, type] : types) {SCOPED_TRACE(name);ASSERT_NO_FATAL_FAILURE(write_tensor("empty.weight", type, 0, 2));- const auto loaded = get_gguf_data(m_path);- const auto& arrays = std::get<1>(loaded);- EXPECT_EQ(arrays.at("empty.weight").get_shape(), (ov::Shape{2, 0}));- EXPECT_EQ(arrays.at("empty.scales").get_shape(), (ov::Shape{2, 0}));- for (const auto& entry : arrays) {- EXPECT_EQ(entry.second.get_size(), 0);+ const auto unpacked = unpack_gguf_weight(std::get<1>(get_gguf_data(m_path)).at("empty.weight"));+ EXPECT_EQ(unpacked.weight.get_shape(), (ov::Shape{2, 0}));+ EXPECT_EQ(unpacked.scales.get_shape(), (ov::Shape{2, 0}));+ for (const auto& tensor : {unpacked.weight, unpacked.scales, unpacked.zero_point}) {+ if (tensor) {+ EXPECT_EQ(tensor.get_size(), 0);+ }}}}@@ -425,18 +410,18 @@ protected:TEST_F(GGUFShards, DiscoversSiblingsFromEitherShardAndKeepsMappingsAlive) {ASSERT_NO_FATAL_FAILURE(write_shard(0, 0));ASSERT_NO_FATAL_FAILURE(write_shard(1, 1));- ov::Tensor retained;+ ov::frontend::gguf::GgufWeight retained;for (size_t index : {0, 1}) {const auto loaded = get_gguf_data(path(index));- EXPECT_EQ(std::get<3>(loaded).size(), 2);+ EXPECT_EQ(std::get<2>(loaded).size(), 2);EXPECT_EQ(std::get<std::string>(std::get<0>(loaded).at("general.architecture")), "qwen3");const auto& arrays = std::get<1>(loaded);ASSERT_EQ(arrays.size(), 2);- EXPECT_FLOAT_EQ(arrays.at("weight0.weight").data<const float>()[0], 1.f);- EXPECT_FLOAT_EQ(arrays.at("weight1.weight").data<const float>()[0], 2.f);+ EXPECT_FLOAT_EQ(arrays.at("weight0.weight").data.data<const float>()[0], 1.f);+ EXPECT_FLOAT_EQ(arrays.at("weight1.weight").data.data<const float>()[0], 2.f);retained = arrays.at("weight1.weight");}- EXPECT_FLOAT_EQ(retained.data<const float>()[1], 3.f);+ EXPECT_FLOAT_EQ(retained.data.data<const float>()[1], 3.f);}TEST_F(GGUFShards, ExplicitListAllowsRenamedFilesInDifferentDirectoriesAndReversedOrder) {@@ -488,19 +473,18 @@ TEST_F(GGUFShards, LegacyGroup128PackingMatchesMergedFileAcrossShards) {get_gguf_data(path(1)),get_gguf_data(std::vector<std::filesystem::path>{path(1), path(0)})}) {for (const std::string stem : {"small", "large"}) {- EXPECT_EQ(std::get<2>(loaded).at(stem + ".qtype"), GGUF_TYPE_PQ2_0);- const auto& arrays = std::get<1>(loaded);- const auto& expected = std::get<1>(reference);- for (const auto& suffix : {".weight", ".scales", ".zp"}) {- const auto& actual = arrays.at(stem + suffix);- const auto& value = expected.at(stem + suffix);- ASSERT_EQ(actual.get_element_type(), value.get_element_type());- ASSERT_EQ(actual.get_shape(), value.get_shape());- EXPECT_EQ(std::memcmp(actual.data(), value.data(), actual.get_byte_size()), 0);+ const auto& source = std::get<1>(loaded).at(stem + ".weight");+ EXPECT_EQ(source.qtype, GGUF_TYPE_PQ2_0);+ auto actual = unpack_gguf_weight(source);+ auto expected = unpack_gguf_weight(std::get<1>(reference).at(stem + ".weight"));+ for (const auto& [lhs, rhs] : {std::pair{actual.weight, expected.weight},+ std::pair{actual.scales, expected.scales},+ std::pair{actual.zero_point, expected.zero_point}}) {+ ASSERT_EQ(lhs.get_element_type(), rhs.get_element_type());+ ASSERT_EQ(lhs.get_shape(), rhs.get_shape());+ EXPECT_EQ(std::memcmp(lhs.data(), rhs.data(), lhs.get_byte_size()), 0);}- const auto node = make_weight_node(- {arrays.at(stem + ".weight"), arrays.at(stem + ".scales"), arrays.at(stem + ".zp")},- GGUF_TYPE_PQ2_0);+ const auto node = make_weight_node(actual, GGUF_TYPE_PQ2_0);const auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});const auto output = run_on_cpu(model, {});for (size_t i = 0; i < output.get_size(); ++i) {diff --git a/src/frontends/gguf/tests/test_shared_linear_inputs.cpp b/src/frontends/gguf/tests/test_shared_linear_inputs.cppindex 88623db9039..f3938d30b45 100644--- a/src/frontends/gguf/tests/test_shared_linear_inputs.cpp+++ b/src/frontends/gguf/tests/test_shared_linear_inputs.cpp@@ -15,6 +15,7 @@#include "openvino/op/matmul.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/transpose.hpp"+#include "pass/materialize_weights.hpp"#include "utils.hpp"namespace {@@ -258,19 +259,19 @@ TEST(GGUFHadamardSharing, DistinguishesSignsDirectionLayoutAndConversionScope) {TEST(GGUFSharedLinearInputs, JointInterleavedProjectionPreservesHeadsBatchesAndTokens) {using namespace ov::frontend::gguf;for (const auto& shape : {ov::PartialShape{2, -1, 8}, ov::PartialShape{2, 1, -1, 8}}) {- std::unordered_map<std::string, ov::Tensor> weights;- std::unordered_map<std::string, GgufTensorType> qtypes;- GraphEmitter emitter(weights, qtypes, "test");+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");const auto x = emitter.add_input("x", ov::element::f32, shape);weights["joint.weight"] = ov::Tensor(ov::element::f32, {12, 8});for (size_t i = 0; i < 96; ++i)- weights["joint.weight"].data<float>()[i] = (static_cast<int>(i % 13) - 6) / 8.f;+ weights["joint.weight"].data.data<float>()[i] = (static_cast<int>(i % 13) - 6) / 8.f;emitter.add_weight("joint.weight");const auto joint = emitter.add_op("GGML_OP_MUL_MAT", "joint", {"joint.weight", "x"});const auto parts = blocks::split_interleaved_projection(emitter, joint, {"q", "gate"}, 3, 2);const auto model =std::make_shared<ov::Model>(ov::OutputVector{emitter.value(parts[0]), emitter.value(parts[1])},ov::ParameterVector{x});+ ASSERT_TRUE(pass::MaterializeGGUFWeights().run_on_model(model));for (const size_t tokens : {1, 3}) {auto input_shape = shape.get_max_shape();input_shape[input_shape.size() - 2] = tokens;@@ -290,7 +291,7 @@ TEST(GGUFSharedLinearInputs, JointInterleavedProjectionPreservesHeadsBatchesAndTfloat expected = 0;for (size_t k = 0; k < 8; ++k)expected += input.data<float>()[row * 8 + k] *- weights["joint.weight"].data<float>()[weight_row * 8 + k];+ weights["joint.weight"].data.data<float>()[weight_row * 8 + k];EXPECT_FLOAT_EQ(outputs[part].data<float>()[row * 6 + n], expected);}}@@ -301,14 +302,13 @@ TEST(GGUFSharedLinearInputs, JointInterleavedProjectionPreservesHeadsBatchesAndTTEST(GGUFSharedLinearInputs, GateUpProjectionKeepsGLUBranchesRank3) {using namespace ov::frontend::gguf;- std::unordered_map<std::string, ov::Tensor> weights;- std::unordered_map<std::string, GgufTensorType> qtypes;- GraphEmitter emitter(weights, qtypes, "test");+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");const auto x = emitter.add_input("x", ov::element::f32, {2, 1, -1, 8});for (const auto* name : {"ffn_gate.weight", "ffn_up.weight"}) {weights[name] = ov::Tensor(ov::element::f32, {3, 8});for (size_t i = 0; i < 24; ++i)- weights[name].data<float>()[i] = (static_cast<int>(i % 7) - 3) / 8.f;+ weights[name].data.data<float>()[i] = (static_cast<int>(i % 7) - 3) / 8.f;}const auto output = blocks::swiglu_gate_up(emitter,"ffn_gate.weight",@@ -323,6 +323,7 @@ TEST(GGUFSharedLinearInputs, GateUpProjectionKeepsGLUBranchesRank3) {EXPECT_EQ(emitter.value("ffn_swiglu").get_partial_shape(), (ov::PartialShape{2, -1, 3}));EXPECT_EQ(emitter.value(output).get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));const auto model = std::make_shared<ov::Model>(ov::OutputVector{emitter.value(output)}, ov::ParameterVector{x});+ ASSERT_TRUE(pass::MaterializeGGUFWeights().run_on_model(model));for (const size_t tokens : {1, 3}) {ov::Tensor input(ov::element::f32, {2, 1, tokens, 8});for (size_t i = 0; i < input.get_size(); ++i)@@ -334,7 +335,7 @@ TEST(GGUFSharedLinearInputs, GateUpProjectionKeepsGLUBranchesRank3) {float projection = 0;for (size_t k = 0; k < 8; ++k)projection +=- input.data<float>()[row * 8 + k] * weights["ffn_gate.weight"].data<float>()[n * 8 + k];+ input.data<float>()[row * 8 + k] * weights["ffn_gate.weight"].data.data<float>()[n * 8 + k];EXPECT_NEAR(outputs[0].data<float>()[row * 3 + n],projection * projection / (1 + std::exp(-projection)),1e-6f);diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cppindex 1dbf116a04d..5f288a15945 100644--- a/src/frontends/gguf/tests/test_weights.cpp+++ b/src/frontends/gguf/tests/test_weights.cpp@@ -17,6 +17,7 @@#include <vector>#include "common_test_utils/file_utils.hpp"+#include "helper_ops/gguf_constant.hpp"#include "node_context.hpp"#include "op_test_utils.hpp"#include "openvino/op/constant.hpp"@@ -28,6 +29,7 @@#include "openvino/op/split.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/unsqueeze.hpp"+#include "pass/materialize_weights.hpp"#include "quant/gguf.hpp"#include "quant/weights.hpp"#include "utils.hpp"@@ -222,17 +224,21 @@ TEST(GGUFWeight, Q8_1CpuMatmulAndGatherMatchRepresentedWeights) {}}-TEST(GGUFWeight, TernaryRowsKeepCompressedDictionaryAndTiedProjection) {+TEST(GGUFWeight, DeferredTernaryRowsKeepCompressedDictionaryAndTiedProjection) {for (const auto& format :std::vector<std::pair<const char*, const char*>>{{"q2_0", "Q2_0"}, {"pq2_0", "PQ2_0"}, {"ptq1_0", "PTQ1_0"}}) {SCOPED_TRACE(format.second);const auto bytes = load_npy<uint8_t>(std::string(format.first) + "_qbytes");- const auto weight = make_weight_node(bytes_to_u8_tensor(bytes), format.second, {kRows, kCols});+ GgufWeight source;+ source.data = bytes_to_u8_tensor(bytes);+ source.shape = {kRows, kCols};+ source.qtype = gguf_type_from_name(format.second);+ const auto leaf = std::make_shared<GGUFConstant>(source);auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1, 1, 1, -1});indices->set_friendly_name("indices");indices->output(0).set_names({"indices"});auto activation = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, kCols});- auto projection = std::make_shared<ov::op::v0::MatMul>(activation, weight, false, true);+ auto projection = std::make_shared<ov::op::v0::MatMul>(activation, leaf, false, true);auto decoder = SingleOpBuilder().op("GGML_OP_GET_ROWS").input("weight", ov::element::f32, {kRows, kCols})@@ -240,11 +246,15 @@ TEST(GGUFWeight, TernaryRowsKeepCompressedDictionaryAndTiedProjection) {.output("rows", ov::element::f32, {1, 1, -1, kCols}).decoder();auto tensors = std::make_shared<TensorMap>();- (*tensors)["weight"] = weight;+ (*tensors)["weight"] = leaf;(*tensors)["indices"] = indices;NodeContext context(decoder, tensors);auto rows = op::translate_get_rows(context)[0];- auto model = std::make_shared<ov::Model>(ov::OutputVector{rows}, ov::ParameterVector{indices});+ auto tied =+ std::make_shared<ov::Model>(ov::OutputVector{rows, projection}, ov::ParameterVector{indices, activation});+ ASSERT_TRUE(pass::MaterializeGGUFWeights().run_on_model(tied));+ const auto weight = projection->get_input_node_shared_ptr(1);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{tied->output(0)}, ov::ParameterVector{indices});size_t dictionaries = 0;const void* dictionary_data = nullptr;for (const auto& node : model->get_ops()) {@@ -256,7 +266,6 @@ TEST(GGUFWeight, TernaryRowsKeepCompressedDictionaryAndTiedProjection) {EXPECT_EQ(constant->get_byte_size(), kRows * kCols / 4);}EXPECT_EQ(dictionaries, 1);- EXPECT_EQ(projection->get_input_node_shared_ptr(1), weight);auto original = std::make_shared<ov::Model>(ov::OutputVector{weight}, ov::ParameterVector{});size_t subtracts = 0;for (const auto& op : original->get_ordered_ops()) {@@ -905,68 +914,6 @@ TEST(GGUFWeight, Mxfp4TwoDim) {EXPECT_FLOAT_EQ(a[j], kF4E2M1[j % 16]) << "element " << j;}-// Regression for a fused-QKV bias (e.g. phi-3's blk.N.attn_qkv.bias) being silently dropped:-// register_fused_qkv split the fused weight into q/k/v parts but never touched a fused bias, so-// attention()'s add_bias calls (gated on !has_fused_qkv) never ran for these archs, and the-// bias never made it into the graph. split_fused_qkv_bias must slice the fused bias into-// exactly the q/k/v parts the weight split uses (n_q, n_k, n_v rows in that order).-TEST(GGUFFusedQkvBias, SplitsIntoExpectedRanges) {- constexpr size_t n_q = 4, n_k = 2, n_v = 2;- ov::Tensor bias(ov::element::f32, ov::Shape{n_q + n_k + n_v});- auto* data = bias.data<float>();- for (size_t i = 0; i < n_q + n_k + n_v; ++i) {- data[i] = static_cast<float>(i);- }- std::unordered_map<std::string, ov::Tensor> weights{{"blk.0.attn_qkv.bias", bias}};-- auto parts = ov::frontend::gguf::split_fused_qkv_bias("blk.0.attn_qkv", weights, n_q, n_k, n_v);-- ASSERT_EQ(parts[0].get_shape(), ov::Shape{n_q});- ASSERT_EQ(parts[1].get_shape(), ov::Shape{n_k});- ASSERT_EQ(parts[2].get_shape(), ov::Shape{n_v});- for (size_t i = 0; i < n_q; ++i) {- EXPECT_FLOAT_EQ(parts[0].data<float>()[i], static_cast<float>(i));- }- for (size_t i = 0; i < n_k; ++i) {- EXPECT_FLOAT_EQ(parts[1].data<float>()[i], static_cast<float>(n_q + i));- }- for (size_t i = 0; i < n_v; ++i) {- EXPECT_FLOAT_EQ(parts[2].data<float>()[i], static_cast<float>(n_q + n_k + i));- }-}--TEST(GGUFFusedQkvWeight, PreservesScalesForGroupedFormats) {- const auto check = [](ov::frontend::gguf::GgufTensorType qtype,- const ov::element::Type& weight_type,- const ov::element::Type& scale_type,- size_t groups) {- constexpr size_t rows = 6;- constexpr size_t cols = 256;- std::unordered_map<std::string, ov::Tensor> weights{- {"fused.weight", ov::Tensor(weight_type, {rows, cols})},- {"fused.scales", ov::Tensor(scale_type, {rows, groups})},- };- std::unordered_map<std::string, ov::frontend::gguf::GgufTensorType> qtypes{{"fused.qtype", qtype}};-- auto qkv = ov::frontend::gguf::split_fused_qkv_extracted("fused", weights, qtypes, 2, 2, 2);- for (const auto& part : qkv) {- ASSERT_TRUE(part.tensors.scales);- EXPECT_EQ(part.tensors.scales.get_shape(), (ov::Shape{2, groups}));- }-- auto q_gate = ov::frontend::gguf::split_interleaved_q_gate("fused", weights, qtypes, 1);- for (const auto& part : q_gate) {- ASSERT_TRUE(part.tensors.scales);- EXPECT_EQ(part.tensors.scales.get_shape(), (ov::Shape{3, groups}));- }- };-- check(ov::frontend::gguf::GGUF_TYPE_MXFP4, ov::element::f4e2m1, ov::element::f8e8m0, 8);- check(ov::frontend::gguf::GGUF_TYPE_Q1_0, ov::element::u1, ov::element::f16, 2);- check(ov::frontend::gguf::GGUF_TYPE_Q8_1, ov::element::i8, ov::element::f16, 8);- check(ov::frontend::gguf::GGUF_TYPE_Q8_K, ov::element::i8, ov::element::f32, 1);-}-TEST(GGUFWeight, RejectsMissingAuxiliaryTensors) {using namespace ov::frontend::gguf;@@ -1033,12 +980,9 @@ TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUsesSymmetricStorageForMatrices) {const bool symmetric = name == "blk.0.ffn_up";ASSERT_NO_FATAL_FAILURE(write_tensor(full_name, bytes));const auto loaded = get_gguf_data(path);- const auto& arrays = std::get<1>(loaded);- const auto& prefix = name;- EXPECT_EQ(std::get<2>(loaded).at(prefix + ".qtype"), GGUF_TYPE_Q5_K);- WeightTensors tensors{arrays.at(full_name), arrays.at(prefix + ".scales"), {}};- if (auto zp = arrays.find(prefix + ".zp"); zp != arrays.end())- tensors.zero_point = zp->second;+ const auto& source = std::get<1>(loaded).at(full_name);+ EXPECT_EQ(source.qtype, GGUF_TYPE_Q5_K);+ const auto tensors = unpack_gguf_weight(source);EXPECT_EQ(tensors.weight.get_element_type(), symmetric ? ov::element::i8 : ov::element::u8);EXPECT_EQ(tensors.scales.get_shape(), (ov::Shape{2, 2, kCols / 32}));EXPECT_EQ(static_cast<bool>(tensors.zero_point), !symmetric);@@ -1050,44 +994,6 @@ TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUsesSymmetricStorageForMatrices) {}}-TEST(GGUFQ5KRequant, FusedSplitsKeepSymmetricStorage) {- using namespace ov::frontend::gguf;- const auto bytes = load_npy<uint8_t>("q5_k_qbytes");- GgufTensor source{};- source.type = GGUF_TYPE_Q5_K;- source.num_weights = kRows * kCols;- source.bsize = bytes.size();- source.weights_data = bytes.data();- WeightTensors tensors{ov::Tensor(ov::element::i8, {kRows, kCols}),- ov::Tensor(ov::element::f16, {kRows, kCols / 32}),- {}};- gguf_fill_q5_k_i8(source, tensors.weight, tensors.scales);- const std::unordered_map<std::string, ov::Tensor> weights{{"fused.weight", tensors.weight},- {"fused.scales", tensors.scales}};- const std::unordered_map<std::string, GgufTensorType> qtypes{{"fused.qtype", GGUF_TYPE_Q5_K}};- const auto qkv = split_fused_qkv_extracted("fused", weights, qtypes, 2, 1, 1);- const auto q_gate = split_interleaved_q_gate("fused", weights, qtypes, 1);- for (const auto& part : qkv) {- EXPECT_FALSE(part.tensors.zero_point);- EXPECT_NO_THROW(make_weight_node(part.tensors, part.qtype));- }- for (size_t part = 0; part < q_gate.size(); ++part) {- EXPECT_FALSE(q_gate[part].tensors.zero_point);- EXPECT_NO_THROW(make_weight_node(q_gate[part].tensors, q_gate[part].qtype));- for (size_t row = 0; row < 2; ++row) {- const size_t source_row = row * 2 + part;- EXPECT_EQ(std::memcmp(q_gate[part].tensors.weight.data<int8_t>() + row * kCols,- tensors.weight.data<int8_t>() + source_row * kCols,- kCols),- 0);- EXPECT_EQ(std::memcmp(q_gate[part].tensors.scales.data<ov::float16>() + row * (kCols / 32),- tensors.scales.data<ov::float16>() + source_row * (kCols / 32),- (kCols / 32) * sizeof(ov::float16)),- 0);- }- }-}-TEST(GGUFQ5KRequant, RejectsMalformedSymmetricGraphTensors) {using namespace ov::frontend::gguf;WeightTensors tensors{ov::Tensor(ov::element::i8, {2, 256}), ov::Tensor(ov::element::f16, {2, 8}), {}};@@ -1104,7 +1010,6 @@ TEST(GGUFQ5KRequant, RejectsMalformedSymmetricGraphTensors) {TEST(GGUFQ5KRequant, RejectsUnsupportedStorageLayouts) {using namespace ov::frontend::gguf;- const std::unordered_map<std::string, GgufTensorType> qtypes{{"fused.qtype", GGUF_TYPE_Q5_K}};for (const auto& type : {ov::element::i8, ov::element::u8, ov::element::f16}) {for (const auto& zp_type : {ov::element::dynamic, ov::element::u8, ov::element::f16}) {if ((type == ov::element::i8 && zp_type == ov::element::dynamic) ||@@ -1113,15 +1018,9 @@ TEST(GGUFQ5KRequant, RejectsUnsupportedStorageLayouts) {SCOPED_TRACE(type.get_type_name());SCOPED_TRACE(zp_type.get_type_name());WeightTensors tensors{ov::Tensor(type, {4, 256}), ov::Tensor(ov::element::f16, {4, 8}), {}};- std::unordered_map<std::string, ov::Tensor> weights{{"fused.weight", tensors.weight},- {"fused.scales", tensors.scales}};- if (zp_type != ov::element::dynamic) {+ if (zp_type != ov::element::dynamic)tensors.zero_point = ov::Tensor(zp_type, {4, 8});- weights.emplace("fused.zp", tensors.zero_point);- }EXPECT_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K), ov::Exception);- EXPECT_THROW(split_fused_qkv_extracted("fused", weights, qtypes, 2, 1, 1), ov::Exception);- EXPECT_THROW(split_interleaved_q_gate("fused", weights, qtypes, 1), ov::Exception);}}}