interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-openvino / ggml-quants.cpp

1373 lines · 65144 bytes Raw Blame History
1#include "ggml-quants.h"
2
3#include "ggml-common.h"
4#include "ggml-impl.h"
5#include "ggml-openvino-extra.h"
6#include "ggml.h"
7
8#include <algorithm>
9#include <cassert>
10#include <cmath>
11#include <cstddef>
12#include <cstdint>
13#include <limits>
14#include <memory>
15#include <openvino/core/except.hpp>
16#include <openvino/core/node.hpp>
17#include <openvino/core/node_output.hpp>
18#include <openvino/core/parallel.hpp>
19#include <openvino/core/shape.hpp>
20#include <openvino/core/type/element_type.hpp>
21#include <openvino/core/type/element_type_traits.hpp>
22#include <openvino/core/type/float16.hpp>
23#include <openvino/core/type/float4_e2m1.hpp>
24#include <openvino/core/type/float8_e8m0.hpp>
25#include <openvino/op/add.hpp>
26#include <openvino/op/constant.hpp>
27#include <openvino/op/convert.hpp>
28#include <openvino/op/multiply.hpp>
29#include <openvino/op/reshape.hpp>
30#include <openvino/op/subtract.hpp>
31#include <openvino/op/util/attr_types.hpp>
32#include <openvino/pass/constant_folding.hpp>
33#include <openvino/runtime/tensor.hpp>
34#include <string>
35#include <vector>
36
37// From <openvino>/src/common/transformations/include/transformations/utils/utils.hpp
38namespace ov::op::util {
39// From <openvino>/src/common/transformations/include/transformations/utils/utils.hpp
40bool get_single_value(const std::shared_ptr<ov::op::v0::Constant> & const_node,
41 float & value,
42 bool check_value_range = true);
43} // namespace ov::op::util
44
45namespace {
46void unpack_32_4(const uint8_t * data, uint8_t * dst) {
47 std::fill_n(dst, 16, 0);
48 for (int j = 0; j < 16; ++j) {
49 uint8_t x = (data[j] & 0x0F);
50 uint8_t y = (data[j] >> 4);
51 if (j % 2 != 0) {
52 x <<= 4;
53 y <<= 4;
54 }
55 dst[j / 2] |= x;
56 dst[8 + j / 2] |= y; // Last 16 weights are in the higher bits
57 }
58}
59
60constexpr size_t MXFP4_BLOCK_SIZE = 32;
61constexpr size_t MXFP4_BLOCK_QS_SIZE = MXFP4_BLOCK_SIZE / 2;
62constexpr size_t MXFP4_BLOCK_BYTES = sizeof(uint8_t) + MXFP4_BLOCK_QS_SIZE;
63
64void pack_32_mxfp4_for_openvino(const uint8_t * data, uint8_t * dst) {
65 for (int j = 0; j < static_cast<int>(MXFP4_BLOCK_QS_SIZE); j += 2) {
66 const uint8_t v0 = data[j] & 0x0F;
67 const uint8_t v1 = (data[j + 1] & 0x0F) << 4;
68 const uint8_t v16 = data[j] >> 4;
69 const uint8_t v17 = data[j + 1] & 0xF0;
70 dst[j / 2] = v0 | v1;
71 dst[MXFP4_BLOCK_SIZE / 4 + j / 2] = v16 | v17;
72 }
73}
74
75void extract_mxfp4_data(const ggml_tensor * tensor, ov::Tensor & weights_arr, ov::Tensor & scales_arr) {
76 GGML_ASSERT(tensor->type == GGML_TYPE_MXFP4);
77 GGML_ASSERT(weights_arr.get_element_type() == ov::element::f4e2m1);
78 GGML_ASSERT(scales_arr.get_element_type() == ov::element::f8e8m0);
79
80 const auto * data = static_cast<const uint8_t *>(tensor->data);
81 auto * weights = static_cast<uint8_t *>(weights_arr.data());
82 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f8e8m0>::value_type>();
83 const size_t n_blocks = scales_arr.get_size();
84
85 ov::parallel_for(n_blocks, [&](size_t i) {
86 const uint8_t * block = data + i * MXFP4_BLOCK_BYTES;
87 pack_32_mxfp4_for_openvino(block + sizeof(uint8_t), weights + i * MXFP4_BLOCK_QS_SIZE);
88 scales[i] = ov::float8_e8m0::from_bits(block[0]);
89 });
90}
91
92// Extracts (weight, scales, zp) from Q4_0 tensors.
93// Data layout is: |16 bit scale|32 x 4bit weights|.
94// When zp_arr is empty (symmetric), weights are stored as signed i4 (value - 8).
95void extract_q4_0_data(const ggml_tensor * tensor,
96 ov::Tensor & weights_arr,
97 ov::Tensor & scales_arr,
98 ov::Tensor & zp_arr) {
99 const uint64_t bytes_per_block = 18; // 2 bytes scale, 32x0.5 byte weights
100
101 auto * data = static_cast<uint8_t *>(tensor->data);
102 auto * weights = static_cast<uint8_t *>(weights_arr.data());
103 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
104
105 bool is_symmetric = (weights_arr.get_element_type() == ov::element::i4); // Signed i4 path
106
107 if (!is_symmetric) {
108 auto * zp = static_cast<uint8_t *>(zp_arr.data());
109 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
110 scales[i] = ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)));
111 // Pack two 4-bit zero points per byte
112 if (i % 2 == 0) {
113 zp[i / 2] = 8; // Lower nibble
114 } else {
115 zp[i / 2] |= (8 << 4); // Upper nibble
116 }
117 unpack_32_4(data + i * bytes_per_block + 2, weights + i * 16);
118 });
119 } else {
120 // Symmetric: unpack as u4 then convert to i4 by subtracting 8 (XOR each nibble)
121 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
122 scales[i] = ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)));
123 unpack_32_4(data + i * bytes_per_block + 2, weights + i * 16);
124 // Convert u4 to i4: subtract 8 from each nibble. XOR 0x88 flips each nibble by 8.
125 for (int j = 0; j < 16; ++j) {
126 weights[i * 16 + j] ^= 0x88;
127 }
128 });
129 }
130}
131
132// Extracts (weight, scales, zp) from Q4_1 tensors.
133// Data layout is: |16 bit scale|16 bit min|32 x 4bit weights|.
134void extract_q4_1_data(const ggml_tensor * tensor,
135 ov::Tensor & weights_arr,
136 ov::Tensor & scales_arr,
137 ov::Tensor & zp_arr,
138 bool use_bias) {
139 const uint64_t bytes_per_block = 20; // 2 bytes scale, 2 bytes min, 32x0.5 byte weights
140
141 auto * data = static_cast<uint8_t *>(tensor->data);
142 auto * weights = static_cast<uint8_t *>(weights_arr.data());
143 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
144
145 if (use_bias) {
146 // Store bias (min) directly as f16 instead of computing u4 zero points
147 auto * bias = zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
148 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
149 float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
150 float min = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
151 scales[i] = ov::float16(scale);
152 bias[i] = ov::float16(min); // bias = min, dequant: w*s + bias
153 unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
154 });
155 } else {
156 auto * zp = static_cast<uint8_t *>(zp_arr.data());
157 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
158 float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
159 float min = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
160 scales[i] = ov::float16(scale);
161 // zp = -min / scale (bias = min, so zp = -bias/scale)
162 uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0;
163 // Pack two 4-bit zero points per byte
164 if (i % 2 == 0) {
165 zp[i / 2] = zp_val & 0x0F; // Lower nibble
166 } else {
167 zp[i / 2] |= (zp_val << 4); // Upper nibble
168 }
169 unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
170 });
171 }
172}
173
174// Extracts (weight, scales, zp) from Q5_1 tensors.
175// Data layout is: |16 bit scale|16 bit min|32 bit qh (5th bits)|32 x 4bit low nibbles|.
176// Reconstructed quant q in [0,31]: q = (low nibble) | (qh_bit << 4). Dequant: w*d + m.
177// Weights are stored as u8 (5-bit values do not fit u4), matching make_int8_weights.
178void extract_q5_1_data(const ggml_tensor * tensor,
179 ov::Tensor & weights_arr,
180 ov::Tensor & scales_arr,
181 ov::Tensor & zp_arr,
182 bool use_bias) {
183 const uint64_t bytes_per_block = 24; // 2 scale + 2 min + 4 qh + 16 (32x0.5) weights
184 const int qk = 32;
185
186 auto * data = static_cast<uint8_t *>(tensor->data);
187 auto * weights = static_cast<uint8_t *>(weights_arr.data()); // u8 weights, one byte per weight
188 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
189
190 // Read a 16-bit little-endian value without aliasing/const-qual violations.
191 auto read_u16 = [](const uint8_t * p) {
192 uint16_t v;
193 memcpy(&v, p, sizeof(v));
194 return v;
195 };
196
197 auto unpack_block = [&](const uint8_t * block, uint8_t * dst) {
198 uint32_t qh;
199 memcpy(&qh, block + 4, sizeof(uint32_t));
200 const uint8_t * qs = block + 8;
201 for (int j = 0; j < qk / 2; ++j) {
202 const uint8_t lo = qs[j] & 0x0F;
203 const uint8_t hi = qs[j] >> 4;
204 const uint8_t bit_lo = (qh >> j) & 1;
205 const uint8_t bit_hi = (qh >> (j + qk / 2)) & 1;
206 dst[j] = lo | (bit_lo << 4); // first 16 weights
207 dst[j + qk / 2] = hi | (bit_hi << 4); // last 16 weights
208 }
209 };
210
211 if (use_bias) {
212 // Store bias (min) directly as f16: dequant w*d + m
213 auto * bias = zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
214 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
215 const uint8_t * block = data + i * bytes_per_block;
216 float scale = static_cast<float>(ov::float16::from_bits(read_u16(block)));
217 float min = static_cast<float>(ov::float16::from_bits(read_u16(block + 2)));
218 scales[i] = ov::float16(scale);
219 bias[i] = ov::float16(min);
220 unpack_block(block, weights + i * qk);
221 });
222 } else {
223 auto * zp = static_cast<uint8_t *>(zp_arr.data()); // u8 zero points
224 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
225 const uint8_t * block = data + i * bytes_per_block;
226 float scale = static_cast<float>(ov::float16::from_bits(read_u16(block)));
227 float min = static_cast<float>(ov::float16::from_bits(read_u16(block + 2)));
228 scales[i] = ov::float16(scale);
229 // zp = -min / scale (dequant: (w - zp) * s == w*s + min)
230 zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0;
231 unpack_block(block, weights + i * qk);
232 });
233 }
234}
235
236// Extracts (weight, scales, zp) from Q8_0 tensors.
237// Data layout is: |16 bit scale|32 x 8bit weights|.
238// When zp_arr is empty (symmetric), weights are stored as signed i8 directly.
239void extract_q8_0_data(const ggml_tensor * tensor,
240 ov::Tensor & weights_arr,
241 ov::Tensor & scales_arr,
242 ov::Tensor & zp_arr) {
243 const uint64_t weights_per_block = 32;
244 const uint64_t bytes_per_block = 34; // 2 bytes scale, 32x1 byte weights
245
246 auto * data = static_cast<uint8_t *>(tensor->data);
247 auto * weights = static_cast<uint8_t *>(weights_arr.data());
248 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
249
250 bool is_symmetric = (weights_arr.get_element_type() == ov::element::i8); // Signed i8 path
251
252 if (!is_symmetric) {
253 auto * zp = static_cast<uint8_t *>(zp_arr.data());
254 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
255 uint8_t * block_data = data + i * bytes_per_block;
256 scales[i] = ov::float16::from_bits(*(uint16_t *) block_data);
257 zp[i] = 128;
258 for (size_t j = 0; j < weights_per_block; ++j) {
259 uint8_t x = block_data[j + 2];
260 x ^= 1 << 7; // Convert int8 to uint8 by flipping sign bit
261 weights[i * weights_per_block + j] = x;
262 }
263 });
264 } else {
265 // Symmetric: store original int8 values directly (no unsigned bias)
266 ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
267 uint8_t * block_data = data + i * bytes_per_block;
268 scales[i] = ov::float16::from_bits(*(uint16_t *) block_data);
269 // Copy int8 weights as-is (the tensor element type is i8)
270 memcpy(weights + i * weights_per_block, block_data + 2, weights_per_block);
271 });
272 }
273}
274
275void unpack_256_4(const uint8_t * data, uint8_t * dst) {
276 // Initialize the output array with zeros
277 std::fill_n(dst, 128, 0);
278
279 for (size_t i = 0; i < 4; ++i) {
280 for (int j = 0; j < 32; ++j) {
281 uint8_t x = (data[i * 32 + j] & 0x0F);
282 uint8_t y = (data[i * 32 + j] >> 4);
283 if (j % 2 != 0) {
284 x <<= 4;
285 y <<= 4;
286 }
287 dst[i * 32 + j / 2] |= x;
288 dst[i * 32 + 16 + j / 2] |= y; // Last 16 weights are in the higher bits
289 }
290 }
291}
292
293void extract_q4_k_data(const ggml_tensor * tensor,
294 ov::Tensor & weights_arr,
295 ov::Tensor & scales_arr,
296 ov::Tensor & zp_arr,
297 bool use_bias) {
298 const uint64_t bytes_per_block = 2 + 2 + 12 + 128;
299 const uint64_t n_super_block = tensor->nb[3] / bytes_per_block;
300
301 auto * data = static_cast<uint8_t *>(tensor->data);
302 auto * weights = static_cast<uint8_t *>(weights_arr.data());
303 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
304
305 // For bias path, zp_arr holds f16 bias values; for zp path, it holds packed u4 zero points
306 auto * zp_u4 = use_bias ? nullptr : static_cast<uint8_t *>(zp_arr.data());
307 auto * bias_f16 = use_bias ? zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>() : nullptr;
308
309 ov::parallel_for(n_super_block, [&](size_t i) {
310 uint8_t * block_data = data + i * bytes_per_block;
311
312 // Extract scale factors and offsets
313 float scale_scales = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data)));
314 float scale_mins = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data + 1)));
315
316 // Extract qs1 and qs2
317 uint8_t * qs1 = block_data + 4;
318
319 // Calculate scales
320 float scale_vals[8];
321 scale_vals[0] = scale_scales * static_cast<float>((*(qs1) & 0b111111));
322 scale_vals[1] = scale_scales * static_cast<float>((*(qs1 + 1) & 0b111111));
323 scale_vals[2] = scale_scales * static_cast<float>((*(qs1 + 2) & 0b111111));
324 scale_vals[3] = scale_scales * static_cast<float>((*(qs1 + 3) & 0b111111));
325 scale_vals[4] = scale_scales * static_cast<float>((*(qs1 + 8) & 0b00001111) | ((*(qs1) >> 6) << 4));
326 scale_vals[5] = scale_scales * static_cast<float>((*(qs1 + 9) & 0b00001111) | ((*(qs1 + 1) >> 6) << 4));
327 scale_vals[6] = scale_scales * static_cast<float>((*(qs1 + 10) & 0b00001111) | ((*(qs1 + 2) >> 6) << 4));
328 scale_vals[7] = scale_scales * static_cast<float>((*(qs1 + 11) & 0b00001111) | ((*(qs1 + 3) >> 6) << 4));
329
330 // Calculate min values (bias = -min)
331 float min_vals[8];
332 min_vals[0] = scale_mins * static_cast<float>((*(qs1 + 4) & 0b111111));
333 min_vals[1] = scale_mins * static_cast<float>((*(qs1 + 5) & 0b111111));
334 min_vals[2] = scale_mins * static_cast<float>((*(qs1 + 6) & 0b111111));
335 min_vals[3] = scale_mins * static_cast<float>((*(qs1 + 7) & 0b111111));
336 min_vals[4] = scale_mins * static_cast<float>((*(qs1 + 8) >> 4) | ((*(qs1 + 4) >> 6) << 4));
337 min_vals[5] = scale_mins * static_cast<float>((*(qs1 + 9) >> 4) | ((*(qs1 + 5) >> 6) << 4));
338 min_vals[6] = scale_mins * static_cast<float>((*(qs1 + 10) >> 4) | ((*(qs1 + 6) >> 6) << 4));
339 min_vals[7] = scale_mins * static_cast<float>((*(qs1 + 11) >> 4) | ((*(qs1 + 7) >> 6) << 4));
340
341 // Store scales and compute zero points or bias
342 for (int j = 0; j < 8; j++) {
343 scales[i * 8 + j] = ov::float16(scale_vals[j]);
344 if (use_bias) {
345 // Store bias = -min directly as f16, dequant: w*s + bias
346 bias_f16[i * 8 + j] = ov::float16(-min_vals[j]);
347 } else {
348 // zp = min / scale (since bias = -min and zp = -bias/scale)
349 uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0;
350 // Pack two 4-bit zero points per byte
351 size_t idx = i * 8 + j;
352 if (idx % 2 == 0) {
353 zp_u4[idx / 2] = zp_val & 0x0F;
354 } else {
355 zp_u4[idx / 2] |= (zp_val << 4);
356 }
357 }
358 }
359 unpack_256_4(block_data + 16, weights + i * 128);
360 });
361}
362
363void extract_q6_k_data(const ggml_tensor * tensor,
364 ov::Tensor & weights_arr,
365 ov::Tensor & scales_arr,
366 ov::Tensor & zp_arr) {
367 const uint64_t bytes_per_block = 128 + 64 + 16 + 2;
368 const uint64_t n_super_block = tensor->nb[3] / bytes_per_block;
369
370 auto * data = static_cast<uint8_t *>(tensor->data);
371 auto * weights = static_cast<uint8_t *>(weights_arr.data());
372 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
373
374 bool is_symmetric = (weights_arr.get_element_type() == ov::element::i8); // Signed i8 path
375
376 if (!is_symmetric) {
377 auto * zp = static_cast<uint8_t *>(zp_arr.data());
378 ov::parallel_for(n_super_block, [&](size_t i) {
379 uint8_t * block_data = data + i * bytes_per_block;
380 float scale_factor = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data + 104)));
381 for (size_t j = 0; j < 16; j++) {
382 scales[j + i * 16] =
383 ov::float16(scale_factor * static_cast<float>(*((int8_t *) (block_data + 128 + 64 + j))));
384 zp[j + i * 16] = 32;
385 }
386 uint8_t * ql = block_data;
387 uint8_t * qh = block_data + 128;
388 for (int64_t j = 0; j < 32; ++j) {
389 weights[i * 256 + j] = (ql[j] & 0xF) | (((qh[j] >> 0) & 3) << 4);
390 weights[i * 256 + j + 32] = (ql[32 + j] & 0xF) | (((qh[j] >> 2) & 3) << 4);
391 weights[i * 256 + j + 64] = (ql[j] >> 4) | (((qh[j] >> 4) & 3) << 4);
392 weights[i * 256 + j + 96] = (ql[32 + j] >> 4) | (((qh[j] >> 6) & 3) << 4);
393 weights[i * 256 + j + 128] = (ql[64 + j] & 0xF) | (((qh[32 + j] >> 0) & 3) << 4);
394 weights[i * 256 + j + 160] = (ql[96 + j] & 0xF) | (((qh[32 + j] >> 2) & 3) << 4);
395 weights[i * 256 + j + 192] = (ql[64 + j] >> 4) | (((qh[32 + j] >> 4) & 3) << 4);
396 weights[i * 256 + j + 224] = (ql[96 + j] >> 4) | (((qh[32 + j] >> 6) & 3) << 4);
397 }
398 });
399 } else {
400 // Symmetric: subtract 32 from each weight to store as signed i8
401 ov::parallel_for(n_super_block, [&](size_t i) {
402 uint8_t * block_data = data + i * bytes_per_block;
403 float scale_factor = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data + 104)));
404 for (size_t j = 0; j < 16; j++) {
405 scales[j + i * 16] =
406 ov::float16(scale_factor * static_cast<float>(*((int8_t *) (block_data + 128 + 64 + j))));
407 }
408 uint8_t * ql = block_data;
409 uint8_t * qh = block_data + 128;
410 auto * signed_weights = reinterpret_cast<int8_t *>(weights);
411 for (int64_t j = 0; j < 32; ++j) {
412 signed_weights[i * 256 + j] = static_cast<int8_t>((ql[j] & 0xF) | (((qh[j] >> 0) & 3) << 4)) - 32;
413 signed_weights[i * 256 + j + 32] =
414 static_cast<int8_t>((ql[32 + j] & 0xF) | (((qh[j] >> 2) & 3) << 4)) - 32;
415 signed_weights[i * 256 + j + 64] = static_cast<int8_t>((ql[j] >> 4) | (((qh[j] >> 4) & 3) << 4)) - 32;
416 signed_weights[i * 256 + j + 96] =
417 static_cast<int8_t>((ql[32 + j] >> 4) | (((qh[j] >> 6) & 3) << 4)) - 32;
418 signed_weights[i * 256 + j + 128] =
419 static_cast<int8_t>((ql[64 + j] & 0xF) | (((qh[32 + j] >> 0) & 3) << 4)) - 32;
420 signed_weights[i * 256 + j + 160] =
421 static_cast<int8_t>((ql[96 + j] & 0xF) | (((qh[32 + j] >> 2) & 3) << 4)) - 32;
422 signed_weights[i * 256 + j + 192] =
423 static_cast<int8_t>((ql[64 + j] >> 4) | (((qh[32 + j] >> 4) & 3) << 4)) - 32;
424 signed_weights[i * 256 + j + 224] =
425 static_cast<int8_t>((ql[96 + j] >> 4) | (((qh[32 + j] >> 6) & 3) << 4)) - 32;
426 }
427 });
428 }
429}
430
431inline void get_scale_min_k4(int j, const uint8_t * q, uint8_t * d, uint8_t * m) {
432 if (j < 4) {
433 *d = q[j] & 63;
434 *m = q[j + 4] & 63;
435 } else {
436 *d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
437 *m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
438 }
439}
440
441void extract_q5_k_data(const ggml_tensor * tensor,
442 ov::Tensor & weights_arr,
443 ov::Tensor & scales_arr,
444 ov::Tensor & zp_arr,
445 bool use_bias) {
446 const uint64_t bytes_per_block = 4 + 12 + 32 + 128;
447 const uint64_t n_super_block = tensor->nb[3] / bytes_per_block;
448
449 auto * data = static_cast<uint8_t *>(tensor->data);
450 auto * weights = static_cast<uint8_t *>(weights_arr.data());
451 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
452
453 // For bias path, zp_arr holds f16 bias values; for zp path, it holds u8 zero points
454 auto * zp_u8 = use_bias ? nullptr : static_cast<uint8_t *>(zp_arr.data());
455 auto * bias_f16 = use_bias ? zp_arr.data<ov::element_type_traits<ov::element::f16>::value_type>() : nullptr;
456
457 ov::parallel_for(n_super_block, [&](size_t i) {
458 uint8_t * block_data = data + i * bytes_per_block;
459
460 const float d = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data)));
461 const float min_factor = static_cast<float>(ov::float16::from_bits(*((uint16_t *) block_data + 1)));
462
463 const uint8_t * scales_data = block_data + 4; // 12 bytes of scales
464 const uint8_t * qh = block_data + 4 + 12; // 32 bytes of high bits
465 const uint8_t * ql = block_data + 4 + 12 + 32; // 128 bytes of low bits
466
467 int is = 0;
468 uint8_t u1 = 1;
469 uint8_t u2 = 2;
470
471 // Process 2 blocks in one iteration
472 for (int j = 0; j < 256; j += 64) { // 256 = QK_K, so 4 iterations of 64
473 uint8_t sc;
474 uint8_t m;
475
476 // Get scale and min for first 32 elements
477 get_scale_min_k4(is + 0, scales_data, &sc, &m);
478 const float d1 = d * sc;
479 const float m1 = min_factor * m;
480
481 // Get scale and min for second 32 elements
482 get_scale_min_k4(is + 1, scales_data, &sc, &m);
483 const float d2 = d * sc;
484 const float m2 = min_factor * m;
485
486 scales[i * 8 + is] = ov::float16(d1);
487 scales[i * 8 + is + 1] = ov::float16(d2);
488 if (use_bias) {
489 // Store bias = -min directly as f16, dequant: w*s + bias
490 bias_f16[i * 8 + is] = ov::float16(-m1);
491 bias_f16[i * 8 + is + 1] = ov::float16(-m2);
492 } else {
493 // zp = min / scale (since bias = -min and zp = -bias/scale)
494 zp_u8[i * 8 + is] = (d1 != 0.0f) ? (uint8_t) std::round(m1 / d1) : 0;
495 zp_u8[i * 8 + is + 1] = (d2 != 0.0f) ? (uint8_t) std::round(m2 / d2) : 0;
496 }
497
498 // Extract weights for first 32 elements (matching deq formula exactly)
499 for (int l = 0; l < 32; ++l) {
500 weights[i * 256 + j + l] = (ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0);
501 }
502
503 // Extract weights for second 32 elements
504 for (int l = 0; l < 32; ++l) {
505 weights[i * 256 + j + l + 32] = (ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0);
506 }
507
508 ql += 32;
509 is += 2;
510 u1 <<= 2;
511 u2 <<= 2;
512 }
513 });
514}
515
516// TODO Reorder for make_intX_weights
517
518// If for_gather_matmul is true, weight may be N-D (e.g. 3D MoE expert weights [n_expert, rows, cols]).
519// The dequantization chain below is built as usual but left in f16 (no final Convert to f32) --
520// ov::pass::MarkDequantization (registered in translate_session.cpp) marks the chain so it survives
521// model-build-time ConstantFolding. mul_mat_id.cpp constructs ov::op::internal::GatherMatmul directly
522// on top of the resulting f16 chain.
523ov::Output<ov::Node> make_int8_weights(ov::Tensor & weight,
524 ov::Tensor & scales,
525 ov::Tensor & zp,
526 size_t group_size = GGML_QUANTIZATION_GROUP_SIZE,
527 bool use_bias = false,
528 bool for_gather_matmul = false) {
529 ov::Shape orig_shape = weight.get_shape();
530 bool is_signed = (weight.get_element_type() == ov::element::i8); // Symmetric: signed weights, no ZP
531
532 // Expand dimensions for scales and zp/bias
533 auto scale_shape = scales.get_shape();
534
535 // Group the innermost (last) dimension. For 2D weights [rows, cols] this yields
536 // [rows, cols/group_size, group_size]; for 3D MoE experts [n_expert, rows, cols] this yields
537 // [n_expert, rows, cols/group_size, group_size].
538 ov::Shape packed_shape = orig_shape;
539 packed_shape.back() /= group_size;
540 packed_shape.push_back(group_size);
541 const size_t group_dim = packed_shape.size() - 2;
542
543 if (packed_shape[group_dim] == 1) {
544 // Requantized channel-wise case
545 packed_shape.erase(packed_shape.begin() + group_dim);
546 } else {
547 scale_shape.push_back(1);
548 scales.set_shape(scale_shape);
549 if (!is_signed && zp.get_size() > 0) {
550 auto zp_shape = zp.get_shape();
551 zp_shape.push_back(1);
552 zp.set_shape(zp_shape);
553 }
554 }
555
556 auto scales_f16 = std::make_shared<ov::op::v0::Constant>(scales);
557
558 ov::Output<ov::Node> result;
559 if (is_signed) {
560 // Signed path: q * s (no zero point subtraction needed)
561 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::i8, packed_shape,
562 static_cast<uint8_t *>(weight.data()), nullptr);
563 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
564 auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
565 auto mul = std::make_shared<ov::op::v1::Multiply>(weights_f16, scales_f16, ov::op::AutoBroadcastType::NUMPY);
566 result = mul;
567 } else {
568 // Unsigned path
569 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::u8, packed_shape,
570 static_cast<uint8_t *>(weight.data()), nullptr);
571 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
572 auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
573
574 if (use_bias && zp.get_size() > 0) {
575 // Accurate dequant in the FUSABLE zero-point form: (w - zp) * s, where the zero
576 // point is an exact f16 value zp = -bias/scale (the zp tensor holds bias values
577 // coming in). Algebraically equal to w*s + bias, but unlike an Add(bias) graph this
578 // matches CompressedWeightsBlock's pattern (Constant->Convert->Subtract->Multiply),
579 // so for_gather_matmul weights still fuse into GatherMatmulCompressed. Also avoids
580 // the round(min/scale) error of an integer zero point. Convert bias -> zero-point IN
581 // PLACE in the (possibly buffer-backed) zp tensor to avoid a duplicate allocation.
582 auto * bias_zp_data = zp.data<ov::float16>();
583 const auto * scale_data = scales.data<ov::float16>();
584 const size_t n = zp.get_size();
585 for (size_t i = 0; i < n; i++) {
586 float s = static_cast<float>(scale_data[i]);
587 float b = static_cast<float>(bias_zp_data[i]);
588 bias_zp_data[i] = ov::float16(s != 0.0f ? -b / s : 0.0f);
589 }
590 auto zero_point_f16 = std::make_shared<ov::op::v0::Constant>(zp);
591 auto w_zp =
592 std::make_shared<ov::op::v1::Subtract>(weights_f16, zero_point_f16, ov::op::AutoBroadcastType::NUMPY);
593 result = std::make_shared<ov::op::v1::Multiply>(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY);
594 } else {
595 // Zero point path: (w - zp) * s
596 auto zero_point = std::make_shared<ov::op::v0::Constant>(zp);
597 float zp_value;
598 if (ov::op::util::get_single_value(zero_point, zp_value)) {
599 zero_point = ov::op::v0::Constant::create(zero_point->get_element_type(), {}, {zp_value});
600 }
601 auto zero_point_f16 = std::make_shared<ov::op::v0::Convert>(zero_point, ov::element::f16);
602 auto w_zp =
603 std::make_shared<ov::op::v1::Subtract>(weights_f16, zero_point_f16, ov::op::AutoBroadcastType::NUMPY);
604 auto mul = std::make_shared<ov::op::v1::Multiply>(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY);
605 result = mul;
606 }
607 }
608
609 if (packed_shape.size() != orig_shape.size()) {
610 // If not requantized channel-wise case, reshape back to original shape
611 auto final_shape =
612 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_shape.size()}, orig_shape);
613 auto reshaped = std::make_shared<ov::op::v1::Reshape>(result, final_shape, false);
614 result = reshaped;
615 }
616
617 if (for_gather_matmul) {
618 return result;
619 }
620 return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
621}
622
623// If for_gather_matmul is true, the weight tensor may be N-D (e.g. 3D MoE expert weights
624// [n_expert, rows, cols]). The dequantization chain (Convert->[Subtract]->Multiply) is built as
625// usual but left in f16 (no final Convert to f32) -- ov::pass::MarkDequantization (registered in
626// translate_session.cpp) marks the chain so it survives model-build-time ConstantFolding -- see
627// make_int8_weights.cpp/make_int4_weights.cpp. mul_mat_id.cpp constructs ov::op::internal::GatherMatmul
628// directly from the resulting f16 dequant chain.
629//
630// When use_bias is true (explicitly, or implicitly because for_gather_matmul is true), the zp
631// tensor is expected to hold an exact f16 bias value (rather than a rounded integer zero point);
632// it is converted in place into an exact zero_point = -bias/scale and consumed via Subtract, not
633// Add, so the chain still matches OpenVINO's Convert->Subtract->Multiply decompression pattern.
634// See make_int8_weights for the meaning of for_gather_matmul.
635ov::Output<ov::Node> make_int4_weights(ov::Tensor & weight,
636 ov::Tensor & scales,
637 ov::Tensor & zp,
638 size_t group_size = GGML_QUANTIZATION_GROUP_SIZE,
639 bool use_bias = false,
640 bool for_gather_matmul = false) {
641 ov::Shape orig_weight_shape = weight.get_shape();
642 bool is_signed = (weight.get_element_type() == ov::element::i4); // Symmetric: signed weights, no ZP
643
644 // Expand dimensions for scales and zp/bias
645 ov::Shape scale_shape = scales.get_shape();
646
647 // Create INT4 weight tensor. Group the innermost (last) dimension: for 2D weights
648 // [rows, cols] this yields [rows, cols/group_size, group_size]; for 3D MoE experts
649 // [n_expert, rows, cols] this yields [n_expert, rows, cols/group_size, group_size].
650 ov::Shape packed_shape = orig_weight_shape;
651 packed_shape.back() /= group_size;
652 packed_shape.push_back(group_size);
653 const size_t group_dim = packed_shape.size() - 2;
654
655 if (packed_shape[group_dim] == 1) {
656 // Requantized channel-wise case
657 packed_shape.erase(packed_shape.begin() + group_dim);
658 } else {
659 scale_shape.push_back(1);
660 scales.set_shape(scale_shape);
661 if (!is_signed && zp.get_size() > 0) {
662 auto zp_shape = zp.get_shape();
663 zp_shape.push_back(1);
664 zp.set_shape(zp_shape);
665 }
666 }
667
668 auto scales_f16 = std::make_shared<ov::op::v0::Constant>(scales);
669
670 ov::Output<ov::Node> result;
671 if (is_signed) {
672 // Signed path: q * s (no zero point subtraction needed)
673 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::i4, packed_shape,
674 static_cast<uint8_t *>(weight.data()), nullptr);
675 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
676 auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
677 auto mul = std::make_shared<ov::op::v1::Multiply>(weights_f16, scales_f16, ov::op::AutoBroadcastType::NUMPY);
678 result = mul;
679 } else {
680 // Unsigned path
681 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::u4, packed_shape,
682 static_cast<uint8_t *>(weight.data()), nullptr);
683 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
684 auto weights_f16 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f16);
685
686 if (use_bias && zp.get_size() > 0) {
687 // Accurate dequant in the FUSABLE zero-point form: (w - zp) * s with an exact f16
688 // zp = -bias/scale. Equivalent to w*s + bias but matches CompressedWeightsBlock's
689 // pattern so for_gather_matmul weights still fuse into GatherMatmulCompressed, and
690 // avoids the round(min/scale) error of an integer zp. Convert bias -> zero-point IN
691 // PLACE in the (possibly buffer-backed) zp tensor to avoid a duplicate allocation.
692 auto * bias_zp_data = zp.data<ov::float16>();
693 const auto * scale_data = scales.data<ov::float16>();
694 const size_t n = zp.get_size();
695 for (size_t i = 0; i < n; i++) {
696 float s = static_cast<float>(scale_data[i]);
697 float b = static_cast<float>(bias_zp_data[i]);
698 bias_zp_data[i] = ov::float16(s != 0.0f ? -b / s : 0.0f);
699 }
700 auto zero_points_f16 = std::make_shared<ov::op::v0::Constant>(zp);
701 auto w_zp =
702 std::make_shared<ov::op::v1::Subtract>(weights_f16, zero_points_f16, ov::op::AutoBroadcastType::NUMPY);
703 result = std::make_shared<ov::op::v1::Multiply>(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY);
704 } else {
705 // Zero point path: (w - zp) * s
706 auto zero_points_node = std::make_shared<ov::op::v0::Constant>(zp);
707 float zp_value;
708 if (ov::op::util::get_single_value(zero_points_node, zp_value)) {
709 zero_points_node = ov::op::v0::Constant::create(zero_points_node->get_element_type(), {}, {zp_value});
710 }
711 auto zero_points_f16 = std::make_shared<ov::op::v0::Convert>(zero_points_node, ov::element::f16);
712 auto w_zp =
713 std::make_shared<ov::op::v1::Subtract>(weights_f16, zero_points_f16, ov::op::AutoBroadcastType::NUMPY);
714 auto mul = std::make_shared<ov::op::v1::Multiply>(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY);
715 result = mul;
716 }
717 }
718
719 if (packed_shape.size() != orig_weight_shape.size()) {
720 // If not requantized channel-wise case, reshape back to original shape
721 auto final_shape = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{orig_weight_shape.size()},
722 orig_weight_shape);
723 auto reshaped = std::make_shared<ov::op::v1::Reshape>(result, final_shape, false);
724 result = reshaped;
725 }
726
727 if (for_gather_matmul) {
728 return result;
729 }
730 return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);
731}
732
733ov::Output<ov::Node> make_mxfp4_weights(ov::Tensor & weight, ov::Tensor & scales) {
734 const ov::Shape final_shape = weight.get_shape();
735 GGML_ASSERT(!final_shape.empty());
736 GGML_ASSERT(final_shape.back() % MXFP4_BLOCK_SIZE == 0);
737
738 ov::Shape packed_shape = final_shape;
739 packed_shape.back() /= MXFP4_BLOCK_SIZE;
740 packed_shape.push_back(MXFP4_BLOCK_SIZE);
741
742 ov::Shape scale_shape = packed_shape;
743 scale_shape.back() = 1;
744 scales.set_shape(scale_shape);
745
746 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::f4e2m1, packed_shape,
747 static_cast<uint8_t *>(weight.data()), nullptr);
748 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
749 auto weights_f32 = std::make_shared<ov::op::v0::Convert>(weights_node, ov::element::f32);
750
751 auto scales_node = std::make_shared<ov::op::v0::Constant>(scales);
752 auto scales_f32 = std::make_shared<ov::op::v0::Convert>(scales_node, ov::element::f32);
753 ov::Output<ov::Node> result =
754 std::make_shared<ov::op::v1::Multiply>(weights_f32, scales_f32, ov::op::AutoBroadcastType::NUMPY);
755
756 auto final_shape_node =
757 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{final_shape.size()}, final_shape);
758 return std::make_shared<ov::op::v1::Reshape>(result, final_shape_node, false);
759}
760
761ov::Output<ov::Node> make_mxfp4_moe_packed_weights(ov::Tensor & weight) {
762 auto weights_node = std::make_shared<ov::op::v0::Constant>(ov::element::u8, weight.get_shape(),
763 static_cast<uint8_t *>(weight.data()), nullptr);
764 weights_node->get_rt_info()["__gguf_tensor_holder"] = weight;
765 weights_node->get_rt_info()["__ggml_openvino_mxfp4_moe_packed"] = true;
766 return weights_node;
767}
768
769void quantize_q4_0(const float * x,
770 ov::Tensor & weights_arr,
771 ov::Tensor & scales_arr,
772 ov::Tensor & zp_arr,
773 int64_t k,
774 int64_t qk) {
775 assert(k % qk == 0);
776 const int nb = k / qk;
777
778 auto * weights = static_cast<uint8_t *>(weights_arr.data());
779 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
780 bool is_symmetric = (weights_arr.get_element_type() == ov::element::i4); // Signed i4 path
781
782 if (!is_symmetric) {
783 auto * zp = static_cast<uint8_t *>(zp_arr.data());
784 for (int i = 0; i < nb; i++) {
785 float amax = 0.0f;
786 float max = 0.0f;
787 for (int j = 0; j < qk; j++) {
788 const float v = x[i * qk + j];
789 if (amax < fabsf(v)) {
790 amax = fabsf(v);
791 max = v;
792 }
793 }
794 const float d = max / -8;
795 if (d == 0) {
796 scales[i] = ov::float16(1.0f);
797 if (i % 2 == 0) {
798 zp[i / 2] = 8;
799 } else {
800 zp[i / 2] |= (8 << 4);
801 }
802 memset(weights + i * qk / 2, 8 | (8 << 4), qk / 2);
803 continue;
804 }
805 const float id = 1.0f / d;
806 scales[i] = ov::float16(d);
807 if (i % 2 == 0) {
808 zp[i / 2] = 8;
809 } else {
810 zp[i / 2] |= (8 << 4);
811 }
812 for (int j = 0; j < qk / 2; ++j) {
813 const float x0 = x[i * qk + 2 * j] * id;
814 const float x1 = x[i * qk + 2 * j + 1] * id;
815 const uint8_t xi0 = MIN(15, (int8_t) (x0 + 8.5f));
816 const uint8_t xi1 = MIN(15, (int8_t) (x1 + 8.5f));
817 weights[i * qk / 2 + j] = xi0 | (xi1 << 4);
818 }
819 }
820 } else {
821 // Symmetric: produce signed i4 values in [-8, 7]
822 for (int i = 0; i < nb; i++) {
823 float amax = 0.0f;
824 float max = 0.0f;
825 for (int j = 0; j < qk; j++) {
826 const float v = x[i * qk + j];
827 if (amax < fabsf(v)) {
828 amax = fabsf(v);
829 max = v;
830 }
831 }
832 const float d = max / -8;
833 if (d == 0) {
834 scales[i] = ov::float16(1.0f);
835 // i4 value 0 packed: 0x00
836 memset(weights + i * qk / 2, 0, qk / 2);
837 continue;
838 }
839 const float id = 1.0f / d;
840 scales[i] = ov::float16(d);
841 for (int j = 0; j < qk / 2; ++j) {
842 const float x0 = x[i * qk + 2 * j] * id;
843 const float x1 = x[i * qk + 2 * j + 1] * id;
844 // Signed i4: range [-8, 7]. Quantize as round(x*id), then pack as 4-bit two's complement.
845 int8_t si0 = (int8_t) std::max(-8, std::min(7, (int) roundf(x0)));
846 int8_t si1 = (int8_t) std::max(-8, std::min(7, (int) roundf(x1)));
847 weights[i * qk / 2 + j] = (si0 & 0x0F) | ((si1 & 0x0F) << 4);
848 }
849 }
850 }
851}
852
853// Asymmetric u4 quantization with a per-group scale and zero point.
854//
855// Unlike quantize_q4_0's unsigned branch, which pins the zero point to 8 and is therefore
856// symmetric, this keeps a real per-group zero point, so a group whose values are not centred on
857// zero does not waste half its range.
858void quantize_q4_1_asym(const float * x,
859 ov::Tensor & weights_arr,
860 ov::Tensor & scales_arr,
861 ov::Tensor & zp_arr,
862 int64_t k,
863 int64_t qk) {
864 assert(k % qk == 0);
865 const int nb = k / qk;
866
867 auto * weights = static_cast<uint8_t *>(weights_arr.data());
868 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>();
869 auto * zp = static_cast<uint8_t *>(zp_arr.data());
870
871 // u4 zero points are packed two per byte, low nibble first, indexed by group -- the same
872 // convention as the unsigned branch of quantize_q4_0.
873 auto store_zp = [zp](int i, uint8_t v) {
874 if (i % 2 == 0) {
875 zp[i / 2] = v & 0x0F;
876 } else {
877 zp[i / 2] |= (uint8_t) ((v & 0x0F) << 4);
878 }
879 };
880
881 for (int i = 0; i < nb; i++) {
882 float vmin = x[i * qk];
883 float vmax = x[i * qk];
884 for (int j = 1; j < qk; j++) {
885 const float v = x[i * qk + j];
886 vmin = std::min(vmin, v);
887 vmax = std::max(vmax, v);
888 }
889 // Include 0 in the range so an all-positive or all-negative group still represents zero
890 // exactly -- these are weights, so an exact zero matters.
891 vmin = std::min(vmin, 0.0f);
892 vmax = std::max(vmax, 0.0f);
893
894 const float d = (vmax - vmin) / 15.0f;
895 if (d == 0.0f) {
896 scales[i] = ov::float16(1.0f);
897 store_zp(i, 0);
898 memset(weights + i * qk / 2, 0, qk / 2);
899 continue;
900 }
901 const float id = 1.0f / d;
902
903 // The zero point is itself a 4-bit integer, so round it and dequantize as (q - zq) * d.
904 const int zq = std::max(0, std::min(15, (int) lroundf(-vmin * id)));
905 scales[i] = ov::float16(d);
906 store_zp(i, (uint8_t) zq);
907
908 for (int j = 0; j < qk / 2; ++j) {
909 const float x0 = x[i * qk + 2 * j] * id;
910 const float x1 = x[i * qk + 2 * j + 1] * id;
911 const uint8_t q0 = (uint8_t) std::max(0, std::min(15, (int) lroundf(x0) + zq));
912 const uint8_t q1 = (uint8_t) std::max(0, std::min(15, (int) lroundf(x1) + zq));
913 weights[i * qk / 2 + j] = (uint8_t) (q0 | (q1 << 4));
914 }
915 }
916}
917
918void quantize_q8_0(const float * x,
919 ov::Tensor & weights_arr,
920 ov::Tensor & scales_arr,
921 ov::Tensor & zp_arr,
922 int64_t k,
923 int64_t qk,
924 int64_t block_offset = 0) {
925 assert(k % qk == 0);
926 const int nb = k / qk;
927
928 // block_offset lets a caller quantize a chunk of blocks into the right place in the
929 // output buffers (used for streaming requant). x points at this chunk's first block;
930 // outputs are advanced by block_offset blocks. Q8 has one scale/zp per block (no
931 // nibble packing), so any block boundary is safe.
932 auto * weights = static_cast<uint8_t *>(weights_arr.data()) + block_offset * qk;
933 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>() + block_offset;
934 bool is_symmetric = (weights_arr.get_element_type() == ov::element::i8); // Signed i8 path
935
936 if (!is_symmetric) {
937 auto * zp = static_cast<uint8_t *>(zp_arr.data()) + block_offset;
938 for (int i = 0; i < nb; i++) {
939 float amax = 0.0f;
940 for (int j = 0; j < qk; j++) {
941 const float v = x[i * qk + j];
942 amax = std::max(amax, fabsf(v));
943 }
944 const float d = amax / 127.0f;
945 const float id = d ? 1.0f / d : 0.0f;
946 scales[i] = ov::float16(d);
947 zp[i] = 128;
948 for (int j = 0; j < qk; ++j) {
949 const float x0 = x[i * qk + j] * id;
950 const int8_t xi0 = roundf(x0);
951 weights[i * qk + j] = (uint8_t) (xi0 + 128);
952 }
953 }
954 } else {
955 // Symmetric: store signed int8 values directly
956 auto * signed_weights = reinterpret_cast<int8_t *>(weights);
957 for (int i = 0; i < nb; i++) {
958 float amax = 0.0f;
959 for (int j = 0; j < qk; j++) {
960 const float v = x[i * qk + j];
961 amax = std::max(amax, fabsf(v));
962 }
963 const float d = amax / 127.0f;
964 const float id = d ? 1.0f / d : 0.0f;
965 scales[i] = ov::float16(d);
966 for (int j = 0; j < qk; ++j) {
967 const float x0 = x[i * qk + j] * id;
968 signed_weights[i * qk + j] = (int8_t) roundf(x0);
969 }
970 }
971 }
972}
973
974void quantize_q8_1(const float * x,
975 ov::Tensor & weights_arr,
976 ov::Tensor & scales_arr,
977 ov::Tensor & zp_arr,
978 int64_t k,
979 int64_t qk,
980 int64_t block_offset = 0) {
981 assert(k % qk == 0);
982 const int nb = k / qk;
983
984 // See quantize_q8_0: block_offset places this chunk's output at the right block.
985 auto * weights = static_cast<uint8_t *>(weights_arr.data()) + block_offset * qk;
986 auto * scales = scales_arr.data<ov::element_type_traits<ov::element::f16>::value_type>() + block_offset;
987 auto * zp = static_cast<uint8_t *>(zp_arr.data()) + block_offset;
988 for (int i = 0; i < nb; i++) {
989 float min = std::numeric_limits<float>::max();
990 float max = std::numeric_limits<float>::lowest();
991
992 for (int j = 0; j < qk; j++) {
993 const float v = x[i * qk + j];
994 min = std::min(v, min);
995 max = std::max(v, max);
996 }
997
998 const float d = (max - min) / ((1 << 8) - 1);
999 const float id = d ? 1.0f / d : 0.0f;
1000 scales[i] = ov::float16(d);
1001 // zp = -min / scale (Q8_1 is asymmetric)
1002 zp[i] = (d != 0.0f) ? (uint8_t) std::round(-min / d) : 0;
1003
1004 for (int j = 0; j < qk; ++j) {
1005 const float x0 = (x[i * qk + j] - min) * id;
1006 const uint8_t xi0 = roundf(x0);
1007 weights[i * qk + j] = xi0;
1008 }
1009 }
1010}
1011
1012// Extract quantized weights from tensor and create weight subgraph
1013// If weights/scales/zp are provided (non-empty), uses them as output buffers
1014// Otherwise allocates new ov::Tensors internally
1015// Returns the weight node (make_int4_weights or make_int8_weights result)
1016std::shared_ptr<ov::Node> extract_quantized_weights(const ggml_tensor * tensor,
1017 const void * data, // Source data pointer (may differ from tensor->data)
1018 ov::Tensor & weights,
1019 ov::Tensor & scales,
1020 ov::Tensor & zp,
1021 // Use an exact f16 zero point (vs. a rounded integer one); always
1022 // used for for_gather_matmul (3D MoE expert) weights regardless of
1023 // this flag, and also settable explicitly for test-backend-ops.
1024 bool use_bias = false) {
1025 // Create a temporary tensor for extraction functions that read from tensor->data
1026 ggml_tensor temp_tensor = *tensor;
1027 temp_tensor.data = const_cast<void *>(data);
1028
1029 if (tensor->type == GGML_TYPE_MXFP4) {
1030 extract_mxfp4_data(&temp_tensor, weights, scales);
1031 auto result = make_mxfp4_weights(weights, scales).get_node_shared_ptr();
1032 result->set_friendly_name(tensor->name);
1033 return result;
1034 }
1035
1036 // Determine block size based on tensor type
1037 int64_t weights_per_block;
1038 bool is_u4;
1039 switch (tensor->type) {
1040 case GGML_TYPE_Q4_0:
1041 case GGML_TYPE_Q4_1:
1042 case GGML_TYPE_Q4_K:
1043 is_u4 = true;
1044 weights_per_block = 32;
1045 break;
1046 case GGML_TYPE_Q8_0:
1047 case GGML_TYPE_Q5_1:
1048 case GGML_TYPE_Q5_K:
1049 is_u4 = false;
1050 weights_per_block = 32;
1051 break;
1052 case GGML_TYPE_Q6_K:
1053 is_u4 = false;
1054 weights_per_block = 16;
1055 break;
1056 default:
1057 throw std::runtime_error("Unsupported quantized type for extraction: " +
1058 std::string(ggml_type_name(tensor->type)));
1059 }
1060
1061 // 3D MoE expert weights (for_gather_matmul) always use the exact f16 zero-point extraction
1062 // (see make_int8_weights/make_int4_weights) rather than the rounded integer zero point --
1063 // round(min/scale) error is what corrupts Q4_K/Q5_1 experts, and the f16-zp form still fuses
1064 // into GatherMatmulCompressed since it stays a Subtract, not an Add.
1065 const bool for_gather_matmul = tensor->ne[2] > 1;
1066 use_bias = use_bias || for_gather_matmul;
1067
1068 // Extract quantized data
1069 switch (tensor->type) {
1070 case GGML_TYPE_Q4_0:
1071 extract_q4_0_data(&temp_tensor, weights, scales, zp);
1072 break;
1073 case GGML_TYPE_Q4_1:
1074 extract_q4_1_data(&temp_tensor, weights, scales, zp, use_bias);
1075 break;
1076 case GGML_TYPE_Q4_K:
1077 extract_q4_k_data(&temp_tensor, weights, scales, zp, use_bias);
1078 break;
1079 case GGML_TYPE_Q5_1:
1080 extract_q5_1_data(&temp_tensor, weights, scales, zp, use_bias);
1081 break;
1082 case GGML_TYPE_Q8_0:
1083 extract_q8_0_data(&temp_tensor, weights, scales, zp);
1084 break;
1085 case GGML_TYPE_Q6_K:
1086 extract_q6_k_data(&temp_tensor, weights, scales, zp);
1087 break;
1088 case GGML_TYPE_Q5_K:
1089 extract_q5_k_data(&temp_tensor, weights, scales, zp, use_bias);
1090 break;
1091 default:
1092 throw std::runtime_error("Unsupported quantized type: " + std::string(ggml_type_name(tensor->type)));
1093 }
1094
1095 // Create the OpenVINO weight subgraph. 3D expert weights (MoE) are routed through the
1096 // GatherMatmul-oriented path: dequantized in f16, with constant folding disabled on the chain.
1097 ov::Output<ov::Node> weight_node;
1098 if (is_u4) {
1099 weight_node = make_int4_weights(weights, scales, zp, weights_per_block, use_bias, for_gather_matmul);
1100 } else {
1101 weight_node = make_int8_weights(weights, scales, zp, weights_per_block, use_bias, for_gather_matmul);
1102 }
1103
1104 auto result = weight_node.get_node_shared_ptr();
1105 result->set_friendly_name(tensor->name);
1106 return result;
1107}
1108
1109// Requantize weights from tensor to target format, writing to provided buffers
1110// For F16 target, only weights buffer is used (scales/zp ignored)
1111// Returns the weight node
1112std::shared_ptr<ov::Node> requantize_to_buffers(const ggml_tensor * tensor,
1113 const void * data, // Source data pointer
1114 ExtraQuantType requant_type,
1115 int64_t block_size,
1116 ov::Tensor & weights,
1117 ov::Tensor & scales,
1118 ov::Tensor & zp) {
1119 int64_t n_elements = ggml_nelements(tensor);
1120 const int64_t ne0 = tensor->ne[0]; // elements per row
1121 const int64_t n_rows = n_elements / ne0;
1122 const auto * type_traits = ggml_get_type_traits(tensor->type);
1123 const size_t src_row_bytes = ggml_row_size(tensor->type, ne0);
1124
1125 bool is_u4 = (requant_type == ExtraQuantType::Q4_0_C || requant_type == ExtraQuantType::Q4_0_128 ||
1126 requant_type == ExtraQuantType::Q4_0_64 || requant_type == ExtraQuantType::Q4_1_64);
1127
1128 // Streaming dequant (opt-in via GGML_OPENVINO_REDUCE_COMPILE_MEM or
1129 // GGML_OPENVINO_MEMORY_OPTIMIZE): instead of
1130 // materializing the full n_elements F32 array (e.g. ~1 GB for token_embd), dequantize
1131 // a chunk of complete rows into a small scratch and quantize/convert it straight into
1132 // the output buffers, capping the transient F32 footprint at CHUNK_ROWS*ne0 floats.
1133 //
1134 // Only valid (and only used) for the Q8_0_C / Q8_1_C / F16 targets whose block size
1135 // divides a row (channel-wise _C uses block_size == ne0) so no target block straddles
1136 // a row boundary, and Q8/F16 have no cross-block packing. The u4 (Q4_0) path packs two
1137 // weights per byte with running zp ORs that assume a single whole-array call, so it is
1138 // never streamed. When the flag is off, behavior is identical to the original
1139 // full-materialization path.
1140 const bool stream_requant = ggml_openvino_reduce_compile_mem_enabled() && !is_u4 &&
1141 !(block_size > 0 && ne0 % block_size != 0);
1142
1143 if (!stream_requant) {
1144 // Full materialization (original behavior): dequantize the whole tensor to F32,
1145 // then convert/quantize in one call.
1146 std::vector<float> weights_f32(n_elements);
1147 type_traits->to_float(data, weights_f32.data(), n_elements);
1148 if (requant_type == ExtraQuantType::F16) {
1149 ggml_get_type_traits(GGML_TYPE_F16)->from_float_ref(weights_f32.data(), weights.data(), n_elements);
1150 auto result = std::make_shared<ov::op::v0::Constant>(weights);
1151 result->set_friendly_name(tensor->name);
1152 return result;
1153 }
1154 if (requant_type == ExtraQuantType::Q4_1_64) {
1155 quantize_q4_1_asym(weights_f32.data(), weights, scales, zp, n_elements, block_size);
1156 } else if (is_u4) {
1157 quantize_q4_0(weights_f32.data(), weights, scales, zp, n_elements, block_size);
1158 } else if (requant_type == ExtraQuantType::Q8_1_C) {
1159 quantize_q8_1(weights_f32.data(), weights, scales, zp, n_elements, block_size);
1160 } else {
1161 quantize_q8_0(weights_f32.data(), weights, scales, zp, n_elements, block_size);
1162 }
1163 } else {
1164 // Streaming path for Q8_0_C / Q8_1_C / F16 (covers token_embd, output.weight,
1165 // and per-layer Q6_K/Q5_K requant — the large transient cases).
1166 const int64_t CHUNK_ROWS = std::min<int64_t>(n_rows, 256);
1167 std::vector<float> scratch(CHUNK_ROWS * ne0);
1168 // F16 destination: 2 bytes/element, advanced per chunk by r0*ne0 elements.
1169 auto * f16_base = static_cast<uint8_t *>(weights.data());
1170 for (int64_t r0 = 0; r0 < n_rows; r0 += CHUNK_ROWS) {
1171 const int64_t rows = std::min(CHUNK_ROWS, n_rows - r0);
1172 const int64_t elems = rows * ne0;
1173 const auto * src = static_cast<const uint8_t *>(data) + r0 * src_row_bytes;
1174 type_traits->to_float(src, scratch.data(), elems);
1175
1176 if (requant_type == ExtraQuantType::F16) {
1177 ggml_get_type_traits(GGML_TYPE_F16)
1178 ->from_float_ref(scratch.data(), f16_base + (r0 * ne0) * sizeof(uint16_t), elems);
1179 } else {
1180 const int64_t block_offset = (r0 * ne0) / block_size;
1181 if (requant_type == ExtraQuantType::Q8_1_C) {
1182 quantize_q8_1(scratch.data(), weights, scales, zp, elems, block_size, block_offset);
1183 } else {
1184 quantize_q8_0(scratch.data(), weights, scales, zp, elems, block_size, block_offset);
1185 }
1186 }
1187 }
1188 if (requant_type == ExtraQuantType::F16) {
1189 auto result = std::make_shared<ov::op::v0::Constant>(weights);
1190 result->set_friendly_name(tensor->name);
1191 return result;
1192 }
1193 }
1194
1195 // Create the OpenVINO weight subgraph
1196 ov::Output<ov::Node> weight_node;
1197 if (is_u4) {
1198 weight_node = make_int4_weights(weights, scales, zp, block_size);
1199 } else {
1200 weight_node = make_int8_weights(weights, scales, zp, block_size);
1201 }
1202
1203 auto result = weight_node.get_node_shared_ptr();
1204 result->set_friendly_name(tensor->name);
1205 return result;
1206}
1207} // namespace
1208
1209OvWeight process_weight_tensor(const ggml_tensor * tensor, const void * data, void * output_base_ptr, bool use_bias) {
1210 GGML_ASSERT(tensor != nullptr);
1211 GGML_ASSERT(data != nullptr);
1212
1213 OvWeight result;
1214
1215 // Get shape for weights: [rows, cols], or [n_expert, rows, cols] for 3D MoE expert weights.
1216 ov::Shape node_shape = (tensor->ne[2] > 1) ?
1217 ov::Shape{static_cast<size_t>(tensor->ne[2]), static_cast<size_t>(tensor->ne[1]),
1218 static_cast<size_t>(tensor->ne[0])} :
1219 ov::Shape{static_cast<size_t>(tensor->ne[1]), static_cast<size_t>(tensor->ne[0])};
1220
1221 // Handle F16/F32/BF16 weights
1222 if (tensor->type == GGML_TYPE_F32 || tensor->type == GGML_TYPE_F16 || tensor->type == GGML_TYPE_BF16) {
1223 ov::element::Type element_type;
1224 switch (tensor->type) {
1225 case GGML_TYPE_F32:
1226 element_type = ov::element::f32;
1227 break;
1228 case GGML_TYPE_F16:
1229 element_type = ov::element::f16;
1230 break;
1231 case GGML_TYPE_BF16:
1232 element_type = ov::element::bf16;
1233 break;
1234 default:
1235 OPENVINO_THROW("Unexpected tensor type in F16/F32/BF16 path");
1236 }
1237
1238 if (output_base_ptr && output_base_ptr != data) {
1239 // Using external buffer - copy data and create shared-memory constant
1240 size_t tensor_bytes = ggml_nbytes(tensor);
1241 memcpy(output_base_ptr, data, tensor_bytes);
1242 result.weights = ov::Tensor(element_type, node_shape, output_base_ptr);
1243 } else {
1244 result.weights = ov::Tensor(element_type, node_shape, data);
1245 }
1246 result.weight_node = std::make_shared<ov::op::v0::Constant>(result.weights);
1247 return result;
1248 }
1249
1250 // Handle quantized weights
1251 if (!ggml_is_quantized(tensor->type)) {
1252 OPENVINO_THROW("Unsupported weight tensor type: ", ggml_type_name(tensor->type));
1253 }
1254
1255 result.layout = ggml_openvino_get_extracted_layout(tensor, use_bias);
1256 const auto & layout = result.layout;
1257 if (layout.total_size == 0) {
1258 OPENVINO_THROW("Unsupported quantized type: ", ggml_type_name(tensor->type));
1259 }
1260
1261 // 3D MoE expert weights (for_gather_matmul) always use the exact f16 zero-point path (see
1262 // extract_quantized_weights) -- must be kept in sync with the "use_bias || for_gather_matmul"
1263 // check in ggml_openvino_get_extracted_layout, which sizes/offsets the zp slot accordingly.
1264 // Requantized tensors (layout.is_requant) are handled by requantize_to_buffers instead, whose
1265 // zp sizing/type is unaffected by for_gather_matmul, so they are excluded here.
1266 const bool for_gather_matmul = tensor->ne[2] > 1;
1267 const bool zp_is_f16 = !layout.is_requant && (use_bias || for_gather_matmul);
1268
1269 const bool is_3d_mxfp4_moe = tensor->type == GGML_TYPE_MXFP4 && (tensor->ne[2] > 1 || tensor->ne[3] > 1);
1270 if (is_3d_mxfp4_moe) {
1271 ov::Shape packed_shape = {static_cast<size_t>(tensor->ne[3]),
1272 static_cast<size_t>(tensor->ne[2]),
1273 static_cast<size_t>(tensor->ne[1]),
1274 static_cast<size_t>(tensor->ne[0] / MXFP4_BLOCK_SIZE),
1275 MXFP4_BLOCK_BYTES};
1276 const size_t tensor_bytes = ggml_nbytes(tensor);
1277 if (output_base_ptr) {
1278 auto * buf_base = static_cast<uint8_t *>(output_base_ptr);
1279 memcpy(buf_base + layout.weights_offset, data, tensor_bytes);
1280 result.weights = ov::Tensor(ov::element::u8, packed_shape, buf_base + layout.weights_offset);
1281 } else {
1282 result.weights = ov::Tensor(ov::element::u8, packed_shape);
1283 memcpy(result.weights.data(), data, tensor_bytes);
1284 }
1285 result.weight_node = make_mxfp4_moe_packed_weights(result.weights).get_node_shared_ptr();
1286 result.weight_node->set_friendly_name(tensor->name);
1287 return result;
1288 }
1289
1290 if (use_bias) {
1291 OPENVINO_ASSERT(!layout.is_requant,
1292 "use_bias is only used for test-backend-ops, which should not have requantization");
1293 // bias node will be created on the fly and not use backend buffer
1294 output_base_ptr = nullptr;
1295 }
1296
1297 // F16 requant path - no separate scales/zp needed in result
1298 if (layout.is_requant && layout.requant_type.has_value() && layout.requant_type.value() == ExtraQuantType::F16) {
1299 if (output_base_ptr) {
1300 result.weights = ov::Tensor(ov::element::f16, node_shape,
1301 static_cast<uint8_t *>(output_base_ptr) + layout.weights_offset);
1302 } else {
1303 result.weights = ov::Tensor(ov::element::f16, node_shape);
1304 }
1305 // Not used for F16:
1306 ov::Tensor dummy_scales;
1307 ov::Tensor dummy_zp;
1308 result.weight_node =
1309 requantize_to_buffers(tensor, data, ExtraQuantType::F16, 0, result.weights, dummy_scales, dummy_zp);
1310 return result;
1311 }
1312
1313 // Quantized path (normal extraction or quantized requant)
1314 // Create weight/scale/zp tensors - shared between both paths
1315 // For symmetric quantization, use signed types (i4/i8) and no ZP tensor
1316 ov::element::Type weight_type;
1317 if (tensor->type == GGML_TYPE_MXFP4) {
1318 weight_type = ov::element::f4e2m1;
1319 } else if (layout.is_symmetric) {
1320 weight_type = layout.is_u4 ? ov::element::i4 : ov::element::i8;
1321 } else {
1322 weight_type = layout.is_u4 ? ov::element::u4 : ov::element::u8;
1323 }
1324 ov::Shape scale_shape = node_shape;
1325 scale_shape.back() /= layout.weights_per_block;
1326
1327 if (tensor->type == GGML_TYPE_MXFP4) {
1328 if (tensor->ne[2] == 1 && tensor->ne[3] == 1) {
1329 node_shape = {static_cast<size_t>(tensor->ne[1]), static_cast<size_t>(tensor->ne[0])};
1330 } else {
1331 node_shape.clear();
1332 for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
1333 node_shape.push_back(static_cast<size_t>(tensor->ne[i]));
1334 }
1335 }
1336
1337 scale_shape = node_shape;
1338 scale_shape.back() /= layout.weights_per_block;
1339 }
1340
1341 const ov::element::Type scale_type = tensor->type == GGML_TYPE_MXFP4 ? ov::element::f8e8m0 : ov::element::f16;
1342 ov::element::Type zp_type = layout.is_u4 ? ov::element::u4 : ov::element::u8;
1343 if (zp_is_f16) {
1344 zp_type = ov::element::f16;
1345 }
1346
1347 if (output_base_ptr) {
1348 uint8_t * buf_base = static_cast<uint8_t *>(output_base_ptr);
1349 result.weights = ov::Tensor(weight_type, node_shape, buf_base + layout.weights_offset);
1350 result.scales = ov::Tensor(scale_type, scale_shape, buf_base + layout.scales_offset);
1351 if (!layout.is_symmetric) {
1352 result.zp = ov::Tensor(zp_type, scale_shape, buf_base + layout.zp_offset);
1353 }
1354 // else: result.zp remains default-constructed (empty) for symmetric
1355 } else {
1356 result.weights = ov::Tensor(weight_type, node_shape);
1357 result.scales = ov::Tensor(scale_type, scale_shape);
1358 if (!layout.is_symmetric) {
1359 result.zp = ov::Tensor(zp_type, scale_shape);
1360 }
1361 // else: result.zp remains default-constructed (empty) for symmetric
1362 }
1363
1364 if (layout.is_requant && layout.requant_type.has_value()) {
1365 result.weight_node = requantize_to_buffers(tensor, data, layout.requant_type.value(), layout.weights_per_block,
1366 result.weights, result.scales, result.zp);
1367 } else {
1368 result.weight_node =
1369 extract_quantized_weights(tensor, data, result.weights, result.scales, result.zp, use_bias);
1370 }
1371
1372 return result;
1373}