Skip to content

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

[GGUF] Requantize Q5_K matrix weights to symmetric i8 (#39145)

Maxim Vafin8dedcb0f0f42
diff --git a/src/frontends/gguf/docs/quantization.md b/src/frontends/gguf/docs/quantization.md
index 7b7c9b9c1be..ff7a6f380be 100644
--- a/src/frontends/gguf/docs/quantization.md
+++ b/src/frontends/gguf/docs/quantization.md
@@ -66,14 +66,20 @@ The type columns describe stored Constants; their decompression or Convert outpu
| Q4_K, fractional zero point | 256 | 144 | `u4` | `f16` | `f16` | `128 + 16 + 16` = 160 | +11.1% |
| Q5_0 | 32 | 22 | `i8` | `f16` | — | `32 + 2` = 34 | +54.5% |
| Q5_1 | 32 | 24 | `i8` | `f16` | `f16` | `32 + 2 + 2` = 36 | +50.0% |
-| Q5_K, integer zero point | 256 | 176 | `u8` | `f16` | `u8` | `256 + 16 + 8` = 280 | +59.1% |
+| Q5_K, ordinary matrix | 256 | 176 | `i8` | `f16` | — | `256 + 16` = 272 | +54.5% |
| Q5_K, fractional zero point | 256 | 176 | `u8` | `f16` | `f16` | `256 + 16 + 16` = 288 | +63.6% |
| Q6_K | 256 | 210 | `i8` | `f16` | — | `256 + 32` = 288 | +37.1% |
| Q8_0 | 32 | 34 | `i8` | `f16` | — | `32 + 2` = 34 | 0% |
| Q8_K | 256 | 292 | `i8` | `f32` | — | `256 + 4` = 260 | -11.0% |
| MXFP4 | 32 | 17 | `f4e2m1` | `f8e8m0` | — | `16 + 1` = 17 | 0% |
-Ordinary native Q4_1/Q4_K and Q5_K matrix weights use integer zero points by default.
+Ordinary native Q4_1/Q4_K matrix weights use integer zero points by default.
+Ordinary native Q5_K matrix weights use symmetric i8 with one F16 scale per 32 weights
+and no zero point. Source values are decoded and requantized using the group maximum
+absolute value; this adds rounding error and changes the grid from the former asymmetric u8
+representation. Conversion uses a 256-value scratch buffer per source block. The converted
+weight/scale payload is 2.86% smaller than the former u8/integer-zero-point payload.
+Group size remains 32 for all devices.
`token_embd.weight` and `output.weight` use fractional zero points for these affine formats;
Q5_1 and Q2_K also use fractional zero points. See [accuracy controls](#accuracy-controls)
to select fractional zero points for all Q4_1/Q4_K tensors.
@@ -248,16 +254,22 @@ Q5_K reconstructs five-bit codes 0..31 and stores them in `u8`. Both store F16 `
F16 `offset/sc` (zero for a zero scale), and their graph arithmetic is F32. Both have the
common affine limitations; Q5_K additionally widens its code payload.
-With an **integer zero point**, both first reconstruct 32 source values in F32, then
-requantize onto a new grid whose range includes zero. Q4_K uses 16 levels in packed `u4`:
+With an **integer zero point**, Q4_K first reconstructs 32 source values in F32, then
+requantizes onto a new grid whose range includes zero. It uses 16 levels in packed `u4`:
min/max initialization, an integer zero point, and a least-squares scale refinement. Candidate
scales are evaluated after F16 rounding. The importer retains the original codes with a
rounded integer zero point unless a candidate reduces squared error without increasing
-maximum absolute error. Q5_K uses 256 levels in `u8`, an F16 min/max scale and a rounded,
-clipped integer zero point; values are rounded and clipped to 0..255.
+maximum absolute error.
+
+Ordinary Q5_K matrix weights use a symmetric 255-level i8 grid. Each 32-value group uses `F16(max(abs(value))/127)` and codes rounded against that stored scale,
+clamped to [-127,127]. There is no zero-point tensor. A skewed range can have a coarser
+grid than asymmetric u8, so this representation changes reconstruction error even though
+both paths requantize once. Embedding/output and other non-matrix Q5_K tensors retain
+the existing u8 handling.
Including zero in a one-sided group coarsens the available grid. Q5_K collapses a group to
-zero if its new F16 scale is nonpositive or nonfinite.
+zero if its new F16 scale rounds to zero. The symmetric path rejects nonfinite source
+values and scales that exceed the F16 range.
### Q4_1
diff --git a/src/frontends/gguf/src/quant/gguf.cpp b/src/frontends/gguf/src/quant/gguf.cpp
index 68df8785b9f..8c505dffac3 100644
--- a/src/frontends/gguf/src/quant/gguf.cpp
+++ b/src/frontends/gguf/src/quant/gguf.cpp
@@ -117,7 +117,7 @@ struct QuantLayout {
bool asymmetric; // carries a per-group zero-point
};
-std::optional<QuantLayout> quant_layout(uint32_t type) {
+std::optional<QuantLayout> quant_layout(uint32_t type, const std::string& name) {
constexpr bool asymmetric = true;
constexpr bool symmetric = false;
switch (type) {
@@ -148,7 +148,8 @@ std::optional<QuantLayout> quant_layout(uint32_t type) {
case GGUF_TYPE_Q5_1:
return QuantLayout{ov::element::i8, 1, ov::element::f16, 32, asymmetric};
case GGUF_TYPE_Q5_K:
- return QuantLayout{ov::element::u8, 1, ov::element::f16, 32, asymmetric};
+ return native_q5_k_is_symmetric(name) ? QuantLayout{ov::element::i8, 1, ov::element::f16, 32, symmetric}
+ : QuantLayout{ov::element::u8, 1, ov::element::f16, 32, asymmetric};
case GGUF_TYPE_MXFP4:
return QuantLayout{ov::element::f4e2m1, 1, ov::element::f8e8m0, 32, symmetric};
default:
@@ -619,7 +620,7 @@ void load_gguf_tensors(GgufFile& file,
};
for (const auto& info : infos) {
- if (const auto layout = quant_layout(info.type)) {
+ if (const auto layout = quant_layout(info.type, info.name)) {
quant_sizes(info, *layout);
}
}
@@ -671,7 +672,7 @@ void load_gguf_tensors(GgufFile& file,
const std::string name_prefix =
ov::util::ends_with(name, WEIGHT_SUFFIX) ? name.substr(0, name.length() - WEIGHT_SUFFIX.length()) : name;
- const auto layout = quant_layout(ti.type);
+ const auto layout = quant_layout(ti.type, ti.name);
if (!layout) {
ov::Tensor loaded = extract_tensor_data(tensor, mapped); // zero-copy mmap view
const bool inserted = arrays.emplace(name, std::move(loaded)).second;
@@ -694,7 +695,9 @@ void load_gguf_tensors(GgufFile& file,
zp = ov::Tensor(gguf_zero_point_type(name, static_cast<GgufTensorType>(ti.type)), scale_shape);
}
- if (ti.type == GGUF_TYPE_MXFP4) {
+ if (ti.type == GGUF_TYPE_Q5_K && !layout->asymmetric) {
+ gguf_fill_q5_k_i8(tensor, weights, scales);
+ } else if (ti.type == GGUF_TYPE_MXFP4) {
gguf_fill_mxfp4(tensor, weights, scales);
} else if (ti.type == GGUF_TYPE_Q2_0 || ti.type == GGUF_TYPE_PQ2_0 || ti.type == GGUF_TYPE_PTQ1_0) {
gguf_fill_q2_0(tensor, weights, scales, zp);
diff --git a/src/frontends/gguf/src/quant/gguf.hpp b/src/frontends/gguf/src/quant/gguf.hpp
index cf7385094ef..967f2e262a4 100644
--- a/src/frontends/gguf/src/quant/gguf.hpp
+++ b/src/frontends/gguf/src/quant/gguf.hpp
@@ -127,6 +127,8 @@ bool requantize_q8_0_channelwise_faithful(const GgufTensor& tensor,
int8_t* out_weights,
ov::float16* out_scales);
+void gguf_fill_q5_k_i8(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales);
+
// Test-only accessors for the per-row faithful K-quant dequant (see test_dequant_vs_ggml.cpp).
void dequant_row_q4_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
void dequant_row_q5_k_f32_for_test(const uint8_t* row, size_t cols, float* y);
diff --git a/src/frontends/gguf/src/quant/gguf_quants.cpp b/src/frontends/gguf/src/quant/gguf_quants.cpp
index ee732d1f12a..bd097a69abb 100644
--- a/src/frontends/gguf/src/quant/gguf_quants.cpp
+++ b/src/frontends/gguf/src/quant/gguf_quants.cpp
@@ -3,6 +3,7 @@
//
#include <algorithm>
+#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
@@ -468,6 +469,42 @@ static void dequant_row_q6_k_f32(const uint8_t* row, size_t cols, float* y) {
}
}
+void gguf_fill_q5_k_i8(const GgufTensor& tensor, ov::Tensor& weights, ov::Tensor& scales) {
+ constexpr size_t group_size = 32;
+ OPENVINO_ASSERT(tensor.type == GGUF_TYPE_Q5_K, "[GGUF] invalid Q5_K symmetric requantization group");
+ OPENVINO_ASSERT(tensor.num_weights % 256 == 0 && tensor.bsize / kQ5K_BLOCK_BYTES == tensor.num_weights / 256 &&
+ tensor.bsize % kQ5K_BLOCK_BYTES == 0,
+ "[GGUF] invalid Q5_K symmetric requantization payload");
+ OPENVINO_ASSERT(weights.get_element_type() == ov::element::i8 && weights.get_size() == tensor.num_weights &&
+ scales.get_element_type() == ov::element::f16 &&
+ scales.get_size() == tensor.num_weights / group_size,
+ "[GGUF] invalid Q5_K symmetric requantization buffers");
+ auto* dst = weights.data<int8_t>();
+ auto* scale_data = scales.data<ov::float16>();
+ ov::parallel_for(tensor.num_weights / 256, [&](size_t block) {
+ std::array<float, 256> values;
+ dequant_row_q45_k_f32<true>(tensor.weights_data + block * kQ5K_BLOCK_BYTES, 256, values.data());
+ for (size_t offset = 0; offset < 256; offset += group_size) {
+ float amax = 0.0f;
+ for (size_t k = offset; k < offset + group_size; ++k) {
+ OPENVINO_ASSERT(std::isfinite(values[k]), "[GGUF] cannot requantize non-finite Q5_K values");
+ amax = std::max(amax, std::fabs(values[k]));
+ }
+ const ov::float16 scale_f16(amax / 127.0f);
+ const float scale = static_cast<float>(scale_f16);
+ OPENVINO_ASSERT(std::isfinite(scale), "[GGUF] Q5_K symmetric scale exceeds f16 range");
+ scale_data[(block * 256 + offset) / group_size] = scale_f16;
+ for (size_t k = offset; k < offset + group_size; ++k) {
+ const float code = scale > 0.0f ? std::round(values[k] / scale) : 0.0f;
+ dst[block * 256 + k] = static_cast<int8_t>(std::clamp(code, -127.0f, 127.0f));
+ }
+ }
+ });
+ if (tensor.num_weights != 0) {
+ notify_lossy_weight_approximation(LossyWeightApproximation::Q5_K_SYMMETRIC_REQUANT);
+ }
+}
+
// Fused faithful dequant + channel-wise Q8_0_C requant, streaming one row at a time so the full f32
// weight is never materialized (holds only `cols` floats). Fills i8 weights [rows,cols] + f16 scales
// [rows,1], matching the upstream Q8_0_C path (amax/127 per row, roundf). qtype selects the exact
diff --git a/src/frontends/gguf/src/quant/weights.cpp b/src/frontends/gguf/src/quant/weights.cpp
index 95d0968a889..d9253238d98 100644
--- a/src/frontends/gguf/src/quant/weights.cpp
+++ b/src/frontends/gguf/src/quant/weights.cpp
@@ -100,6 +100,21 @@ WeightFormat get_weight_format(GgufTensorType qtype) {
}
}
+WeightFormat get_weight_format(GgufTensorType qtype,
+ const ov::Tensor& weight,
+ const ov::Tensor& zero_point,
+ const std::string& name) {
+ const auto format = get_weight_format(qtype);
+ if (qtype != GGUF_TYPE_Q5_K) {
+ return format;
+ }
+ const auto et = weight.get_element_type();
+ OPENVINO_ASSERT((et == ov::element::u8 && zero_point) || (et == ov::element::i8 && !zero_point),
+ "[GGUF] unsupported Q5_K storage layout: ",
+ name);
+ return et == ov::element::i8 ? WeightFormat{FillKind::SYMMETRIC, 32, ov::element::i8} : format;
+}
+
const ov::Tensor& get(const std::unordered_map<std::string, ov::Tensor>& weights, const std::string& key) {
auto it = weights.find(key);
OPENVINO_ASSERT(it != weights.end(), "[GGUF] missing weight tensor: ", key);
@@ -371,6 +386,10 @@ bool q4_k_f16_zero_point_enabled() {
} // namespace
+bool native_q5_k_is_symmetric(const std::string& name) {
+ return !is_embedding_or_output(name) && ov::util::ends_with(name, ".weight");
+}
+
void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
// Written to std::cerr, NOT OPENVINO_WARN: the latter expands to a no-op unless the build sets
// ENABLE_OPENVINO_DEBUG (cmake/features.cmake defaults it OFF), so in every shipped build it
@@ -382,6 +401,7 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
static std::once_flag requant_once;
static std::once_flag zero_point_once;
static std::once_flag q5_k_zero_point_once;
+ static std::once_flag q5_k_symmetric_once;
switch (kind) {
case LossyWeightApproximation::Q8_0_C_REQUANT:
@@ -402,6 +422,15 @@ void notify_lossy_weight_approximation(LossyWeightApproximation kind) {
<< std::endl;
});
break;
+ case LossyWeightApproximation::Q5_K_SYMMETRIC_REQUANT:
+ std::call_once(q5_k_symmetric_once, [] {
+ std::cerr << "[GGUF] accuracy notice: Q5_K matrix weights are faithfully decoded and requantized "
+ "to symmetric int8 with one f16 scale per 32 weights and no zero point. This adds "
+ "quantization error, so results may differ from the original GGUF weights. "
+ "Reported once per process."
+ << std::endl;
+ });
+ break;
case LossyWeightApproximation::Q5_K_REQUANT:
std::call_once(q5_k_zero_point_once, [] {
std::cerr << "[GGUF] accuracy notice: Q5_K weights are faithfully decoded and requantized group-wise "
@@ -434,7 +463,7 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,
GgufTensorType qtype,
const std::string& name) {
OPENVINO_ASSERT(tensors.weight, "[GGUF] missing weight tensor: ", name);
- const auto format = get_weight_format(qtype);
+ const auto format = get_weight_format(qtype, tensors.weight, tensors.zero_point, 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);
@@ -446,6 +475,18 @@ std::shared_ptr<ov::Node> make_weight_node(const WeightTensors& tensors,
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);
+ } else if (qtype == GGUF_TYPE_Q5_K && format.fill == FillKind::SYMMETRIC) {
+ const auto& shape = tensors.weight.get_shape();
+ const auto& scale_shape = tensors.scales.get_shape();
+ OPENVINO_ASSERT(!shape.empty() && scale_shape.size() == shape.size() && shape.back() != 0 &&
+ shape.back() % 32 == 0 && scale_shape.back() == shape.back() / 32 &&
+ std::equal(shape.begin(), shape.end() - 1, scale_shape.begin()),
+ "[GGUF] invalid Q5_K symmetric scale shape: ",
+ name);
+ OPENVINO_ASSERT(tensors.scales.get_element_type() == ov::element::f16,
+ "[GGUF] Q5_K symmetric scales must be f16: ",
+ name);
+ node = make_compressed(tensors, format.node_element_type(), false);
} else if (format.fill == FillKind::MXFP4) {
node = make_mxfp4(tensors);
} else {
@@ -502,13 +543,16 @@ GgufTensorType lookup_qtype(const std::string& base, const std::unordered_map<st
// the weight and, if present for this qtype's format, the scales and zero-point.
template <typename SliceFn>
FusedQkvPart make_split_part(GgufTensorType qtype,
- const WeightFormat& format,
const std::unordered_map<std::string, ov::Tensor>& weights,
const std::string& base,
const SliceFn& slice) {
+ const auto& weight = get(weights, base + ".weight");
+ const auto zp = weights.find(base + ".zp");
+ const ov::Tensor zero_point = zp != weights.end() ? zp->second : ov::Tensor{};
+ const auto format = get_weight_format(qtype, weight, zero_point, base);
FusedQkvPart part;
part.qtype = qtype;
- part.tensors.weight = slice(get(weights, base + ".weight"));
+ part.tensors.weight = slice(weight);
if (format.has_scales()) {
part.tensors.scales = slice(get(weights, base + ".scales"));
}
@@ -525,7 +569,6 @@ std::array<FusedQkvPart, 3> split_fused_qkv_extracted(const std::string& base,
size_t n_k,
size_t n_v) {
const GgufTensorType qtype = lookup_qtype(base, qtypes);
- const auto format = get_weight_format(qtype);
const size_t total_rows = get(weights, base + ".weight").get_shape()[0];
OPENVINO_ASSERT(n_q + n_k + n_v == total_rows, "[GGUF] fused qkv row mismatch for ", base);
@@ -537,7 +580,7 @@ std::array<FusedQkvPart, 3> split_fused_qkv_extracted(const std::string& base,
for (size_t i = 0; i < 3; ++i) {
const size_t r0 = ranges[i].first;
const size_t r1 = ranges[i].second;
- out[i] = make_split_part(qtype, format, weights, base, [&](const ov::Tensor& t) {
+ out[i] = make_split_part(qtype, weights, base, [&](const ov::Tensor& t) {
return slice_leading(t, r0, r1);
});
}
@@ -564,7 +607,6 @@ std::array<FusedQkvPart, 2> split_interleaved_q_gate(const std::string& base,
const std::unordered_map<std::string, GgufTensorType>& qtypes,
size_t head_dim) {
const GgufTensorType qtype = lookup_qtype(base, qtypes);
- const auto format = get_weight_format(qtype);
const size_t block = 2 * head_dim;
OPENVINO_ASSERT(get(weights, base + ".weight").get_shape()[0] % block == 0,
@@ -575,7 +617,7 @@ std::array<FusedQkvPart, 2> split_interleaved_q_gate(const std::string& base,
std::array<FusedQkvPart, 2> out;
for (size_t i = 0; i < 2; ++i) {
- out[i] = make_split_part(qtype, format, weights, base, [&](const ov::Tensor& t) {
+ out[i] = make_split_part(qtype, weights, base, [&](const ov::Tensor& t) {
return gather_rows_strided(t, block, head_dim, offsets[i]);
});
}
diff --git a/src/frontends/gguf/src/quant/weights.hpp b/src/frontends/gguf/src/quant/weights.hpp
index 5791879f8aa..dc80d083fc0 100644
--- a/src/frontends/gguf/src/quant/weights.hpp
+++ b/src/frontends/gguf/src/quant/weights.hpp
@@ -21,10 +21,12 @@ namespace ov::frontend::gguf {
// 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 and Q4_1 matmul weights are faithfully decoded and requantized to u4 with an integer
-// zero-point, which keeps the compressed-FullyConnected path available on CPU and GPU. Q5_K matmul
-// weights are requantized the same way to an 8-bit u8 grid. token_embd/output keep an f16 zero-point.
+// zero-point, which keeps the compressed-FullyConnected path available on CPU and GPU. Native
+// Q5_K matmul weights use symmetric i8. token_embd/output keep an f16 zero-point.
ov::element::Type gguf_zero_point_type(const std::string& name, GgufTensorType qtype);
+bool native_q5_k_is_symmetric(const std::string& name);
+
// A lossy weight approximation the frontend deliberately makes, reported to the user once so a
// later accuracy investigation starts from the right place.
enum class LossyWeightApproximation {
@@ -34,6 +36,7 @@ enum class LossyWeightApproximation {
Q4_REQUANT,
// Q5_K asymmetric weights faithfully decoded and requantized group-wise to OpenVINO u8.
Q5_K_REQUANT,
+ Q5_K_SYMMETRIC_REQUANT,
};
// Warn -- ONCE per process and per approximation kind -- that weights are being converted with a
diff --git a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
index 62222858789..ca2c9184e9b 100644
--- a/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
+++ b/src/frontends/gguf/tests/test_dequant_vs_ggml.cpp
@@ -337,3 +337,89 @@ TEST(GGUFDequant, IntegerZeroPointRequantizationTracksGgml) {
}
}
}
+
+TEST(GGUFQ5KRequant, SymmetricGroupsTrackRealGgml) {
+ const auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ const auto reference = load_npy<float>("q5_k_deq");
+ ASSERT_EQ(reference.size(), kRows * kCols);
+ GgufTensor source{};
+ source.type = GGUF_TYPE_Q5_K;
+ source.num_weights = reference.size();
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ constexpr size_t group_size = 32;
+ WeightTensors tensors{ov::Tensor(ov::element::i8, {kRows, kCols}),
+ ov::Tensor(ov::element::f16, {kRows, kCols / group_size}),
+ {}};
+ gguf_fill_q5_k_i8(source, tensors.weight, tensors.scales);
+ ASSERT_FALSE(tensors.zero_point);
+ const auto node = make_weight_node(tensors, GGUF_TYPE_Q5_K);
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{node}, ov::ParameterVector{});
+ bool has_i8 = false;
+ for (const auto& op : model->get_ops()) {
+ EXPECT_STRNE(op->get_type_name(), "Subtract");
+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op))
+ has_i8 |= constant->get_element_type() == ov::element::i8;
+ }
+ EXPECT_TRUE(has_i8);
+ const auto expanded = eval_as_f32(node);
+ ASSERT_EQ(expanded.size(), reference.size());
+ for (size_t group = 0; group < reference.size() / group_size; ++group) {
+ float maxabs = 0.0f;
+ for (size_t k = group * group_size; k < (group + 1) * group_size; ++k)
+ maxabs = std::max(maxabs, std::fabs(reference[k]));
+ const ov::float16 expected_scale(maxabs / 127.0f);
+ EXPECT_EQ(tensors.scales.data<ov::float16>()[group].to_bits(), expected_scale.to_bits());
+ const float scale = static_cast<float>(expected_scale);
+ for (size_t k = group * group_size; k < (group + 1) * group_size; ++k) {
+ const int code = tensors.weight.data<int8_t>()[k];
+ EXPECT_GE(code, -127);
+ EXPECT_LE(code, 127);
+ const float expected_code = scale > 0.0f ? std::round(reference[k] / scale) : 0.0f;
+ EXPECT_EQ(code, static_cast<int>(std::clamp(expected_code, -127.0f, 127.0f)));
+ EXPECT_LE(std::fabs(expanded[k] - reference[k]), scale * 0.501f + maxabs * 1e-3f + 1e-7f);
+ }
+ }
+}
+
+TEST(GGUFQ5KRequant, ZeroAndUnderflowGroupsStayFinite) {
+ auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ GgufTensor source{};
+ source.type = GGUF_TYPE_Q5_K;
+ source.num_weights = kRows * kCols;
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ for (bool tiny : {false, true}) {
+ std::fill(bytes.begin(), bytes.end(), uint8_t{0});
+ if (tiny) {
+ for (size_t block = 0; block < bytes.size() / 176; ++block) {
+ bytes[block * 176] = 1;
+ std::fill_n(bytes.begin() + block * 176 + 4, 4, uint8_t{1});
+ std::fill_n(bytes.begin() + block * 176 + 48, 128, uint8_t{0x11});
+ }
+ }
+ constexpr size_t group_size = 32;
+ WeightTensors tensors{ov::Tensor(ov::element::i8, {kRows, kCols}),
+ ov::Tensor(ov::element::f16, {kRows, kCols / group_size}),
+ {}};
+ gguf_fill_q5_k_i8(source, tensors.weight, tensors.scales);
+ for (size_t k = 0; k < tensors.weight.get_size(); ++k)
+ EXPECT_EQ(tensors.weight.data<int8_t>()[k], 0);
+ for (size_t k = 0; k < tensors.scales.get_size(); ++k)
+ EXPECT_EQ(tensors.scales.data<ov::float16>()[k].to_bits(), 0);
+ }
+}
+
+TEST(GGUFQ5KRequant, RejectsNonFiniteSource) {
+ auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ const uint16_t infinity = 0x7c00;
+ std::memcpy(bytes.data(), &infinity, sizeof(infinity));
+ GgufTensor source{};
+ source.type = GGUF_TYPE_Q5_K;
+ source.num_weights = kRows * kCols;
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ ov::Tensor weights(ov::element::i8, {kRows, kCols});
+ ov::Tensor scales(ov::element::f16, {kRows, kCols / 32});
+ EXPECT_THROW(gguf_fill_q5_k_i8(source, weights, scales), ov::Exception);
+}
diff --git a/src/frontends/gguf/tests/test_weights.cpp b/src/frontends/gguf/tests/test_weights.cpp
index 382065b762c..efead58903d 100644
--- a/src/frontends/gguf/tests/test_weights.cpp
+++ b/src/frontends/gguf/tests/test_weights.cpp
@@ -13,10 +13,13 @@
#include <cmath>
#include <cstring>
+#include <fstream>
#include <vector>
+#include "common_test_utils/file_utils.hpp"
#include "op_test_utils.hpp"
#include "openvino/op/constant.hpp"
+#include "quant/gguf.hpp"
#include "quant/weights.hpp"
using namespace ov_gguf_test;
@@ -355,3 +358,139 @@ TEST(GGUFWeight, UsesIntegerZeroPointForRequantizedMatmulWeights) {
EXPECT_EQ(gguf_zero_point_type("output.weight", GGUF_TYPE_Q5_K), ov::element::f16);
EXPECT_EQ(gguf_zero_point_type("blk.0.attn_q.weight", GGUF_TYPE_Q2_0), ov::element::u8);
}
+
+class GGUFQ5KNative : public ::testing::Test {
+protected:
+ void SetUp() override {
+ path = ov::test::utils::generateTestFilePrefix() + ".gguf";
+ }
+ void TearDown() override {
+ ov::test::utils::removeFile(path);
+ }
+ void write_tensor(const std::string& name, const std::vector<uint8_t>& bytes) {
+ std::ofstream out(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});
+ put(uint64_t{0});
+ put(uint64_t{name.size()});
+ out.write(name.data(), name.size());
+ put(uint32_t{3});
+ put(uint64_t{kCols});
+ put(uint64_t{2});
+ put(uint64_t{2});
+ put(uint32_t{ov::frontend::gguf::GGUF_TYPE_Q5_K});
+ put(uint64_t{0});
+ while (static_cast<size_t>(out.tellp()) % 32 != 0)
+ out.put('\0');
+ out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
+ ASSERT_TRUE(out);
+ }
+ std::string path;
+};
+
+TEST_F(GGUFQ5KNative, KeepsDiskTypeAndUsesSymmetricStorageForMatrices) {
+ using namespace ov::frontend::gguf;
+ const auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ for (const std::string name : {"blk.0.ffn_up", "token_embd", "output", "blk.0.attn_q.bias"}) {
+ SCOPED_TRACE(name);
+ const auto full_name = name == "blk.0.attn_q.bias" ? name : name + ".weight";
+ const bool symmetric = name == "blk.0.ffn_up";
+ ASSERT_NO_FATAL_FAILURE(write_tensor(full_name, bytes));
+ const auto loaded = get_gguf_data(path);
+ const auto& arrays = std::get<1>(loaded);
+ const auto& prefix = name;
+ EXPECT_EQ(std::get<2>(loaded).at(prefix + ".qtype"), GGUF_TYPE_Q5_K);
+ WeightTensors tensors{arrays.at(full_name), arrays.at(prefix + ".scales"), {}};
+ if (auto zp = arrays.find(prefix + ".zp"); zp != arrays.end())
+ tensors.zero_point = zp->second;
+ EXPECT_EQ(tensors.weight.get_element_type(), symmetric ? ov::element::i8 : ov::element::u8);
+ EXPECT_EQ(tensors.scales.get_shape(), (ov::Shape{2, 2, kCols / 32}));
+ EXPECT_EQ(static_cast<bool>(tensors.zero_point), !symmetric);
+ EXPECT_NO_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K, full_name));
+ if (!symmetric) {
+ EXPECT_EQ(tensors.zero_point.get_element_type(),
+ name == "blk.0.attn_q.bias" ? ov::element::u8 : ov::element::f16);
+ }
+ }
+}
+
+TEST(GGUFQ5KRequant, FusedSplitsKeepSymmetricStorage) {
+ using namespace ov::frontend::gguf;
+ const auto bytes = load_npy<uint8_t>("q5_k_qbytes");
+ GgufTensor source{};
+ source.type = GGUF_TYPE_Q5_K;
+ source.num_weights = kRows * kCols;
+ source.bsize = bytes.size();
+ source.weights_data = bytes.data();
+ WeightTensors tensors{ov::Tensor(ov::element::i8, {kRows, kCols}),
+ ov::Tensor(ov::element::f16, {kRows, kCols / 32}),
+ {}};
+ gguf_fill_q5_k_i8(source, tensors.weight, tensors.scales);
+ const std::unordered_map<std::string, ov::Tensor> weights{{"fused.weight", tensors.weight},
+ {"fused.scales", tensors.scales}};
+ const std::unordered_map<std::string, GgufTensorType> qtypes{{"fused.qtype", GGUF_TYPE_Q5_K}};
+ const auto qkv = split_fused_qkv_extracted("fused", weights, qtypes, 2, 1, 1);
+ const auto q_gate = split_interleaved_q_gate("fused", weights, qtypes, 1);
+ for (const auto& part : qkv) {
+ EXPECT_FALSE(part.tensors.zero_point);
+ EXPECT_NO_THROW(make_weight_node(part.tensors, part.qtype));
+ }
+ for (size_t part = 0; part < q_gate.size(); ++part) {
+ EXPECT_FALSE(q_gate[part].tensors.zero_point);
+ EXPECT_NO_THROW(make_weight_node(q_gate[part].tensors, q_gate[part].qtype));
+ for (size_t row = 0; row < 2; ++row) {
+ const size_t source_row = row * 2 + part;
+ EXPECT_EQ(std::memcmp(q_gate[part].tensors.weight.data<int8_t>() + row * kCols,
+ tensors.weight.data<int8_t>() + source_row * kCols,
+ kCols),
+ 0);
+ EXPECT_EQ(std::memcmp(q_gate[part].tensors.scales.data<ov::float16>() + row * (kCols / 32),
+ tensors.scales.data<ov::float16>() + source_row * (kCols / 32),
+ (kCols / 32) * sizeof(ov::float16)),
+ 0);
+ }
+ }
+}
+
+TEST(GGUFQ5KRequant, RejectsMalformedSymmetricGraphTensors) {
+ using namespace ov::frontend::gguf;
+ WeightTensors tensors{ov::Tensor(ov::element::i8, {2, 256}), ov::Tensor(ov::element::f16, {2, 8}), {}};
+ for (const ov::Shape& shape : {ov::Shape{1, 8}, ov::Shape{2, 2}, ov::Shape{2, 0}, ov::Shape{2, 8, 1}}) {
+ tensors.scales = ov::Tensor(ov::element::f16, shape);
+ EXPECT_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K), ov::Exception);
+ }
+ tensors.scales = ov::Tensor(ov::element::f32, {2, 8});
+ EXPECT_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K), ov::Exception);
+ tensors.weight = ov::Tensor(ov::element::u8, {2, 256});
+ tensors.scales = ov::Tensor(ov::element::f16, {2, 8});
+ EXPECT_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K), ov::Exception);
+}
+
+TEST(GGUFQ5KRequant, RejectsUnsupportedStorageLayouts) {
+ using namespace ov::frontend::gguf;
+ const std::unordered_map<std::string, GgufTensorType> qtypes{{"fused.qtype", GGUF_TYPE_Q5_K}};
+ for (const auto& type : {ov::element::i8, ov::element::u8, ov::element::f16}) {
+ for (const auto& zp_type : {ov::element::dynamic, ov::element::u8, ov::element::f16}) {
+ if ((type == ov::element::i8 && zp_type == ov::element::dynamic) ||
+ (type == ov::element::u8 && zp_type != ov::element::dynamic))
+ continue;
+ SCOPED_TRACE(type.get_type_name());
+ SCOPED_TRACE(zp_type.get_type_name());
+ WeightTensors tensors{ov::Tensor(type, {4, 256}), ov::Tensor(ov::element::f16, {4, 8}), {}};
+ std::unordered_map<std::string, ov::Tensor> weights{{"fused.weight", tensors.weight},
+ {"fused.scales", tensors.scales}};
+ if (zp_type != ov::element::dynamic) {
+ tensors.zero_point = ov::Tensor(zp_type, {4, 8});
+ weights.emplace("fused.zp", tensors.zero_point);
+ }
+ EXPECT_THROW(make_weight_node(tensors, GGUF_TYPE_Q5_K), ov::Exception);
+ EXPECT_THROW(split_fused_qkv_extracted("fused", weights, qtypes, 2, 1, 1), ov::Exception);
+ EXPECT_THROW(split_interleaved_q_gate("fused", weights, qtypes, 1), ov::Exception);
+ }
+ }
+}
diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fc_horizontal_fusion.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fc_horizontal_fusion.cpp
index d0838e26794..80181bdcf49 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations/fc_horizontal_fusion.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations/fc_horizontal_fusion.cpp
@@ -173,6 +173,21 @@ FullyConnectedHorizontalFusion::FullyConnectedHorizontalFusion(bool fuse_mlp_swi
// unfolded Concat on weights (e.g. in case of unsupported precision) may then fail the pipeline if the GPU also doesn't support this.
// So if the concatenation at ov::Model is not possible, the transformation just returns false
auto concat_and_fold = [](const ov::OutputVector& outputs, int64_t axis, std::string_view name_suffix) -> std::shared_ptr<ov::Node> {
+ const auto& reference_shape = outputs.front().get_partial_shape();
+ if (!reference_shape.is_static() || axis < 0 || axis >= reference_shape.rank().get_length()) {
+ return nullptr;
+ }
+ for (const auto& output : outputs) {
+ const auto& shape = output.get_partial_shape();
+ if (!shape.is_static() || shape.rank() != reference_shape.rank() || output.get_element_type() != outputs.front().get_element_type()) {
+ return nullptr;
+ }
+ for (int64_t dim = 0; dim < shape.rank().get_length(); ++dim) {
+ if (dim != axis && shape[dim] != reference_shape[dim]) {
+ return nullptr;
+ }
+ }
+ }
auto concat = std::make_shared<ov::op::v0::Concat>(outputs, axis);
auto folded = ov::util::get_constant_from_source(concat);
if (!folded) {
diff --git a/src/plugins/intel_gpu/tests/unit/transformations/horizontal_fc_fusion_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/horizontal_fc_fusion_test.cpp
index d81e1fd76c2..a2db941bf1e 100644
--- a/src/plugins/intel_gpu/tests/unit/transformations/horizontal_fc_fusion_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/transformations/horizontal_fc_fusion_test.cpp
@@ -5,6 +5,8 @@
#include <gtest/gtest.h>
#include "common_test_utils/graph_comparator.hpp"
#include "common_test_utils/ov_test_utils.hpp"
+#include "intel_gpu/op/fully_connected_compressed.hpp"
+#include "intel_gpu/op/placeholder.hpp"
#include <string>
#include <memory>
@@ -641,4 +643,58 @@ TEST_F(TransformationTestsF, FullyConnectedHorizontalFusion_mixed_scale_orientat
} // namespace intel_gpu
} // namespace test
-} // namespace ov
\ No newline at end of file
+} // namespace ov
+namespace {
+
+std::shared_ptr<ov::Model> make_i8_fc_model(const std::vector<ov::Shape>& scale_shapes, bool transpose_b = true) {
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 7, 256});
+ ov::ResultVector results;
+ const std::vector<size_t> rows{4, 2, 2};
+ for (size_t i = 0; i < rows.size(); ++i) {
+ const ov::Shape weight_shape = transpose_b ? ov::Shape{rows[i], 256} : ov::Shape{256, rows[i]};
+ auto weight = ov::op::v0::Constant::create(ov::element::i8, weight_shape, {static_cast<int8_t>(i + 1)});
+ auto bias = std::make_shared<ov::intel_gpu::op::Placeholder>();
+ auto scale = ov::op::v0::Constant::create(ov::element::f16, scale_shapes[i], {0.25f * (i + 1)});
+ auto fc = std::make_shared<ov::intel_gpu::op::FullyConnectedCompressed>(input, weight, bias, scale, ov::element::dynamic, transpose_b);
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(
+ fc, ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 0, -1}), true);
+ results.push_back(std::make_shared<ov::op::v0::Result>(reshape));
+ }
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{input});
+}
+
+} // namespace
+
+TEST_F(TransformationTestsF, FullyConnectedHorizontalFusion_mixed_q5_q6_groups) {
+ model = make_i8_fc_model({{4, 8}, {2, 8}, {2, 16}});
+ manager.register_pass<FullyConnectedHorizontalFusion>();
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ comparator.enable(FunctionsComparator::CONST_VALUES);
+}
+
+TEST_F(TransformationTestsF, FullyConnectedHorizontalFusion_matching_i8_group32) {
+ model = make_i8_fc_model({{4, 8}, {2, 8}, {2, 8}});
+ manager.register_pass<FullyConnectedHorizontalFusion>();
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ comparator.enable(FunctionsComparator::CONST_VALUES);
+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{-1, 7, 256});
+ std::vector<int8_t> codes(8 * 256, 1);
+ std::fill(codes.begin() + 4 * 256, codes.begin() + 6 * 256, 2);
+ std::fill(codes.begin() + 6 * 256, codes.end(), 3);
+ auto weight = ov::op::v0::Constant::create(ov::element::i8, {8, 256}, codes);
+ std::vector<float> scales(8 * 8, 0.25f);
+ std::fill(scales.begin() + 4 * 8, scales.begin() + 6 * 8, 0.5f);
+ std::fill(scales.begin() + 6 * 8, scales.end(), 0.75f);
+ auto scale = ov::op::v0::Constant::create(ov::element::f16, {8, 8}, scales);
+ auto fc = std::make_shared<ov::intel_gpu::op::FullyConnectedCompressed>(input, weight, std::make_shared<ov::intel_gpu::op::Placeholder>(), scale);
+ auto split = std::make_shared<ov::op::v1::VariadicSplit>(fc,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {2}),
+ ov::op::v0::Constant::create(ov::element::i64, {3}, {4, 2, 2}));
+ ov::ResultVector results;
+ for (size_t i = 0; i < 3; ++i) {
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(
+ split->output(i), ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 0, -1}), true);
+ results.push_back(std::make_shared<ov::op::v0::Result>(reshape));
+ }
+ model_ref = std::make_shared<ov::Model>(results, ov::ParameterVector{input});
+}