Skip to content

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

[GGUF] Simplify and deduplicate the quant layer (#38135)

Maxim Vafin98a207551cda
diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cpp
index 48391e8e736..725bc8d3b88 100644
--- a/src/frontends/gguf/src/quant/gguf.cpp
+++ b/src/frontends/gguf/src/quant/gguf.cpp
@@ -9,15 +9,21 @@
#include "gguf.hpp"
+#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
+#include <limits>
#include <optional>
+#include <string_view>
#include "openvino/core/except.hpp"
+#include "openvino/core/memory_util.hpp"
+#include "openvino/core/shape_util.hpp"
#include "openvino/core/type/element_type_traits.hpp"
#include "openvino/runtime/aligned_buffer.hpp"
#include "openvino/runtime/shared_buffer.hpp"
+#include "openvino/util/common_util.hpp"
#include "openvino/util/math_util.hpp"
#include "openvino/util/mmap_object.hpp"
#include "weights.hpp"
@@ -30,6 +36,7 @@ namespace {
constexpr uint32_t GGUF_MAGIC = 0x46554747; // "GGUF" little-endian
constexpr 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 {
@@ -88,6 +95,51 @@ TypeTraits type_traits(uint32_t type) {
}
}
+// Layout of the REPACKED tensors a quantized GGUF type is unpacked into: the element types and
+// shapes the gguf_fill_* functions write into quant_buf. Single source of truth for both the
+// pass-1 size reservation and the pass-2 view carving below, so the two cannot disagree about a
+// divisor. Returns nullopt for the non-quantized types, which are mmap views instead.
+struct QuantLayout {
+ ov::element::Type weight_type; // element type of the repacked weight blob
+ size_t weight_div; // innermost-dim divisor of the weight shape (8 = u32-packed u4)
+ ov::element::Type scale_type;
+ size_t group_size; // weights per scale
+ bool asymmetric; // carries a per-group zero-point
+};
+
+std::optional<QuantLayout> quant_layout(uint32_t type) {
+ constexpr bool asymmetric = true;
+ constexpr bool symmetric = false;
+ switch (type) {
+ case GGUF_TYPE_Q4_0:
+ return QuantLayout{ov::element::i4, 1, ov::element::f16, 32, symmetric};
+ case GGUF_TYPE_Q3_K:
+ return QuantLayout{ov::element::i4, 1, ov::element::f16, 16, symmetric};
+ case GGUF_TYPE_Q5_0:
+ case GGUF_TYPE_Q8_0:
+ return QuantLayout{ov::element::i8, 1, ov::element::f16, 32, symmetric};
+ case GGUF_TYPE_Q6_K:
+ return QuantLayout{ov::element::i8, 1, ov::element::f16, 16, symmetric};
+ case GGUF_TYPE_Q8_K:
+ // 256 i8 weights + an f32 (not f16) scale + 16 i16 bsums, which the dequant ignores.
+ return QuantLayout{ov::element::i8, 1, ov::element::f32, 256, symmetric};
+ case GGUF_TYPE_Q2_K:
+ return QuantLayout{ov::element::u2, 1, ov::element::f16, 16, asymmetric};
+ case GGUF_TYPE_Q2_0:
+ return QuantLayout{ov::element::u2, 1, ov::element::f16, 64, asymmetric};
+ case GGUF_TYPE_Q4_1:
+ case GGUF_TYPE_Q4_K:
+ return QuantLayout{ov::element::u32, 8, ov::element::f16, 32, asymmetric};
+ case GGUF_TYPE_Q5_1:
+ case GGUF_TYPE_Q5_K:
+ return QuantLayout{ov::element::i8, 1, ov::element::f16, 32, asymmetric};
+ case GGUF_TYPE_MXFP4:
+ return QuantLayout{ov::element::f4e2m1, 1, ov::element::f8e8m0, 32, symmetric};
+ default:
+ return std::nullopt;
+ }
+}
+
std::optional<ov::element::Type> gguf_type_to_dtype(uint32_t gguf_type) {
switch (gguf_type) {
case GGUF_TYPE_F64:
@@ -160,28 +212,6 @@ private:
uint64_t m_off = 0;
};
-size_t value_type_size(uint32_t type) {
- switch (type) {
- case GGUF_VALUE_TYPE_UINT8:
- case GGUF_VALUE_TYPE_INT8:
- case GGUF_VALUE_TYPE_BOOL:
- return 1;
- case GGUF_VALUE_TYPE_UINT16:
- case GGUF_VALUE_TYPE_INT16:
- return 2;
- case GGUF_VALUE_TYPE_UINT32:
- case GGUF_VALUE_TYPE_INT32:
- case GGUF_VALUE_TYPE_FLOAT32:
- return 4;
- case GGUF_VALUE_TYPE_UINT64:
- case GGUF_VALUE_TYPE_INT64:
- case GGUF_VALUE_TYPE_FLOAT64:
- return 8;
- default:
- return 0; // string / array handled separately
- }
-}
-
ov::element::Type value_type_to_dtype(uint32_t type) {
switch (type) {
case GGUF_VALUE_TYPE_UINT8:
@@ -236,7 +266,7 @@ void read_metadata_value(Cursor& cur, uint32_t type, GGUFMetaData& out) {
return;
}
auto dtype = value_type_to_dtype(elem_type);
- const size_t elem_size = value_type_size(elem_type);
+ const size_t elem_size = dtype.size();
// `len` and `elem_size` are both attacker-controlled (elem_size indirectly, via
// elem_type) and size a Tensor allocation and a memcpy below; validate `len` against the
// cursor's remaining bytes -- via a division, not `len * elem_size`, which could itself
@@ -256,7 +286,7 @@ void read_metadata_value(Cursor& cur, uint32_t type, GGUFMetaData& out) {
// Scalar: store as a shape-{} ov::Tensor of the right element type.
auto dtype = value_type_to_dtype(type);
ov::Tensor t(dtype, ov::Shape(0));
- const size_t nbytes = value_type_size(type);
+ const size_t nbytes = dtype.size();
OPENVINO_ASSERT(nbytes <= cur.remaining(), "[load_gguf] scalar metadata value runs past end of file");
std::memcpy(t.data(), cur.ptr(), nbytes);
cur.skip(nbytes);
@@ -339,6 +369,48 @@ bool metadata_to_bool_or(const std::unordered_map<std::string, GGUFMetaData>& me
return *(tensor.data<ov::element_type_traits<ov::element::boolean>::value_type>()) != 0;
}
+// Read a metadata array of integer elements as a vector<int32_t>, empty when the key is absent.
+// GGUF writers disagree on the element type for the same key (llama.cpp emits
+// rope.dimension_sections as INT32 and attention.recurrent_layers as UINT32, and boolean arrays
+// carry the sliding-window pattern), so accept any 1- or 4-byte integer encoding.
+// `max_n` caps how many entries are taken (rope.dimension_sections reads at most 4).
+std::vector<int32_t> metadata_to_i32_vector(const std::unordered_map<std::string, GGUFMetaData>& metadata,
+ const std::string& key,
+ size_t max_n = std::numeric_limits<size_t>::max()) {
+ std::vector<int32_t> out;
+ auto it = metadata.find(key);
+ if (it == metadata.end()) {
+ return out;
+ }
+ const auto* t = std::get_if<ov::Tensor>(&it->second);
+ OPENVINO_ASSERT(t && t->data(), "[GGUF] metadata key '", key, "' is not an array as expected");
+ const auto& et = t->get_element_type();
+ OPENVINO_ASSERT(et.is_integral() && (et.size() == 1 || et.size() == 4),
+ "[GGUF] metadata key '",
+ key,
+ "' is not an integer array as expected, got ",
+ et);
+ const auto* bytes = static_cast<const uint8_t*>(t->data());
+ const size_t n = std::min(t->get_size(), max_n);
+ out.reserve(n);
+ for (size_t i = 0; i < n; ++i) {
+ if (et == ov::element::boolean) {
+ // Only a boolean array normalizes to 0/1. A byte-sized INTEGER array keeps its
+ // value: these keys carry counts and widths (a rope section of 32 must not
+ // become 1), not just flags.
+ out.push_back(bytes[i] ? 1 : 0);
+ } else if (et.size() == 1) {
+ out.push_back(et.is_signed() ? static_cast<int32_t>(static_cast<int8_t>(bytes[i]))
+ : static_cast<int32_t>(bytes[i]));
+ } else {
+ int32_t v = 0;
+ std::memcpy(&v, bytes + i * 4, sizeof(v));
+ out.push_back(v);
+ }
+ }
+ return out;
+}
+
} // namespace
ov::Shape get_shape(const GgufTensor& tensor) {
@@ -420,136 +492,55 @@ GGUFLoad get_gguf_data(const std::string& file) {
}
// Tensor data starts at the next `alignment`-aligned offset after the info section.
- uint64_t data_off = cur.offset();
- if (uint64_t rem = data_off % alignment) {
- data_off += alignment - rem;
- }
+ uint64_t data_off = cur.offset() + ov::util::align_padding_size(alignment, cur.offset());
- // Helper: for a quantized tensor, compute (weights_bytes, scale_bytes, zp_bytes).
- // Symmetric types (Q4_0, Q8_0, Q5_0, Q6_K): zp_bytes = 0.
- // Asymmetric types: zero-points use the element type selected by gguf_zero_point_type.
+ // Bytes the repacked (weight, scale, zero-point) tensors of a quantized tensor occupy in
+ // quant_buf, derived from its QuantLayout. Symmetric types have no zero-point; asymmetric
+ // ones use the element type selected by gguf_zero_point_type.
//
- // Every dim comes straight from the file, so shape products (and the total below) use
- // ov::util::mul_overflow/add_overflow instead of raw `*=`/`+=`: wrapped products could
- // otherwise under-size quant_buf while the fill functions still write the real,
- // attacker-controlled shape into it.
- auto size_prod = [](const ov::Shape& s) -> size_t {
- size_t result = 1;
- for (auto d : s) {
- size_t next = 0;
- OPENVINO_ASSERT(!ov::util::mul_overflow(result, static_cast<size_t>(d), next),
- "[load_gguf] tensor element count overflows size_t");
- result = next;
- }
- return result;
- };
- auto quant_sizes = [&size_prod](const TensorInfo& ti) -> std::tuple<size_t, size_t, size_t> {
- auto shape = [&]() {
+ // Every dim comes straight from the file, so the element and byte counts go through the
+ // overflow-checked ov::util helpers: a wrapped product could otherwise under-size quant_buf
+ // while the fill functions still write the real, attacker-controlled shape into it.
+ auto quant_sizes = [](const TensorInfo& ti, const QuantLayout& ql) -> std::array<size_t, 3> {
+ const ov::Shape shape = [&ti]() {
ov::Shape s;
for (int i = static_cast<int>(ti.ndim) - 1; i >= 0; --i)
s.push_back(ti.dim[i]);
return s;
}();
OPENVINO_ASSERT(!shape.empty(), "[load_gguf] tensor '", ti.name, "' is quantized but has rank 0");
-
- if (ti.type == GGUF_TYPE_Q8_K) {
- // Q8_K: 256 i8 weights + f32 scale + 16 i16 bsums (ignored) per block.
- const size_t nelems = size_prod(shape);
- const size_t n_blocks = nelems / 256;
- return {nelems, n_blocks * sizeof(float), 0}; // w_bytes, s_bytes(f32), no zp
- }
-
if (ti.type == GGUF_TYPE_MXFP4) {
- const size_t nelems = size_prod(shape);
- const size_t cols = shape.back();
- OPENVINO_ASSERT(cols != 0, "[load_gguf] tensor '", ti.name, "' has a zero-sized dimension");
- const size_t groups = cols / 32;
- size_t rows = nelems / cols;
- const size_t w_bytes = (nelems + 1) / 2; // f4e2m1: 4-bit
- const size_t s_bytes = rows * groups; // f8e8m0: 1 byte/group
- return {w_bytes, s_bytes, 0};
- }
-
- const size_t w_nelems = size_prod(shape);
-
- // Q2_K: u2 (4 per byte), 16 sub-blocks of 16 per super-block.
- if (ti.type == GGUF_TYPE_Q2_K) {
- const size_t w_bytes = (w_nelems + 3) / 4; // u2: 4 values per byte
- auto scale_shape = shape;
- scale_shape.back() /= 16;
- const size_t s_nelems = size_prod(scale_shape);
- return {w_bytes, s_nelems * sizeof(uint16_t), s_nelems}; // zp: u8 per sub-block
+ OPENVINO_ASSERT(shape.back() != 0, "[load_gguf] tensor '", ti.name, "' has a zero-sized dimension");
}
- // Q2_0: u2 (4 per byte), one f16 scale per 64 weights, constant zero-point of 1.
- if (ti.type == GGUF_TYPE_Q2_0) {
- const size_t w_bytes = (w_nelems + 3) / 4; // u2: 4 values per byte
- auto scale_shape = shape;
- scale_shape.back() /= 64;
- const size_t s_nelems = size_prod(scale_shape);
- return {w_bytes, s_nelems * sizeof(uint16_t), s_nelems}; // zp: u8 per block
- }
-
- // Q3_K: i4 packed (2 per byte), 16 sub-blocks of 16 per super-block.
- if (ti.type == GGUF_TYPE_Q3_K) {
- const size_t w_bytes = (w_nelems + 1) / 2; // i4: 2 values per byte
- auto scale_shape = shape;
- scale_shape.back() /= 16;
- const size_t s_nelems = size_prod(scale_shape);
- return {w_bytes, s_nelems * sizeof(uint16_t), 0}; // symmetric: no zp
- }
-
- // Weights: i8 or u8 stored in byte arrays (u32 only for asymmetric 4-bit).
- // 4-bit types: Q4_0(i4), Q4_1(u4 in u32), Q4_K(u4 in u32).
- // 8-bit types: Q8_0(i8), Q5_0(i8), Q5_1(i8), Q5_K(i8), Q6_K(i8).
- const bool is_4bit = (ti.type == GGUF_TYPE_Q4_0 || ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K);
- uint64_t weights_per_byte = is_4bit ? 2 : 1;
- // Q6_K: 16 weights per sub-block (16 sub-blocks × 16 = 256 per super-block).
- uint64_t weights_per_block = (ti.type == GGUF_TYPE_Q6_K) ? 16 : 32;
-
- size_t w_bytes;
- if (is_4bit) {
- // u32-packed nibbles: floor((n+7)/8)*4 bytes
- w_bytes = ((w_nelems / weights_per_byte) / 4) * sizeof(uint32_t);
- } else {
- // i8 byte per element
- w_bytes = w_nelems;
- }
-
- auto scale_shape = shape;
- scale_shape.back() /= weights_per_block;
- const size_t s_nelems = size_prod(scale_shape);
- const size_t s_bytes = s_nelems * sizeof(uint16_t);
-
- // Zero-point bytes. Symmetric formats have none; asymmetric formats use the same
- // element count as scales and the representation selected by gguf_zero_point_type.
- size_t z_bytes = 0;
- if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||
- ti.type == GGUF_TYPE_Q5_1) {
- OPENVINO_ASSERT(
- !ov::util::mul_overflow(s_nelems,
- gguf_zero_point_type(ti.name, static_cast<GgufTensorType>(ti.type)).size(),
- z_bytes),
- "[load_gguf] zero-point byte count overflows size_t");
- }
- return {w_bytes, s_bytes, z_bytes};
+ const auto bytes = [&ti](const ov::element::Type& et, const ov::Shape& s) {
+ const auto n = ov::util::get_memory_size_safe(et, s);
+ OPENVINO_ASSERT(n.has_value(), "[load_gguf] tensor '", ti.name, "' byte count overflows size_t");
+ return *n;
+ };
+
+ ov::Shape weight_shape = shape;
+ weight_shape.back() /= ql.weight_div;
+ ov::Shape scale_shape = shape;
+ scale_shape.back() /= ql.group_size;
+ const size_t z_bytes =
+ ql.asymmetric ? bytes(gguf_zero_point_type(ti.name, static_cast<GgufTensorType>(ti.type)), scale_shape) : 0;
+ return {bytes(ql.weight_type, weight_shape), bytes(ql.scale_type, scale_shape), z_bytes};
};
- // ---- Pass 1: total bytes needed for all repacked quantized data ----
+ // ---- Pass 1: size, and record, every tensor's slice of the repacked quantized data ----
+ std::vector<std::array<size_t, 3>> quant_bytes(infos.size(), {0, 0, 0});
size_t total_quant_bytes = 0;
- for (const auto& ti : infos) {
- const bool is_quant = ti.type == GGUF_TYPE_Q4_0 || ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q5_0 ||
- ti.type == GGUF_TYPE_Q5_1 || ti.type == GGUF_TYPE_Q8_0 || ti.type == GGUF_TYPE_Q2_K ||
- ti.type == GGUF_TYPE_Q3_K || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||
- ti.type == GGUF_TYPE_Q6_K || ti.type == GGUF_TYPE_Q8_K || ti.type == GGUF_TYPE_MXFP4 ||
- ti.type == GGUF_TYPE_Q2_0;
- if (!is_quant)
+ for (size_t i = 0; i < infos.size(); ++i) {
+ const auto layout = quant_layout(infos[i].type);
+ if (!layout) {
continue;
- auto [wb, sb, bb] = quant_sizes(ti);
- size_t sum = 0;
- OPENVINO_ASSERT(!ov::util::add_overflow(wb, sb, sum) && !ov::util::add_overflow(sum, bb, sum) &&
- !ov::util::add_overflow(total_quant_bytes, sum, total_quant_bytes),
- "[load_gguf] total quantized buffer size overflows size_t");
+ }
+ quant_bytes[i] = quant_sizes(infos[i], *layout);
+ for (const size_t part : quant_bytes[i]) {
+ const bool overflow = ov::util::add_overflow(total_quant_bytes, part, total_quant_bytes);
+ OPENVINO_ASSERT(!overflow, "[load_gguf] total quantized buffer size overflows size_t");
+ }
}
// Single allocation for all repacked quantized data (IR-frontend AlignedBuffer pattern).
@@ -557,7 +548,8 @@ GGUFLoad get_gguf_data(const std::string& file) {
// ---- Pass 2: materialize tensors, slicing into quant_buf for quantized ones ----
size_t quant_offset = 0;
- for (const auto& ti : infos) {
+ for (size_t idx = 0; idx < infos.size(); ++idx) {
+ const TensorInfo& ti = infos[idx];
GgufTensor tensor;
tensor.name = ti.name.data();
tensor.namelen = ti.name.size();
@@ -596,251 +588,66 @@ GGUFLoad get_gguf_data(const std::string& file) {
tensor.weights_data = base + abs_off;
const std::string& name = ti.name;
- constexpr std::string_view weight_suffix = ".weight";
- const bool has_weight_suffix =
- name.size() >= weight_suffix.size() &&
- name.compare(name.size() - weight_suffix.size(), weight_suffix.size(), weight_suffix) == 0;
// 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 =
- has_weight_suffix ? name.substr(0, name.length() - weight_suffix.length()) : name;
- if (ti.type == GGUF_TYPE_Q4_0) {
- // Symmetric: i4 weights (XORed u4) + f16 scales, no bias tensor.
- auto [wb, sb, bb] = quant_sizes(ti);
- char* buf_ptr = quant_buf->get_ptr<char>();
- auto shape = get_shape(tensor);
- auto scale_shape = shape;
- scale_shape.back() /= 32;
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::i4, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
-
- gguf_fill_sym(tensor, weights, scales);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
- qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q4_0);
- } else if (ti.type == GGUF_TYPE_Q3_K) {
- // Symmetric: i4 weights (2 per byte) + f16 scales. No zero-point.
- auto [wb, sb, zb] = quant_sizes(ti);
- (void)zb;
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- auto scale_shape = shape;
- scale_shape.back() /= 16; // 16 sub-blocks per super-block
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::i4, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
+ ov::util::ends_with(name, WEIGHT_SUFFIX) ? name.substr(0, name.length() - WEIGHT_SUFFIX.length()) : name;
- gguf_fill_sym(tensor, weights, scales);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
- qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q3_K);
- } else if (ti.type == GGUF_TYPE_Q2_K) {
- // Asymmetric: u2 weights (4 per byte) + f16 scales + u8 zp per sub-block.
- auto [wb, sb, zb] = quant_sizes(ti);
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- auto scale_shape = shape;
- scale_shape.back() /= 16; // 16 sub-blocks per super-block
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::u2, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
- // Fractional zp (= min/scale) in the scale's element type -- see the Q4_K/Q5_K branch.
- ov::Tensor zp(scales.get_element_type(), scale_shape);
- quant_offset += zb;
+ const auto layout = quant_layout(ti.type);
+ 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;
+ }
- gguf_fill_asym(tensor, weights, scales, zp);
- mapped->hint_evict(abs_off, tensor.bsize);
+ 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;
+
+ // Carve each repacked tensor out of the single quant_buf allocation, in the same order
+ // and with the same sizes pass 1 reserved for it.
+ char* buf_ptr = quant_buf->get_ptr<char>();
+ std::shared_ptr<void> so_buf(quant_buf);
+ size_t part = 0;
+ const auto carve = [&](const ov::element::Type& et, const ov::Shape& s) {
+ ov::Tensor view(et, s, static_cast<void*>(buf_ptr + quant_offset));
+ quant_offset += quant_bytes[idx][part++];
+ return ov::Tensor(view, so_buf);
+ };
+ ov::Tensor weights = carve(layout->weight_type, weight_shape);
+ ov::Tensor scales = carve(layout->scale_type, scale_shape);
+ ov::Tensor zp;
+ if (layout->asymmetric) {
+ // Preserve the native zero-point representation, including u8 for Q2_0.
+ zp = carve(gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type)), scale_shape);
+ }
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
- arrays.emplace(name_prefix + ".zp", std::move(zp));
- qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q2_K);
+ if (ti.type == GGUF_TYPE_MXFP4) {
+ gguf_fill_mxfp4(tensor, weights, scales);
} else if (ti.type == GGUF_TYPE_Q2_0) {
- // Ternary: u2 weights (4 per byte) + one f16 scale per 64 + integer zp of exactly 1.
- // ggml packs Q2_0 codes LSB-first, 4 per byte -- the same order OpenVINO's u2 Constant
- // expects -- so the code bytes are copied verbatim, no repacking.
- auto [wb, sb, zb] = quant_sizes(ti);
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- auto scale_shape = shape;
- scale_shape.back() /= 64; // one scale per 64-weight block
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::u2, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
- // Integer zero-point: (code - 1) * scale, so zp is the constant 1 for every block.
- ov::Tensor zp(ov::element::u8, scale_shape);
- quant_offset += zb;
-
gguf_fill_q2_0(tensor, weights, scales, zp);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
- arrays.emplace(name_prefix + ".zp", std::move(zp));
- qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q2_0);
- } else if (ti.type == GGUF_TYPE_Q8_K) {
- // Q8_K: 256 weights/block, f32 scale (NOT f16), 16 i16 bsums (ignored).
- // block_q8_K: [f32 d][i8 qs[256]][i16 bsums[16]] = 4+256+32 = 292 bytes.
- auto [wb, sb, zb] = quant_sizes(ti);
- (void)zb;
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- auto scale_shape = shape;
- scale_shape.back() /= 256; // one f32 scale per 256-weight block
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::i8, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights_t(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f32, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales_t(s_view, so_buf);
- quant_offset += sb;
-
- gguf_fill_sym(tensor, weights_t, scales_t);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- arrays.emplace(name, std::move(weights_t));
- arrays.emplace(name_prefix + ".scales", std::move(scales_t));
- qtype.emplace(name_prefix + ".qtype", GGUF_TYPE_Q8_K);
- } else if (ti.type == GGUF_TYPE_Q8_0 || ti.type == GGUF_TYPE_Q5_0 || ti.type == GGUF_TYPE_Q6_K) {
- // Symmetric: i8 weights (no u32 packing) + f16 scales. No zero-point.
- auto [wb, sb, zb] = quant_sizes(ti);
- (void)zb;
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- const uint64_t weights_per_block = (ti.type == GGUF_TYPE_Q6_K) ? 16 : 32;
- auto scale_shape = shape;
- scale_shape.back() /= weights_per_block;
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::i8, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
-
- gguf_fill_sym(tensor, weights, scales);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
- qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));
- } else if (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K || ti.type == GGUF_TYPE_Q5_K ||
- ti.type == GGUF_TYPE_Q5_1) {
- // Asymmetric: weights + f16 scales + zero-point. Q4_K matmul weights are decoded and
- // requantized group-wise to u4 with an integer zero-point; Q8_0_C sources keep f16.
- auto [wb, sb, zb] = quant_sizes(ti);
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- const bool is_4bit = (ti.type == GGUF_TYPE_Q4_1 || ti.type == GGUF_TYPE_Q4_K);
- const uint64_t weights_per_block = 32;
-
- auto weights_shape = shape;
- if (is_4bit)
- weights_shape.back() /= 8; // u32 packs 8 u4
- auto scale_shape = shape;
- scale_shape.back() /= weights_per_block;
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::element::Type w_elem = is_4bit ? ov::element::u32 : ov::element::i8;
- ov::Tensor w_view(w_elem, is_4bit ? weights_shape : shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
- ov::Tensor s_view(ov::element::f16, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
- // Both ingest paths must agree on the zero-point representation; see
- // gguf_zero_point_type in quant/weights.hpp for why it matters.
- const auto zp_elem = gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type));
- // Q4_K performs a real group-wise requantization; Q2_0's integer zero-point is exact.
- if (zp_elem == ov::element::u8 && ti.type == GGUF_TYPE_Q4_K) {
- notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);
- }
- ov::Tensor zp(zp_elem, scale_shape);
- quant_offset += zb;
-
+ } else if (layout->asymmetric) {
gguf_fill_asym(tensor, weights, scales, zp);
- mapped->hint_evict(abs_off, tensor.bsize);
+ } else {
+ gguf_fill_sym(tensor, weights, scales);
+ }
+ mapped->hint_evict(abs_off, tensor.bsize);
- arrays.emplace(name, std::move(weights));
- arrays.emplace(name_prefix + ".scales", std::move(scales));
+ 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));
- } else if (ti.type == GGUF_TYPE_MXFP4) {
- // MXFP4: slice weight (f4e2m1) + scale (f8e8m0) out of quant_buf.
- auto [wb, sb, dummy_bb] = quant_sizes(ti);
- (void)dummy_bb;
- char* buf_ptr = quant_buf->get_ptr<char>();
-
- auto shape = get_shape(tensor);
- const size_t cols = shape.back();
- const size_t groups = cols / 32;
- ov::Shape scale_shape = shape;
- scale_shape.back() = groups;
-
- std::shared_ptr<void> so_buf(quant_buf);
- ov::Tensor w_view(ov::element::f4e2m1, shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor weights(w_view, so_buf);
- quant_offset += wb;
-
- ov::Tensor s_view(ov::element::f8e8m0, scale_shape, static_cast<void*>(buf_ptr + quant_offset));
- ov::Tensor scales(s_view, so_buf);
- quant_offset += sb;
-
- gguf_fill_mxfp4(tensor, weights, scales);
- mapped->hint_evict(abs_off, tensor.bsize);
-
- constexpr std::string_view weight_suffix = ".weight";
- const std::string prefix = name.substr(0, name.length() - weight_suffix.length());
- arrays.emplace(name, std::move(weights));
- arrays.emplace(prefix + ".scales", std::move(scales));
- qtype.emplace(prefix + ".qtype", GGUF_TYPE_MXFP4);
- } else {
- ov::Tensor loaded = extract_tensor_data(tensor, mapped); // zero-copy mmap view
- OPENVINO_ASSERT(arrays.emplace(name, loaded).second, "[load_gguf] duplicate tensor name '", name, "'");
- constexpr std::string_view weight_suffix = ".weight";
- if (name.size() >= weight_suffix.size()) {
- const std::string name_prefix = name.substr(0, name.length() - weight_suffix.length());
- qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));
- }
}
+ qtype.emplace(name_prefix + ".qtype", static_cast<GgufTensorType>(ti.type));
}
- return {metadata, arrays, qtype, mapped, quant_buf};
+ return {std::move(metadata), std::move(arrays), std::move(qtype), std::move(mapped), std::move(quant_buf)};
}
std::map<std::string, GGUFMetaData> decoder_config_from_meta(
@@ -984,30 +791,10 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
config["nextn_predict_layers"] = ssm_key("nextn_predict_layers");
// Explicit per-layer recurrent flags. llama.cpp consults this FIRST and only falls back to
// full_attention_interval when it is absent (src/models/qwen35.cpp load_arch_hparams).
- {
- std::vector<int32_t> recr;
- const std::string key = arch + ".attention.recurrent_layers";
- if (metadata.count(key)) {
- const auto& t = std::get<ov::Tensor>(metadata.at(key));
- const auto* p = t.data<uint32_t>();
- for (size_t i = 0; i < t.get_size(); ++i)
- recr.push_back(static_cast<int32_t>(p[i]));
- }
- config["recurrent_layer_flags"] = recr;
- }
+ config["recurrent_layer_flags"] = metadata_to_i32_vector(metadata, arch + ".attention.recurrent_layers");
// M-RoPE section widths (qwen35 / qwen3vl): 4 per-axis rotary section sizes.
- {
- std::vector<int32_t> sections;
- const std::string key = arch + ".rope.dimension_sections";
- if (metadata.count(key)) {
- const auto& t = std::get<ov::Tensor>(metadata.at(key));
- const auto* p = t.data<uint32_t>();
- for (size_t i = 0; i < t.get_size() && i < 4; ++i)
- sections.push_back(static_cast<int32_t>(p[i]));
- }
- config["rope_sections"] = sections;
- }
+ config["rope_sections"] = metadata_to_i32_vector(metadata, arch + ".rope.dimension_sections", 4);
// Optional explicit attention (softmax) scale; 0 -> use 1/sqrt(head_size).
// Gemma4 uses scale=1.0 (no pre-attn scaling), per llama.cpp hparams.f_attention_scale=1.0.
@@ -1064,12 +851,8 @@ std::map<std::string, GGUFMetaData> decoder_config_from_meta(
const auto& t = std::get<ov::Tensor>(v);
if (t.get_element_type() == ov::element::boolean) {
// Boolean array: convert to vector<int32_t> (1=SWA, 0=global) for the builder.
- const size_t n = t.get_size();
- std::vector<int32_t> swa_flags(n);
- const auto* bdata = t.data<uint8_t>();
- for (size_t i = 0; i < n; ++i)
- swa_flags[i] = bdata[i] ? 1 : 0;
- config["swa_layer_flags"] = swa_flags;
+ config["swa_layer_flags"] =
+ metadata_to_i32_vector(metadata, arch + ".attention.sliding_window_pattern");
config["swa_layer_pattern"] = 0; // 0 = use per-layer flags, not period
} else {
config["swa_layer_pattern"] = metadata_to_int(metadata, arch + ".attention.sliding_window_pattern");
diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hpp
index fe632f392f9..4cd33f7843a 100644
--- a/src/frontends/gguf/src/quant/gguf.hpp
+++ b/src/frontends/gguf/src/quant/gguf.hpp
@@ -112,6 +112,11 @@ void gguf_fill_mxfp4(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor&
// The zero-point is the constant 1 for every block: value = (code - 1) * scale.
void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp);
+// Quantize one row to Q8_0_C: a single channel-wise f16 scale (amax/127) plus signed int8
+// weights. Shared by every channel-wise requant source so the rounding and the zero-row rule
+// live in one place.
+void quantize_row_q8_0_c(const float* x, size_t cols, int8_t* out_weights, ov::float16& out_scale);
+
// Fused bit-exact ggml dequant + channel-wise Q8_0_C requant for the token_embd/output/Q6_K/Q5_K
// requant path. Streams one row at a time (never materializes the full f32 weight). Fills i8
// weights [rows,cols] + f16 scales [rows,1]; matches upstream's to_float->quantize_q8_0 exactly so
diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cpp
index 19dbecf9b70..6940768ab23 100644
--- a/src/frontends/gguf/src/quant/gguf_quants.cpp
+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp
@@ -15,6 +15,7 @@
#include "gguf.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/element_type_traits.hpp"
+#include "weights.hpp"
namespace ov {
namespace frontend {
@@ -31,7 +32,85 @@ static constexpr uint64_t kQ6K_BLOCK_BYTES = 128 + 64 + 16 + 2; // ql + qh
static inline uint8_t quantize_zp_u8(float zpval) {
OPENVINO_ASSERT(std::isfinite(zpval), "[GGUF] cannot quantize a non-finite zero-point");
long r = std::lround(zpval);
- return static_cast<uint8_t>(std::min<long>(255, std::max<long>(0, r)));
+ return static_cast<uint8_t>(std::clamp(r, 0L, 255L));
+}
+
+// A block's zero-point in quantized units: its affine offset divided by its scale. A zero scale
+// means every value in the block is the same, so any zero-point reconstructs it.
+static inline float zp_from_offset(float offset, float scale) {
+ return (scale != 0.f) ? (offset / scale) : 0.f;
+}
+
+// 6-bit packed sub-scale/min extraction for K-quants (Q4_K/Q5_K 12-byte scale block).
+static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t* m) {
+ if (j < 4) {
+ *d = q[j] & 63;
+ *m = q[j + 4] & 63;
+ } else {
+ *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
+ *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
+ }
+}
+
+// Writes per-block zero-points in whichever representation the destination tensor selected:
+// - u8 -> INTEGER zp: keeps the dequant in the low-precision form the CPU plugin fuses into
+// the MatMul (matches the original ggml-openvino backend).
+// - f16 -> FRACTIONAL zp: numerically faithful, used on the requant path where the dequant is
+// consumed by channel-wise Q8_0_C rather than fed to the compressed MatMul.
+// See fill_q4_k for the full rationale.
+class ZeroPointWriter {
+public:
+ explicit ZeroPointWriter(ov::Tensor& zp_arr) : m_integer(zp_arr.get_element_type() == ov::element::u8) {
+ if (m_integer) {
+ m_u8 = static_cast<uint8_t*>(zp_arr.data());
+ } else {
+ m_f16 = zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
+ }
+ }
+
+ bool is_integer() const {
+ return m_integer;
+ }
+
+ void store(size_t idx, float zpval) const {
+ if (m_integer) {
+ m_u8[idx] = quantize_zp_u8(zpval);
+ } else {
+ m_f16[idx] = ov::float16(zpval);
+ }
+ }
+
+ // Store an already-integral zero-point produced by a requantization.
+ void store_integer(size_t idx, uint8_t zpval) const {
+ OPENVINO_ASSERT(m_integer, "[GGUF] integer zero-point written to a fractional zero-point tensor");
+ m_u8[idx] = zpval;
+ }
+
+private:
+ bool m_integer;
+ uint8_t* m_u8 = nullptr;
+ ov::element_type_traits<ov::element::f16>::value_type* m_f16 = nullptr;
+};
+
+// Quantize one row to Q8_0_C: a single channel-wise f16 scale (amax/127) plus signed int8
+// weights. Shared by every requant source so the rounding and the zero-row rule live in one
+// place.
+void quantize_row_q8_0_c(const float* x, size_t cols, int8_t* out_weights, ov::float16& out_scale) {
+ float amax = 0.0f;
+ for (size_t c = 0; c < cols; ++c) {
+ amax = std::max(amax, std::fabs(x[c]));
+ }
+ const float d = amax / 127.0f;
+ // A zero row has a zero scale and must remain zero. Keep the division in a
+ // branch where its divisor is known to be non-zero.
+ float id = 0.0f;
+ if (d != 0.0f) {
+ id = 1.0f / d;
+ }
+ out_scale = ov::float16(d);
+ for (size_t c = 0; c < cols; ++c) {
+ out_weights[c] = static_cast<int8_t>(std::lround(x[c] * id));
+ }
}
void unpack_32_4(const uint8_t* data, uint8_t* dst) {
@@ -48,32 +127,33 @@ void unpack_32_4(const uint8_t* data, uint8_t* dst) {
}
}
+// Q5_0/Q5_1 block body: |32-bit qh|16 bytes ql (32x4bit low)|. weight = lo | (hi << 4) in
+// [0..31]; `bias` centers it (-16 for Q5_0's symmetric layout, 0 for Q5_1's raw asymmetric one).
+static inline void unpack_q5_block(const uint8_t* qh_ql, int8_t* dst, int bias) {
+ uint32_t qh;
+ std::memcpy(&qh, qh_ql, sizeof(qh));
+ const uint8_t* ql = qh_ql + 4;
+ for (uint64_t j = 0; j < 32; ++j) {
+ const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);
+ const uint8_t hi = (qh >> j) & 1;
+ dst[j] = static_cast<int8_t>((lo | (hi << 4)) + bias);
+ }
+}
+
// Q4_1 asymmetric: block = |f16 scale|f16 min|32x4bit weights|.
// Dequant w = sc*q + mn = sc*(q - zp), zp = -mn/sc.
-// The zp element type selects the representation (see fill_q4_k for the rationale):
-// - u8 -> INTEGER zp = round(-mn/sc): keeps the dequant in the low-precision form the CPU
-// plugin fuses into the MatMul (matches the original ggml-openvino backend).
-// - f16 -> FRACTIONAL zp = -mn/sc: numerically faithful, used on the requant path where the
-// dequant is consumed by channel-wise Q8_0_C rather than fed to the compressed MatMul.
// Outputs u32-packed u4 weights + f16 scales + zero-points (one per block).
void fill_q4_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& scales_arr, ov::Tensor& zp_arr) {
const uint64_t bytes_per_block = 20; // 2 bytes scale, 2 bytes min, 32x0.5 byte weights
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<uint8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);
- auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;
- const size_t n = scales_arr.get_size();
- ov::parallel_for(n, [&](size_t i) {
+ const ZeroPointWriter zp(zp_arr);
+ ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
const float sc = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block))));
const float mn = static_cast<float>(ov::float16::from_bits(*((uint16_t*)(data + i * bytes_per_block + 2))));
scales[i] = ov::float16(sc);
- const float zpval = (sc != 0.f) ? (-mn / sc) : 0.f;
- if (int_zp)
- zp_u8[i] = quantize_zp_u8(zpval);
- else
- zp_f16[i] = ov::float16(zpval);
+ zp.store(i, zp_from_offset(-mn, sc));
unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
});
}
@@ -104,14 +184,7 @@ void fill_q5_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
const uint8_t* block_data = data + i * bytes_per_block;
scales[i] = ov::float16::from_bits(*(uint16_t*)block_data);
- uint32_t qh;
- std::memcpy(&qh, block_data + 2, sizeof(qh));
- const uint8_t* ql = block_data + 6;
- for (uint64_t j = 0; j < weights_per_block; ++j) {
- const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);
- const uint8_t hi = (qh >> j) & 1;
- weights[i * weights_per_block + j] = static_cast<int8_t>((lo | (hi << 4)) - 16);
- }
+ unpack_q5_block(block_data + 2, weights + i * weights_per_block, -16);
});
}
@@ -151,9 +224,11 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<uint8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);
- auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;
+ const ZeroPointWriter zp_out(zp_arr);
+ if (zp_out.is_integer()) {
+ // An integer zero-point means this tensor is being requantized onto a new u4 grid below.
+ notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);
+ }
ov::parallel_for(n_super_block, [&](size_t i) {
const uint8_t* block_data = data + i * bytes_per_block;
@@ -165,22 +240,15 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
" has non-finite scale metadata");
const uint8_t* qs1 = block_data + 4;
- // 8 sub-blocks: 6-bit scale and 6-bit min packed in 12 bytes.
- uint8_t sc_raw[8], m_raw[8];
- for (int j = 0; j < 4; ++j) {
- sc_raw[j] = qs1[j] & 0x3F;
- m_raw[j] = qs1[j + 4] & 0x3F;
- sc_raw[j + 4] = (qs1[j + 8] & 0x0F) | ((qs1[j] >> 6) << 4);
- m_raw[j + 4] = (qs1[j + 8] >> 4) | ((qs1[j + 4] >> 6) << 4);
- }
-
for (int j = 0; j < 8; ++j) {
- const float sc = d * sc_raw[j];
- const float mn = dmin * m_raw[j];
- if (!int_zp) {
+ // 8 sub-blocks: 6-bit scale and 6-bit min packed in 12 bytes.
+ uint8_t sc_raw, m_raw;
+ get_scale_min_k4(j, qs1, &sc_raw, &m_raw);
+ const float sc = d * sc_raw;
+ const float mn = dmin * m_raw;
+ if (!zp_out.is_integer()) {
scales[i * 8 + j] = ov::float16(sc);
- const float zpval = (sc != 0.f) ? (mn / sc) : 0.f;
- zp_f16[i * 8 + j] = ov::float16(zpval);
+ zp_out.store(i * 8 + j, zp_from_offset(mn, sc));
continue;
}
@@ -216,7 +284,7 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
uint8_t best_q[32];
std::copy_n(source_q, 32, best_q);
ov::float16 best_scale(sc);
- uint8_t best_zp = quantize_zp_u8((sc != 0.0f) ? (mn / sc) : 0.0f);
+ uint8_t best_zp = quantize_zp_u8(zp_from_offset(mn, sc));
Error best_error = measure(static_cast<float>(best_scale), best_zp, best_q);
const float fallback_max_error = best_error.max_abs;
@@ -225,7 +293,7 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
initial_scale = std::numeric_limits<float>::epsilon();
}
const auto rounded_zp = static_cast<long>(std::nearbyint(-min_value / initial_scale));
- const uint8_t zp = static_cast<uint8_t>(std::min<long>(15, std::max<long>(0, rounded_zp)));
+ const uint8_t zp = static_cast<uint8_t>(std::clamp(rounded_zp, 0L, 15L));
const auto evaluate = [&](float scale_candidate, uint8_t* quantized) {
const ov::float16 scale_f16(scale_candidate);
@@ -237,16 +305,17 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
}
for (int k = 0; k < 32; ++k) {
const long rounded = static_cast<long>(std::nearbyint(values[k] / runtime_scale)) + zp;
- quantized[k] = static_cast<uint8_t>(std::min<long>(15, std::max<long>(0, rounded)));
+ quantized[k] = static_cast<uint8_t>(std::clamp(rounded, 0L, 15L));
}
return std::make_pair(scale_f16, measure(runtime_scale, zp, quantized));
};
const auto accept = [&](const std::pair<ov::float16, Error>& candidate, const uint8_t* candidate_q) {
- if (candidate.second.squared < best_error.squared && candidate.second.max_abs <= fallback_max_error) {
- best_scale = candidate.first;
+ const auto& [scale, error] = candidate;
+ if (error.squared < best_error.squared && error.max_abs <= fallback_max_error) {
+ best_scale = scale;
best_zp = zp;
- best_error = candidate.second;
+ best_error = error;
std::copy_n(candidate_q, 32, best_q);
}
};
@@ -271,30 +340,19 @@ void fill_q4_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
}
scales[i * 8 + j] = best_scale;
- zp_u8[i * 8 + j] = best_zp;
+ zp_out.store_integer(i * 8 + j, best_zp);
uint8_t* destination = weights + i * 128 + j * 16;
std::fill_n(destination, 16, 0);
for (int k = 0; k < 32; ++k) {
destination[k / 2] |= static_cast<uint8_t>(best_q[k] << (4 * (k % 2)));
}
}
- if (!int_zp) {
+ if (!zp_out.is_integer()) {
unpack_256_4(block_data + 16, weights + i * 128);
}
});
}
-// 6-bit packed sub-scale/min extraction for K-quants (Q4_K/Q5_K 12-byte scale block).
-static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t* m) {
- if (j < 4) {
- *d = q[j] & 63;
- *m = q[j + 4] & 63;
- } else {
- *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
- *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
- }
-}
-
// ---------------------------------------------------------------------------------------------
// Bit-exact per-row K-quant dequant used ONLY as the source for the Q8_0_C requant of the
// token_embd/output/Q6_K/Q5_K tensors (see requantize_q8_0_channelwise_faithful). These are verbatim
@@ -303,43 +361,18 @@ static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t* d, uint8_t
// backend feeds into its Q8_0_C requant. This is NOT the general dequant path -- the compressed
// matmul weights still go through fill_*/make_int4 unchanged. Each function
// fills ONE row (`cols` floats) so the caller never materializes the whole f32 weight.
-static void dequant_row_q4_k_f32(const uint8_t* row, size_t cols, float* y) {
- const uint64_t bpb = kQ4K_BLOCK_BYTES;
- for (size_t b = 0; b < cols / 256; ++b, y += 256) {
- const uint8_t* blk = row + b * bpb;
- const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk)));
- const float dmin = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk + 1)));
- const uint8_t* sc = blk + 4;
- const uint8_t* q = blk + 16;
- int is = 0;
- float* yy = y;
- for (int j = 0; j < 256; j += 64) {
- uint8_t s1, m1, s2, m2;
- get_scale_min_k4(is + 0, sc, &s1, &m1);
- get_scale_min_k4(is + 1, sc, &s2, &m2);
- const float d1 = d * s1, mn1 = dmin * m1, d2 = d * s2, mn2 = dmin * m2;
- for (int l = 0; l < 32; ++l) {
- yy[l] = d1 * (q[l] & 0xF) - mn1;
- }
- for (int l = 0; l < 32; ++l) {
- yy[32 + l] = d2 * (q[l] >> 4) - mn2;
- }
- q += 32;
- is += 2;
- yy += 64;
- }
- }
-}
-
-static void dequant_row_q5_k_f32(const uint8_t* row, size_t cols, float* y) {
- const uint64_t bpb = kQ5K_BLOCK_BYTES;
+// Q4_K and Q5_K share this layout exactly; Q5_K only adds a fifth bit per value, taken from a
+// 32-byte qh section that sits between the scales and the nibbles.
+template <bool HAS_QH>
+static void dequant_row_q45_k_f32(const uint8_t* row, size_t cols, float* y) {
+ constexpr uint64_t bpb = HAS_QH ? kQ5K_BLOCK_BYTES : kQ4K_BLOCK_BYTES;
for (size_t b = 0; b < cols / 256; ++b, y += 256) {
const uint8_t* blk = row + b * bpb;
const float d = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk)));
const float dmin = static_cast<float>(ov::float16::from_bits(*((const uint16_t*)blk + 1)));
const uint8_t* sc = blk + 4;
const uint8_t* qh = blk + 16;
- const uint8_t* ql = blk + 48;
+ const uint8_t* ql = HAS_QH ? blk + 48 : blk + 16;
int is = 0;
uint8_t u1 = 1, u2 = 2;
float* yy = y;
@@ -349,10 +382,12 @@ static void dequant_row_q5_k_f32(const uint8_t* row, size_t cols, float* y) {
get_scale_min_k4(is + 1, sc, &s2, &m2);
const float d1 = d * s1, mn1 = dmin * m1, d2 = d * s2, mn2 = dmin * m2;
for (int l = 0; l < 32; ++l) {
- yy[l] = d1 * static_cast<float>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0)) - mn1;
+ const int hi = (HAS_QH && (qh[l] & u1)) ? 16 : 0;
+ yy[l] = d1 * static_cast<float>((ql[l] & 0xF) + hi) - mn1;
}
for (int l = 0; l < 32; ++l) {
- yy[32 + l] = d2 * static_cast<float>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - mn2;
+ const int hi = (HAS_QH && (qh[l] & u2)) ? 16 : 0;
+ yy[32 + l] = d2 * static_cast<float>((ql[l] >> 4) + hi) - mn2;
}
ql += 32;
is += 2;
@@ -406,11 +441,11 @@ bool requantize_q8_0_channelwise_faithful(const GgufTensor& tensor,
uint64_t bytes_per_row = 0;
switch (qtype) {
case GGUF_TYPE_Q4_K:
- dq = dequant_row_q4_k_f32;
+ dq = dequant_row_q45_k_f32<false>;
bytes_per_row = (cols / 256) * kQ4K_BLOCK_BYTES;
break;
case GGUF_TYPE_Q5_K:
- dq = dequant_row_q5_k_f32;
+ dq = dequant_row_q45_k_f32<true>;
bytes_per_row = (cols / 256) * kQ5K_BLOCK_BYTES;
break;
case GGUF_TYPE_Q6_K:
@@ -422,35 +457,22 @@ bool requantize_q8_0_channelwise_faithful(const GgufTensor& tensor,
}
const uint8_t* data = static_cast<const uint8_t*>(tensor.weights_data);
ov::parallel_for(rows, [&](size_t r) {
- // Per-thread scratch reused across rows (dq() overwrites all cols); avoids per-row malloc.
+ // Reuse scratch across rows; capacity follows the largest row seen and is retained
+ // until the worker thread exits. dq() overwrites all cols, avoiding per-row allocation.
thread_local std::vector<float> rowf;
rowf.resize(cols);
dq(data + r * bytes_per_row, cols, rowf.data());
- float amax = 0.0f;
- for (size_t c = 0; c < cols; ++c) {
- amax = std::max(amax, std::fabs(rowf[c]));
- }
- const float d = amax / 127.0f;
- // A zero row has a zero scale and must remain zero. Keep the division in a
- // branch where its divisor is known to be non-zero.
- float id = 0.0f;
- if (d != 0.0f) {
- id = 1.0f / d;
- }
- out_scales[r] = ov::float16(d);
- for (size_t c = 0; c < cols; ++c) {
- out_weights[r * cols + c] = static_cast<int8_t>(std::lround(rowf[c] * id));
- }
+ quantize_row_q8_0_c(rowf.data(), cols, out_weights + r * cols, out_scales[r]);
});
return true;
}
// Test-only thin wrappers exposing the file-static per-row dequant to the unit tests.
void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
- dequant_row_q4_k_f32(row, cols, y);
+ dequant_row_q45_k_f32<false>(row, cols, y);
}
void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
- dequant_row_q5_k_f32(row, cols, y);
+ dequant_row_q45_k_f32<true>(row, cols, y);
}
void dequant_row_q6_k_f32_for_test(const uint8_t* row, size_t cols, float* y) {
dequant_row_q6_k_f32(row, cols, y);
@@ -466,16 +488,7 @@ void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<int8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);
- auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;
- const auto store_zp = [&](size_t idx, float scale, float mn) {
- const float zpval = (scale != 0.f) ? (mn / scale) : 0.f;
- if (int_zp)
- zp_u8[idx] = quantize_zp_u8(zpval);
- else
- zp_f16[idx] = ov::float16(zpval);
- };
+ const ZeroPointWriter zp(zp_arr);
ov::parallel_for(n_super_block, [&](size_t i) {
const uint8_t* block_data = data + i * bytes_per_block;
@@ -495,8 +508,8 @@ void fill_q5_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
const float d2 = d * sc, m2 = dmin * m;
scales[i * 8 + is] = ov::float16(d1);
scales[i * 8 + is + 1] = ov::float16(d2);
- store_zp(i * 8 + is, d1, m1);
- store_zp(i * 8 + is + 1, d2, m2);
+ zp.store(i * 8 + is, zp_from_offset(m1, d1));
+ zp.store(i * 8 + is + 1, zp_from_offset(m2, d2));
for (int l = 0; l < 32; ++l) {
weights[i * 256 + j + l] = static_cast<int8_t>((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0));
weights[i * 256 + j + l + 32] = static_cast<int8_t>((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0));
@@ -519,27 +532,14 @@ void fill_q5_1(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<int8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);
- auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;
+ const ZeroPointWriter zp(zp_arr);
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
const uint8_t* block = data + i * bytes_per_block;
const float d = static_cast<float>(ov::float16::from_bits(*(uint16_t*)block));
const float m = static_cast<float>(ov::float16::from_bits(*(uint16_t*)(block + 2)));
scales[i] = ov::float16(d);
- const float zpval = (d != 0.f) ? (-m / d) : 0.f;
- if (int_zp)
- zp_u8[i] = quantize_zp_u8(zpval);
- else
- zp_f16[i] = ov::float16(zpval);
- uint32_t qh;
- std::memcpy(&qh, block + 4, sizeof(qh));
- const uint8_t* ql = block + 8;
- for (uint64_t j = 0; j < weights_per_block; ++j) {
- const uint8_t lo = (j < 16) ? (ql[j] & 0x0F) : (ql[j - 16] >> 4);
- const uint8_t hi = (qh >> j) & 1;
- weights[i * weights_per_block + j] = static_cast<int8_t>(lo | (hi << 4));
- }
+ zp.store(i, zp_from_offset(-m, d));
+ unpack_q5_block(block + 4, weights + i * weights_per_block, 0);
});
}
@@ -607,9 +607,7 @@ void fill_q2_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<uint8_t*>(weights_arr.data()); // packed u2 (4 per byte, LSB-first)
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool int_zp = (zp_arr.get_element_type() == ov::element::u8);
- auto zp_f16 = int_zp ? nullptr : zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- auto zp_u8 = int_zp ? static_cast<uint8_t*>(zp_arr.data()) : nullptr;
+ const ZeroPointWriter zp(zp_arr);
ov::parallel_for(n_super_block, [&](size_t i) {
const uint8_t* block = data + i * bytes_per_block;
const uint8_t* sc = block; // 16 bytes: per-sub-block scale+min nibbles
@@ -620,11 +618,7 @@ void fill_q2_k(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tensor& sc
const float dl = d * static_cast<float>(sc[j] & 0xF);
const float ml = dmin * static_cast<float>(sc[j] >> 4);
scales[i * 16 + j] = ov::float16(dl);
- const float zpval = (dl != 0.f) ? (ml / dl) : 0.f;
- if (int_zp)
- zp_u8[i * 16 + j] = quantize_zp_u8(zpval);
- else
- zp_f16[i * 16 + j] = ov::float16(zpval);
+ zp.store(i * 16 + j, zp_from_offset(ml, dl));
}
// Unpack in ggml element order (see dequantize_row_q2_K).
uint8_t* wdst = weights + i * 64;
@@ -711,21 +705,14 @@ void gguf_fill_mxfp4(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor&
const uint8_t* block = data + (r * groups + g) * bytes_per_block;
sdst[r * groups + g] = block[0];
const uint8_t* qs = block + 1;
- const uint64_t base = r * cols + g * qk;
- for (uint64_t j = 0; j < qk / 2; ++j) {
- const uint8_t lo = qs[j] & 0x0F;
- const uint8_t hi = qs[j] >> 4;
- auto put = [&](uint64_t elem, uint8_t nib) {
- uint64_t idx = base + elem;
- uint8_t& byte = wdst[idx / 2];
- if (idx & 1) {
- byte = (byte & 0x0F) | (nib << 4);
- } else {
- byte = (byte & 0xF0) | nib;
- }
- };
- put(j, lo);
- put(j + qk / 2, hi);
+ // `cols` and qk are both multiples of 32, so the block's first element index is even
+ // and every output byte packs a known pair of source nibbles. Write whole bytes
+ // rather than read-modify-writing each nibble: the low half of the block takes the
+ // low nibbles of qs[2t], qs[2t+1], the high half their high nibbles.
+ uint8_t* out = wdst + (r * cols + g * qk) / 2;
+ for (uint64_t t = 0; t < qk / 4; ++t) {
+ out[t] = static_cast<uint8_t>((qs[2 * t] & 0x0F) | ((qs[2 * t + 1] & 0x0F) << 4));
+ out[qk / 4 + t] = static_cast<uint8_t>((qs[2 * t] >> 4) | (qs[2 * t + 1] & 0xF0));
}
}
});
@@ -776,9 +763,7 @@ void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tenso
auto data = static_cast<const uint8_t*>(tensor.weights_data);
auto weights = static_cast<uint8_t*>(weights_arr.data());
auto scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
- const bool zp_is_f16 = zp_arr.get_element_type() == ov::element::f16;
- auto zp_u8 = zp_is_f16 ? nullptr : static_cast<uint8_t*>(zp_arr.data());
- auto zp_f16 = zp_is_f16 ? zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>() : nullptr;
+ const ZeroPointWriter zp(zp_arr);
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
const uint8_t* block = data + i * bytes_per_block;
@@ -786,48 +771,46 @@ void gguf_fill_q2_0(const GgufTensor& tensor, ov::Tensor& weights_arr, ov::Tenso
std::memcpy(&scale_bits, block, sizeof(scale_bits));
scales[i] = ov::float16::from_bits(scale_bits);
std::memcpy(weights + i * bytes_per_block_codes, block + 2, bytes_per_block_codes);
- if (zp_is_f16) {
- zp_f16[i] = ov::float16(1.0f);
- } else {
- zp_u8[i] = 1;
- }
+ zp.store(i, 1.0f);
});
}
// Symmetric types (Q4_0, Q8_0, Q5_0, Q6_K, Q3_K): fill weights + scales (f16), no zero-point.
// Q8_K uses f32 scales and is handled by a separate overload dispatched on tensor.type.
void gguf_fill_sym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {
- if (tensor.type == GGUF_TYPE_Q4_0) {
- fill_q4_0(tensor, weights, scales);
- } else if (tensor.type == GGUF_TYPE_Q8_0) {
- fill_q8_0(tensor, weights, scales);
- } else if (tensor.type == GGUF_TYPE_Q5_0) {
- fill_q5_0(tensor, weights, scales);
- } else if (tensor.type == GGUF_TYPE_Q6_K) {
- fill_q6_k(tensor, weights, scales);
- } else if (tensor.type == GGUF_TYPE_Q3_K) {
- fill_q3_k(tensor, weights, scales);
- } else if (tensor.type == GGUF_TYPE_Q8_K) {
- fill_q8_k(tensor, weights, scales);
- } else {
- OPENVINO_ASSERT(false, "Unsupported tensor type in 'gguf_fill_sym'");
+ switch (tensor.type) {
+ case GGUF_TYPE_Q4_0:
+ return fill_q4_0(tensor, weights, scales);
+ case GGUF_TYPE_Q8_0:
+ return fill_q8_0(tensor, weights, scales);
+ case GGUF_TYPE_Q5_0:
+ return fill_q5_0(tensor, weights, scales);
+ case GGUF_TYPE_Q6_K:
+ return fill_q6_k(tensor, weights, scales);
+ case GGUF_TYPE_Q3_K:
+ return fill_q3_k(tensor, weights, scales);
+ case GGUF_TYPE_Q8_K:
+ return fill_q8_k(tensor, weights, scales);
+ default:
+ OPENVINO_THROW("Unsupported tensor type in 'gguf_fill_sym': ", tensor.type);
}
}
// Asymmetric types (Q4_1, Q4_K, Q5_K, Q5_1, Q2_K): fill weights, scales, and zero-points.
void gguf_fill_asym(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales, ov::Tensor& zp) {
- if (tensor.type == GGUF_TYPE_Q4_1) {
- fill_q4_1(tensor, weights, scales, zp);
- } else if (tensor.type == GGUF_TYPE_Q4_K) {
- fill_q4_k(tensor, weights, scales, zp);
- } else if (tensor.type == GGUF_TYPE_Q5_K) {
- fill_q5_k(tensor, weights, scales, zp);
- } else if (tensor.type == GGUF_TYPE_Q5_1) {
- fill_q5_1(tensor, weights, scales, zp);
- } else if (tensor.type == GGUF_TYPE_Q2_K) {
- fill_q2_k(tensor, weights, scales, zp);
- } else {
- OPENVINO_ASSERT(false, "Unsupported tensor type in 'gguf_fill_asym'");
+ switch (tensor.type) {
+ case GGUF_TYPE_Q4_1:
+ return fill_q4_1(tensor, weights, scales, zp);
+ case GGUF_TYPE_Q4_K:
+ return fill_q4_k(tensor, weights, scales, zp);
+ case GGUF_TYPE_Q5_K:
+ return fill_q5_k(tensor, weights, scales, zp);
+ case GGUF_TYPE_Q5_1:
+ return fill_q5_1(tensor, weights, scales, zp);
+ case GGUF_TYPE_Q2_K:
+ return fill_q2_k(tensor, weights, scales, zp);
+ default:
+ OPENVINO_THROW("Unsupported tensor type in 'gguf_fill_asym': ", tensor.type);
}
}
diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cpp
index ecc932fbd3e..81f7a524c1a 100644
--- a/src/frontends/gguf/src/quant/weights.cpp
+++ b/src/frontends/gguf/src/quant/weights.cpp
@@ -11,8 +11,6 @@
#include "weights.hpp"
#include <array>
-#include <cctype>
-#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
@@ -20,16 +18,15 @@
#include <vector>
#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
#include "openvino/core/type/float16.hpp"
#include "openvino/decompositions/low_precision_dequantize.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/reshape.hpp"
-#include "openvino/op/result.hpp"
#include "openvino/op/subtract.hpp"
-#include "openvino/pass/constant_folding.hpp"
-#include "openvino/pass/manager.hpp"
+#include "openvino/util/common_util.hpp"
namespace ov {
namespace frontend {
@@ -37,53 +34,65 @@ namespace gguf {
namespace {
-enum class WeightLayout { PLAIN, MXFP4, SYMMETRIC_I4, SYMMETRIC_I8, ASYMMETRIC_I2, ASYMMETRIC_I4, ASYMMETRIC_I8 };
-
enum class FillKind { NONE, MXFP4, SYMMETRIC, ASYMMETRIC, Q2_0 };
struct WeightFormat {
- WeightLayout layout;
FillKind fill;
size_t group_size;
- bool has_scales;
- bool has_zero_point;
- // Element type gguf_fill_* writes the weight blob as, and whether it's u32-packed (8
- // sub-byte elements per word) rather than one element per byte. Only meaningful for
- // FillKind::MXFP4/SYMMETRIC/ASYMMETRIC/Q2_0 -- the raw-bytes make_weight_node() overload.
+ // Element type gguf_fill_* writes the weight blob as; dynamic for the non-quantized formats.
ov::element::Type weight_element_type;
- bool packed_u32;
+
+ // A non-quantized weight: a plain Constant, no scales or zero-point.
+ bool is_plain() const {
+ return weight_element_type == ov::element::dynamic;
+ }
+ bool has_scales() const {
+ return !is_plain();
+ }
+ bool has_zero_point() const {
+ return fill == FillKind::ASYMMETRIC || fill == FillKind::Q2_0;
+ }
+ // u32-packed weights hold 8 sub-byte elements per word rather than one element per byte.
+ bool packed_u32() const {
+ return weight_element_type == ov::element::u32;
+ }
+ // Element type of the weight Constant in the decompression subgraph: the storage type,
+ // except that a u32-packed blob is read back as the u4 elements it actually holds.
+ ov::element::Type node_element_type() const {
+ return packed_u32() ? ov::element::u4 : weight_element_type;
+ }
};
WeightFormat get_weight_format(GgufTensorType qtype) {
switch (qtype) {
case GGUF_TYPE_MXFP4:
- return {WeightLayout::MXFP4, FillKind::MXFP4, 32, true, false, ov::element::f4e2m1, false};
+ return {FillKind::MXFP4, 32, ov::element::f4e2m1};
case GGUF_TYPE_Q4_0:
- return {WeightLayout::SYMMETRIC_I4, FillKind::SYMMETRIC, 32, true, false, ov::element::i4, false};
+ return {FillKind::SYMMETRIC, 32, ov::element::i4};
case GGUF_TYPE_Q3_K:
- return {WeightLayout::SYMMETRIC_I4, FillKind::SYMMETRIC, 16, true, false, ov::element::i4, false};
+ return {FillKind::SYMMETRIC, 16, ov::element::i4};
case GGUF_TYPE_Q5_0:
case GGUF_TYPE_Q8_0:
- return {WeightLayout::SYMMETRIC_I8, FillKind::SYMMETRIC, 32, true, false, ov::element::i8, false};
+ return {FillKind::SYMMETRIC, 32, ov::element::i8};
case GGUF_TYPE_Q6_K:
- return {WeightLayout::SYMMETRIC_I8, FillKind::SYMMETRIC, 16, true, false, ov::element::i8, false};
+ return {FillKind::SYMMETRIC, 16, ov::element::i8};
case GGUF_TYPE_Q8_K:
- return {WeightLayout::SYMMETRIC_I8, FillKind::NONE, 256, true, false, ov::element::i8, false};
+ return {FillKind::NONE, 256, ov::element::i8};
case GGUF_TYPE_Q2_K:
- return {WeightLayout::ASYMMETRIC_I2, FillKind::ASYMMETRIC, 16, true, true, ov::element::u2, false};
+ return {FillKind::ASYMMETRIC, 16, ov::element::u2};
case GGUF_TYPE_Q2_0:
- return {WeightLayout::ASYMMETRIC_I2, FillKind::Q2_0, 64, true, true, ov::element::u2, false};
+ return {FillKind::Q2_0, 64, ov::element::u2};
case GGUF_TYPE_Q4_1:
case GGUF_TYPE_Q4_K:
- return {WeightLayout::ASYMMETRIC_I4, FillKind::ASYMMETRIC, 32, true, true, ov::element::u32, true};
+ return {FillKind::ASYMMETRIC, 32, ov::element::u32};
case GGUF_TYPE_Q5_1:
case GGUF_TYPE_Q5_K:
- return {WeightLayout::ASYMMETRIC_I8, FillKind::ASYMMETRIC, 32, true, true, ov::element::i8, false};
+ return {FillKind::ASYMMETRIC, 32, ov::element::i8};
case GGUF_TYPE_F16:
case GGUF_TYPE_F32:
case GGUF_TYPE_BF16:
default:
- return {WeightLayout::PLAIN, FillKind::NONE, 0, false, false, ov::element::dynamic, false};
+ return {FillKind::NONE, 0, ov::element::dynamic};
}
}
@@ -93,26 +102,17 @@ const ov::Tensor& get(const std::unordered_map<std::string, ov::Tensor>& weights
return it->second;
}
-// Copy rows [r0, r1) out of a 2D tensor. 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.
-ov::Tensor slice_rows(const ov::Tensor& t, size_t r0, size_t r1) {
- const auto& s = t.get_shape();
- OPENVINO_ASSERT(s.size() == 2 && r1 <= s[0] && r0 <= r1, "[GGUF] bad row slice");
- ov::Shape out_shape{r1 - r0, s[1]};
+// 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);
- const size_t row_bytes = t.get_byte_size() / s[0];
- std::memcpy(out.data(), static_cast<const uint8_t*>(t.data()) + r0 * row_bytes, (r1 - r0) * row_bytes);
- return out;
-}
-
-// Copy elements [r0, r1) out of a 1D tensor. Used for a fused attn_qkv.bias, which -- unlike the
-// weight -- is a plain unquantized array, so a byte-range copy is exact regardless of dtype.
-ov::Tensor slice_1d(const ov::Tensor& t, size_t r0, size_t r1) {
- const auto& s = t.get_shape();
- OPENVINO_ASSERT(s.size() == 1 && r1 <= s[0] && r0 <= r1, "[GGUF] bad 1D slice");
- ov::Tensor out(t.get_element_type(), ov::Shape{r1 - r0});
- const size_t elem_bytes = t.get_byte_size() / s[0];
- std::memcpy(out.data(), static_cast<const uint8_t*>(t.data()) + r0 * elem_bytes, (r1 - r0) * elem_bytes);
+ std::memcpy(out.data(), static_cast<const uint8_t*>(t.data()) + r0 * stride, (r1 - r0) * stride);
return out;
}
@@ -161,168 +161,52 @@ std::shared_ptr<ov::op::v0::Constant> make_compressed_weight_constant(ov::elemen
std::make_shared<ov::Tensor>(weight));
}
-// Symmetric 8-bit (Q8_0, Q5_0, Q6_K): i8 weights (pre-centered) + per-group f16 scale.
-// Q6_K uses explicit f32 arithmetic to preserve the reference dequantization accuracy; the other
-// formats use the compressed-weight decomposition.
-std::shared_ptr<ov::Node> make_sym_int8(const WeightTensors& tensors, GgufTensorType qtype) {
- ov::Tensor weight = tensors.weight; // i8 byte per element
- ov::Tensor scales = tensors.scales;
-
- const ov::Shape& orig_shape = weight.get_shape();
- const size_t num_groups = scales.get_shape().back();
- const size_t group_size = orig_shape.back() / num_groups;
-
- auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);
- auto scale_shape = per_group_shape(orig_shape, num_groups);
- scales.set_shape(scale_shape);
-
- auto weights_node = make_compressed_weight_constant(ov::element::i8, grouped_shape, weight);
- auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- auto final_shape_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
-
- if (qtype == GGUF_TYPE_Q6_K) {
- auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);
- auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);
- auto dequant = std::make_shared<ov::op::v1::Multiply>(values, scales_f32);
- return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);
+// Build the decompression subgraph for one grouped compressed weight: an `et` weight Constant
+// viewed as [.., num_groups, group_size], a per-group scale, and an optional per-group
+// zero-point, reshaped back to the weight's logical shape. Covers every quantized format
+// except MXFP4 (which keeps its own f16 arithmetic, see make_mxfp4).
+//
+// `explicit_f32` builds Convert -> [Subtract] -> Multiply -> Reshape in f32 instead of the
+// low_precision_dequantize decomposition.
+std::shared_ptr<ov::Node> make_compressed(const WeightTensors& tensors, ov::element::Type et, bool explicit_f32) {
+ ov::Shape orig_shape = tensors.weight.get_shape();
+ if (tensors.weight.get_element_type() == ov::element::u32) {
+ orig_shape.back() *= sizeof(uint32_t) / sizeof(uint8_t) * 2; // u32 packs 8 u4
}
+ const size_t num_groups = tensors.scales.get_shape().back();
+ const auto scale_shape = per_group_shape(orig_shape, num_groups);
- auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),
- scales_node->output(0),
- {},
- final_shape_node->output(0));
- return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
-}
-
-// 4-bit asymmetric (Q4_1/Q4_K): u4 weights + per-group scale and zero-point. Fractional f16
-// zero-points use explicit f32 dequantization; exact integer zero-points keep the compressed path.
-std::shared_ptr<ov::Node> make_int4(const WeightTensors& tensors) {
- ov::Tensor weight = tensors.weight; // u32-packed u4
ov::Tensor scales = tensors.scales;
- ov::Tensor zp_t = tensors.zero_point;
-
- ov::Shape orig_shape = weight.get_shape();
- orig_shape.back() *= sizeof(uint32_t) / sizeof(uint8_t) * 2; // u32 packs 8 u4
- const size_t num_groups = scales.get_shape().back();
- const size_t group_size = orig_shape.back() / num_groups;
-
- auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);
- auto scale_shape = per_group_shape(orig_shape, num_groups);
scales.set_shape(scale_shape);
- zp_t.set_shape(scale_shape);
-
- auto weights_node = make_compressed_weight_constant(ov::element::u4, grouped_shape, weight);
- auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);
- auto final_shape_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
-
- if (zp_t.get_element_type() == ov::element::f16) {
- auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);
- auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);
- auto zp_f32 = std::make_shared<ov::op::v0::Convert>(zp_node, ov::element::f32);
- auto dequant =
- std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v1::Subtract>(values, zp_f32), scales_f32);
- return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);
+ ov::Tensor zp_t = tensors.zero_point;
+ if (zp_t) {
+ zp_t.set_shape(scale_shape);
}
- auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),
- scales_node->output(0),
- zp_node->output(0),
- final_shape_node->output(0));
- return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
-}
-
-// Symmetric 4-bit (Q3_K): i4 weights (centered [-4..3]) + per-group f16 scale. No zero-point.
-// Emits: Multiply(Convert(i4_const, f16), scale) [-> Reshape].
-std::shared_ptr<ov::Node> make_sym_int4(const WeightTensors& tensors) {
- ov::Tensor weight = tensors.weight; // i4 packed, 2 per byte
- ov::Tensor scales = tensors.scales;
-
- const ov::Shape& orig_shape = weight.get_shape();
- const size_t num_groups = scales.get_shape().back();
- const size_t group_size = orig_shape.back() / num_groups;
-
- auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);
- auto scale_shape = per_group_shape(orig_shape, num_groups);
- scales.set_shape(scale_shape);
-
- auto weights_node = make_compressed_weight_constant(ov::element::i4, grouped_shape, weight);
- auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- auto final_shape_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
-
- auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),
- scales_node->output(0),
- {},
- final_shape_node->output(0));
- return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
-}
-
-// Asymmetric 2-bit (Q2_K): u2 weights (raw [0..3]) + per-group f16 scale + u8 zp.
-// Emits: Multiply(Subtract(Convert(u2_const, f16), zp_u8), scale) [-> Reshape].
-std::shared_ptr<ov::Node> make_int2(const WeightTensors& tensors) {
- ov::Tensor weight = tensors.weight; // u2 packed, 4 per byte
- ov::Tensor scales = tensors.scales;
- ov::Tensor zp_t = tensors.zero_point; // u8 integer zero-points
-
- const ov::Shape& orig_shape = weight.get_shape();
- const size_t num_groups = scales.get_shape().back();
- const size_t group_size = orig_shape.back() / num_groups;
-
- auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);
- auto scale_shape = per_group_shape(orig_shape, num_groups);
- scales.set_shape(scale_shape);
- zp_t.set_shape(scale_shape);
-
- auto weights_node = make_compressed_weight_constant(ov::element::u2, grouped_shape, weight);
- auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);
- auto final_shape_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
-
- auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),
- scales_node->output(0),
- zp_node->output(0),
- final_shape_node->output(0));
- return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
-}
-
-// Asymmetric 8-bit (Q5_K): i8 weights (raw 5-bit value, not centered) + f16 scales + u8 zp.
-// Emits: Multiply(Subtract(Convert(i8_const, f16), zp_u8), scale) [-> Reshape].
-std::shared_ptr<ov::Node> make_asym_int8(const WeightTensors& tensors) {
- ov::Tensor weight = tensors.weight; // i8 byte per element
- ov::Tensor scales = tensors.scales;
- ov::Tensor zp_t = tensors.zero_point; // u8 integer zero-points
-
- const ov::Shape& orig_shape = weight.get_shape();
- const size_t num_groups = scales.get_shape().back();
- const size_t group_size = orig_shape.back() / num_groups;
-
- auto grouped_shape = grouped_weight_shape(orig_shape, num_groups, group_size);
- auto scale_shape = per_group_shape(orig_shape, num_groups);
- scales.set_shape(scale_shape);
- zp_t.set_shape(scale_shape);
-
- auto weights_node = make_compressed_weight_constant(ov::element::i8, grouped_shape, weight);
+ auto weights_node =
+ make_compressed_weight_constant(et,
+ grouped_weight_shape(orig_shape, num_groups, orig_shape.back() / num_groups),
+ tensors.weight);
auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
- auto zp_node = std::make_shared<ov::op::v0::Constant>(zp_t);
+ const auto zp_node = zp_t ? std::make_shared<ov::op::v0::Constant>(zp_t) : nullptr;
auto final_shape_node =
std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
- if (zp_t.get_element_type() == ov::element::f16) {
- auto values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);
+ if (explicit_f32) {
+ ov::Output<ov::Node> values = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);
+ if (zp_node) {
+ values = std::make_shared<ov::op::v1::Subtract>(
+ values,
+ std::make_shared<ov::op::v0::Convert>(zp_node, ov::element::f32));
+ }
auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);
- auto zp_f32 = std::make_shared<ov::op::v0::Convert>(zp_node, ov::element::f32);
- auto dequant =
- std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v1::Subtract>(values, zp_f32), scales_f32);
+ auto dequant = std::make_shared<ov::op::v1::Multiply>(values, scales_f32);
return std::make_shared<ov::op::v1::Reshape>(dequant, final_shape_node, false);
}
auto result = ov::decomposition::low_precision_dequantize(weights_node->output(0),
scales_node->output(0),
- zp_node->output(0),
+ zp_node ? zp_node->output(0) : ov::Output<ov::Node>{},
final_shape_node->output(0));
return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
}
@@ -362,13 +246,10 @@ std::shared_ptr<ov::Node> make_mxfp4(const WeightTensors& tensors) {
return std::make_shared<ov::op::v0::Convert>(reshaped, ov::element::f32);
}
-// Channel-wise requantization to Q8_0_C, matching the llama.cpp ggml-openvino backend's
-// CPU/GPU weight pipeline (ggml_openvino_get_requant_type -> Q8_0_C for embed/output/Q6_K/
-// Q5_K). `x` is the row-major f32 weight (rows*cols); one f16 scale per row (channel-wise);
-// signed int8 weights. ggml-free (the f32 input is produced by the frontend's own faithful
-// dequant, which the unit tests prove matches ggml to_float).
// Build the Q8_0_C compressed-weights OV subgraph from pre-filled i8 weights [rows,cols] +
-// f16 scales [rows,1]. Shared by the (legacy) f32-vector requant and the fused faithful requant.
+// f16 scales [rows,1] -- channel-wise requantization matching the llama.cpp ggml-openvino
+// backend's CPU/GPU weight pipeline (ggml_openvino_get_requant_type -> Q8_0_C for
+// embed/output/Q6_K/Q5_K). Shared by the extracted-tensor requant and the fused faithful one.
static std::shared_ptr<ov::Node> build_q8_0_c_node(ov::Tensor weights, ov::Tensor scales, size_t rows, size_t cols) {
// Build the channel-wise compressed-weights subgraph exactly as the llama.cpp
// ggml-openvino backend does for Q8_0_C: a 2D i8 Constant (rows x cols) + 2D f16 scale
@@ -376,96 +257,76 @@ static std::shared_ptr<ov::Node> build_q8_0_c_node(ov::Tensor weights, ov::Tenso
// The 2D form (group == cols, a single group per row) is what the CPU/GPU plugin fuses
// into an int8 MatMul; routing it through the grouped low_precision_dequantize path
// (3D weight + Reshape) defeats that fusion and roughly halves prefill throughput.
- auto weights_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i8,
- ov::Shape{rows, cols},
- static_cast<const void*>(weights.data()),
- std::shared_ptr<void>(new ov::Tensor(weights), [](ov::Tensor* p) {
- delete p;
- }));
+ auto weights_node = make_compressed_weight_constant(ov::element::i8, ov::Shape{rows, cols}, weights);
auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
auto scales_node = std::make_shared<ov::op::v0::Constant>(scales); // {rows, 1}
auto scaled = std::make_shared<ov::op::v1::Multiply>(weights_f16, scales_node, ov::op::AutoBroadcastType::NUMPY);
return std::make_shared<ov::op::v0::Convert>(scaled, ov::element::f32);
}
-// Legacy path: requant from an already-materialized f32 weight vector (used for token_embd/output
-// when the type has no faithful per-row dequant, and for any non-K requant source).
-std::shared_ptr<ov::Node> requantize_q8_0_channelwise(const std::vector<float>& x, size_t rows, size_t cols) {
- ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});
- ov::Tensor scales(ov::element::f16, ov::Shape{rows, 1});
- auto* w = weights.data<int8_t>();
- auto* s = scales.data<ov::float16>();
- for (size_t r = 0; r < rows; ++r) {
- float amax = 0.0f;
- for (size_t c = 0; c < cols; ++c) {
- amax = std::max(amax, std::fabs(x[r * cols + c]));
- }
- const float d = amax / 127.0f;
- // A zero row has a zero scale and must remain zero. Keep the division in a
- // branch where its divisor is known to be non-zero.
- float id = 0.0f;
- if (d != 0.0f) {
- id = 1.0f / d;
- }
- s[r] = ov::float16(d);
- for (size_t c = 0; c < cols; ++c) {
- w[r * cols + c] = static_cast<int8_t>(std::lround(x[r * cols + c] * id));
- }
- }
- return build_q8_0_c_node(weights, scales, rows, cols);
-}
-
-// Dequantize the gguf_fill_* output (i8, i4, u2, or u32-packed u4 weights + per-group f16 scale
-// and optional f16 zero-point) to row-major f32: f32 = (w - zp) * scale, grouped along cols.
-std::vector<float> dequant_extracted_to_f32(const WeightTensors& tensors, size_t rows, size_t cols) {
+// Dequantize ONE row of the gguf_fill_* output (i8, i4, u2, or u32-packed u4 weights +
+// per-group f16 scale and optional f16 zero-point) to f32: f32 = (w - zp) * scale, grouped
+// along cols. Iterating group-major keeps the scale/zero-point lookup (and the group division)
+// out of the per-element loop.
+void dequant_extracted_row_to_f32(const WeightTensors& tensors, size_t r, size_t cols, float* out) {
const ov::Tensor& weight = tensors.weight;
- const ov::Tensor& scales = tensors.scales;
- const size_t num_groups = scales.get_shape().back();
+ const size_t num_groups = tensors.scales.get_shape().back();
const size_t group = cols / num_groups;
- const auto* s = scales.data<ov::float16>();
+ const auto* s = tensors.scales.data<ov::float16>() + r * num_groups;
const bool has_zp = static_cast<bool>(tensors.zero_point);
- const ov::float16* z = has_zp ? tensors.zero_point.data<ov::float16>() : nullptr;
+ const ov::float16* z = has_zp ? tensors.zero_point.data<ov::float16>() + r * num_groups : nullptr;
const auto et = weight.get_element_type();
- std::vector<float> out(rows * cols);
- const auto emit = [&](size_t r, size_t c, float qval) {
- size_t g = r * num_groups + c / group;
- float zpf = z ? static_cast<float>(z[g]) : 0.0f;
- out[r * cols + c] = (qval - zpf) * static_cast<float>(s[g]);
- };
- if (et == ov::element::i8) {
- const auto* q = weight.data<int8_t>();
- for (size_t r = 0; r < rows; ++r)
- for (size_t c = 0; c < cols; ++c)
- emit(r, c, static_cast<float>(q[r * cols + c]));
- } else if (et == ov::element::u2) {
- // Q2_K / Q2_0: u2 weights, 4 per byte LSB-first, raw [0..3] with a zero-point.
- const auto* bytes = static_cast<const uint8_t*>(weight.data());
- const size_t per_row_bytes = cols / 4;
- for (size_t r = 0; r < rows; ++r)
- for (size_t c = 0; c < cols; ++c) {
- uint8_t v = (bytes[r * per_row_bytes + c / 4] >> ((c % 4) * 2)) & 0x3;
- emit(r, c, static_cast<float>(v));
+ for (size_t g = 0; g < num_groups; ++g) {
+ const float scale = static_cast<float>(s[g]);
+ const float zpf = z ? static_cast<float>(z[g]) : 0.0f;
+ float* dst = out + g * group;
+ if (et == ov::element::i8) {
+ const auto* q = weight.data<int8_t>() + r * cols + g * group;
+ for (size_t k = 0; k < group; ++k) {
+ dst[k] = (static_cast<float>(q[k]) - zpf) * scale;
}
- } else {
- // u32-packed 4-bit, 8 nibbles per u32. With a zero-point (Q4_1/Q4_K) the nibbles are
- // unsigned u4; without one (Q4_0 XOR-encoded, Q3_K centered) they are signed i4.
- const bool signed_u4 = !has_zp;
- const auto* packed = static_cast<const uint32_t*>(weight.data());
- const size_t per_row_u32 = cols / 8;
- for (size_t r = 0; r < rows; ++r)
- for (size_t c = 0; c < cols; ++c) {
- uint32_t word = packed[r * per_row_u32 + c / 8];
- uint8_t nib = (word >> ((c % 8) * 4)) & 0xF;
- float qval = signed_u4
- ? static_cast<float>(nib < 8 ? static_cast<int>(nib) : static_cast<int>(nib) - 16)
- : static_cast<float>(nib);
- emit(r, c, qval);
+ } else if (et == ov::element::u2) {
+ // Q2_K / Q2_0: u2 weights, 4 per byte LSB-first, raw [0..3] with a zero-point.
+ const auto* bytes = static_cast<const uint8_t*>(weight.data()) + r * (cols / 4) + (g * group) / 4;
+ for (size_t k = 0; k < group; ++k) {
+ const uint8_t v = (bytes[k / 4] >> ((k % 4) * 2)) & 0x3;
+ dst[k] = (static_cast<float>(v) - zpf) * scale;
}
+ } else {
+ // u32-packed 4-bit, 8 nibbles per u32. With a zero-point (Q4_1/Q4_K) the nibbles are
+ // unsigned u4; without one (Q4_0 XOR-encoded, Q3_K centered) they are signed i4.
+ const auto* packed = static_cast<const uint32_t*>(weight.data()) + r * (cols / 8) + (g * group) / 8;
+ for (size_t k = 0; k < group; ++k) {
+ const int nib = static_cast<int>((packed[k / 8] >> ((k % 8) * 4)) & 0xF);
+ const int q = (!has_zp && nib >= 8) ? nib - 16 : nib;
+ dst[k] = (static_cast<float>(q) - zpf) * scale;
+ }
+ }
}
- return out;
+}
+
+// Reproduce the backend's channel-wise Q8_0_C from already-extracted tensors, for the requant
+// sources that have no faithful per-row dequant (e.g. an F16 / Q4_0 / Q8_0 token_embd). Streams
+// one row at a time, like requantize_q8_0_channelwise_faithful, so the full f32 weight is never
+// materialized -- for a 150k x 4k embedding that temporary would be gigabytes.
+std::shared_ptr<ov::Node> requantize_extracted_q8_0_channelwise(const WeightTensors& tensors,
+ size_t rows,
+ size_t cols) {
+ ov::Tensor weights(ov::element::i8, ov::Shape{rows, cols});
+ ov::Tensor scales(ov::element::f16, ov::Shape{rows, 1});
+ auto* w = weights.data<int8_t>();
+ auto* s = scales.data<ov::float16>();
+ ov::parallel_for(rows, [&](size_t r) {
+ // Reuse scratch across rows; capacity follows the largest row seen and is retained
+ // until the worker thread exits, avoiding per-row allocation.
+ thread_local std::vector<float> rowf;
+ rowf.resize(cols);
+ dequant_extracted_row_to_f32(tensors, r, cols, rowf.data());
+ quantize_row_q8_0_c(rowf.data(), cols, w + r * cols, s[r]);
+ });
+ return build_q8_0_c_node(weights, scales, rows, cols);
}
// Decide whether a weight is requantized to Q8_0_C, mirroring llama.cpp's
@@ -480,8 +341,13 @@ bool needs_q8_0_c_requant(const std::string& name, GgufTensorType qtype) {
// Keep an exact-decode escape hatch for strict validation against ggml's original Q4_K values.
// Production leaves this unset and uses the compressed-FC-friendly u4 requantization.
bool q4_k_f16_zero_point_enabled() {
- const char* env = std::getenv("OV_GGUF_Q4_K_ZP_F16");
- return env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0;
+ // Read once: this sits on a per-tensor path (gguf_zero_point_type is consulted for every
+ // asymmetric weight, twice per tensor during parsing).
+ static const bool enabled = [] {
+ const char* env = std::getenv("OV_GGUF_Q4_K_ZP_F16");
+ return env != nullptr && *env != '\0' && std::strcmp(env, "0") != 0;
+ }();
+ return enabled;
}
} // namespace
@@ -525,10 +391,11 @@ ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType q
// decoded and requantized to an OpenVINO u4 grid with an integer zero-point. Strict oracle
// validation can request Q4_K's faithful f16 zero-point via OV_GGUF_Q4_K_ZP_F16. Q2_0's
// zero-point is exactly 1, so u8 is faithful there. Other asymmetric formats keep f16 because
- // their zero-point can exceed u8 range. Tensors selected for Q8_0_C are excluded because their
- // faithful dequantization feeds that separate requantization path.
- const bool integer_zp = qtype == GGUF_TYPE_Q2_0 || (qtype == GGUF_TYPE_Q4_K && !q4_k_f16_zero_point_enabled());
- return (integer_zp && !needs_q8_0_c_requant(name, qtype)) ? ov::element::u8 : ov::element::f16;
+ // their zero-point can exceed u8 range. Q4_K tensors selected for Q8_0_C retain a faithful
+ // f16 zero-point for that separate requantization path.
+ const bool integer_zp = qtype == GGUF_TYPE_Q2_0 || (qtype == GGUF_TYPE_Q4_K && !q4_k_f16_zero_point_enabled() &&
+ !needs_q8_0_c_requant(name, qtype));
+ return integer_zp ? ov::element::u8 : ov::element::f16;
}
std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,
@@ -536,38 +403,29 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,
const std::string& name) {
OPENVINO_ASSERT(tensors.weight, "[GGUF] missing weight tensor: ", name);
const auto format = get_weight_format(qtype);
- OPENVINO_ASSERT(!format.has_scales || tensors.scales, "[GGUF] missing scales tensor: ", name);
- OPENVINO_ASSERT(!format.has_zero_point || tensors.zero_point, "[GGUF] missing zero-point tensor: ", name);
+ OPENVINO_ASSERT(!format.has_scales() || tensors.scales, "[GGUF] missing scales tensor: ", name);
+ OPENVINO_ASSERT(!format.has_zero_point() || tensors.zero_point, "[GGUF] missing zero-point tensor: ", name);
std::shared_ptr<ov::Node> node;
- switch (format.layout) {
- case WeightLayout::MXFP4:
- node = make_mxfp4(tensors);
- break;
- case WeightLayout::ASYMMETRIC_I4:
- node = make_int4(tensors);
- break;
- case WeightLayout::ASYMMETRIC_I2:
- node = make_int2(tensors);
- break;
- case WeightLayout::ASYMMETRIC_I8:
- node = make_asym_int8(tensors);
- break;
- case WeightLayout::SYMMETRIC_I4:
- node = make_sym_int4(tensors);
- break;
- case WeightLayout::SYMMETRIC_I8:
- node = make_sym_int8(tensors, qtype);
- break;
- case WeightLayout::PLAIN: {
+ if (format.is_plain()) {
// Non-quantized weight: a plain Constant (converted to f32 for the translators).
- ov::Tensor w = tensors.weight;
+ const ov::Tensor& w = tensors.weight;
auto cnst = std::make_shared<ov::op::v0::Constant>(w);
node = (w.get_element_type() == ov::element::f32)
? std::static_pointer_cast<ov::Node>(cnst)
: std::make_shared<ov::op::v0::Convert>(cnst, ov::element::f32);
- break;
- }
+ } else if (format.fill == FillKind::MXFP4) {
+ node = make_mxfp4(tensors);
+ } else {
+ const auto node_et = format.node_element_type();
+ // Explicit f32 arithmetic instead of the low-precision decomposition when:
+ // - Q6_K, to preserve the reference dequantization accuracy; or
+ // - a 4-/8-bit weight carries a FRACTIONAL f16 zero-point, which cannot fold into a
+ // compressed FullyConnected anyway, so the exact f32 form costs nothing.
+ // The 2-bit formats (Q2_K/Q2_0) always stay on the decomposition.
+ const bool fractional_zp = tensors.zero_point && tensors.zero_point.get_element_type() == ov::element::f16;
+ const bool explicit_f32 = qtype == GGUF_TYPE_Q6_K || (fractional_zp && node_et.bitwidth() >= 4);
+ node = make_compressed(tensors, node_et, explicit_f32);
}
node->set_friendly_name(name);
return node;
@@ -591,12 +449,8 @@ GgufTensorType gguf_type_from_name(const std::string& quant_type) {
{"MXFP4", GGUF_TYPE_MXFP4},
{"Q2_0", GGUF_TYPE_Q2_0}};
// Accept ggml's lowercase type names ("q4_0", "q6_K", "f16", ...) as well as the
- // canonical uppercase form by upper-casing the prefix before the "_K"/"_0" suffix.
- std::string key = quant_type;
- for (auto& ch : key) {
- ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
- }
- auto it = names.find(key);
+ // canonical uppercase form.
+ auto it = names.find(ov::util::to_upper(quant_type));
OPENVINO_ASSERT(it != names.end(), "[GGUF] unsupported weight quant type: ", quant_type);
return it->second;
}
@@ -620,10 +474,10 @@ FusedQkvPart make_split_part(GgufTensorType qtype,
FusedQkvPart part;
part.qtype = qtype;
part.tensors.weight = slice(get(weights, base + ".weight"));
- if (format.has_scales) {
+ if (format.has_scales()) {
part.tensors.scales = slice(get(weights, base + ".scales"));
}
- if (format.has_zero_point) {
+ if (format.has_zero_point()) {
part.tensors.zero_point = slice(get(weights, base + ".zp"));
}
return part;
@@ -649,7 +503,7 @@ std::array<FusedQkvPart, 3> split_fused_qkv_extracted(const std::string& base,
const size_t r0 = ranges[i].first;
const size_t r1 = ranges[i].second;
out[i] = make_split_part(qtype, format, weights, base, [&](const ov::Tensor& t) {
- return slice_rows(t, r0, r1);
+ return slice_leading(t, r0, r1);
});
}
return out;
@@ -664,7 +518,7 @@ std::array<ov::Tensor, 3> split_fused_qkv_bias(const std::string& base,
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_1d(b, 0, n_q), slice_1d(b, n_q, n_q + n_k), slice_1d(b, n_q + n_k, s[0])};
+ 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
@@ -766,14 +620,10 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,
// they are not perf-critical here, and their zp = -min/scale can fall outside u8 range. The
// requant path (token_embd/output) also keeps f16 -- its dequant feeds channel-wise Q8_0_C.
const bool requant = needs_q8_0_c_requant(name, qtype);
- const ov::element::Type zp_type = gguf_zero_point_type(name, qtype);
+ const ov::element::Type zp_type = requant ? ov::element::f16 : gguf_zero_point_type(name, qtype);
if (requant) {
notify_lossy_weight_approximation(LossyWeightApproximation::Q8_0_C_REQUANT);
}
- // Q4_K performs a real group-wise requantization; Q2_0's integer zero-point is exact.
- if (zp_type == ov::element::u8 && qtype == GGUF_TYPE_Q4_K) {
- notify_lossy_weight_approximation(LossyWeightApproximation::Q4_K_REQUANT);
- }
// K-quant requant sources: the fused dequant -> Q8_0_C streams from the raw bytes, so skip the
// full-tensor gguf_fill_* extraction below (it would be discarded) and return before the switch.
@@ -812,7 +662,7 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,
break;
}
case FillKind::ASYMMETRIC: {
- ov::Tensor weights(format.weight_element_type, ov::Shape{rows, format.packed_u32 ? cols / 8 : cols});
+ ov::Tensor weights(format.weight_element_type, ov::Shape{rows, format.packed_u32() ? cols / 8 : cols});
ov::Tensor scales(ov::element::f16, ov::Shape{rows, sub_blocks_per_row(format.group_size)});
ov::Tensor zp(zp_type, scales.get_shape());
gguf_fill_asym(tensor, weights, scales, zp);
@@ -840,8 +690,7 @@ std::shared_ptr<ov::Node> make_weight_node(const ov::Tensor& data,
// above already handled Q4_K/Q5_K/Q6_K, so here reproduce the backend's channel-wise Q8_0_C by
// dequantizing to f32 from the extracted tensors, then re-quantizing.
if (requant) {
- auto f32 = dequant_extracted_to_f32(tensors, rows, cols);
- return requantize_q8_0_channelwise(f32, rows, cols);
+ return requantize_extracted_q8_0_channelwise(tensors, rows, cols);
}
return make_weight_node(tensors, qtype, name);
diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hpp
index 9185659af10..74a3f18057b 100644
--- a/src/frontends/gguf/src/quant/weights.hpp
+++ b/src/frontends/gguf/src/quant/weights.hpp
@@ -17,8 +17,9 @@ class Node;
namespace ov::frontend::gguf {
-// Element type of the zero-point constant for an asymmetric quantized weight. Both ingest
-// paths must agree on this: it decides whether the CPU folds the dequant into the MatMul.
+// Element type of the zero-point constant for an asymmetric quantized weight.
+// Q2_0 always uses u8. The raw-byte Q8_0_C requantization path separately uses temporary f16
+// zero-points for its host dequantizer, including Q2_0 embedding/output tensors.
// Q4_K matmul weights are faithfully decoded and requantized to u4 with an integer zero-point,
// which keeps the CPU compressed-FullyConnected path available. Q4_K tensors selected for the
// channel-wise Q8_0_C path retain an f16 zero-point while feeding that separate requantization.
diff --git a/src/frontends/gguf/tests/CMakeLists.txt b/src/frontends/gguf/tests/CMakeLists.txt
index 1d66ed5008d..778f3d56c85 100644
--- a/src/frontends/gguf/tests/CMakeLists.txt
+++ b/src/frontends/gguf/tests/CMakeLists.txt
@@ -102,6 +102,7 @@ set(TEST_SRCS
"${CMAKE_CURRENT_SOURCE_DIR}/test_extensions.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_op_coverage.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_ops.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/test_parser.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/test_weights.cpp"
)
diff --git a/src/frontends/gguf/tests/test_parser.cpp b/src/frontends/gguf/tests/test_parser.cpp
new file mode 100644
index 00000000000..aa9adfa620f
--- /dev/null
+++ b/src/frontends/gguf/tests/test_parser.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <array>
+#include <fstream>
+#include <utility>
+
+#include "common_test_utils/common_utils.hpp"
+#include "op_test_utils.hpp"
+#include "quant/weights.hpp"
+
+using namespace ov_gguf_test;
+
+namespace {
+
+class GGUFParser : public ::testing::Test {
+protected:
+ void SetUp() override {
+ m_path = ov::test::utils::generateTestFilePrefix() + ".gguf";
+ }
+
+ void TearDown() override {
+ ov::test::utils::removeFile(m_path);
+ }
+
+ // One tensor, no metadata. Dimensions use GGUF order (columns first).
+ void write_tensor(const std::string& name,
+ GgufTensorType type,
+ uint64_t cols,
+ uint64_t rows,
+ const std::vector<uint8_t>& data = {}) {
+ std::ofstream out(m_path, std::ios::binary);
+ ASSERT_TRUE(out);
+ const auto put = [&out](auto value) {
+ out.write(reinterpret_cast<const char*>(&value), sizeof(value));
+ };
+ put(uint32_t{0x46554747});
+ put(uint32_t{3});
+ put(uint64_t{1}); // tensor count
+ put(uint64_t{0}); // metadata count
+ put(uint64_t{name.size()});
+ out.write(name.data(), name.size());
+ put(uint32_t{2});
+ put(cols);
+ put(rows);
+ put(static_cast<uint32_t>(type));
+ put(uint64_t{0}); // tensor offset
+ while (static_cast<size_t>(out.tellp()) % 32 != 0) {
+ out.put('\0');
+ }
+ if (!data.empty()) {
+ out.write(reinterpret_cast<const char*>(data.data()), data.size());
+ }
+ ASSERT_TRUE(out);
+ }
+
+ std::string m_path;
+};
+
+TEST_F(GGUFParser, Q2_0KeepsIntegerZeroPointsForAllWeightNames) {
+ const auto bytes = load_npy<uint8_t>("q2_0_qbytes");
+ const auto reference = load_npy<float>("q2_0_deq");
+ 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");
+ 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) {
+ EXPECT_EQ(zp.data<uint8_t>()[i], 1);
+ }
+ const auto node = make_weight_node({weights, scales, zp}, GGUF_TYPE_Q2_0, name);
+ 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_FLOAT_EQ(output.data<float>()[i], reference[i]);
+ }
+ }
+}
+
+TEST_F(GGUFParser, AcceptsEmptyQuantizedTensors) {
+ constexpr std::array types{
+ std::pair{"Q4_0", GGUF_TYPE_Q4_0},
+ std::pair{"Q4_1", GGUF_TYPE_Q4_1},
+ std::pair{"Q5_0", GGUF_TYPE_Q5_0},
+ std::pair{"Q5_1", GGUF_TYPE_Q5_1},
+ std::pair{"Q8_0", GGUF_TYPE_Q8_0},
+ std::pair{"Q2_K", GGUF_TYPE_Q2_K},
+ std::pair{"Q2_0", GGUF_TYPE_Q2_0},
+ std::pair{"Q3_K", GGUF_TYPE_Q3_K},
+ std::pair{"Q4_K", GGUF_TYPE_Q4_K},
+ std::pair{"Q5_K", GGUF_TYPE_Q5_K},
+ std::pair{"Q6_K", GGUF_TYPE_Q6_K},
+ std::pair{"Q8_K", GGUF_TYPE_Q8_K},
+ };
+ 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);
+ }
+ }
+}
+
+TEST_F(GGUFParser, RejectsMXFP4WithZeroColumns) {
+ ASSERT_NO_FATAL_FAILURE(write_tensor("empty.weight", GGUF_TYPE_MXFP4, 0, 2));
+ try {
+ get_gguf_data(m_path);
+ FAIL() << "MXFP4 with zero columns must be rejected";
+ } catch (const ov::Exception& e) {
+ EXPECT_NE(std::string(e.what()).find("zero-sized dimension"), std::string::npos);
+ }
+}
+
+} // namespace
diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cpp
index d2ac87bdc35..a9f075c3865 100644
--- a/src/frontends/gguf/tests/test_weights.cpp
+++ b/src/frontends/gguf/tests/test_weights.cpp
@@ -93,26 +93,29 @@ INSTANTIATE_TEST_SUITE_P(AllQuantTypes,
// token_embd / output are requantized to channel-wise Q8_0_C, and that path reads the zero-point
// as f16 -- Q2_0 used to hard-code u8 here, which threw for every ternary model.
-TEST(GGUFWeightRequant, Q2_0AsTokenEmbd) {
+TEST(GGUFWeightRequant, Q2_0AsTokenEmbdAndOutput) {
const auto qbytes = load_npy<uint8_t>("q2_0_qbytes");
const auto ref = load_npy<float>("q2_0_deq");
ASSERT_EQ(ref.size(), kRows * kCols);
- auto model = SingleOpBuilder()
- .op("GGML_OP_NONE")
- .output("token_embd.weight", ov::element::f32, {kRows, kCols})
- .attr<ov::Tensor>("data", bytes_to_u8_tensor(qbytes))
- .attr<std::string>("quant_type", "Q2_0")
- .build();
-
- auto out = run_on_cpu(model, {});
- ASSERT_EQ(out.get_size(), ref.size());
-
- const float* a = out.data<float>();
- float max_diff = 0.f;
- for (size_t i = 0; i < ref.size(); ++i)
- max_diff = std::max(max_diff, std::fabs(a[i] - ref[i]));
- EXPECT_LE(max_diff, kTolRequant) << "Q2_0 token_embd requant diverges from ggml to_float";
+ for (const std::string name : {"token_embd.weight", "output.weight"}) {
+ SCOPED_TRACE(name);
+ auto model = SingleOpBuilder()
+ .op("GGML_OP_NONE")
+ .output(name, ov::element::f32, {kRows, kCols})
+ .attr<ov::Tensor>("data", bytes_to_u8_tensor(qbytes))
+ .attr<std::string>("quant_type", "Q2_0")
+ .build();
+
+ auto out = run_on_cpu(model, {});
+ ASSERT_EQ(out.get_size(), ref.size());
+
+ const float* a = out.data<float>();
+ float max_diff = 0.f;
+ for (size_t i = 0; i < ref.size(); ++i)
+ max_diff = std::max(max_diff, std::fabs(a[i] - ref[i]));
+ EXPECT_LE(max_diff, kTolRequant) << "Q2_0 requant diverges from ggml to_float";
+ }
}
// An F16 weight is wrapped directly as a constant (no dequant); round-trips the raw bytes.